text
stringlengths
2
99.9k
meta
dict
/* * linux/sound/soc/ep93xx-i2s.c * EP93xx I2S driver * * Copyright (C) 2010 Ryan Mallon <[email protected]> * * Based on the original driver by: * Copyright (C) 2007 Chase Douglas <chasedouglas@gmail> * Copyright (C) 2006 Lennert Buytenhek <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/io.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/initval.h> #include <sound/soc.h> #include <mach/hardware.h> #include <mach/ep93xx-regs.h> #include <mach/dma.h> #include "ep93xx-pcm.h" #define EP93XX_I2S_TXCLKCFG 0x00 #define EP93XX_I2S_RXCLKCFG 0x04 #define EP93XX_I2S_GLCTRL 0x0C #define EP93XX_I2S_TXLINCTRLDATA 0x28 #define EP93XX_I2S_TXCTRL 0x2C #define EP93XX_I2S_TXWRDLEN 0x30 #define EP93XX_I2S_TX0EN 0x34 #define EP93XX_I2S_RXLINCTRLDATA 0x58 #define EP93XX_I2S_RXCTRL 0x5C #define EP93XX_I2S_RXWRDLEN 0x60 #define EP93XX_I2S_RX0EN 0x64 #define EP93XX_I2S_WRDLEN_16 (0 << 0) #define EP93XX_I2S_WRDLEN_24 (1 << 0) #define EP93XX_I2S_WRDLEN_32 (2 << 0) #define EP93XX_I2S_LINCTRLDATA_R_JUST (1 << 2) /* Right justify */ #define EP93XX_I2S_CLKCFG_LRS (1 << 0) /* lrclk polarity */ #define EP93XX_I2S_CLKCFG_CKP (1 << 1) /* Bit clock polarity */ #define EP93XX_I2S_CLKCFG_REL (1 << 2) /* First bit transition */ #define EP93XX_I2S_CLKCFG_MASTER (1 << 3) /* Master mode */ #define EP93XX_I2S_CLKCFG_NBCG (1 << 4) /* Not bit clock gating */ struct ep93xx_i2s_info { struct clk *mclk; struct clk *sclk; struct clk *lrclk; struct ep93xx_pcm_dma_params *dma_params; struct resource *mem; void __iomem *regs; }; struct ep93xx_pcm_dma_params ep93xx_i2s_dma_params[] = { [SNDRV_PCM_STREAM_PLAYBACK] = { .name = "i2s-pcm-out", .dma_port = EP93XX_DMA_M2P_PORT_I2S1, }, [SNDRV_PCM_STREAM_CAPTURE] = { .name = "i2s-pcm-in", .dma_port = EP93XX_DMA_M2P_PORT_I2S1, }, }; static inline void ep93xx_i2s_write_reg(struct ep93xx_i2s_info *info, unsigned reg, unsigned val) { __raw_writel(val, info->regs + reg); } static inline unsigned ep93xx_i2s_read_reg(struct ep93xx_i2s_info *info, unsigned reg) { return __raw_readl(info->regs + reg); } static void ep93xx_i2s_enable(struct ep93xx_i2s_info *info, int stream) { unsigned base_reg; int i; if ((ep93xx_i2s_read_reg(info, EP93XX_I2S_TX0EN) & 0x1) == 0 && (ep93xx_i2s_read_reg(info, EP93XX_I2S_RX0EN) & 0x1) == 0) { /* Enable clocks */ clk_enable(info->mclk); clk_enable(info->sclk); clk_enable(info->lrclk); /* Enable i2s */ ep93xx_i2s_write_reg(info, EP93XX_I2S_GLCTRL, 1); } /* Enable fifos */ if (stream == SNDRV_PCM_STREAM_PLAYBACK) base_reg = EP93XX_I2S_TX0EN; else base_reg = EP93XX_I2S_RX0EN; for (i = 0; i < 3; i++) ep93xx_i2s_write_reg(info, base_reg + (i * 4), 1); } static void ep93xx_i2s_disable(struct ep93xx_i2s_info *info, int stream) { unsigned base_reg; int i; /* Disable fifos */ if (stream == SNDRV_PCM_STREAM_PLAYBACK) base_reg = EP93XX_I2S_TX0EN; else base_reg = EP93XX_I2S_RX0EN; for (i = 0; i < 3; i++) ep93xx_i2s_write_reg(info, base_reg + (i * 4), 0); if ((ep93xx_i2s_read_reg(info, EP93XX_I2S_TX0EN) & 0x1) == 0 && (ep93xx_i2s_read_reg(info, EP93XX_I2S_RX0EN) & 0x1) == 0) { /* Disable i2s */ ep93xx_i2s_write_reg(info, EP93XX_I2S_GLCTRL, 0); /* Disable clocks */ clk_disable(info->lrclk); clk_disable(info->sclk); clk_disable(info->mclk); } } static int ep93xx_i2s_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct ep93xx_i2s_info *info = snd_soc_dai_get_drvdata(dai); struct snd_soc_dai *cpu_dai = rtd->cpu_dai; snd_soc_dai_set_dma_data(cpu_dai, substream, &info->dma_params[substream->stream]); return 0; } static void ep93xx_i2s_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct ep93xx_i2s_info *info = snd_soc_dai_get_drvdata(dai); ep93xx_i2s_disable(info, substream->stream); } static int ep93xx_i2s_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt) { struct ep93xx_i2s_info *info = snd_soc_dai_get_drvdata(cpu_dai); unsigned int clk_cfg, lin_ctrl; clk_cfg = ep93xx_i2s_read_reg(info, EP93XX_I2S_RXCLKCFG); lin_ctrl = ep93xx_i2s_read_reg(info, EP93XX_I2S_RXLINCTRLDATA); switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: clk_cfg |= EP93XX_I2S_CLKCFG_REL; lin_ctrl &= ~EP93XX_I2S_LINCTRLDATA_R_JUST; break; case SND_SOC_DAIFMT_LEFT_J: clk_cfg &= ~EP93XX_I2S_CLKCFG_REL; lin_ctrl &= ~EP93XX_I2S_LINCTRLDATA_R_JUST; break; case SND_SOC_DAIFMT_RIGHT_J: clk_cfg &= ~EP93XX_I2S_CLKCFG_REL; lin_ctrl |= EP93XX_I2S_LINCTRLDATA_R_JUST; break; default: return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: /* CPU is master */ clk_cfg |= EP93XX_I2S_CLKCFG_MASTER; break; case SND_SOC_DAIFMT_CBM_CFM: /* Codec is master */ clk_cfg &= ~EP93XX_I2S_CLKCFG_MASTER; break; default: return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_NB_NF: /* Negative bit clock, lrclk low on left word */ clk_cfg &= ~(EP93XX_I2S_CLKCFG_CKP | EP93XX_I2S_CLKCFG_REL); break; case SND_SOC_DAIFMT_NB_IF: /* Negative bit clock, lrclk low on right word */ clk_cfg &= ~EP93XX_I2S_CLKCFG_CKP; clk_cfg |= EP93XX_I2S_CLKCFG_REL; break; case SND_SOC_DAIFMT_IB_NF: /* Positive bit clock, lrclk low on left word */ clk_cfg |= EP93XX_I2S_CLKCFG_CKP; clk_cfg &= ~EP93XX_I2S_CLKCFG_REL; break; case SND_SOC_DAIFMT_IB_IF: /* Positive bit clock, lrclk low on right word */ clk_cfg |= EP93XX_I2S_CLKCFG_CKP | EP93XX_I2S_CLKCFG_REL; break; } /* Write new register values */ ep93xx_i2s_write_reg(info, EP93XX_I2S_RXCLKCFG, clk_cfg); ep93xx_i2s_write_reg(info, EP93XX_I2S_TXCLKCFG, clk_cfg); ep93xx_i2s_write_reg(info, EP93XX_I2S_RXLINCTRLDATA, lin_ctrl); ep93xx_i2s_write_reg(info, EP93XX_I2S_TXLINCTRLDATA, lin_ctrl); return 0; } static int ep93xx_i2s_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct ep93xx_i2s_info *info = snd_soc_dai_get_drvdata(dai); unsigned word_len, div, sdiv, lrdiv; int err; switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: word_len = EP93XX_I2S_WRDLEN_16; break; case SNDRV_PCM_FORMAT_S24_LE: word_len = EP93XX_I2S_WRDLEN_24; break; case SNDRV_PCM_FORMAT_S32_LE: word_len = EP93XX_I2S_WRDLEN_32; break; default: return -EINVAL; } if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ep93xx_i2s_write_reg(info, EP93XX_I2S_TXWRDLEN, word_len); else ep93xx_i2s_write_reg(info, EP93XX_I2S_RXWRDLEN, word_len); /* * EP93xx I2S module can be setup so SCLK / LRCLK value can be * 32, 64, 128. MCLK / SCLK value can be 2 and 4. * We set LRCLK equal to `rate' and minimum SCLK / LRCLK * value is 64, because our sample size is 32 bit * 2 channels. * I2S standard permits us to transmit more bits than * the codec uses. */ div = clk_get_rate(info->mclk) / params_rate(params); sdiv = 4; if (div > (256 + 512) / 2) { lrdiv = 128; } else { lrdiv = 64; if (div < (128 + 256) / 2) sdiv = 2; } err = clk_set_rate(info->sclk, clk_get_rate(info->mclk) / sdiv); if (err) return err; err = clk_set_rate(info->lrclk, clk_get_rate(info->sclk) / lrdiv); if (err) return err; ep93xx_i2s_enable(info, substream->stream); return 0; } static int ep93xx_i2s_set_sysclk(struct snd_soc_dai *cpu_dai, int clk_id, unsigned int freq, int dir) { struct ep93xx_i2s_info *info = snd_soc_dai_get_drvdata(cpu_dai); if (dir == SND_SOC_CLOCK_IN || clk_id != 0) return -EINVAL; return clk_set_rate(info->mclk, freq); } #ifdef CONFIG_PM static int ep93xx_i2s_suspend(struct snd_soc_dai *dai) { struct ep93xx_i2s_info *info = snd_soc_dai_get_drvdata(dai); if (!dai->active) return 0; ep93xx_i2s_disable(info, SNDRV_PCM_STREAM_PLAYBACK); ep93xx_i2s_disable(info, SNDRV_PCM_STREAM_CAPTURE); return 0; } static int ep93xx_i2s_resume(struct snd_soc_dai *dai) { struct ep93xx_i2s_info *info = snd_soc_dai_get_drvdata(dai); if (!dai->active) return 0; ep93xx_i2s_enable(info, SNDRV_PCM_STREAM_PLAYBACK); ep93xx_i2s_enable(info, SNDRV_PCM_STREAM_CAPTURE); return 0; } #else #define ep93xx_i2s_suspend NULL #define ep93xx_i2s_resume NULL #endif static struct snd_soc_dai_ops ep93xx_i2s_dai_ops = { .startup = ep93xx_i2s_startup, .shutdown = ep93xx_i2s_shutdown, .hw_params = ep93xx_i2s_hw_params, .set_sysclk = ep93xx_i2s_set_sysclk, .set_fmt = ep93xx_i2s_set_dai_fmt, }; #define EP93XX_I2S_FORMATS (SNDRV_PCM_FMTBIT_S32_LE) static struct snd_soc_dai_driver ep93xx_i2s_dai = { .symmetric_rates= 1, .suspend = ep93xx_i2s_suspend, .resume = ep93xx_i2s_resume, .playback = { .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_192000, .formats = EP93XX_I2S_FORMATS, }, .capture = { .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_192000, .formats = EP93XX_I2S_FORMATS, }, .ops = &ep93xx_i2s_dai_ops, }; static int ep93xx_i2s_probe(struct platform_device *pdev) { struct ep93xx_i2s_info *info; struct resource *res; int err; info = kzalloc(sizeof(struct ep93xx_i2s_info), GFP_KERNEL); if (!info) { err = -ENOMEM; goto fail; } dev_set_drvdata(&pdev->dev, info); info->dma_params = ep93xx_i2s_dma_params; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { err = -ENODEV; goto fail; } info->mem = request_mem_region(res->start, resource_size(res), pdev->name); if (!info->mem) { err = -EBUSY; goto fail; } info->regs = ioremap(info->mem->start, resource_size(info->mem)); if (!info->regs) { err = -ENXIO; goto fail_release_mem; } info->mclk = clk_get(&pdev->dev, "mclk"); if (IS_ERR(info->mclk)) { err = PTR_ERR(info->mclk); goto fail_unmap_mem; } info->sclk = clk_get(&pdev->dev, "sclk"); if (IS_ERR(info->sclk)) { err = PTR_ERR(info->sclk); goto fail_put_mclk; } info->lrclk = clk_get(&pdev->dev, "lrclk"); if (IS_ERR(info->lrclk)) { err = PTR_ERR(info->lrclk); goto fail_put_sclk; } err = snd_soc_register_dai(&pdev->dev, &ep93xx_i2s_dai); if (err) goto fail_put_lrclk; return 0; fail_put_lrclk: clk_put(info->lrclk); fail_put_sclk: clk_put(info->sclk); fail_put_mclk: clk_put(info->mclk); fail_unmap_mem: iounmap(info->regs); fail_release_mem: release_mem_region(info->mem->start, resource_size(info->mem)); kfree(info); fail: return err; } static int __devexit ep93xx_i2s_remove(struct platform_device *pdev) { struct ep93xx_i2s_info *info = dev_get_drvdata(&pdev->dev); snd_soc_unregister_dai(&pdev->dev); clk_put(info->lrclk); clk_put(info->sclk); clk_put(info->mclk); iounmap(info->regs); release_mem_region(info->mem->start, resource_size(info->mem)); kfree(info); return 0; } static struct platform_driver ep93xx_i2s_driver = { .probe = ep93xx_i2s_probe, .remove = __devexit_p(ep93xx_i2s_remove), .driver = { .name = "ep93xx-i2s", .owner = THIS_MODULE, }, }; static int __init ep93xx_i2s_init(void) { return platform_driver_register(&ep93xx_i2s_driver); } static void __exit ep93xx_i2s_exit(void) { platform_driver_unregister(&ep93xx_i2s_driver); } module_init(ep93xx_i2s_init); module_exit(ep93xx_i2s_exit); MODULE_ALIAS("platform:ep93xx-i2s"); MODULE_AUTHOR("Ryan Mallon <[email protected]>"); MODULE_DESCRIPTION("EP93XX I2S driver"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
/* * Copyright 2019-2020 Hans-Kristian Arntzen * * 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. */ #ifndef SPIRV_CROSS_C_API_H #define SPIRV_CROSS_C_API_H #include <stddef.h> #include "spirv.h" /* * C89-compatible wrapper for SPIRV-Cross' API. * Documentation here is sparse unless the behavior does not map 1:1 with C++ API. * It is recommended to look at the canonical C++ API for more detailed information. */ #ifdef __cplusplus extern "C" { #endif /* Bumped if ABI or API breaks backwards compatibility. */ #define SPVC_C_API_VERSION_MAJOR 0 /* Bumped if APIs or enumerations are added in a backwards compatible way. */ #define SPVC_C_API_VERSION_MINOR 30 /* Bumped if internal implementation details change. */ #define SPVC_C_API_VERSION_PATCH 0 #if !defined(SPVC_PUBLIC_API) #if defined(SPVC_EXPORT_SYMBOLS) /* Exports symbols. Standard C calling convention is used. */ #if defined(__GNUC__) #define SPVC_PUBLIC_API __attribute__((visibility("default"))) #elif defined(_MSC_VER) #define SPVC_PUBLIC_API __declspec(dllexport) #else #define SPVC_PUBLIC_API #endif #else #define SPVC_PUBLIC_API #endif #endif /* * Gets the SPVC_C_API_VERSION_* used to build this library. * Can be used to check for ABI mismatch if so-versioning did not catch it. */ SPVC_PUBLIC_API void spvc_get_version(unsigned *major, unsigned *minor, unsigned *patch); /* Gets a human readable version string to identify which commit a particular binary was created from. */ SPVC_PUBLIC_API const char *spvc_get_commit_revision_and_timestamp(void); /* These types are opaque to the user. */ typedef struct spvc_context_s *spvc_context; typedef struct spvc_parsed_ir_s *spvc_parsed_ir; typedef struct spvc_compiler_s *spvc_compiler; typedef struct spvc_compiler_options_s *spvc_compiler_options; typedef struct spvc_resources_s *spvc_resources; struct spvc_type_s; typedef const struct spvc_type_s *spvc_type; typedef struct spvc_constant_s *spvc_constant; struct spvc_set_s; typedef const struct spvc_set_s *spvc_set; /* * Shallow typedefs. All SPIR-V IDs are plain 32-bit numbers, but this helps communicate which data is used. * Maps to a SPIRType. */ typedef SpvId spvc_type_id; /* Maps to a SPIRVariable. */ typedef SpvId spvc_variable_id; /* Maps to a SPIRConstant. */ typedef SpvId spvc_constant_id; /* See C++ API. */ typedef struct spvc_reflected_resource { spvc_variable_id id; spvc_type_id base_type_id; spvc_type_id type_id; const char *name; } spvc_reflected_resource; /* See C++ API. */ typedef struct spvc_entry_point { SpvExecutionModel execution_model; const char *name; } spvc_entry_point; /* See C++ API. */ typedef struct spvc_combined_image_sampler { spvc_variable_id combined_id; spvc_variable_id image_id; spvc_variable_id sampler_id; } spvc_combined_image_sampler; /* See C++ API. */ typedef struct spvc_specialization_constant { spvc_constant_id id; unsigned constant_id; } spvc_specialization_constant; /* See C++ API. */ typedef struct spvc_buffer_range { unsigned index; size_t offset; size_t range; } spvc_buffer_range; /* See C++ API. */ typedef struct spvc_hlsl_root_constants { unsigned start; unsigned end; unsigned binding; unsigned space; } spvc_hlsl_root_constants; /* See C++ API. */ typedef struct spvc_hlsl_vertex_attribute_remap { unsigned location; const char *semantic; } spvc_hlsl_vertex_attribute_remap; /* * Be compatible with non-C99 compilers, which do not have stdbool. * Only recent MSVC compilers supports this for example, and ideally SPIRV-Cross should be linkable * from a wide range of compilers in its C wrapper. */ typedef unsigned char spvc_bool; #define SPVC_TRUE ((spvc_bool)1) #define SPVC_FALSE ((spvc_bool)0) typedef enum spvc_result { /* Success. */ SPVC_SUCCESS = 0, /* The SPIR-V is invalid. Should have been caught by validation ideally. */ SPVC_ERROR_INVALID_SPIRV = -1, /* The SPIR-V might be valid or invalid, but SPIRV-Cross currently cannot correctly translate this to your target language. */ SPVC_ERROR_UNSUPPORTED_SPIRV = -2, /* If for some reason we hit this, new or malloc failed. */ SPVC_ERROR_OUT_OF_MEMORY = -3, /* Invalid API argument. */ SPVC_ERROR_INVALID_ARGUMENT = -4, SPVC_ERROR_INT_MAX = 0x7fffffff } spvc_result; typedef enum spvc_capture_mode { /* The Parsed IR payload will be copied, and the handle can be reused to create other compiler instances. */ SPVC_CAPTURE_MODE_COPY = 0, /* * The payload will now be owned by the compiler. * parsed_ir should now be considered a dead blob and must not be used further. * This is optimal for performance and should be the go-to option. */ SPVC_CAPTURE_MODE_TAKE_OWNERSHIP = 1, SPVC_CAPTURE_MODE_INT_MAX = 0x7fffffff } spvc_capture_mode; typedef enum spvc_backend { /* This backend can only perform reflection, no compiler options are supported. Maps to spirv_cross::Compiler. */ SPVC_BACKEND_NONE = 0, SPVC_BACKEND_GLSL = 1, /* spirv_cross::CompilerGLSL */ SPVC_BACKEND_HLSL = 2, /* CompilerHLSL */ SPVC_BACKEND_MSL = 3, /* CompilerMSL */ SPVC_BACKEND_CPP = 4, /* CompilerCPP */ SPVC_BACKEND_JSON = 5, /* CompilerReflection w/ JSON backend */ SPVC_BACKEND_INT_MAX = 0x7fffffff } spvc_backend; /* Maps to C++ API. */ typedef enum spvc_resource_type { SPVC_RESOURCE_TYPE_UNKNOWN = 0, SPVC_RESOURCE_TYPE_UNIFORM_BUFFER = 1, SPVC_RESOURCE_TYPE_STORAGE_BUFFER = 2, SPVC_RESOURCE_TYPE_STAGE_INPUT = 3, SPVC_RESOURCE_TYPE_STAGE_OUTPUT = 4, SPVC_RESOURCE_TYPE_SUBPASS_INPUT = 5, SPVC_RESOURCE_TYPE_STORAGE_IMAGE = 6, SPVC_RESOURCE_TYPE_SAMPLED_IMAGE = 7, SPVC_RESOURCE_TYPE_ATOMIC_COUNTER = 8, SPVC_RESOURCE_TYPE_PUSH_CONSTANT = 9, SPVC_RESOURCE_TYPE_SEPARATE_IMAGE = 10, SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS = 11, SPVC_RESOURCE_TYPE_ACCELERATION_STRUCTURE = 12, SPVC_RESOURCE_TYPE_INT_MAX = 0x7fffffff } spvc_resource_type; /* Maps to spirv_cross::SPIRType::BaseType. */ typedef enum spvc_basetype { SPVC_BASETYPE_UNKNOWN = 0, SPVC_BASETYPE_VOID = 1, SPVC_BASETYPE_BOOLEAN = 2, SPVC_BASETYPE_INT8 = 3, SPVC_BASETYPE_UINT8 = 4, SPVC_BASETYPE_INT16 = 5, SPVC_BASETYPE_UINT16 = 6, SPVC_BASETYPE_INT32 = 7, SPVC_BASETYPE_UINT32 = 8, SPVC_BASETYPE_INT64 = 9, SPVC_BASETYPE_UINT64 = 10, SPVC_BASETYPE_ATOMIC_COUNTER = 11, SPVC_BASETYPE_FP16 = 12, SPVC_BASETYPE_FP32 = 13, SPVC_BASETYPE_FP64 = 14, SPVC_BASETYPE_STRUCT = 15, SPVC_BASETYPE_IMAGE = 16, SPVC_BASETYPE_SAMPLED_IMAGE = 17, SPVC_BASETYPE_SAMPLER = 18, SPVC_BASETYPE_ACCELERATION_STRUCTURE = 19, SPVC_BASETYPE_INT_MAX = 0x7fffffff } spvc_basetype; #define SPVC_COMPILER_OPTION_COMMON_BIT 0x1000000 #define SPVC_COMPILER_OPTION_GLSL_BIT 0x2000000 #define SPVC_COMPILER_OPTION_HLSL_BIT 0x4000000 #define SPVC_COMPILER_OPTION_MSL_BIT 0x8000000 #define SPVC_COMPILER_OPTION_LANG_BITS 0x0f000000 #define SPVC_COMPILER_OPTION_ENUM_BITS 0xffffff #define SPVC_MAKE_MSL_VERSION(major, minor, patch) ((major) * 10000 + (minor) * 100 + (patch)) /* Maps to C++ API. */ typedef enum spvc_msl_platform { SPVC_MSL_PLATFORM_IOS = 0, SPVC_MSL_PLATFORM_MACOS = 1, SPVC_MSL_PLATFORM_MAX_INT = 0x7fffffff } spvc_msl_platform; /* Maps to C++ API. */ typedef enum spvc_msl_vertex_format { SPVC_MSL_VERTEX_FORMAT_OTHER = 0, SPVC_MSL_VERTEX_FORMAT_UINT8 = 1, SPVC_MSL_VERTEX_FORMAT_UINT16 = 2 } spvc_msl_vertex_format; /* Maps to C++ API. */ typedef struct spvc_msl_vertex_attribute { unsigned location; unsigned msl_buffer; unsigned msl_offset; unsigned msl_stride; spvc_bool per_instance; spvc_msl_vertex_format format; SpvBuiltIn builtin; } spvc_msl_vertex_attribute; /* * Initializes the vertex attribute struct. */ SPVC_PUBLIC_API void spvc_msl_vertex_attribute_init(spvc_msl_vertex_attribute *attr); /* Maps to C++ API. */ typedef struct spvc_msl_resource_binding { SpvExecutionModel stage; unsigned desc_set; unsigned binding; unsigned msl_buffer; unsigned msl_texture; unsigned msl_sampler; } spvc_msl_resource_binding; /* * Initializes the resource binding struct. * The defaults are non-zero. */ SPVC_PUBLIC_API void spvc_msl_resource_binding_init(spvc_msl_resource_binding *binding); #define SPVC_MSL_PUSH_CONSTANT_DESC_SET (~(0u)) #define SPVC_MSL_PUSH_CONSTANT_BINDING (0) #define SPVC_MSL_SWIZZLE_BUFFER_BINDING (~(1u)) #define SPVC_MSL_BUFFER_SIZE_BUFFER_BINDING (~(2u)) #define SPVC_MSL_ARGUMENT_BUFFER_BINDING (~(3u)) /* Obsolete. Sticks around for backwards compatibility. */ #define SPVC_MSL_AUX_BUFFER_STRUCT_VERSION 1 /* Runtime check for incompatibility. Obsolete. */ SPVC_PUBLIC_API unsigned spvc_msl_get_aux_buffer_struct_version(void); /* Maps to C++ API. */ typedef enum spvc_msl_sampler_coord { SPVC_MSL_SAMPLER_COORD_NORMALIZED = 0, SPVC_MSL_SAMPLER_COORD_PIXEL = 1, SPVC_MSL_SAMPLER_INT_MAX = 0x7fffffff } spvc_msl_sampler_coord; /* Maps to C++ API. */ typedef enum spvc_msl_sampler_filter { SPVC_MSL_SAMPLER_FILTER_NEAREST = 0, SPVC_MSL_SAMPLER_FILTER_LINEAR = 1, SPVC_MSL_SAMPLER_FILTER_INT_MAX = 0x7fffffff } spvc_msl_sampler_filter; /* Maps to C++ API. */ typedef enum spvc_msl_sampler_mip_filter { SPVC_MSL_SAMPLER_MIP_FILTER_NONE = 0, SPVC_MSL_SAMPLER_MIP_FILTER_NEAREST = 1, SPVC_MSL_SAMPLER_MIP_FILTER_LINEAR = 2, SPVC_MSL_SAMPLER_MIP_FILTER_INT_MAX = 0x7fffffff } spvc_msl_sampler_mip_filter; /* Maps to C++ API. */ typedef enum spvc_msl_sampler_address { SPVC_MSL_SAMPLER_ADDRESS_CLAMP_TO_ZERO = 0, SPVC_MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE = 1, SPVC_MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER = 2, SPVC_MSL_SAMPLER_ADDRESS_REPEAT = 3, SPVC_MSL_SAMPLER_ADDRESS_MIRRORED_REPEAT = 4, SPVC_MSL_SAMPLER_ADDRESS_INT_MAX = 0x7fffffff } spvc_msl_sampler_address; /* Maps to C++ API. */ typedef enum spvc_msl_sampler_compare_func { SPVC_MSL_SAMPLER_COMPARE_FUNC_NEVER = 0, SPVC_MSL_SAMPLER_COMPARE_FUNC_LESS = 1, SPVC_MSL_SAMPLER_COMPARE_FUNC_LESS_EQUAL = 2, SPVC_MSL_SAMPLER_COMPARE_FUNC_GREATER = 3, SPVC_MSL_SAMPLER_COMPARE_FUNC_GREATER_EQUAL = 4, SPVC_MSL_SAMPLER_COMPARE_FUNC_EQUAL = 5, SPVC_MSL_SAMPLER_COMPARE_FUNC_NOT_EQUAL = 6, SPVC_MSL_SAMPLER_COMPARE_FUNC_ALWAYS = 7, SPVC_MSL_SAMPLER_COMPARE_FUNC_INT_MAX = 0x7fffffff } spvc_msl_sampler_compare_func; /* Maps to C++ API. */ typedef enum spvc_msl_sampler_border_color { SPVC_MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK = 0, SPVC_MSL_SAMPLER_BORDER_COLOR_OPAQUE_BLACK = 1, SPVC_MSL_SAMPLER_BORDER_COLOR_OPAQUE_WHITE = 2, SPVC_MSL_SAMPLER_BORDER_COLOR_INT_MAX = 0x7fffffff } spvc_msl_sampler_border_color; /* Maps to C++ API. */ typedef enum spvc_msl_format_resolution { SPVC_MSL_FORMAT_RESOLUTION_444 = 0, SPVC_MSL_FORMAT_RESOLUTION_422, SPVC_MSL_FORMAT_RESOLUTION_420, SPVC_MSL_FORMAT_RESOLUTION_INT_MAX = 0x7fffffff } spvc_msl_format_resolution; /* Maps to C++ API. */ typedef enum spvc_msl_chroma_location { SPVC_MSL_CHROMA_LOCATION_COSITED_EVEN = 0, SPVC_MSL_CHROMA_LOCATION_MIDPOINT, SPVC_MSL_CHROMA_LOCATION_INT_MAX = 0x7fffffff } spvc_msl_chroma_location; /* Maps to C++ API. */ typedef enum spvc_msl_component_swizzle { SPVC_MSL_COMPONENT_SWIZZLE_IDENTITY = 0, SPVC_MSL_COMPONENT_SWIZZLE_ZERO, SPVC_MSL_COMPONENT_SWIZZLE_ONE, SPVC_MSL_COMPONENT_SWIZZLE_R, SPVC_MSL_COMPONENT_SWIZZLE_G, SPVC_MSL_COMPONENT_SWIZZLE_B, SPVC_MSL_COMPONENT_SWIZZLE_A, SPVC_MSL_COMPONENT_SWIZZLE_INT_MAX = 0x7fffffff } spvc_msl_component_swizzle; /* Maps to C++ API. */ typedef enum spvc_msl_sampler_ycbcr_model_conversion { SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY = 0, SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY, SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709, SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601, SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020, SPVC_MSL_SAMPLER_YCBCR_MODEL_CONVERSION_INT_MAX = 0x7fffffff } spvc_msl_sampler_ycbcr_model_conversion; /* Maps to C+ API. */ typedef enum spvc_msl_sampler_ycbcr_range { SPVC_MSL_SAMPLER_YCBCR_RANGE_ITU_FULL = 0, SPVC_MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW, SPVC_MSL_SAMPLER_YCBCR_RANGE_INT_MAX = 0x7fffffff } spvc_msl_sampler_ycbcr_range; /* Maps to C++ API. */ typedef struct spvc_msl_constexpr_sampler { spvc_msl_sampler_coord coord; spvc_msl_sampler_filter min_filter; spvc_msl_sampler_filter mag_filter; spvc_msl_sampler_mip_filter mip_filter; spvc_msl_sampler_address s_address; spvc_msl_sampler_address t_address; spvc_msl_sampler_address r_address; spvc_msl_sampler_compare_func compare_func; spvc_msl_sampler_border_color border_color; float lod_clamp_min; float lod_clamp_max; int max_anisotropy; spvc_bool compare_enable; spvc_bool lod_clamp_enable; spvc_bool anisotropy_enable; } spvc_msl_constexpr_sampler; /* * Initializes the constexpr sampler struct. * The defaults are non-zero. */ SPVC_PUBLIC_API void spvc_msl_constexpr_sampler_init(spvc_msl_constexpr_sampler *sampler); /* Maps to the sampler Y'CbCr conversion-related portions of MSLConstexprSampler. See C++ API for defaults and details. */ typedef struct spvc_msl_sampler_ycbcr_conversion { unsigned planes; spvc_msl_format_resolution resolution; spvc_msl_sampler_filter chroma_filter; spvc_msl_chroma_location x_chroma_offset; spvc_msl_chroma_location y_chroma_offset; spvc_msl_component_swizzle swizzle[4]; spvc_msl_sampler_ycbcr_model_conversion ycbcr_model; spvc_msl_sampler_ycbcr_range ycbcr_range; unsigned bpc; } spvc_msl_sampler_ycbcr_conversion; /* * Initializes the constexpr sampler struct. * The defaults are non-zero. */ SPVC_PUBLIC_API void spvc_msl_sampler_ycbcr_conversion_init(spvc_msl_sampler_ycbcr_conversion *conv); /* Maps to C++ API. */ typedef enum spvc_hlsl_binding_flag_bits { SPVC_HLSL_BINDING_AUTO_NONE_BIT = 0, SPVC_HLSL_BINDING_AUTO_PUSH_CONSTANT_BIT = 1 << 0, SPVC_HLSL_BINDING_AUTO_CBV_BIT = 1 << 1, SPVC_HLSL_BINDING_AUTO_SRV_BIT = 1 << 2, SPVC_HLSL_BINDING_AUTO_UAV_BIT = 1 << 3, SPVC_HLSL_BINDING_AUTO_SAMPLER_BIT = 1 << 4, SPVC_HLSL_BINDING_AUTO_ALL = 0x7fffffff } spvc_hlsl_binding_flag_bits; typedef unsigned spvc_hlsl_binding_flags; #define SPVC_HLSL_PUSH_CONSTANT_DESC_SET (~(0u)) #define SPVC_HLSL_PUSH_CONSTANT_BINDING (0) /* Maps to C++ API. */ typedef struct spvc_hlsl_resource_binding_mapping { unsigned register_space; unsigned register_binding; } spvc_hlsl_resource_binding_mapping; typedef struct spvc_hlsl_resource_binding { SpvExecutionModel stage; unsigned desc_set; unsigned binding; spvc_hlsl_resource_binding_mapping cbv, uav, srv, sampler; } spvc_hlsl_resource_binding; /* * Initializes the resource binding struct. * The defaults are non-zero. */ SPVC_PUBLIC_API void spvc_hlsl_resource_binding_init(spvc_hlsl_resource_binding *binding); /* Maps to the various spirv_cross::Compiler*::Option structures. See C++ API for defaults and details. */ typedef enum spvc_compiler_option { SPVC_COMPILER_OPTION_UNKNOWN = 0, SPVC_COMPILER_OPTION_FORCE_TEMPORARY = 1 | SPVC_COMPILER_OPTION_COMMON_BIT, SPVC_COMPILER_OPTION_FLATTEN_MULTIDIMENSIONAL_ARRAYS = 2 | SPVC_COMPILER_OPTION_COMMON_BIT, SPVC_COMPILER_OPTION_FIXUP_DEPTH_CONVENTION = 3 | SPVC_COMPILER_OPTION_COMMON_BIT, SPVC_COMPILER_OPTION_FLIP_VERTEX_Y = 4 | SPVC_COMPILER_OPTION_COMMON_BIT, SPVC_COMPILER_OPTION_GLSL_SUPPORT_NONZERO_BASE_INSTANCE = 5 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_GLSL_SEPARATE_SHADER_OBJECTS = 6 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_GLSL_ENABLE_420PACK_EXTENSION = 7 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_GLSL_VERSION = 8 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_GLSL_ES = 9 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_GLSL_VULKAN_SEMANTICS = 10 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_GLSL_ES_DEFAULT_FLOAT_PRECISION_HIGHP = 11 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_GLSL_ES_DEFAULT_INT_PRECISION_HIGHP = 12 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_HLSL_SHADER_MODEL = 13 | SPVC_COMPILER_OPTION_HLSL_BIT, SPVC_COMPILER_OPTION_HLSL_POINT_SIZE_COMPAT = 14 | SPVC_COMPILER_OPTION_HLSL_BIT, SPVC_COMPILER_OPTION_HLSL_POINT_COORD_COMPAT = 15 | SPVC_COMPILER_OPTION_HLSL_BIT, SPVC_COMPILER_OPTION_HLSL_SUPPORT_NONZERO_BASE_VERTEX_BASE_INSTANCE = 16 | SPVC_COMPILER_OPTION_HLSL_BIT, SPVC_COMPILER_OPTION_MSL_VERSION = 17 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_TEXEL_BUFFER_TEXTURE_WIDTH = 18 | SPVC_COMPILER_OPTION_MSL_BIT, /* Obsolete, use SWIZZLE_BUFFER_INDEX instead. */ SPVC_COMPILER_OPTION_MSL_AUX_BUFFER_INDEX = 19 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_SWIZZLE_BUFFER_INDEX = 19 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_INDIRECT_PARAMS_BUFFER_INDEX = 20 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_SHADER_OUTPUT_BUFFER_INDEX = 21 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_SHADER_PATCH_OUTPUT_BUFFER_INDEX = 22 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_SHADER_TESS_FACTOR_OUTPUT_BUFFER_INDEX = 23 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_SHADER_INPUT_WORKGROUP_INDEX = 24 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_ENABLE_POINT_SIZE_BUILTIN = 25 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_DISABLE_RASTERIZATION = 26 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_CAPTURE_OUTPUT_TO_BUFFER = 27 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_SWIZZLE_TEXTURE_SAMPLES = 28 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_PAD_FRAGMENT_OUTPUT_COMPONENTS = 29 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_TESS_DOMAIN_ORIGIN_LOWER_LEFT = 30 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_PLATFORM = 31 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_ARGUMENT_BUFFERS = 32 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_GLSL_EMIT_PUSH_CONSTANT_AS_UNIFORM_BUFFER = 33 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_MSL_TEXTURE_BUFFER_NATIVE = 34 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_GLSL_EMIT_UNIFORM_BUFFER_AS_PLAIN_UNIFORMS = 35 | SPVC_COMPILER_OPTION_GLSL_BIT, SPVC_COMPILER_OPTION_MSL_BUFFER_SIZE_BUFFER_INDEX = 36 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_EMIT_LINE_DIRECTIVES = 37 | SPVC_COMPILER_OPTION_COMMON_BIT, SPVC_COMPILER_OPTION_MSL_MULTIVIEW = 38 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_VIEW_MASK_BUFFER_INDEX = 39 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_DEVICE_INDEX = 40 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_VIEW_INDEX_FROM_DEVICE_INDEX = 41 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_DISPATCH_BASE = 42 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_DYNAMIC_OFFSETS_BUFFER_INDEX = 43 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_TEXTURE_1D_AS_2D = 44 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_ENABLE_BASE_INDEX_ZERO = 45 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_IOS_FRAMEBUFFER_FETCH_SUBPASS = 46 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_INVARIANT_FP_MATH = 47 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_EMULATE_CUBEMAP_ARRAY = 48 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_ENABLE_DECORATION_BINDING = 49 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_FORCE_ACTIVE_ARGUMENT_BUFFER_RESOURCES = 50 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_MSL_FORCE_NATIVE_ARRAYS = 51 | SPVC_COMPILER_OPTION_MSL_BIT, SPVC_COMPILER_OPTION_ENABLE_STORAGE_IMAGE_QUALIFIER_DEDUCTION = 52 | SPVC_COMPILER_OPTION_COMMON_BIT, SPVC_COMPILER_OPTION_HLSL_FORCE_STORAGE_BUFFER_AS_UAV = 53 | SPVC_COMPILER_OPTION_HLSL_BIT, SPVC_COMPILER_OPTION_FORCE_ZERO_INITIALIZED_VARIABLES = 54 | SPVC_COMPILER_OPTION_COMMON_BIT, SPVC_COMPILER_OPTION_HLSL_NONWRITABLE_UAV_TEXTURE_AS_SRV = 55 | SPVC_COMPILER_OPTION_HLSL_BIT, SPVC_COMPILER_OPTION_INT_MAX = 0x7fffffff } spvc_compiler_option; /* * Context is the highest-level API construct. * The context owns all memory allocations made by its child object hierarchy, including various non-opaque structs and strings. * This means that the API user only has to care about one "destroy" call ever when using the C API. * All pointers handed out by the APIs are only valid as long as the context * is alive and spvc_context_release_allocations has not been called. */ SPVC_PUBLIC_API spvc_result spvc_context_create(spvc_context *context); /* Frees all memory allocations and objects associated with the context and its child objects. */ SPVC_PUBLIC_API void spvc_context_destroy(spvc_context context); /* Frees all memory allocations and objects associated with the context and its child objects, but keeps the context alive. */ SPVC_PUBLIC_API void spvc_context_release_allocations(spvc_context context); /* Get the string for the last error which was logged. */ SPVC_PUBLIC_API const char *spvc_context_get_last_error_string(spvc_context context); /* Get notified in a callback when an error triggers. Useful for debugging. */ typedef void (*spvc_error_callback)(void *userdata, const char *error); SPVC_PUBLIC_API void spvc_context_set_error_callback(spvc_context context, spvc_error_callback cb, void *userdata); /* SPIR-V parsing interface. Maps to Parser which then creates a ParsedIR, and that IR is extracted into the handle. */ SPVC_PUBLIC_API spvc_result spvc_context_parse_spirv(spvc_context context, const SpvId *spirv, size_t word_count, spvc_parsed_ir *parsed_ir); /* * Create a compiler backend. Capture mode controls if we construct by copy or move semantics. * It is always recommended to use SPVC_CAPTURE_MODE_TAKE_OWNERSHIP if you only intend to cross-compile the IR once. */ SPVC_PUBLIC_API spvc_result spvc_context_create_compiler(spvc_context context, spvc_backend backend, spvc_parsed_ir parsed_ir, spvc_capture_mode mode, spvc_compiler *compiler); /* Maps directly to C++ API. */ SPVC_PUBLIC_API unsigned spvc_compiler_get_current_id_bound(spvc_compiler compiler); /* Create compiler options, which will initialize defaults. */ SPVC_PUBLIC_API spvc_result spvc_compiler_create_compiler_options(spvc_compiler compiler, spvc_compiler_options *options); /* Override options. Will return error if e.g. MSL options are used for the HLSL backend, etc. */ SPVC_PUBLIC_API spvc_result spvc_compiler_options_set_bool(spvc_compiler_options options, spvc_compiler_option option, spvc_bool value); SPVC_PUBLIC_API spvc_result spvc_compiler_options_set_uint(spvc_compiler_options options, spvc_compiler_option option, unsigned value); /* Set compiler options. */ SPVC_PUBLIC_API spvc_result spvc_compiler_install_compiler_options(spvc_compiler compiler, spvc_compiler_options options); /* Compile IR into a string. *source is owned by the context, and caller must not free it themselves. */ SPVC_PUBLIC_API spvc_result spvc_compiler_compile(spvc_compiler compiler, const char **source); /* Maps to C++ API. */ SPVC_PUBLIC_API spvc_result spvc_compiler_add_header_line(spvc_compiler compiler, const char *line); SPVC_PUBLIC_API spvc_result spvc_compiler_require_extension(spvc_compiler compiler, const char *ext); SPVC_PUBLIC_API spvc_result spvc_compiler_flatten_buffer_block(spvc_compiler compiler, spvc_variable_id id); SPVC_PUBLIC_API spvc_bool spvc_compiler_variable_is_depth_or_compare(spvc_compiler compiler, spvc_variable_id id); /* * HLSL specifics. * Maps to C++ API. */ SPVC_PUBLIC_API spvc_result spvc_compiler_hlsl_set_root_constants_layout(spvc_compiler compiler, const spvc_hlsl_root_constants *constant_info, size_t count); SPVC_PUBLIC_API spvc_result spvc_compiler_hlsl_add_vertex_attribute_remap(spvc_compiler compiler, const spvc_hlsl_vertex_attribute_remap *remap, size_t remaps); SPVC_PUBLIC_API spvc_variable_id spvc_compiler_hlsl_remap_num_workgroups_builtin(spvc_compiler compiler); SPVC_PUBLIC_API spvc_result spvc_compiler_hlsl_set_resource_binding_flags(spvc_compiler compiler, spvc_hlsl_binding_flags flags); SPVC_PUBLIC_API spvc_result spvc_compiler_hlsl_add_resource_binding(spvc_compiler compiler, const spvc_hlsl_resource_binding *binding); SPVC_PUBLIC_API spvc_bool spvc_compiler_hlsl_is_resource_used(spvc_compiler compiler, SpvExecutionModel model, unsigned set, unsigned binding); /* * MSL specifics. * Maps to C++ API. */ SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_is_rasterization_disabled(spvc_compiler compiler); /* Obsolete. Renamed to needs_swizzle_buffer. */ SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_aux_buffer(spvc_compiler compiler); SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_swizzle_buffer(spvc_compiler compiler); SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_buffer_size_buffer(spvc_compiler compiler); SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_output_buffer(spvc_compiler compiler); SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_patch_output_buffer(spvc_compiler compiler); SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_needs_input_threadgroup_mem(spvc_compiler compiler); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_vertex_attribute(spvc_compiler compiler, const spvc_msl_vertex_attribute *attrs); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_resource_binding(spvc_compiler compiler, const spvc_msl_resource_binding *binding); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_discrete_descriptor_set(spvc_compiler compiler, unsigned desc_set); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_set_argument_buffer_device_address_space(spvc_compiler compiler, unsigned desc_set, spvc_bool device_address); SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_is_vertex_attribute_used(spvc_compiler compiler, unsigned location); SPVC_PUBLIC_API spvc_bool spvc_compiler_msl_is_resource_used(spvc_compiler compiler, SpvExecutionModel model, unsigned set, unsigned binding); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_remap_constexpr_sampler(spvc_compiler compiler, spvc_variable_id id, const spvc_msl_constexpr_sampler *sampler); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_remap_constexpr_sampler_by_binding(spvc_compiler compiler, unsigned desc_set, unsigned binding, const spvc_msl_constexpr_sampler *sampler); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_remap_constexpr_sampler_ycbcr(spvc_compiler compiler, spvc_variable_id id, const spvc_msl_constexpr_sampler *sampler, const spvc_msl_sampler_ycbcr_conversion *conv); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_remap_constexpr_sampler_by_binding_ycbcr(spvc_compiler compiler, unsigned desc_set, unsigned binding, const spvc_msl_constexpr_sampler *sampler, const spvc_msl_sampler_ycbcr_conversion *conv); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_set_fragment_output_components(spvc_compiler compiler, unsigned location, unsigned components); SPVC_PUBLIC_API unsigned spvc_compiler_msl_get_automatic_resource_binding(spvc_compiler compiler, spvc_variable_id id); SPVC_PUBLIC_API unsigned spvc_compiler_msl_get_automatic_resource_binding_secondary(spvc_compiler compiler, spvc_variable_id id); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_dynamic_buffer(spvc_compiler compiler, unsigned desc_set, unsigned binding, unsigned index); SPVC_PUBLIC_API spvc_result spvc_compiler_msl_add_inline_uniform_block(spvc_compiler compiler, unsigned desc_set, unsigned binding); /* * Reflect resources. * Maps almost 1:1 to C++ API. */ SPVC_PUBLIC_API spvc_result spvc_compiler_get_active_interface_variables(spvc_compiler compiler, spvc_set *set); SPVC_PUBLIC_API spvc_result spvc_compiler_set_enabled_interface_variables(spvc_compiler compiler, spvc_set set); SPVC_PUBLIC_API spvc_result spvc_compiler_create_shader_resources(spvc_compiler compiler, spvc_resources *resources); SPVC_PUBLIC_API spvc_result spvc_compiler_create_shader_resources_for_active_variables(spvc_compiler compiler, spvc_resources *resources, spvc_set active); SPVC_PUBLIC_API spvc_result spvc_resources_get_resource_list_for_type(spvc_resources resources, spvc_resource_type type, const spvc_reflected_resource **resource_list, size_t *resource_size); /* * Decorations. * Maps to C++ API. */ SPVC_PUBLIC_API void spvc_compiler_set_decoration(spvc_compiler compiler, SpvId id, SpvDecoration decoration, unsigned argument); SPVC_PUBLIC_API void spvc_compiler_set_decoration_string(spvc_compiler compiler, SpvId id, SpvDecoration decoration, const char *argument); SPVC_PUBLIC_API void spvc_compiler_set_name(spvc_compiler compiler, SpvId id, const char *argument); SPVC_PUBLIC_API void spvc_compiler_set_member_decoration(spvc_compiler compiler, spvc_type_id id, unsigned member_index, SpvDecoration decoration, unsigned argument); SPVC_PUBLIC_API void spvc_compiler_set_member_decoration_string(spvc_compiler compiler, spvc_type_id id, unsigned member_index, SpvDecoration decoration, const char *argument); SPVC_PUBLIC_API void spvc_compiler_set_member_name(spvc_compiler compiler, spvc_type_id id, unsigned member_index, const char *argument); SPVC_PUBLIC_API void spvc_compiler_unset_decoration(spvc_compiler compiler, SpvId id, SpvDecoration decoration); SPVC_PUBLIC_API void spvc_compiler_unset_member_decoration(spvc_compiler compiler, spvc_type_id id, unsigned member_index, SpvDecoration decoration); SPVC_PUBLIC_API spvc_bool spvc_compiler_has_decoration(spvc_compiler compiler, SpvId id, SpvDecoration decoration); SPVC_PUBLIC_API spvc_bool spvc_compiler_has_member_decoration(spvc_compiler compiler, spvc_type_id id, unsigned member_index, SpvDecoration decoration); SPVC_PUBLIC_API const char *spvc_compiler_get_name(spvc_compiler compiler, SpvId id); SPVC_PUBLIC_API unsigned spvc_compiler_get_decoration(spvc_compiler compiler, SpvId id, SpvDecoration decoration); SPVC_PUBLIC_API const char *spvc_compiler_get_decoration_string(spvc_compiler compiler, SpvId id, SpvDecoration decoration); SPVC_PUBLIC_API unsigned spvc_compiler_get_member_decoration(spvc_compiler compiler, spvc_type_id id, unsigned member_index, SpvDecoration decoration); SPVC_PUBLIC_API const char *spvc_compiler_get_member_decoration_string(spvc_compiler compiler, spvc_type_id id, unsigned member_index, SpvDecoration decoration); SPVC_PUBLIC_API const char *spvc_compiler_get_member_name(spvc_compiler compiler, spvc_type_id id, unsigned member_index); /* * Entry points. * Maps to C++ API. */ SPVC_PUBLIC_API spvc_result spvc_compiler_get_entry_points(spvc_compiler compiler, const spvc_entry_point **entry_points, size_t *num_entry_points); SPVC_PUBLIC_API spvc_result spvc_compiler_set_entry_point(spvc_compiler compiler, const char *name, SpvExecutionModel model); SPVC_PUBLIC_API spvc_result spvc_compiler_rename_entry_point(spvc_compiler compiler, const char *old_name, const char *new_name, SpvExecutionModel model); SPVC_PUBLIC_API const char *spvc_compiler_get_cleansed_entry_point_name(spvc_compiler compiler, const char *name, SpvExecutionModel model); SPVC_PUBLIC_API void spvc_compiler_set_execution_mode(spvc_compiler compiler, SpvExecutionMode mode); SPVC_PUBLIC_API void spvc_compiler_unset_execution_mode(spvc_compiler compiler, SpvExecutionMode mode); SPVC_PUBLIC_API void spvc_compiler_set_execution_mode_with_arguments(spvc_compiler compiler, SpvExecutionMode mode, unsigned arg0, unsigned arg1, unsigned arg2); SPVC_PUBLIC_API spvc_result spvc_compiler_get_execution_modes(spvc_compiler compiler, const SpvExecutionMode **modes, size_t *num_modes); SPVC_PUBLIC_API unsigned spvc_compiler_get_execution_mode_argument(spvc_compiler compiler, SpvExecutionMode mode); SPVC_PUBLIC_API unsigned spvc_compiler_get_execution_mode_argument_by_index(spvc_compiler compiler, SpvExecutionMode mode, unsigned index); SPVC_PUBLIC_API SpvExecutionModel spvc_compiler_get_execution_model(spvc_compiler compiler); /* * Type query interface. * Maps to C++ API, except it's read-only. */ SPVC_PUBLIC_API spvc_type spvc_compiler_get_type_handle(spvc_compiler compiler, spvc_type_id id); /* Pulls out SPIRType::self. This effectively gives the type ID without array or pointer qualifiers. * This is necessary when reflecting decoration/name information on members of a struct, * which are placed in the base type, not the qualified type. * This is similar to spvc_reflected_resource::base_type_id. */ SPVC_PUBLIC_API spvc_type_id spvc_type_get_base_type_id(spvc_type type); SPVC_PUBLIC_API spvc_basetype spvc_type_get_basetype(spvc_type type); SPVC_PUBLIC_API unsigned spvc_type_get_bit_width(spvc_type type); SPVC_PUBLIC_API unsigned spvc_type_get_vector_size(spvc_type type); SPVC_PUBLIC_API unsigned spvc_type_get_columns(spvc_type type); SPVC_PUBLIC_API unsigned spvc_type_get_num_array_dimensions(spvc_type type); SPVC_PUBLIC_API spvc_bool spvc_type_array_dimension_is_literal(spvc_type type, unsigned dimension); SPVC_PUBLIC_API SpvId spvc_type_get_array_dimension(spvc_type type, unsigned dimension); SPVC_PUBLIC_API unsigned spvc_type_get_num_member_types(spvc_type type); SPVC_PUBLIC_API spvc_type_id spvc_type_get_member_type(spvc_type type, unsigned index); SPVC_PUBLIC_API SpvStorageClass spvc_type_get_storage_class(spvc_type type); /* Image type query. */ SPVC_PUBLIC_API spvc_type_id spvc_type_get_image_sampled_type(spvc_type type); SPVC_PUBLIC_API SpvDim spvc_type_get_image_dimension(spvc_type type); SPVC_PUBLIC_API spvc_bool spvc_type_get_image_is_depth(spvc_type type); SPVC_PUBLIC_API spvc_bool spvc_type_get_image_arrayed(spvc_type type); SPVC_PUBLIC_API spvc_bool spvc_type_get_image_multisampled(spvc_type type); SPVC_PUBLIC_API spvc_bool spvc_type_get_image_is_storage(spvc_type type); SPVC_PUBLIC_API SpvImageFormat spvc_type_get_image_storage_format(spvc_type type); SPVC_PUBLIC_API SpvAccessQualifier spvc_type_get_image_access_qualifier(spvc_type type); /* * Buffer layout query. * Maps to C++ API. */ SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_struct_size(spvc_compiler compiler, spvc_type struct_type, size_t *size); SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_struct_size_runtime_array(spvc_compiler compiler, spvc_type struct_type, size_t array_size, size_t *size); SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_struct_member_size(spvc_compiler compiler, spvc_type type, unsigned index, size_t *size); SPVC_PUBLIC_API spvc_result spvc_compiler_type_struct_member_offset(spvc_compiler compiler, spvc_type type, unsigned index, unsigned *offset); SPVC_PUBLIC_API spvc_result spvc_compiler_type_struct_member_array_stride(spvc_compiler compiler, spvc_type type, unsigned index, unsigned *stride); SPVC_PUBLIC_API spvc_result spvc_compiler_type_struct_member_matrix_stride(spvc_compiler compiler, spvc_type type, unsigned index, unsigned *stride); /* * Workaround helper functions. * Maps to C++ API. */ SPVC_PUBLIC_API spvc_result spvc_compiler_build_dummy_sampler_for_combined_images(spvc_compiler compiler, spvc_variable_id *id); SPVC_PUBLIC_API spvc_result spvc_compiler_build_combined_image_samplers(spvc_compiler compiler); SPVC_PUBLIC_API spvc_result spvc_compiler_get_combined_image_samplers(spvc_compiler compiler, const spvc_combined_image_sampler **samplers, size_t *num_samplers); /* * Constants * Maps to C++ API. */ SPVC_PUBLIC_API spvc_result spvc_compiler_get_specialization_constants(spvc_compiler compiler, const spvc_specialization_constant **constants, size_t *num_constants); SPVC_PUBLIC_API spvc_constant spvc_compiler_get_constant_handle(spvc_compiler compiler, spvc_constant_id id); SPVC_PUBLIC_API spvc_constant_id spvc_compiler_get_work_group_size_specialization_constants(spvc_compiler compiler, spvc_specialization_constant *x, spvc_specialization_constant *y, spvc_specialization_constant *z); /* * Buffer ranges * Maps to C++ API. */ SPVC_PUBLIC_API spvc_result spvc_compiler_get_active_buffer_ranges(spvc_compiler compiler, spvc_variable_id id, const spvc_buffer_range **ranges, size_t *num_ranges); /* * No stdint.h until C99, sigh :( * For smaller types, the result is sign or zero-extended as appropriate. * Maps to C++ API. * TODO: The SPIRConstant query interface and modification interface is not quite complete. */ SPVC_PUBLIC_API float spvc_constant_get_scalar_fp16(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API float spvc_constant_get_scalar_fp32(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API double spvc_constant_get_scalar_fp64(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API unsigned spvc_constant_get_scalar_u32(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API int spvc_constant_get_scalar_i32(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API unsigned spvc_constant_get_scalar_u16(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API int spvc_constant_get_scalar_i16(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API unsigned spvc_constant_get_scalar_u8(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API int spvc_constant_get_scalar_i8(spvc_constant constant, unsigned column, unsigned row); SPVC_PUBLIC_API void spvc_constant_get_subconstants(spvc_constant constant, const spvc_constant_id **constituents, size_t *count); SPVC_PUBLIC_API spvc_type_id spvc_constant_get_type(spvc_constant constant); /* * Misc reflection * Maps to C++ API. */ SPVC_PUBLIC_API spvc_bool spvc_compiler_get_binary_offset_for_decoration(spvc_compiler compiler, spvc_variable_id id, SpvDecoration decoration, unsigned *word_offset); SPVC_PUBLIC_API spvc_bool spvc_compiler_buffer_is_hlsl_counter_buffer(spvc_compiler compiler, spvc_variable_id id); SPVC_PUBLIC_API spvc_bool spvc_compiler_buffer_get_hlsl_counter_buffer(spvc_compiler compiler, spvc_variable_id id, spvc_variable_id *counter_id); SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_capabilities(spvc_compiler compiler, const SpvCapability **capabilities, size_t *num_capabilities); SPVC_PUBLIC_API spvc_result spvc_compiler_get_declared_extensions(spvc_compiler compiler, const char ***extensions, size_t *num_extensions); SPVC_PUBLIC_API const char *spvc_compiler_get_remapped_declared_block_name(spvc_compiler compiler, spvc_variable_id id); SPVC_PUBLIC_API spvc_result spvc_compiler_get_buffer_block_decorations(spvc_compiler compiler, spvc_variable_id id, const SpvDecoration **decorations, size_t *num_decorations); #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
## API documentation See our [API documentation](https://moov-io.github.io/ach/api/) for Moov ACH endpoints. ## Setup our ACH file Creating an Automated Clearing House (ACH) file can be done several ways: - [using Go and our generated client](#go-client) - [uploading a JSON representation](#upload-a-json-representation) - [uploading a raw ACH file](#upload-a-json-representation) ### Go Client We have an example of [using our Go client and uploading the JSON representation](https://github.com/moov-io/ach/blob/master/examples/http/main.go). The basic idea follows this structure: 1. Create a [BatchHeader](https://godoc.org/github.com/moov-io/ach#BatchHeader) record with `ach.NewBatchHeader()`. 1. Create an [EntryDetail](https://godoc.org/github.com/moov-io/ach#EntryDetail) record with `ach.NewEntryDetail()`. 1. Create a [Batch](https://godoc.org/github.com/moov-io/ach#Batch) from our `BatchHeader` and `EntryDetail`. 1. Using a constructor like `batch := ach.NewBatchPPD(batchHeader)` and adding the batch with `batch.AddEntry(entry)`. 1. Call and verify `batch.Create()` returns no error. 1. Create our ACH File record `file := ach.NewFile()` and [FileHeader](https://godoc.org/github.com/moov-io/ach#FileHeader) with `ach.NewFileHeader()` 1. Add the `FileHeader` (via `file.SetHeader(fileHeader)`) and `Batch` records to the file (via `file.AddBatch(batch)`). 1. Call and verify `file.Create()` returns no error. 1. Encode the `File` to JSON (via `json.NewEncoder(&buf).Encode(&file)`) for a `net/http` request. ### Upload a JSON representation In Ruby we have an example of [creating an ACH file from JSON](https://github.com/moov-io/ruby-ach-demo/blob/master/main.rb). The JSON structure corresponds to our [api endpoint for creating files](https://api.moov.io/#operation/createFile) that the ACH HTTP server expects. We have [example ACH files](https://github.com/moov-io/ach/blob/master/test/testdata/ppd-valid.json) in JSON. Note: The header `Content-Type: application/json` must be set. ### Upload a raw ACH file Our ACH HTTP server also handles [uploading raw ACH files](https://api.moov.io/#operation/createFile) which is the NACHA text format. We have example files in their NACHA format and example code for creating the files and reading the files | SEC Code | Description | Example ACH File | Read | Create | :---: | :---: | :---: | :--- | :--- | | ACK | Acknowledgment Entry for CCD | [Credit](https://github.com/moov-io/ach/blob/master/test/ach-ack-read/ack-read.ach) | [ACK Read](https://github.com/moov-io/ach/blob/master/examples/ach-ack-read/main.go) | [ACK Create](https://github.com/moov-io/ach/blob/master/examples/ach-ack-write/main.go) | | ADV | Automated Accounting Advice | [Prenote Debit](https://github.com/moov-io/ach/blob/master/test/ach-adv-read/adv-read.ach) | [ADV Read](https://github.com/moov-io/ach/blob/master/examples/ach-adv-read/main.go) | [ADV Create](https://github.com/moov-io/ach/blob/master/examples/ach-adv-write/main.go) | | ARC | Accounts Receivable Entry | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-arc-read/arc-debit.ach) | [ARC Read](https://github.com/moov-io/ach/blob/master/examples/ach-arc-read/main.go) | [ARC Create](https://github.com/moov-io/ach/blob/master/examples/ach-arc-write/main.go) | | ATX | Acknowledgment Entry for CTX | [Credit](https://github.com/moov-io/ach/blob/master/test/ach-atx-read/atx-read.ach) | [ATX Read](https://github.com/moov-io/ach/blob/master/examples/ach-atx-read/main.go) | [ATX Create](https://github.com/moov-io/ach/blob/master/examples/ach-atx-write/main.go) | | BOC | Back Office Conversion | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-boc-read/boc-debit.ach) | [BOC Read](https://github.com/moov-io/ach/blob/master/examples/ach-boc-read/main.go) | [BOC Create](https://github.com/moov-io/ach/blob/master/examples/ach-boc-write/main.go) | | CCD | Corporate credit or debit | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-ccd-read/ccd-debit.ach) | [CCD Read](https://github.com/moov-io/ach/blob/master/examples/ach-ccd-read/main.go) | [CCD Create](https://github.com/moov-io/ach/blob/master/examples/ach-ccd-write/main.go) | | CIE | Customer-Initiated Entry | [Credit](https://github.com/moov-io/ach/blob/master/test/ach-cie-read/cie-credit.ach) | [CIE Read](https://github.com/moov-io/ach/blob/master/examples/ach-cie-read/main.go) | [CIE Create](https://github.com/moov-io/ach/blob/master/examples/ach-cie-write/main.go) | | COR | Automated Notification of Change(NOC) | [NOC](https://github.com/moov-io/ach/blob/master/test/ach-cor-read/cor-read.ach) | [COR Read](https://github.com/moov-io/ach/blob/master/examples/ach-cor-read/main.go) | [COR Create](https://github.com/moov-io/ach/blob/master/examples/ach-cor-write/main.go) | | CTX | Corporate Trade Exchange | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-ctx-read/ctx-debit.ach) | [CTX Read](https://github.com/moov-io/ach/blob/master/examples/ach-ctx-read/main.go) | [CTX Create](https://github.com/moov-io/ach/blob/master/examples/ach-ctx-write/main.go) | | DNE | Death Notification Entry | [DNE](https://github.com/moov-io/ach/blob/master/test/ach-dne-read/dne-read.ach) | [DNE Read](https://github.com/moov-io/ach/blob/master/examples/ach-dne-read/main.go) | [DNE Create](https://github.com/moov-io/ach/blob/master/examples/ach-dne-write/main.go) | | ENR | Automatic Enrollment Entry | [ENR](https://github.com/moov-io/ach/blob/master/test/ach-enr-read/enr-read.ach) | [ENR Read](https://github.com/moov-io/ach/blob/master/examples/ach-enr-read/main.go) | [ENR Create](https://github.com/moov-io/ach/blob/master/examples/ach-enr-write/main.go) | | IAT | International ACH Transactions | [Credit](https://github.com/moov-io/ach/blob/master/test/ach-iat-read/iat-credit.ach) | [IAT Read](https://github.com/moov-io/ach/blob/master/examples/ach-iat-read/main.go) | [IAT Create](https://github.com/moov-io/ach/blob/master/examples/ach-iat-write/main.go) | | MTE | Machine Transfer Entry | [Credit](https://github.com/moov-io/ach/blob/master/test/ach-mte-read/mte-read.ach) | [MTE Read](https://github.com/moov-io/ach/blob/master/examples/ach-mte-read/main.go) | [MTE Create](https://github.com/moov-io/ach/blob/master/examples/ach-mte-write/main.go) | | POP | Point of Purchase | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-pop-read/pop-debit.ach) | [POP Read](https://github.com/moov-io/ach/blob/master/examples/ach-pop-read/main.go) | [POP Create](https://github.com/moov-io/ach/blob/master/examples/ach-pop-write/main.go) | | POS | Point of Sale | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-pos-read/pos-debit.ach) | [POS Read](https://github.com/moov-io/ach/blob/master/examples/ach-pos-read/main.go) | [POS Create](https://github.com/moov-io/ach/blob/master/examples/ach-pos-write/main.go) | | PPD | Prearranged payment and deposits | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-ppd-read/ppd-debit.ach) and [Credit](https://github.com/moov-io/ach/blob/master/test/ach-ppd-read/ppd-credit.ach) | [PPD Read](https://github.com/moov-io/ach/blob/master/examples/ach-ppd-read/main.go) | [PPD Create](https://github.com/moov-io/ach/blob/master/examples/ach-ppd-write/main.go) | | RCK | Represented Check Entries | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-rck-read/rck-debit.ach) | [RCK Read](https://github.com/moov-io/ach/blob/master/examples/ach-rck-read/main.go) | [RCK Create](https://github.com/moov-io/ach/blob/master/examples/ach-rck-write/main.go) | | SHR | Shared Network Entry | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-shr-read/shr-debit.ach) | [SHR Read](https://github.com/moov-io/ach/blob/master/examples/ach-shr-read/main.go) | [SHR Create](https://github.com/moov-io/ach/blob/master/examples/ach-shr-write/main.go) | | TEL | Telephone-Initiated Entry | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-tel-read/tel-debit.ach) | [TEL Read](https://github.com/moov-io/ach/blob/master/examples/ach-tel-read/main.go) | [TEL Create](https://github.com/moov-io/ach/blob/master/examples/ach-tel-write/main.go) | | TRC | Truncated Check Entry | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-trc-read/trc-debit.ach) | [TRC Read](https://github.com/moov-io/ach/blob/master/examples/ach-trc-read/main.go) | [TRC Create](https://github.com/moov-io/ach/blob/master/examples/ach-trc-write/main.go) | | TRX | Check Truncation Entries Exchange | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-trx-read/trx-debit.ach) | [TRX Read](https://github.com/moov-io/ach/blob/master/examples/ach-trx-read/main.go) | [TRX Create](https://github.com/moov-io/ach/blob/master/examples/ach-trx-write/main.go) | | WEB | Internet-initiated Entries | [Credit](https://github.com/moov-io/ach/blob/master/test/ach-web-read/web-credit.ach) | [WEB Read](https://github.com/moov-io/ach/blob/master/examples/ach-web-read/main.go) | [WEB Create](https://github.com/moov-io/ach/blob/master/examples/ach-web-write/main.go) | | XCK | Destroyed Check Entry | [Debit](https://github.com/moov-io/ach/blob/master/test/ach-xck-read/xck-debit.ach) | [XCK Read](https://github.com/moov-io/ach/blob/master/examples/ach-xck-read/main.go) | [XCK Create](https://github.com/moov-io/ach/blob/master/examples/ach-xck-write/main.go) | Note: The header `Content-Type: text/plain` should be set.
{ "pile_set_name": "Github" }
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // 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. // // Questions? Contact Christian R. Trott ([email protected]) // // ************************************************************************ //@HEADER */ #include <threads/TestThreads_Category.hpp> #include <TestViewSubview.hpp> namespace Test { TEST(threads, view_subview_2d_from_3d_atomic) { TestViewSubview::test_2d_subview_3d<TEST_EXECSPACE, Kokkos::MemoryTraits<Kokkos::Atomic> >(); } } // namespace Test
{ "pile_set_name": "Github" }
class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration { var count: Int { get } func object(at index: Int) -> AnyObject init(objects objects: UnsafePointer<AnyObject?>, count cnt: Int) init?(coder aDecoder: NSCoder) func copy(with zone: NSZone = nil) -> AnyObject func mutableCopy(with zone: NSZone = nil) -> AnyObject class func supportsSecureCoding() -> Bool func encode(with aCoder: NSCoder) func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int } extension NSArray : ArrayLiteralConvertible { } extension NSArray : SequenceType { } extension NSArray { convenience init(objects elements: AnyObject...) } extension NSArray { @objc(_swiftInitWithArray_NSArray:) convenience init(array anArray: NSArray) } extension NSArray : CustomReflectable { } extension NSArray { func adding(_ anObject: AnyObject) -> [AnyObject] func addingObjects(from otherArray: [AnyObject]) -> [AnyObject] func componentsJoined(by separator: String) -> String func contains(_ anObject: AnyObject) -> Bool func description(withLocale locale: AnyObject?) -> String func description(withLocale locale: AnyObject?, indent level: Int) -> String func firstObjectCommon(with otherArray: [AnyObject]) -> AnyObject? func getObjects(_ objects: AutoreleasingUnsafeMutablePointer<AnyObject?>, range range: NSRange) func index(of anObject: AnyObject) -> Int func index(of anObject: AnyObject, in range: NSRange) -> Int func indexOfObjectIdentical(to anObject: AnyObject) -> Int func indexOfObjectIdentical(to anObject: AnyObject, in range: NSRange) -> Int func isEqual(to otherArray: [AnyObject]) -> Bool @available(watchOS 2.0, *) var firstObject: AnyObject? { get } var lastObject: AnyObject? { get } func objectEnumerator() -> NSEnumerator func reverseObjectEnumerator() -> NSEnumerator @NSCopying var sortedArrayHint: NSData { get } func sortedArray(_ comparator: @convention(c) (AnyObject, AnyObject, UnsafeMutablePointer<Void>) -> Int, context context: UnsafeMutablePointer<Void>) -> [AnyObject] func sortedArray(_ comparator: @convention(c) (AnyObject, AnyObject, UnsafeMutablePointer<Void>) -> Int, context context: UnsafeMutablePointer<Void>, hint hint: NSData?) -> [AnyObject] func sortedArray(using comparator: Selector) -> [AnyObject] func subarray(with range: NSRange) -> [AnyObject] func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool func write(to url: NSURL, atomically atomically: Bool) -> Bool func objects(at indexes: NSIndexSet) -> [AnyObject] @available(watchOS 2.0, *) subscript(_ idx: Int) -> AnyObject { get } @available(watchOS 2.0, *) func enumerateObjects(_ block: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Void) @available(watchOS 2.0, *) func enumerateObjects(_ opts: NSEnumerationOptions = [], using block: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Void) @available(watchOS 2.0, *) func enumerateObjects(at s: NSIndexSet, options opts: NSEnumerationOptions = [], using block: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Void) @available(watchOS 2.0, *) func indexOfObject(passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int @available(watchOS 2.0, *) func indexOfObject(_ opts: NSEnumerationOptions = [], passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int @available(watchOS 2.0, *) func indexOfObject(at s: NSIndexSet, options opts: NSEnumerationOptions = [], passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int @available(watchOS 2.0, *) func indexesOfObjects(passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet @available(watchOS 2.0, *) func indexesOfObjects(_ opts: NSEnumerationOptions = [], passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet @available(watchOS 2.0, *) func indexesOfObjects(at s: NSIndexSet, options opts: NSEnumerationOptions = [], passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet @available(watchOS 2.0, *) func sortedArray(comparator cmptr: NSComparator) -> [AnyObject] @available(watchOS 2.0, *) func sortedArray(_ opts: NSSortOptions = [], usingComparator cmptr: NSComparator) -> [AnyObject] @available(watchOS 2.0, *) func index(of obj: AnyObject, inSortedRange r: NSRange, options opts: NSBinarySearchingOptions = [], usingComparator cmp: NSComparator) -> Int } struct NSBinarySearchingOptions : OptionSetType { init(rawValue rawValue: UInt) let rawValue: UInt static var firstEqual: NSBinarySearchingOptions { get } static var lastEqual: NSBinarySearchingOptions { get } static var insertionIndex: NSBinarySearchingOptions { get } } extension NSArray { convenience init(object anObject: AnyObject) convenience init(array array: [AnyObject]) convenience init(array array: [AnyObject], copyItems flag: Bool) convenience init?(contentsOfFile path: String) convenience init?(contentsOf url: NSURL) } extension NSArray { func getObjects(_ objects: AutoreleasingUnsafeMutablePointer<AnyObject?>) } class NSMutableArray : NSArray { func add(_ anObject: AnyObject) func insert(_ anObject: AnyObject, at index: Int) func removeLastObject() func removeObject(at index: Int) func replaceObject(at index: Int, with anObject: AnyObject) init(capacity numItems: Int) } extension NSMutableArray { func addObjects(from otherArray: [AnyObject]) func exchangeObject(at idx1: Int, withObjectAt idx2: Int) func removeAllObjects() func remove(_ anObject: AnyObject, in range: NSRange) func remove(_ anObject: AnyObject) func removeObjectIdentical(to anObject: AnyObject, in range: NSRange) func removeObjectIdentical(to anObject: AnyObject) @available(watchOS, introduced=2.0, deprecated=2.0) func removeObjects(fromIndices indices: UnsafeMutablePointer<Int>, numIndices cnt: Int) func removeObjects(in otherArray: [AnyObject]) func removeObjects(in range: NSRange) func replaceObjects(in range: NSRange, withObjectsFrom otherArray: [AnyObject], range otherRange: NSRange) func replaceObjects(in range: NSRange, withObjectsFrom otherArray: [AnyObject]) func setArray(_ otherArray: [AnyObject]) func sort(_ compare: @convention(c) (AnyObject, AnyObject, UnsafeMutablePointer<Void>) -> Int, context context: UnsafeMutablePointer<Void>) func sort(using comparator: Selector) func insert(_ objects: [AnyObject], at indexes: NSIndexSet) func removeObjects(at indexes: NSIndexSet) func replaceObjects(at indexes: NSIndexSet, with objects: [AnyObject]) @available(watchOS 2.0, *) func sort(comparator cmptr: NSComparator) @available(watchOS 2.0, *) func sort(_ opts: NSSortOptions = [], usingComparator cmptr: NSComparator) } extension NSMutableArray { }
{ "pile_set_name": "Github" }
/* * Matrix test. */ #include "io/streams/cout.hh" #include "lang/array.hh" #include "math/matrices/matrix.hh" #include "lang/exceptions/ex_index_out_of_bounds.hh" using io::streams::cout; using lang::array; using math::matrices::matrix; int main() { try { matrix<> m(3,2); m(0,0) = 0.1; m(0,1) = 0.02; m(1,0) = 1.0; m(1,1) = 2.0; m(2,0) = 10; m(2,1) = 30; matrix<> m_ramp = matrix<>::ramp(-0.5, 0.25, 0.5); array<unsigned long> dims1(1); dims1[0] = m_ramp.size(); matrix<> m_ramp1 = reshape(m_ramp,dims1); cout << m << "\n"; cout << m_ramp << "\n"; cout << m_ramp1 << "\n"; cout << "--- convolution 1D (full) ---\n"; cout << conv(m_ramp1,m_ramp1) << "\n"; cout << "--- convolution 1D (cropped) ---\n"; cout << conv_crop(m_ramp1,m_ramp1) << "\n"; cout << "--- convolution 1D (cropped strict) ---\n"; cout << conv_crop_strict(m_ramp1,m_ramp1) << "\n"; cout << "--- convolution 2D (full) ---\n"; cout << conv(m,m) << "\n"; cout << conv(m,transpose(m)) << "\n"; cout << conv(m,m_ramp) << "\n"; cout << conv(m_ramp,m) << "\n"; cout << conv(m_ramp,transpose(m_ramp)) << "\n"; cout << "--- convolution 2D (cropped) ---\n"; cout << conv_crop(m,m) << "\n"; cout << conv_crop(m,transpose(m)) << "\n"; cout << conv_crop(m,m_ramp) << "\n"; cout << conv_crop(m_ramp,m) << "\n"; cout << conv_crop(m_ramp,transpose(m_ramp)) << "\n"; cout << "--- convolution 2D (cropped strict) ---\n"; cout << conv_crop_strict(m,m) << "\n"; cout << conv_crop_strict(m,transpose(m)) << "\n"; cout << conv_crop_strict(m,m_ramp) << "\n"; cout << conv_crop_strict(m_ramp,m) << "\n"; cout << conv_crop_strict(m_ramp,transpose(m_ramp)) << "\n"; cout << "--- min, max, sum, prod ---\n"; cout << min(m,0) << "\n"; cout << min(m,1) << "\n"; cout << max(m,0) << "\n"; cout << max(m,1) << "\n"; cout << sum(m,0) << "\n"; cout << sum(m,1) << "\n"; cout << prod(m,0) << "\n"; cout << prod(m,1) << "\n"; cout << "--- cumsum, cumprod ---\n"; cout << cumsum(m,0) << "\n"; cout << cumsum(m,1) << "\n"; cout << cumprod(m,0) << "\n"; cout << cumprod(m,1) << "\n"; cout << "--- mean, var ---\n"; cout << mean(m) << "\n"; cout << var(m) << "\n"; cout << mean(m,0) << "\n"; cout << mean(m,1) << "\n"; cout << var(m,0) << "\n"; cout << var(m,1) << "\n"; cout << "--- gradient ---\n"; cout << gradient(m,0) << "\n"; cout << gradient(m,1) << "\n"; cout << "--- reverse ---\n"; cout << m.reverse(0) << "\n"; cout << m.reverse(1) << "\n"; cout << "--- vertcat, horzcat, concat ---\n"; cout << vertcat(m,m) << "\n"; cout << horzcat(m,m) << "\n"; cout << concat(m,m,4) << "\n"; cout << "--- resize, transpose ---\n"; cout << resize(m,2,2) << "\n"; cout << resize(m,4,4) << "\n"; cout << transpose(resize(m,4,4)) << "\n"; array<unsigned long> order(3); order[0] = 2; order[1] = 1; order[2] = 0; cout << permute_dimensions(resize(m,4,4),order) << "\n"; order[1] = 3; order.resize(2); cout << "--- repmat ---\n"; cout << repmat(m,order) << "\n"; cout << "--- sort ---\n"; cout << m << "\n"; cout << m.sort_idx(0) << "\n"; cout << m << "\n"; cout << m.sort_idx(1) << "\n"; cout << m << "\n"; } catch (lang::exceptions::ex_index_out_of_bounds& e) { cout << e << "\n"; cout << e.index() << "\n"; } return 0; }
{ "pile_set_name": "Github" }
(* * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <[email protected]> *) open Owl_types (* Functor of making a Lazy engine, just an alias of CPU engine. *) module Make (A : Ndarray_Mutable) = struct include Owl_computation_cpu_engine.Make (A) end (* Make functor ends *)
{ "pile_set_name": "Github" }
import React from "react"; import { mount, shallow } from "enzyme"; import $ from "jquery"; import { Component, ComponentList } from "../js/src/components/component-list"; import { Metrics } from "../js/src/components/metrics"; describe('ComponentList', () => { it('fetches the components url', () => { var ajax = $.ajax; $.ajax = jest.fn(); const componentList = mount( <ComponentList url={"components.json"}/> ); expect($.ajax.mock.calls.length).toBe(1); expect($.ajax.mock.calls[0][0].url).toBe("components.json"); $.ajax = ajax; }); it('has component-list as classname', () => { const componentList = shallow(<ComponentList />); expect(componentList.find(".component-list").length).toBe(1); }); it('renders a component for each one that was fetched', () => { $.getJSON= jest.fn(); var ajax = $.ajax; $.ajax = jest.fn((obj) => { obj.success({components: ["registry", "big-sibling"]}); }); const componentList = mount(<ComponentList />); var components = componentList.find(Component); expect(components.length).toBe(2); expect(components.first().props().name).toBe("registry"); expect(components.last().props().name).toBe("big-sibling"); $.ajax = ajax; }); }); describe('Component', () => { it('renders Metrics for the component', () => { var ajax = $.ajax; $.ajax = jest.fn(); const component = mount( <Component name={"big-sibling"}/> ); var metrics = component.find(Metrics); expect(metrics.length).toBe(1); expect(metrics.props().targetName).toBe("big-sibling"); expect(metrics.props().targetType).toBe("component"); $.ajax = ajax; }); it('has component as classname', () => { const component = shallow(<Component />); expect(component.find(".component").length).toBe(1); }); });
{ "pile_set_name": "Github" }
// RUN: %compile-run-and-check #include <omp.h> #include <stdio.h> int main() { int res = 0; #pragma omp parallel num_threads(2) reduction(+:res) { int tid = omp_get_thread_num(); #pragma omp target teams distribute reduction(+:res) for (int i = tid; i < 2; i++) ++res; } // The first thread makes 2 iterations, the second - 1. Expected result of the // reduction res is 3. // CHECK: res = 3. printf("res = %d.\n", res); return 0; }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && ( typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string' )); } module.exports = isNode;
{ "pile_set_name": "Github" }
<?php /** * @package Gantry5 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2017 RocketTheme, LLC * @license Dual License: MIT or GNU/GPLv2 and later * * http://opensource.org/licenses/MIT * http://www.gnu.org/licenses/gpl-2.0.html * * Gantry Framework code that extends GPL code is considered GNU/GPLv2 and later */ namespace Gantry\Component\Layout\Version; /** * Read layout from simplified yaml file. */ class Format1 { protected $scopes = [0 => 'grid', 1 => 'block']; protected $data; protected $keys = []; public function __construct(array $data) { $this->data = $data; } public function load() { $data = &$this->data; // Check if we have preset. $preset = []; if (isset($data['preset']) && is_array($data['preset']) && isset($data['layout']) && is_array($data['layout'])) { $preset = $data['preset']; $data = $data['layout']; } // We have user entered file; let's build the layout. // Two last items are always offcanvas and atoms. $offcanvas = isset($data['offcanvas']) ? $data['offcanvas'] : []; $atoms = isset($data['atoms']) ? $data['atoms'] : []; unset($data['offcanvas'], $data['atoms']); $data['offcanvas'] = $offcanvas; if ($atoms) { $data['atoms'] = $atoms; } $result = []; foreach ($data as $field => $params) { $child = $this->parse($field, (array) $params, 0); unset($child->size); $result[] = $child; } return ['preset' => $preset] + $result; } public function store(array $preset, array $structure) { return ['preset' => $preset, 'children' => $structure]; } protected function normalize(&$item, $container = false) { if ($item->type === 'pagecontent') { // Update pagecontent to match the new standards. $item->type = 'system'; if (!$item->subtype || $item->subtype == 'pagecontent') { $item->subtype = 'content'; $item->title = 'Page Content'; } else { $item->subtype ='messages'; $item->title = 'System Messages'; } } if ($item->type === 'section') { // Update section to match the new standards. $section = strtolower($item->title); $item->id = $section; $item->subtype = (in_array($section, ['aside', 'nav', 'article', 'header', 'footer', 'main']) ? $section : 'section'); } elseif ($item->type === 'offcanvas') { $item->id = $item->subtype = $item->type; unset ($item->attributes->name, $item->attributes->boxed); return; } else { // Update all ids to match the new standards. $item->id = $this->id($item->type, $item->subtype); } if (!empty($item->attributes->extra)) { foreach ($item->attributes->extra as $i => $extra) { $v = reset($extra); $k = key($extra); if ($k === 'id') { $item->id = preg_replace('/^g-/', '', $v); $item->attributes->id = $v; unset ($item->attributes->extra[$i]); } } if (empty($item->attributes->extra)) { unset ($item->attributes->extra); } } $item->subtype = $item->subtype ?: $item->type; $item->layout = in_array($item->type, ['container', 'section', 'grid', 'block', 'offcanvas']); if (isset($item->attributes->boxed)) { // Boxed already set, just change boxed=0 to boxed='' to use default settings. $item->attributes->boxed = $item->attributes->boxed ?: ''; return; } if (!$container) { return; } // Update boxed model to match the new standards. if (isset($item->children) && count($item->children) === 1) { $child = reset($item->children); if ($item->type === 'container') { // Remove parent container only if the only child is a section. if ($child->type === 'section') { $child->attributes->boxed = 1; $item = $child; } $item->attributes->boxed = ''; } elseif ($child->type === 'container') { // Remove child container. $item->attributes->boxed = ''; $item->children = $child->children; } } } /** * @param int|string $field * @param array $content * @param int $scope * @param bool|null $container * @return array */ protected function parse($field, array $content, $scope, $container = true) { if (is_numeric($field)) { // Row or block $type = $this->scopes[$scope]; $result = (object) ['id' => null, 'type' => $type, 'subtype' => $type, 'layout' => true, 'attributes' => (object) []]; $scope = ($scope + 1) % 2; } elseif (substr($field, 0, 9) == 'container') { // Container $type = 'container'; $result = (object) ['id' => null, 'type' => $type, 'subtype' => $type, 'layout' => true, 'attributes' => (object) []]; $id = substr($field, 10) ?: null; if ($id !== null) { $result->attributes->id = $id; } } else { // Section $list = explode(' ', $field, 2); $field = array_shift($list); $size = ((float) array_shift($list)) ?: null; $type = in_array($field, ['atoms', 'offcanvas']) ? $field : 'section'; $subtype = in_array($field, ['aside', 'nav', 'article', 'header', 'footer', 'main']) ? $field : 'section'; $result = (object) [ 'id' => null, 'type' => $type, 'subtype' => $subtype, 'layout' => true, 'title' => ucfirst($field), 'attributes' => (object) ['id' => 'g-' . $field] ]; if ($size) { $result->size = $size; } } if (!empty($content)) { $result->children = []; foreach ($content as $child => $params) { if (is_array($params)) { $child = $this->parse($child, $params, $scope, false); } else { $child = $this->resolve($params, $scope); } if (!empty($child->size)) { $result->attributes->size = $child->size; } unset($child->size); $result->children[] = $child; } } $this->normalize($result, $container); return $result; } /** * @param string $field * @param int $scope * @return array */ protected function resolve($field, $scope) { $list = explode(' ', $field, 2); $list2 = explode('-', array_shift($list), 2); $size = ((float) array_shift($list)) ?: null; $type = array_shift($list2); $subtype = array_shift($list2) ?: false; $title = ucfirst($subtype ?: $type); $attributes = new \stdClass; $attributes->enabled = 1; if ($subtype && $type === 'position') { $attributes->key = $subtype; $subtype = false; } $result = (object) ['id' => $this->id($type, $subtype), 'title' => $title, 'type' => $type, 'subtype' => $subtype, 'attributes' => $attributes]; $this->normalize($result); if ($scope > 1) { if ($size) { $result->attributes->size = $size; } return $result; } if ($scope <= 1) { $result = (object) ['id' => $this->id('block'), 'type' => 'block', 'subtype' => 'block', 'layout' => true, 'children' => [$result], 'attributes' => new \stdClass]; if ($size) { $result->attributes->size = $size; } } if ($scope == 0) { $result = (object) ['id' => $this->id('grid'), 'type' => 'grid', 'subtype' => 'grid', 'layout' => true, 'children' => [$result], 'attributes' => new \stdClass]; } return $result; } protected function id($type, $subtype = null) { if ($type === 'atoms') { return $type; } $result = []; if ($type !== 'particle' && $type !== 'atom') { $result[] = $type; } if ($subtype && $subtype !== $type) { $result[] = $subtype; } $key = implode('-', $result); while ($id = rand(1000, 9999)) { if (!isset($this->keys[$key][$id])) { break; } } $this->keys[$key][$id] = true; return $key . '-'. $id; } }
{ "pile_set_name": "Github" }
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The EAGLView class is a UIView subclass that renders OpenGL scene. */ #import "EAGLView.h" #import "ES2Renderer.h" @interface EAGLView () { ES2Renderer* _renderer; EAGLContext* _context; NSInteger _animationFrameInterval; CADisplayLink* _displayLink; } @end @implementation EAGLView // Must return the CAEAGLLayer class so that CA allocates an EAGLLayer backing for this view + (Class) layerClass { return [CAEAGLLayer class]; } // The GL view is stored in the storyboard file. When it's unarchived it's sent -initWithCoder: - (instancetype) initWithCoder:(NSCoder*)coder { if ((self = [super initWithCoder:coder])) { // Get the layer CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; eaglLayer.opaque = TRUE; eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil]; _context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; if (!_context || ![EAGLContext setCurrentContext:_context]) { return nil; } _renderer = [[ES2Renderer alloc] initWithContext:_context AndDrawable:(id<EAGLDrawable>)self.layer]; if (!_renderer) { return nil; } _animating = FALSE; _animationFrameInterval = 1; _displayLink = nil; } return self; } - (void) drawView:(id)sender { [EAGLContext setCurrentContext:_context]; [_renderer render]; } - (void) layoutSubviews { [_renderer resizeFromLayer:(CAEAGLLayer*)self.layer]; [self drawView:nil]; } - (NSInteger) animationFrameInterval { return _animationFrameInterval; } - (void) setAnimationFrameInterval:(NSInteger)frameInterval { // Frame interval defines how many display frames must pass between each time the // display link fires. The display link will only fire 30 times a second when the // frame internal is two on a display that refreshes 60 times a second. The default // frame interval setting of one will fire 60 times a second when the display refreshes // at 60 times a second. A frame interval setting of less than one results in undefined // behavior. if (frameInterval >= 1) { _animationFrameInterval = frameInterval; if (_animating) { [self stopAnimation]; [self startAnimation]; } } } - (void) startAnimation { if (!_animating) { // Create the display link and set the callback to our drawView method _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView:)]; // Set it to our _animationFrameInterval [_displayLink setFrameInterval:_animationFrameInterval]; // Have the display link run on the default runn loop (and the main thread) [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; _animating = TRUE; } } - (void)stopAnimation { if (_animating) { [_displayLink invalidate]; _displayLink = nil; _animating = FALSE; } } - (void) dealloc { // tear down context if ([EAGLContext currentContext] == _context) [EAGLContext setCurrentContext:nil]; } @end
{ "pile_set_name": "Github" }
% Penalised least squares objective function and derivatives % phi(u) = 1/lambda * ||X*u-y||_2^2 + 2*sum( pen(s) ), s=B*u-t % % [f,df,d2f] = phi(u,X,y,B,t,lam,pen,varargin) where penaliser is evaluated % by feval(pen,s,varargin{:}) % % The return arguments have the following meaning: % f = phi(u), [1,1] scalar % df = d phi(u) / du, and [n,1] gradient vector (same size as u) % d2f = d^2 phi(u) / du^2. [n,n] Hessian matrix % % See also PLSALGORITHMS.M. % % (c) by Hannes Nickisch, Philips Research, 2013 August 30 function [f,df,d2f] = phi(u,X,y,B,t,lam,pen,varargin) s = B*u-t; r = X*u-y; if nargout==1 p = feval(pen,s,varargin{:}); elseif nargout==2 [p,dp] = feval(pen,s,varargin{:}); else [p,dp,d2p] = feval(pen,s,varargin{:}); end f = norm(r,2)^2/lam + 2*sum(p); if nargout>1 df = 2*([X']*r/lam + [B']*dp); if nargout>2 % evaluation of the Hessian is dangerous for large n if numel(dp)==numel(d2p) d2f = 2*(X'*X/lam + B'*diag(d2p)*B); % d2p is a vector else d2f = 2*(X'*X/lam + B'*d2p*B); % d2p is a scalar or a full matrix end end end
{ "pile_set_name": "Github" }
(function (g) { function t(a, b, d) { return "rgba(" + [Math.round(a[0] + (b[0] - a[0]) * d), Math.round(a[1] + (b[1] - a[1]) * d), Math.round(a[2] + (b[2] - a[2]) * d), a[3] + (b[3] - a[3]) * d].join(",") + ")" } var u = function () { }, o = g.getOptions(), i = g.each, p = g.extend, z = g.format, A = g.pick, q = g.wrap, l = g.Chart, n = g.seriesTypes, v = n.pie, m = n.column, w = HighchartsAdapter.fireEvent, x = HighchartsAdapter.inArray, r = []; p(o.lang, {drillUpText: "◁ Back to {series.name}"}); o.drilldown = { activeAxisLabelStyle: { cursor: "pointer", color: "#0d233a", fontWeight: "bold", textDecoration: "underline" }, activeDataLabelStyle: {cursor: "pointer", color: "#0d233a", fontWeight: "bold", textDecoration: "underline"}, animation: {duration: 500}, drillUpButton: {position: {align: "right", x: -10, y: 10}} }; g.SVGRenderer.prototype.Element.prototype.fadeIn = function (a) { this.attr({opacity: 0.1, visibility: "inherit"}).animate({opacity: A(this.newOpacity, 1)}, a || {duration: 250}) }; l.prototype.addSeriesAsDrilldown = function (a, b) { this.addSingleSeriesAsDrilldown(a, b); this.applyDrilldown() }; l.prototype.addSingleSeriesAsDrilldown = function (a, b) { var d = a.series, c = d.xAxis, f = d.yAxis, h; h = a.color || d.color; var e, y = [], g = [], k; k = d.levelNumber || 0; b = p({color: h}, b); e = x(a, d.points); i(d.chart.series, function (a) { if (a.xAxis === c)y.push(a), g.push(a.userOptions), a.levelNumber = a.levelNumber || k }); h = { levelNumber: k, seriesOptions: d.userOptions, levelSeriesOptions: g, levelSeries: y, shapeArgs: a.shapeArgs, bBox: a.graphic.getBBox(), color: h, lowerSeriesOptions: b, pointOptions: d.options.data[e], pointIndex: e, oldExtremes: { xMin: c && c.userMin, xMax: c && c.userMax, yMin: f && f.userMin, yMax: f && f.userMax } }; if (!this.drilldownLevels)this.drilldownLevels = []; this.drilldownLevels.push(h); h = h.lowerSeries = this.addSeries(b, !1); h.levelNumber = k + 1; if (c)c.oldPos = c.pos, c.userMin = c.userMax = null, f.userMin = f.userMax = null; if (d.type === h.type)h.animate = h.animateDrilldown || u, h.options.animation = !0 }; l.prototype.applyDrilldown = function () { var a = this.drilldownLevels, b; if (a && a.length > 0)b = a[a.length - 1].levelNumber, i(this.drilldownLevels, function (a) { a.levelNumber === b && i(a.levelSeries, function (a) { a.levelNumber === b && a.remove(!1) }) }); this.redraw(); this.showDrillUpButton() }; l.prototype.getDrilldownBackText = function () { var a = this.drilldownLevels; if (a && a.length > 0)return a = a[a.length - 1], a.series = a.seriesOptions, z(this.options.lang.drillUpText, a) }; l.prototype.showDrillUpButton = function () { var a = this, b = this.getDrilldownBackText(), d = a.options.drilldown.drillUpButton, c, f; this.drillUpButton ? this.drillUpButton.attr({text: b}).align() : (f = (c = d.theme) && c.states, this.drillUpButton = this.renderer.button(b, null, null, function () { a.drillUp() }, c, f && f.hover, f && f.select).attr({ align: d.position.align, zIndex: 9 }).add().align(d.position, !1, d.relativeTo || "plotBox")) }; l.prototype.drillUp = function () { for (var a = this, b = a.drilldownLevels, d = b[b.length - 1].levelNumber, c = b.length, f = a.series, h = f.length, e, g, j, k, l = function (b) { var c; i(f, function (a) { a.userOptions === b && (c = a) }); c = c || a.addSeries(b, !1); if (c.type === g.type && c.animateDrillupTo)c.animate = c.animateDrillupTo; b === e.seriesOptions && (j = c) }; c--;)if (e = b[c], e.levelNumber === d) { b.pop(); g = e.lowerSeries; if (!g.chart)for (; h--;)if (f[h].options.id === e.lowerSeriesOptions.id) { g = f[h]; break } g.xData = []; i(e.levelSeriesOptions, l); w(a, "drillup", {seriesOptions: e.seriesOptions}); if (j.type === g.type)j.drilldownLevel = e, j.options.animation = a.options.drilldown.animation, g.animateDrillupFrom && g.animateDrillupFrom(e); j.levelNumber = d; g.remove(!1); if (j.xAxis)k = e.oldExtremes, j.xAxis.setExtremes(k.xMin, k.xMax, !1), j.yAxis.setExtremes(k.yMin, k.yMax, !1) } this.redraw(); this.drilldownLevels.length === 0 ? this.drillUpButton = this.drillUpButton.destroy() : this.drillUpButton.attr({text: this.getDrilldownBackText()}).align(); r.length = [] }; m.prototype.supportsDrilldown = !0; m.prototype.animateDrillupTo = function (a) { if (!a) { var b = this, d = b.drilldownLevel; i(this.points, function (a) { a.graphic.hide(); a.dataLabel && a.dataLabel.hide(); a.connector && a.connector.hide() }); setTimeout(function () { i(b.points, function (a, b) { var h = b === (d && d.pointIndex) ? "show" : "fadeIn", e = h === "show" ? !0 : void 0; a.graphic[h](e); if (a.dataLabel)a.dataLabel[h](e); if (a.connector)a.connector[h](e) }) }, Math.max(this.chart.options.drilldown.animation.duration - 50, 0)); this.animate = u } }; m.prototype.animateDrilldown = function (a) { var b = this, d = this.chart.drilldownLevels, c = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1].shapeArgs, f = this.chart.options.drilldown.animation; if (!a)i(d, function (a) { if (b.userOptions === a.lowerSeriesOptions)c = a.shapeArgs }), c.x += this.xAxis.oldPos - this.xAxis.pos, i(this.points, function (a) { a.graphic && a.graphic.attr(c).animate(a.shapeArgs, f); a.dataLabel && a.dataLabel.fadeIn(f) }), this.animate = null }; m.prototype.animateDrillupFrom = function (a) { var b = this.chart.options.drilldown.animation, d = this.group, c = this; i(c.trackerGroups, function (a) { if (c[a])c[a].on("mouseover") }); delete this.group; i(this.points, function (c) { var h = c.graphic, e = g.Color(c.color).rgba, i = g.Color(a.color).rgba, j = function () { h.destroy(); d && (d = d.destroy()) }; h && (delete c.graphic, b ? h.animate(a.shapeArgs, g.merge(b, { step: function (a, b) { b.prop === "start" && e.length === 4 && i.length === 4 && this.attr({fill: t(e, i, b.pos)}) }, complete: j })) : (h.attr(a.shapeArgs), j())) }) }; v && p(v.prototype, { supportsDrilldown: !0, animateDrillupTo: m.prototype.animateDrillupTo, animateDrillupFrom: m.prototype.animateDrillupFrom, animateDrilldown: function (a) { var b = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], d = this.chart.options.drilldown.animation, c = b.shapeArgs, f = c.start, h = (c.end - f) / this.points.length, e = g.Color(b.color).rgba; if (!a)i(this.points, function (a, b) { var i = g.Color(a.color).rgba; a.graphic.attr(g.merge(c, { start: f + b * h, end: f + (b + 1) * h }))[d ? "animate" : "attr"](a.shapeArgs, g.merge(d, { step: function (a, b) { b.prop === "start" && e.length === 4 && i.length === 4 && this.attr({fill: t(e, i, b.pos)}) } })) }), this.animate = null } }); g.Point.prototype.doDrilldown = function (a) { for (var b = this.series.chart, d = b.options.drilldown, c = (d.series || []).length, f; c-- && !f;)d.series[c].id === this.drilldown && x(this.drilldown, r) === -1 && (f = d.series[c], r.push(this.drilldown)); w(b, "drilldown", {point: this, seriesOptions: f}); f && (a ? b.addSingleSeriesAsDrilldown(this, f) : b.addSeriesAsDrilldown(this, f)) }; q(g.Point.prototype, "init", function (a, b, d, c) { var f = a.call(this, b, d, c), h = b.chart, e = (a = b.xAxis && b.xAxis.ticks[c]) && a.label; if (f.drilldown) { if (g.addEvent(f, "click", function () { f.doDrilldown() }), e) { if (!e.basicStyles)e.basicStyles = g.merge(e.styles); e.addClass("highcharts-drilldown-axis-label").css(h.options.drilldown.activeAxisLabelStyle).on("click", function () { i(e.ddPoints, function (a) { a.doDrilldown && a.doDrilldown(!0) }); h.applyDrilldown() }); if (!e.ddPoints)e.ddPoints = []; e.ddPoints.push(f) } } else if (e && e.basicStyles)e.styles = {}, e.css(e.basicStyles); return f }); q(g.Series.prototype, "drawDataLabels", function (a) { var b = this.chart.options.drilldown.activeDataLabelStyle; a.call(this); i(this.points, function (a) { if (a.drilldown && a.dataLabel)a.dataLabel.attr({"class": "highcharts-drilldown-data-label"}).css(b).on("click", function () { a.doDrilldown() }) }) }); var s, o = function (a) { a.call(this); i(this.points, function (a) { a.drilldown && a.graphic && a.graphic.attr({"class": "highcharts-drilldown-point"}).css({cursor: "pointer"}) }) }; for (s in n)n[s].prototype.supportsDrilldown && q(n[s].prototype, "drawTracker", o) })(Highcharts);
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <tallies> <mesh id="1"> <type>regular</type> <lower_left>-10 -1 -1 </lower_left> <upper_right>10 1 1</upper_right> <dimension>10 1 1</dimension> </mesh> <filter id="1"> <type>mesh</type> <bins>1</bins> </filter> <tally id="1"> <filters>1</filters> <scores>flux</scores> </tally> </tallies>
{ "pile_set_name": "Github" }
module tests.it.runtime.regressions; import tests.it.runtime; import reggae.reggae; import std.path; @("Issue 14: builddir not expanded") @Tags(["ninja", "regressions"]) unittest { with(immutable ReggaeSandbox()) { writeFile("reggaefile.d", q{ import reggae; enum ao = objectFile(SourceFile("a.c")); enum liba = Target("$builddir/liba.a", "ar rcs $out $in", [ao]); mixin build!(liba); }); writeFile("a.c"); runReggae("-b", "ninja"); ninja.shouldExecuteOk; } } @("Issue 12: can't set executable as a dependency") @Tags(["ninja", "regressions"]) unittest { with(immutable ReggaeSandbox()) { writeFile("reggaefile.d", q{ import reggae; alias app = scriptlike!(App(SourceFileName("main.d"), BinaryFileName("$builddir/myapp")), Flags("-g -debug"), ImportPaths(["/path/to/imports"]) ); alias code_gen = target!("out.c", "./myapp $in $out", target!"in.txt", app); mixin build!(code_gen); }); writeFile("main.d", q{ import std.stdio; import std.algorithm; import std.conv; void main(string[] args) { auto inFileName = args[1]; auto outFileName = args[2]; auto lines = File(inFileName).byLine. map!(a => a.to!string). map!(a => a ~ ` ` ~ a); auto outFile = File(outFileName, `w`); foreach(line; lines) outFile.writeln(line); } }); writeFile("in.txt", ["foo", "bar", "baz"]); runReggae("-b", "ninja"); ninja.shouldExecuteOk; ["cat", "out.c"].shouldExecuteOk; shouldEqualLines("out.c", ["foo foo", "bar bar", "baz baz"]); } } @("Issue 10: dubConfigurationTarget doesn't work for unittest builds") @Tags(["ninja", "regressions"]) unittest { import std.path; import std.file; with(immutable ReggaeSandbox()) { writeFile("dub.json", ` { "name": "dubproj", "configurations": [ { "name": "executable", "targetName": "foo"}, { "name": "unittest", "targetName": "ut"} ] }`); writeFile("reggaefile.d", q{ import reggae; alias ut = dubConfigurationTarget!(Configuration(`unittest`), CompilerFlags(`-g -debug -cov`)); mixin build!ut; }); mkdir(buildPath(testPath, "source")); writeFile(buildPath("source", "src.d"), q{ unittest { static assert(false, `oopsie`); } int add(int i, int j) { return i + j; } }); writeFile(buildPath("source", "main.d"), q{ import src; void main() {} }); runReggae("-b", "ninja"); ninja.shouldFailToExecute(testPath); } }
{ "pile_set_name": "Github" }
from pyomo.environ import * # create the concrete model model = ConcreteModel() # set the data (native python data) k1 = 5.0/6.0 # min^-1 k2 = 5.0/3.0 # min^-1 k3 = 1.0/6000.0 # m^3/(gmol min) caf = 10000.0 # gmol/m^3 # create the variables model.sv = Var(initialize = 1.0, within=PositiveReals) model.ca = Var(initialize = 5000.0, within=PositiveReals) model.cb = Var(initialize = 2000.0, within=PositiveReals) model.cc = Var(initialize = 2000.0, within=PositiveReals) model.cd = Var(initialize = 1000.0, within=PositiveReals) # create the objective model.obj = Objective(expr = model.cb, sense=maximize) # create the constraints model.ca_bal = Constraint(expr = (0 == model.sv * caf \ - model.sv * model.ca - k1 * model.ca \ - 2.0 * k3 * model.ca ** 2.0)) model.cb_bal = Constraint(expr=(0 == -model.sv * model.cb \ + k1 * model.ca - k2 * model.cb)) model.cc_bal = Constraint(expr=(0 == -model.sv * model.cc \ + k2 * model.cb)) model.cd_bal = Constraint(expr=(0 == -model.sv * model.cd \ + k3 * model.ca ** 2.0)) # run the sequence of square problems solver = SolverFactory('ipopt') model.sv.fixed = True sv_values = [1.0 + v * 0.05 for v in range(1, 20)] print(" %s %s" % (str('sv'.rjust(10)), str('cb'.rjust(10)))) for sv_value in sv_values: model.sv = sv_value solver.solve(model) print(" %s %s" %(str(model.sv.value).rjust(10),\ str(model.cb.value).rjust(15)))
{ "pile_set_name": "Github" }
<template lang="html"> <div> <b-modal ref="tokenModal" :title="$t('interface.tokens.modal.title')" hide-footer class="bootstrap-modal nopadding max-height-1" centered static lazy @hidden="resetCompState" > <form class="tokens-modal-body" @keydown.enter.prevent> <div> <input v-model="tokenAddress" v-validate="'required'" :class="[ 'custom-input-text-1', tokenAddress !== '' && !validAddress ? 'invalid-address' : '' ]" :placeholder="$t('interface.tokens.modal.ph-contract-addr')" name="Address" type="text" /> <span v-show="tokenAddress !== '' && !validAddress" class="error-message" > {{ $t('interface.tokens.modal.error.addr') }} </span> <input v-model="tokenSymbol" :placeholder="$t('interface.tokens.modal.ph-symbol')" name="Symbol" type="text" class="custom-input-text-1" /> <input v-model="tokenDecimal" :placeholder="$t('interface.tokens.modal.ph-decimals')" name="Decimal" type="number" min="0" max="18" class="custom-input-text-1" /> <span v-show="tokenDecimal < 0 || tokenDecimal > 18" class="error-message" > {{ $t('interface.tokens.modal.error.decimals') }} </span> </div> <div class="button-block"> <button :class="[ allFieldsValid ? '' : 'disabled', 'save-button large-round-button-green-filled clickable' ]" @click.prevent="addToken(tokenAddress, tokenSymbol, tokenDecimal)" > {{ $t('common.save') }} </button> <interface-bottom-text :link-text="$t('common.help-center')" :question="$t('common.dont-know')" link="https://kb.myetherwallet.com" /> </div> </form> </b-modal> </div> </template> <script> import InterfaceBottomText from '@/components/InterfaceBottomText'; import { mapState } from 'vuex'; import { isAddress } from '@/helpers/addressUtils'; export default { components: { 'interface-bottom-text': InterfaceBottomText }, props: { addToken: { type: Function, default: function () {} } }, data() { return { tokenAddress: '', tokenSymbol: '', tokenDecimal: '', validAddress: false }; }, computed: { ...mapState('main', ['web3']), allFieldsValid() { if (!this.validAddress) return false; if (this.tokenSymbol === '') return false; if ( this.tokenDecimal < 0 || this.tokenDecimal > 18 || this.tokenDecimal === '' ) return false; if ( this.errors.has('address') || this.errors.has('symbol') || this.errors.has('decimal') ) return false; return true; } }, watch: { tokenAddress(newVal) { const strippedWhitespace = newVal.toLowerCase().trim(); const regTest = new RegExp(/[a-zA-Z0-9]/g); this.validAddress = regTest.test(strippedWhitespace) && isAddress(strippedWhitespace); this.toAddress = strippedWhitespace; this.tokenAddress = strippedWhitespace; }, tokenSymbol(newVal) { this.tokenSymbol = newVal.substr(0, 7); } }, methods: { resetCompState() { this.tokenAddress = ''; this.tokenSymbol = ''; this.tokenDecimal = ''; this.validAddress = false; } } }; </script> <style lang="scss" scoped> @import 'InterfaceTokensModal.scss'; </style>
{ "pile_set_name": "Github" }
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category design * @package base_default * @copyright Copyright (c) 2006-2020 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ ?> <div class="page-title"> <h1><?php echo $this->__('Share Your Wishlist') ?></h1> </div> <?php echo $this->getMessagesBlock()->toHtml() ?> <form action="<?php echo $this->getSendUrl() ?>" id="form-validate" method="post"> <div class="fieldset"> <?php echo $this->getBlockHtml('formkey')?> <h2 class="legend"><?php echo $this->__('Sharing Information') ?></h2> <ul class="form-list"> <li class="wide"> <label for="email_address" class="required"><em>*</em><?php echo $this->__('Up to 5 email addresses, separated by commas') ?></label> <div class="input-box"> <textarea name="emails" cols="60" rows="5" id="email_address" class="validate-emails required-entry"><?php echo $this->getEnteredData('emails') ?></textarea> </div> </li> <li class="wide"> <label for="message"><?php echo $this->__('Message') ?></label> <div class="input-box"> <textarea id="message" name="message" cols="60" rows="3"><?php echo $this->getEnteredData('message') ?></textarea> </div> </li> <?php if($this->helper('wishlist')->isRssAllow()): ?> <li class="control"> <div class="input-box"> <input type="checkbox" name="rss_url" id="rss_url" value="1" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Check this checkbox if you want to add a link to an rss feed to your wishlist.')) ?>" class="checkbox" /> </div> <label for="rss_url"><?php echo $this->__('Check this checkbox if you want to add a link to an rss feed to your wishlist.') ?></label> </li> <?php endif; ?> <?php echo $this->getChildHtml('wishlist.sharing.form.additional.info'); ?> </ul> </div> <div class="buttons-set form-buttons"> <p class="required"><?php echo $this->__('* Required Fields') ?></p> <p class="back-link"><a href="<?php echo $this->getBackUrl(); ?>"><small>&laquo; </small><?php echo $this->__('Back')?></a></p> <button type="submit" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Share Wishlist')) ?>" class="button"><span><span><?php echo $this->__('Share Wishlist') ?></span></span></button> </div> </form> <script type="text/javascript"> //<![CDATA[ Validation.addAllThese([ ['validate-emails', '<?php echo Mage::helper('core')->jsQuoteEscape($this->__('Please enter a valid email addresses, separated by commas. For example [email protected], [email protected].')) ?>', function (v) { if(Validation.get('IsEmpty').test(v)) { return true; } var valid_regexp = /^[a-z0-9\._-]{1,30}@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,4}$/i; var emails = v.split(','); for (var i=0; i<emails.length; i++) { if(!valid_regexp.test(emails[i].strip())) { return false; } } return true; }] ]); var dataForm = new VarienForm('form-validate', true); //]]> </script>
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <title>APIドキュメント</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap.min.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/prettify.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap-responsive.min.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/application.css'/> <!-- IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container-fluid"> <div class="row-fluid"> <div id='container'> <ul class='breadcrumb'> <li> <a href='../../../apidoc/v2.ja.html'>Foreman v2</a> <span class='divider'>/</span> </li> <li> <a href='../../../apidoc/v2/architectures.ja.html'> Architectures </a> <span class='divider'>/</span> </li> <li class='active'>create</li> <li class='pull-right'> &nbsp;[ <a href="../../../apidoc/v2/architectures/create.ca.html">ca</a> | <a href="../../../apidoc/v2/architectures/create.cs_CZ.html">cs_CZ</a> | <a href="../../../apidoc/v2/architectures/create.de.html">de</a> | <a href="../../../apidoc/v2/architectures/create.en.html">en</a> | <a href="../../../apidoc/v2/architectures/create.en_GB.html">en_GB</a> | <a href="../../../apidoc/v2/architectures/create.es.html">es</a> | <a href="../../../apidoc/v2/architectures/create.fr.html">fr</a> | <a href="../../../apidoc/v2/architectures/create.gl.html">gl</a> | <a href="../../../apidoc/v2/architectures/create.it.html">it</a> | <b><a href="../../../apidoc/v2/architectures/create.ja.html">ja</a></b> | <a href="../../../apidoc/v2/architectures/create.ko.html">ko</a> | <a href="../../../apidoc/v2/architectures/create.nl_NL.html">nl_NL</a> | <a href="../../../apidoc/v2/architectures/create.pl.html">pl</a> | <a href="../../../apidoc/v2/architectures/create.pt_BR.html">pt_BR</a> | <a href="../../../apidoc/v2/architectures/create.ru.html">ru</a> | <a href="../../../apidoc/v2/architectures/create.sv_SE.html">sv_SE</a> | <a href="../../../apidoc/v2/architectures/create.zh_CN.html">zh_CN</a> | <a href="../../../apidoc/v2/architectures/create.zh_TW.html">zh_TW</a> ] </li> </ul> <div class='page-header'> <h1> POST /api/architectures <br> <small>アーキテクチャーの作成</small> </h1> </div> <div> <h2>例</h2> <pre class="prettyprint">POST /api/architectures { &quot;architecture&quot;: { &quot;name&quot;: &quot;i386&quot; } } 201 { &quot;created_at&quot;: &quot;2020-03-11 07:55:01 UTC&quot;, &quot;updated_at&quot;: &quot;2020-03-11 07:55:01 UTC&quot;, &quot;name&quot;: &quot;i386&quot;, &quot;id&quot;: 922134522, &quot;operatingsystems&quot;: [], &quot;images&quot;: [] }</pre> <h2>パラメーター</h2> <table class='table'> <thead> <tr> <th>パラメーター名</th> <th>記述</th> </tr> </thead> <tbody> <tr style='background-color:rgb(255,255,255);'> <td> <strong>location_id </strong><br> <small> 任意 </small> </td> <td> <p>Set the current location context for the request</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a Integer</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>organization_id </strong><br> <small> 任意 </small> </td> <td> <p>Set the current organization context for the request</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a Integer</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>architecture </strong><br> <small> 必須 </small> </td> <td> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a Hash</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(250,250,250);'> <td> <strong>architecture[name] </strong><br> <small> 必須 </small> </td> <td> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a String</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(250,250,250);'> <td> <strong>architecture[operatingsystem_ids] </strong><br> <small> 任意 , nil可 </small> </td> <td> <p>オペレーティングシステム ID</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be an array of any type</p> </li> </ul> </td> </tr> </tbody> </table> </div> </div> </div> <hr> <footer></footer> </div> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/jquery.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/bootstrap-collapse.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/prettify.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/apipie.js'></script> </body> </html>
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <UIFoundation/NSCollectionViewLayout.h> @interface NSCollectionViewLayout (NSPrivateItemSequence) + (BOOL)itemLayoutIsSequential; @end
{ "pile_set_name": "Github" }
# @generated by autocargo from //hphp/hack/src/hhbc:emit_fatal_rust [package] name = "emit_fatal_rust" edition = "2018" version = "0.0.0" include = ["../../emit_fatal.rs"] [lib] path = "../../emit_fatal.rs" [dependencies] emit_pos_rust = { path = "../emit_pos" } hhbc_ast_rust = { path = "../hhbc_ast" } instruction_sequence_rust = { path = "../instruction_sequence" } oxidized = { path = "../../../oxidized" }
{ "pile_set_name": "Github" }
Change Log ========== 0.2.1 (2016-04-15) ------------------ * Packaging fix 0.2 (2016-04-15) ---------------- * Added docs and tests * Published on PyPI 0.1 (2016-04-11) ---------------- Initial release
{ "pile_set_name": "Github" }
// // EncryptionKit.swift // ProtonMail - Created on 12/18/18. // // // Copyright (c) 2019 Proton Technologies AG // // This file is part of ProtonMail. // // ProtonMail is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ProtonMail 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 ProtonMail. If not, see <https://www.gnu.org/licenses/>. import Foundation /// initally for push notification key struct EncryptionKit: Codable, Equatable { var passphrase, privateKey, publicKey: String }
{ "pile_set_name": "Github" }
### Arguments #### `argument_name` * Is required: yes * Is array: no * Default: `NULL`
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>QUnit Test Suite - Canvas Addon</title> <link rel="stylesheet" href="../../qunit/qunit.css" type="text/css" media="screen"> <script type="text/javascript" src="../../qunit/qunit.js"></script> <script type="text/javascript" src="qunit-canvas.js"></script> <script type="text/javascript" src="canvas-test.js"></script> </head> <body> <h1 id="qunit-header">QUnit Test Suite - Canvas Addon</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <canvas id="qunit-canvas" width="5" height="5"></canvas> </body> </html>
{ "pile_set_name": "Github" }
name: rdev_get_ringparam ID: 721 format: field:unsigned short common_type; offset:0; size:2; signed:0; field:unsigned char common_flags; offset:2; size:1; signed:0; field:unsigned char common_preempt_count; offset:3; size:1; signed:0; field:int common_pid; offset:4; size:4; signed:1; field:char wiphy_name[32]; offset:8; size:32; signed:0; print fmt: "%s", REC->wiphy_name
{ "pile_set_name": "Github" }
/* * jccoefct.c * * Copyright (C) 1994-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the coefficient buffer controller for compression. * This controller is the top level of the JPEG compressor proper. * The coefficient buffer lies between forward-DCT and entropy encoding steps. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* We use a full-image coefficient buffer when doing Huffman optimization, * and also for writing multiple-scan JPEG files. In all cases, the DCT * step is run during the first pass, and subsequent passes need only read * the buffered coefficients. */ #ifdef ENTROPY_OPT_SUPPORTED #define FULL_COEF_BUFFER_SUPPORTED #else #ifdef C_MULTISCAN_FILES_SUPPORTED #define FULL_COEF_BUFFER_SUPPORTED #endif #endif /* Private buffer controller object */ typedef struct { struct jpeg_c_coef_controller pub; /* public fields */ JDIMENSION iMCU_row_num; /* iMCU row # within image */ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */ int MCU_vert_offset; /* counts MCU rows within iMCU row */ int MCU_rows_per_iMCU_row; /* number of such rows needed */ /* For single-pass compression, it's sufficient to buffer just one MCU * (although this may prove a bit slow in practice). We allocate a * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each * MCU constructed and sent. (On 80x86, the workspace is FAR even though * it's not really very big; this is to keep the module interfaces unchanged * when a large coefficient buffer is necessary.) * In multi-pass modes, this array points to the current MCU's blocks * within the virtual arrays. */ JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU]; /* In multi-pass modes, we need a virtual block array for each component. */ jvirt_barray_ptr whole_image[MAX_COMPONENTS]; } my_coef_controller; typedef my_coef_controller * my_coef_ptr; /* Forward declarations */ METHODDEF(boolean) compress_data JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); #ifdef FULL_COEF_BUFFER_SUPPORTED METHODDEF(boolean) compress_first_pass JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); METHODDEF(boolean) compress_output JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf)); #endif LOCAL(void) start_iMCU_row (j_compress_ptr cinfo) /* Reset within-iMCU-row counters for a new row */ { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; /* In an interleaved scan, an MCU row is the same as an iMCU row. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. * But at the bottom of the image, process only what's left. */ if (cinfo->comps_in_scan > 1) { coef->MCU_rows_per_iMCU_row = 1; } else { if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1)) coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; else coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; } coef->mcu_ctr = 0; coef->MCU_vert_offset = 0; } /* * Initialize for a processing pass. */ METHODDEF(void) start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; coef->iMCU_row_num = 0; start_iMCU_row(cinfo); switch (pass_mode) { case JBUF_PASS_THRU: if (coef->whole_image[0] != NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); coef->pub.compress_data = compress_data; break; #ifdef FULL_COEF_BUFFER_SUPPORTED case JBUF_SAVE_AND_PASS: if (coef->whole_image[0] == NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); coef->pub.compress_data = compress_first_pass; break; case JBUF_CRANK_DEST: if (coef->whole_image[0] == NULL) ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); coef->pub.compress_data = compress_output; break; #endif default: ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); break; } } /* * Process some data in the single-pass case. * We process the equivalent of one fully interleaved MCU row ("iMCU" row) * per call, ie, v_samp_factor block rows for each component in the image. * Returns TRUE if the iMCU row is completed, FALSE if suspended. * * NB: input_buf contains a plane for each component in image, * which we index according to the component's SOF position. */ METHODDEF(boolean) compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; int blkn, bi, ci, yindex, yoffset, blockcnt; JDIMENSION ypos, xpos; jpeg_component_info *compptr; /* Loop to write as much as one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) { /* Determine where data comes from in input_buf and do the DCT thing. * Each call on forward_DCT processes a horizontal row of DCT blocks * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks * sequentially. Dummy blocks at the right or bottom edge are filled in * specially. The data in them does not matter for image reconstruction, * so we fill them with values that will encode to the smallest amount of * data, viz: all zeroes in the AC entries, DC entries equal to previous * block's DC value. (Thanks to Thomas Kinsman for this idea.) */ blkn = 0; for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width : compptr->last_col_width; xpos = MCU_col_num * compptr->MCU_sample_width; ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */ for (yindex = 0; yindex < compptr->MCU_height; yindex++) { if (coef->iMCU_row_num < last_iMCU_row || yoffset+yindex < compptr->last_row_height) { (*cinfo->fdct->forward_DCT) (cinfo, compptr, input_buf[compptr->component_index], coef->MCU_buffer[blkn], ypos, xpos, (JDIMENSION) blockcnt); if (blockcnt < compptr->MCU_width) { /* Create some dummy blocks at the right edge of the image. */ jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt], (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK)); for (bi = blockcnt; bi < compptr->MCU_width; bi++) { coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0]; } } } else { /* Create a row of dummy blocks at the bottom of the image. */ jzero_far((void FAR *) coef->MCU_buffer[blkn], compptr->MCU_width * SIZEOF(JBLOCK)); for (bi = 0; bi < compptr->MCU_width; bi++) { coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0]; } } blkn += compptr->MCU_width; ypos += DCTSIZE; } } /* Try to write the MCU. In event of a suspension failure, we will * re-DCT the MCU on restart (a bit inefficient, could be fixed...) */ if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->mcu_ctr = MCU_col_num; return FALSE; } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->mcu_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ coef->iMCU_row_num++; start_iMCU_row(cinfo); return TRUE; } #ifdef FULL_COEF_BUFFER_SUPPORTED /* * Process some data in the first pass of a multi-pass case. * We process the equivalent of one fully interleaved MCU row ("iMCU" row) * per call, ie, v_samp_factor block rows for each component in the image. * This amount of data is read from the source buffer, DCT'd and quantized, * and saved into the virtual arrays. We also generate suitable dummy blocks * as needed at the right and lower edges. (The dummy blocks are constructed * in the virtual arrays, which have been padded appropriately.) This makes * it possible for subsequent passes not to worry about real vs. dummy blocks. * * We must also emit the data to the entropy encoder. This is conveniently * done by calling compress_output() after we've loaded the current strip * of the virtual arrays. * * NB: input_buf contains a plane for each component in image. All * components are DCT'd and loaded into the virtual arrays in this pass. * However, it may be that only a subset of the components are emitted to * the entropy encoder during this first pass; be careful about looking * at the scan-dependent variables (MCU dimensions, etc). */ METHODDEF(boolean) compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; JDIMENSION blocks_across, MCUs_across, MCUindex; int bi, ci, h_samp_factor, block_row, block_rows, ndummy; JCOEF lastDC; jpeg_component_info *compptr; JBLOCKARRAY buffer; JBLOCKROW thisblockrow, lastblockrow; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Align the virtual buffer for this component. */ buffer = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[ci], coef->iMCU_row_num * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, TRUE); /* Count non-dummy DCT block rows in this iMCU row. */ if (coef->iMCU_row_num < last_iMCU_row) block_rows = compptr->v_samp_factor; else { /* NB: can't use last_row_height here, since may not be set! */ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (block_rows == 0) block_rows = compptr->v_samp_factor; } blocks_across = compptr->width_in_blocks; h_samp_factor = compptr->h_samp_factor; /* Count number of dummy blocks to be added at the right margin. */ ndummy = (int) (blocks_across % h_samp_factor); if (ndummy > 0) ndummy = h_samp_factor - ndummy; /* Perform DCT for all non-dummy blocks in this iMCU row. Each call * on forward_DCT processes a complete horizontal row of DCT blocks. */ for (block_row = 0; block_row < block_rows; block_row++) { thisblockrow = buffer[block_row]; (*cinfo->fdct->forward_DCT) (cinfo, compptr, input_buf[ci], thisblockrow, (JDIMENSION) (block_row * DCTSIZE), (JDIMENSION) 0, blocks_across); if (ndummy > 0) { /* Create dummy blocks at the right edge of the image. */ thisblockrow += blocks_across; /* => first dummy block */ jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK)); lastDC = thisblockrow[-1][0]; for (bi = 0; bi < ndummy; bi++) { thisblockrow[bi][0] = lastDC; } } } /* If at end of image, create dummy block rows as needed. * The tricky part here is that within each MCU, we want the DC values * of the dummy blocks to match the last real block's DC value. * This squeezes a few more bytes out of the resulting file... */ if (coef->iMCU_row_num == last_iMCU_row) { blocks_across += ndummy; /* include lower right corner */ MCUs_across = blocks_across / h_samp_factor; for (block_row = block_rows; block_row < compptr->v_samp_factor; block_row++) { thisblockrow = buffer[block_row]; lastblockrow = buffer[block_row-1]; jzero_far((void FAR *) thisblockrow, (size_t) (blocks_across * SIZEOF(JBLOCK))); for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) { lastDC = lastblockrow[h_samp_factor-1][0]; for (bi = 0; bi < h_samp_factor; bi++) { thisblockrow[bi][0] = lastDC; } thisblockrow += h_samp_factor; /* advance to next MCU in row */ lastblockrow += h_samp_factor; } } } } /* NB: compress_output will increment iMCU_row_num if successful. * A suspension return will result in redoing all the work above next time. */ /* Emit data to the entropy encoder, sharing code with subsequent passes */ return compress_output(cinfo, input_buf); } /* * Process some data in subsequent passes of a multi-pass case. * We process the equivalent of one fully interleaved MCU row ("iMCU" row) * per call, ie, v_samp_factor block rows for each component in the scan. * The data is obtained from the virtual arrays and fed to the entropy coder. * Returns TRUE if the iMCU row is completed, FALSE if suspended. * * NB: input_buf is ignored; it is likely to be a NULL pointer. */ METHODDEF(boolean) compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ int blkn, ci, xindex, yindex, yoffset; JDIMENSION start_col; JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; JBLOCKROW buffer_ptr; jpeg_component_info *compptr; /* Align the virtual buffers for the components used in this scan. * NB: during first pass, this is safe only because the buffers will * already be aligned properly, so jmemmgr.c won't need to do any I/O. */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; buffer[ci] = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index], coef->iMCU_row_num * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, FALSE); } /* Loop to process one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row; MCU_col_num++) { /* Construct list of pointers to DCT blocks belonging to this MCU */ blkn = 0; /* index of current DCT block within MCU */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; start_col = MCU_col_num * compptr->MCU_width; for (yindex = 0; yindex < compptr->MCU_height; yindex++) { buffer_ptr = buffer[ci][yindex+yoffset] + start_col; for (xindex = 0; xindex < compptr->MCU_width; xindex++) { coef->MCU_buffer[blkn++] = buffer_ptr++; } } } /* Try to write the MCU. */ if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->mcu_ctr = MCU_col_num; return FALSE; } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->mcu_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ coef->iMCU_row_num++; start_iMCU_row(cinfo); return TRUE; } #endif /* FULL_COEF_BUFFER_SUPPORTED */ /* * Initialize coefficient buffer controller. */ GLOBAL(void) jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer) { my_coef_ptr coef; coef = (my_coef_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_coef_controller)); cinfo->coef = (struct jpeg_c_coef_controller *) coef; coef->pub.start_pass = start_pass_coef; /* Create the coefficient buffer. */ if (need_full_buffer) { #ifdef FULL_COEF_BUFFER_SUPPORTED /* Allocate a full-image virtual array for each component, */ /* padded to a multiple of samp_factor DCT blocks in each direction. */ int ci; jpeg_component_info *compptr; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { coef->whole_image[ci] = (*cinfo->mem->request_virt_barray) ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, (JDIMENSION) jround_up((long) compptr->width_in_blocks, (long) compptr->h_samp_factor), (JDIMENSION) jround_up((long) compptr->height_in_blocks, (long) compptr->v_samp_factor), (JDIMENSION) compptr->v_samp_factor); } #else ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); #endif } else { /* We only need a single-MCU buffer. */ JBLOCKROW buffer; int i; buffer = (JBLOCKROW) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) { coef->MCU_buffer[i] = buffer + i; } coef->whole_image[0] = NULL; /* flag for no virtual arrays */ } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_JFR_RECORDER_CHECKPOINT_TYPES_JFRTHREADSTATE_HPP #define SHARE_VM_JFR_RECORDER_CHECKPOINT_TYPES_JFRTHREADSTATE_HPP #include "memory/allocation.hpp" class JfrCheckpointWriter; class JfrThreadState : public AllStatic { public: static void serialize(JfrCheckpointWriter& writer); }; #endif // SHARE_VM_JFR_RECORDER_CHECKPOINT_TYPES_JFRTHREADSTATE_HPP
{ "pile_set_name": "Github" }
/* Copyright 2015 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. ==============================================================================*/ #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/concat_lib_cpu.h" #include <vector> #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/kernels/concat_lib.h" namespace tensorflow { namespace { template <typename T> struct MemCpyCopier { inline void Copy(T* dst, const T* src, int input_index, size_t n) { if (DataTypeCanUseMemcpy(DataTypeToEnum<T>::v())) { memcpy(dst, src, n * sizeof(T)); } else { for (size_t k = 0; k < n; ++k) { *dst++ = *src++; } } } }; template <> struct MemCpyCopier<ResourceHandle> { inline void Copy(ResourceHandle* dst, const ResourceHandle* src, int input_index, size_t n) { for (size_t k = 0; k < n; ++k) { *dst++ = *src++; } } }; } // namespace template <typename T> void ConcatCPU(DeviceBase* d, const std::vector< std::unique_ptr<typename TTypes<T, 2>::ConstMatrix>>& inputs, typename TTypes<T, 2>::Matrix* output) { if (std::is_same<T, string>::value) { // use a large cost here to force strings to be handled by separate threads ConcatCPUImpl<T>(d, inputs, 100000, MemCpyCopier<T>(), output); } else { ConcatCPUImpl<T>(d, inputs, sizeof(T) /* cost_per_unit */, MemCpyCopier<T>(), output); } } #define REGISTER(T) \ template void ConcatCPU<T>( \ DeviceBase*, \ const std::vector<std::unique_ptr<typename TTypes<T, 2>::ConstMatrix>>&, \ typename TTypes<T, 2>::Matrix* output); TF_CALL_ALL_TYPES(REGISTER) REGISTER(quint8) REGISTER(qint8) REGISTER(quint16) REGISTER(qint16) REGISTER(qint32) REGISTER(bfloat16) TF_CALL_variant(REGISTER) #if defined(IS_MOBILE_PLATFORM) && !defined(SUPPORT_SELECTIVE_REGISTRATION) && \ !defined(__ANDROID_TYPES_FULL__) // Primarily used for SavedModel support on mobile. Registering it here only // if __ANDROID_TYPES_FULL__ is not defined (which already registers string) // to avoid duplicate registration. REGISTER(string); #endif // defined(IS_MOBILE_PLATFORM) && // !defined(SUPPORT_SELECTIVE_REGISTRATION) && // !defined(__ANDROID_TYPES_FULL__) #ifdef TENSORFLOW_USE_SYCL template <typename T> void ConcatSYCL(const Eigen::SyclDevice& d, const std::vector< std::unique_ptr<typename TTypes<T, 2>::ConstMatrix>>& inputs, typename TTypes<T, 2>::Matrix* output) { ConcatSYCLImpl<T>(d, inputs, sizeof(T) /* cost_per_unit */, MemCpyCopier<T>(), output); } #define REGISTER_SYCL(T) \ template void ConcatSYCL<T>( \ const Eigen::SyclDevice&, \ const std::vector<std::unique_ptr<typename TTypes<T, 2>::ConstMatrix>>&, \ typename TTypes<T, 2>::Matrix* output); TF_CALL_GPU_NUMBER_TYPES_NO_HALF(REGISTER_SYCL) #undef REGISTER_SYCL #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow
{ "pile_set_name": "Github" }
#!/usr/bin/env bash ##################################################################### # genallfont.sh for Marlin # # This script generates font data for language headers # # Copyright 2015-2018 Yunhui Fu <[email protected]> # License: GPL/BSD ##################################################################### my_getpath() { local PARAM_DN="$1" shift #readlink -f local DN="${PARAM_DN}" local FN= if [ ! -d "${DN}" ]; then FN=$(basename "${DN}") DN=$(dirname "${DN}") fi cd "${DN}" > /dev/null 2>&1 DN=$(pwd) cd - > /dev/null 2>&1 echo -n "${DN}" [[ -z "$FN" ]] || echo -n "/${FN}" } #DN_EXEC=`echo "$0" | ${EXEC_AWK} -F/ '{b=$1; for (i=2; i < NF; i ++) {b=b "/" $(i)}; print b}'` DN_EXEC=$(dirname $(my_getpath "$0") ) EXEC_WXGGEN="${DN_EXEC}/uxggenpages.sh" # # Locate the bdf2u8g command # EXEC_BDF2U8G=`which bdf2u8g` [ -x "${EXEC_BDF2U8G}" ] || EXEC_BDF2U8G="${DN_EXEC}/bdf2u8g" [ -x "${EXEC_BDF2U8G}" ] || EXEC_BDF2U8G="${PWD}/bdf2u8g" [ -x "${EXEC_BDF2U8G}" ] || { EOL=$'\n' ; echo "ERR: Can't find bdf2u8g!${EOL}See uxggenpages.md for bdf2u8g build instructions." >&2 ; exit 1; } # # Get language arguments # LANG_ARG="$@" # # Use 6x12 combined font data for Western languages # FN_FONT="${DN_EXEC}/marlin-6x12-3.bdf" # # Change to working directory 'Marlin' # OLDWD=`pwd` [[ $(basename "$OLDWD") != 'Marlin' && -d "Marlin" ]] && cd Marlin [[ -f "Configuration.h" ]] || { echo -n "cd to the 'Marlin' folder to run " ; basename $0 ; exit 1; } # # Compile the 'genpages' command in-place # (cd ${DN_EXEC}; gcc -o genpages genpages.c getline.c) # # By default loop through all languages # LANGS_DEFAULT="an bg ca cz da de el el_gr en es eu fi fr gl hr it jp_kana ko_KR nl pl pt pt_br ru sk tr uk vi zh_CN zh_TW test" # # Generate data for language list MARLIN_LANGS or all if not provided # for LANG in ${LANG_ARG:=$LANGS_DEFAULT} ; do echo "Generating Marlin language data for '${LANG}'" >&2 case "$LANG" in zh_* ) FONTFILE="wenquanyi_12pt" ;; ko_* ) FONTFILE="${DN_EXEC}/NanumGothic.bdf" ;; * ) FONTFILE="${DN_EXEC}/marlin-6x12-3.bdf" ;; esac DN_WORK=`mktemp -d` cp Configuration.h ${DN_WORK}/ cp src/lcd/language/language_${LANG}.h ${DN_WORK}/ cd "${DN_WORK}" ${EXEC_WXGGEN} "${FONTFILE}" sed -i fontutf8-data.h -e 's|fonts//|fonts/|g' -e 's|fonts//|fonts/|g' -e 's|[/0-9a-zA-Z_\-]*buildroot/share/fonts|buildroot/share/fonts|' 2>/dev/null cd - >/dev/null mv ${DN_WORK}/fontutf8-data.h src/lcd/dogm/fontdata/langdata_${LANG}.h rm -rf ${DN_WORK} done # # Generate default ASCII font (char range 0-255): # Marlin/src/lcd/dogm/fontdata/fontdata_ISO10646_1.h # #if [ "${MARLIN_LANGS}" == "${LANGS_DEFAULT}" ]; then if [ 1 = 1 ]; then DN_WORK=`mktemp -d` cd ${DN_WORK} ${EXEC_BDF2U8G} -b 1 -e 127 ${FN_FONT} ISO10646_1_5x7 tmp1.h >/dev/null ${EXEC_BDF2U8G} -b 1 -e 255 ${FN_FONT} ISO10646_1_5x7 tmp2.h >/dev/null TMP1=$(cat tmp1.h) TMP2=$(cat tmp2.h) cd - >/dev/null rm -rf ${DN_WORK} cat <<EOF >src/lcd/dogm/fontdata/fontdata_ISO10646_1.h /** * Marlin 3D Printer Firmware * Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <U8glib.h> #if defined(__AVR__) && ENABLED(NOT_EXTENDED_ISO10646_1_5X7) // reduced font (only symbols 1 - 127) - saves about 1278 bytes of FLASH $TMP1 #else // extended (original) font (symbols 1 - 255) $TMP2 #endif EOF fi (cd ${DN_EXEC}; rm genpages) cd "$OLDWD"
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef URLInputType_h #define URLInputType_h #include "BaseTextInputType.h" namespace WebCore { class URLInputType : public BaseTextInputType { public: static PassOwnPtr<InputType> create(HTMLInputElement*); private: URLInputType(HTMLInputElement* element) : BaseTextInputType(element) { } virtual const AtomicString& formControlType() const; virtual bool typeMismatchFor(const String&) const; virtual bool typeMismatch() const; virtual String typeMismatchText() const; virtual bool isURLField() const; }; } // namespace WebCore #endif // URLInputType_h
{ "pile_set_name": "Github" }
version: 1 dn: m-oid=1.3.6.1.4.1.42.2.27.4.1.6,ou=attributeTypes,cn=java,ou=schema creatorsname: uid=admin,ou=system objectclass: metaAttributeType objectclass: metaTop objectclass: top m-equality: caseExactMatch m-syntax: 1.3.6.1.4.1.1466.115.121.1.15 m-singlevalue: TRUE m-collective: FALSE m-nousermodification: FALSE m-usage: USER_APPLICATIONS m-oid: 1.3.6.1.4.1.42.2.27.4.1.6 m-name: javaClassName m-description: Fully qualified name of distinguished Java class or interface m-obsolete: FALSE entryUUID: 0306e4a6-82a3-43f5-8990-42b6ff9b1714 entryCSN: 20130919081858.901000Z#000000#000#000000 entryParentId: b6bd9cdf-6973-431e-beae-f51d70d1183a createTimestamp: 20130919081908.481Z
{ "pile_set_name": "Github" }
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from .box_head.box_head import build_roi_box_head from .mask_head.mask_head import build_roi_mask_head from .keypoint_head.keypoint_head import build_roi_keypoint_head class CombinedROIHeads(torch.nn.ModuleDict): """ Combines a set of individual heads (for box prediction or masks) into a single head. """ def __init__(self, cfg, heads): super(CombinedROIHeads, self).__init__(heads) self.cfg = cfg.clone() if cfg.MODEL.MASK_ON and cfg.MODEL.ROI_MASK_HEAD.SHARE_BOX_FEATURE_EXTRACTOR: self.mask.feature_extractor = self.box.feature_extractor if cfg.MODEL.KEYPOINT_ON and cfg.MODEL.ROI_KEYPOINT_HEAD.SHARE_BOX_FEATURE_EXTRACTOR: self.keypoint.feature_extractor = self.box.feature_extractor def forward(self, features, proposals, targets=None): losses = {} # TODO rename x to roi_box_features, if it doesn't increase memory consumption x, detections, loss_box = self.box(features, proposals, targets) losses.update(loss_box) if self.cfg.MODEL.MASK_ON: mask_features = features # optimization: during training, if we share the feature extractor between # the box and the mask heads, then we can reuse the features already computed if ( self.training and self.cfg.MODEL.ROI_MASK_HEAD.SHARE_BOX_FEATURE_EXTRACTOR ): mask_features = x # During training, self.box() will return the unaltered proposals as "detections" # this makes the API consistent during training and testing x, detections, loss_mask = self.mask(mask_features, detections, targets) losses.update(loss_mask) if self.cfg.MODEL.KEYPOINT_ON: keypoint_features = features # optimization: during training, if we share the feature extractor between # the box and the mask heads, then we can reuse the features already computed if ( self.training and self.cfg.MODEL.ROI_KEYPOINT_HEAD.SHARE_BOX_FEATURE_EXTRACTOR ): keypoint_features = x # During training, self.box() will return the unaltered proposals as "detections" # this makes the API consistent during training and testing x, detections, loss_keypoint = self.keypoint(keypoint_features, detections, targets) losses.update(loss_keypoint) return x, detections, losses def build_roi_heads(cfg): # individually create the heads, that will be combined together # afterwards roi_heads = [] if cfg.MODEL.RETINANET_ON: return [] if not cfg.MODEL.RPN_ONLY: roi_heads.append(("box", build_roi_box_head(cfg))) if cfg.MODEL.MASK_ON: roi_heads.append(("mask", build_roi_mask_head(cfg))) if cfg.MODEL.KEYPOINT_ON: roi_heads.append(("keypoint", build_roi_keypoint_head(cfg))) # combine individual heads in a single module if roi_heads: roi_heads = CombinedROIHeads(cfg, roi_heads) return roi_heads
{ "pile_set_name": "Github" }
page_title: Managing Data in Containers page_description: How to manage data inside your Docker containers. page_keywords: Examples, Usage, volume, docker, documentation, user guide, data, volumes # Managing Data in Containers So far we've been introduced to some [basic Docker concepts](/userguide/usingdocker/), seen how to work with [Docker images](/userguide/dockerimages/) as well as learned about [networking and links between containers](/userguide/dockerlinks/). In this section we're going to discuss how you can manage data inside and between your Docker containers. We're going to look at the two primary ways you can manage data in Docker. * Data volumes, and * Data volume containers. ## Data volumes A *data volume* is a specially-designated directory within one or more containers that bypasses the [*Union File System*](/terms/layer/#union-file-system) to provide several useful features for persistent or shared data: - Volumes are initialized when a container is created - Data volumes can be shared and reused between containers - Changes to a data volume are made directly - Changes to a data volume will not be included when you update an image - Volumes persist until no containers use them ### Adding a data volume You can add a data volume to a container using the `-v` flag with the `docker create` and `docker run` command. You can use the `-v` multiple times to mount multiple data volumes. Let's mount a single volume now in our web application container. $ sudo docker run -d -P --name web -v /webapp training/webapp python app.py This will create a new volume inside a container at `/webapp`. > **Note:** > You can also use the `VOLUME` instruction in a `Dockerfile` to add one or > more new volumes to any container created from that image. ### Mount a Host Directory as a Data Volume In addition to creating a volume using the `-v` flag you can also mount a directory from your Docker daemon's host into a container. > **Note:** > If you are using Boot2Docker, your Docker daemon only has limited access to > your OSX/Windows filesystem. Boot2Docker tries to auto-share your `/Users` > (OSX) or `C:\Users` (Windows) directory - and so you can mount files or directories > using `docker run -v /Users/<path>:/<container path> ...` (OSX) or > `docker run -v /c/Users/<path>:/<container path ...` (Windows). All other paths > come from the Boot2Docker virtual machine's filesystem. $ sudo docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py This will mount the host directory, `/src/webapp`, into the container at `/opt/webapp`. > **Note:** > If the path `/opt/webapp` already exists inside the container's image, its > contents will be replaced by the contents of `/src/webapp` on the host to stay > consistent with the expected behavior of `mount` This is very useful for testing, for example we can mount our source code inside the container and see our application at work as we change the source code. The directory on the host must be specified as an absolute path and if the directory doesn't exist Docker will automatically create it for you. > **Note:** > This is not available from a `Dockerfile` due to the portability > and sharing purpose of built images. The host directory is, by its nature, > host-dependent, so a host directory specified in a `Dockerfile` probably > wouldn't work on all hosts. Docker defaults to a read-write volume but we can also mount a directory read-only. $ sudo docker run -d -P --name web -v /src/webapp:/opt/webapp:ro training/webapp python app.py Here we've mounted the same `/src/webapp` directory but we've added the `ro` option to specify that the mount should be read-only. ### Mount a Host File as a Data Volume The `-v` flag can also be used to mount a single file - instead of *just* directories - from the host machine. $ sudo docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash This will drop you into a bash shell in a new container, you will have your bash history from the host and when you exit the container, the host will have the history of the commands typed while in the container. > **Note:** > Many tools used to edit files including `vi` and `sed --in-place` may result > in an inode change. Since Docker v1.1.0, this will produce an error such as > "*sed: cannot rename ./sedKdJ9Dy: Device or resource busy*". In the case where > you want to edit the mounted file, it is often easiest to instead mount the > parent directory. ## Creating and mounting a Data Volume Container If you have some persistent data that you want to share between containers, or want to use from non-persistent containers, it's best to create a named Data Volume Container, and then to mount the data from it. Let's create a new named container with a volume to share. While this container doesn't run an application, it reuses the `training/postgres` image so that all containers are using layers in common, saving disk space. $ sudo docker create -v /dbdata --name dbdata training/postgres You can then use the `--volumes-from` flag to mount the `/dbdata` volume in another container. $ sudo docker run -d --volumes-from dbdata --name db1 training/postgres And another: $ sudo docker run -d --volumes-from dbdata --name db2 training/postgres You can use multiple `--volumes-from` parameters to bring together multiple data volumes from multiple containers. You can also extend the chain by mounting the volume that came from the `dbdata` container in yet another container via the `db1` or `db2` containers. $ sudo docker run -d --name db3 --volumes-from db1 training/postgres If you remove containers that mount volumes, including the initial `dbdata` container, or the subsequent containers `db1` and `db2`, the volumes will not be deleted. To delete the volume from disk, you must explicitly call `docker rm -v` against the last container with a reference to the volume. This allows you to upgrade, or effectively migrate data volumes between containers. ## Backup, restore, or migrate data volumes Another useful function we can perform with volumes is use them for backups, restores or migrations. We do this by using the `--volumes-from` flag to create a new container that mounts that volume, like so: $ sudo docker run --volumes-from dbdata -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata Here we've launched a new container and mounted the volume from the `dbdata` container. We've then mounted a local host directory as `/backup`. Finally, we've passed a command that uses `tar` to backup the contents of the `dbdata` volume to a `backup.tar` file inside our `/backup` directory. When the command completes and the container stops we'll be left with a backup of our `dbdata` volume. You could then restore it to the same container, or another that you've made elsewhere. Create a new container. $ sudo docker run -v /dbdata --name dbdata2 ubuntu /bin/bash Then un-tar the backup file in the new container's data volume. $ sudo docker run --volumes-from dbdata2 -v $(pwd):/backup busybox tar xvf /backup/backup.tar You can use the techniques above to automate backup, migration and restore testing using your preferred tools. # Next steps Now we've learned a bit more about how to use Docker we're going to see how to combine Docker with the services available on [Docker Hub](https://hub.docker.com) including Automated Builds and private repositories. Go to [Working with Docker Hub](/userguide/dockerrepos).
{ "pile_set_name": "Github" }
#pragma once #include <iterator> // random_access_iterator_tag #include <nlohmann/detail/meta/void_t.hpp> #include <nlohmann/detail/meta/cpp_future.hpp> namespace nlohmann { namespace detail { template<typename It, typename = void> struct iterator_types {}; template<typename It> struct iterator_types < It, void_t<typename It::difference_type, typename It::value_type, typename It::pointer, typename It::reference, typename It::iterator_category >> { using difference_type = typename It::difference_type; using value_type = typename It::value_type; using pointer = typename It::pointer; using reference = typename It::reference; using iterator_category = typename It::iterator_category; }; // This is required as some compilers implement std::iterator_traits in a way that // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. template<typename T, typename = void> struct iterator_traits { }; template<typename T> struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >> : iterator_types<T> { }; template<typename T> struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>> { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; }; } // namespace detail } // namespace nlohmann
{ "pile_set_name": "Github" }
<!DOCTYPE html> <meta charset="utf-8"> <title>IDBObjectStore.createIndex() - empty keyPath</title> <link rel="author" href="mailto:[email protected]" title="Odin Hørthe Omdal"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="support.js"></script> <script> var db, aborted, t = async_test() var open_rq = createdb(t); open_rq.onupgradeneeded = function(e) { db = e.target.result; var txn = e.target.transaction, objStore = db.createObjectStore("store"); for (var i = 0; i < 5; i++) objStore.add("object_" + i, i); var rq = objStore.createIndex("index", "") rq.onerror = function() { assert_unreached("error: " + rq.error.name); } rq.onsuccess = function() { } objStore.index("index") .get('object_4') .onsuccess = t.step_func(function(e) { assert_equals(e.target.result, 'object_4', 'result'); }); } open_rq.onsuccess = function() { t.done(); } </script> <div id="log"></div>
{ "pile_set_name": "Github" }
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, [email protected]) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ if(Object.isUndefined(Effect)) throw("dragdrop.js requires including script.aculo.us' effects.js library"); var Droppables = { drops: [], remove: function(element) { this.drops = this.drops.reject(function(d) { return d.element==$(element) }); }, add: function(element) { element = $(element); var options = Object.extend({ greedy: true, hoverclass: null, tree: false }, arguments[1] || { }); // cache containers if(options.containment) { options._containers = []; var containment = options.containment; if(Object.isArray(containment)) { containment.each( function(c) { options._containers.push($(c)) }); } else { options._containers.push($(containment)); } } if(options.accept) options.accept = [options.accept].flatten(); Element.makePositioned(element); // fix IE options.element = element; this.drops.push(options); }, findDeepestChild: function(drops) { deepest = drops[0]; for (i = 1; i < drops.length; ++i) if (Element.isParent(drops[i].element, deepest.element)) deepest = drops[i]; return deepest; }, isContained: function(element, drop) { var containmentNode; if(drop.tree) { containmentNode = element.treeNode; } else { containmentNode = element.parentNode; } return drop._containers.detect(function(c) { return containmentNode == c }); }, isAffected: function(point, element, drop) { return ( (drop.element!=element) && ((!drop._containers) || this.isContained(element, drop)) && ((!drop.accept) || (Element.classNames(element).detect( function(v) { return drop.accept.include(v) } ) )) && Position.within(drop.element, point[0], point[1]) ); }, deactivate: function(drop) { if(drop.hoverclass) Element.removeClassName(drop.element, drop.hoverclass); this.last_active = null; }, activate: function(drop) { if(drop.hoverclass) Element.addClassName(drop.element, drop.hoverclass); this.last_active = drop; }, show: function(point, element) { if(!this.drops.length) return; var drop, affected = []; this.drops.each( function(drop) { if(Droppables.isAffected(point, element, drop)) affected.push(drop); }); if(affected.length>0) drop = Droppables.findDeepestChild(affected); if(this.last_active && this.last_active != drop) this.deactivate(this.last_active); if (drop) { Position.within(drop.element, point[0], point[1]); if(drop.onHover) drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); if (drop != this.last_active) Droppables.activate(drop); } }, fire: function(event, element) { if(!this.last_active) return; Position.prepare(); if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) if (this.last_active.onDrop) { this.last_active.onDrop(element, this.last_active.element, event); return true; } }, reset: function() { if(this.last_active) this.deactivate(this.last_active); } }; var Draggables = { drags: [], observers: [], register: function(draggable) { if(this.drags.length == 0) { this.eventMouseUp = this.endDrag.bindAsEventListener(this); this.eventMouseMove = this.updateDrag.bindAsEventListener(this); this.eventKeypress = this.keyPress.bindAsEventListener(this); Event.observe(document, "mouseup", this.eventMouseUp); Event.observe(document, "mousemove", this.eventMouseMove); Event.observe(document, "keypress", this.eventKeypress); } this.drags.push(draggable); }, unregister: function(draggable) { this.drags = this.drags.reject(function(d) { return d==draggable }); if(this.drags.length == 0) { Event.stopObserving(document, "mouseup", this.eventMouseUp); Event.stopObserving(document, "mousemove", this.eventMouseMove); Event.stopObserving(document, "keypress", this.eventKeypress); } }, activate: function(draggable) { if(draggable.options.delay) { this._timeout = setTimeout(function() { Draggables._timeout = null; window.focus(); Draggables.activeDraggable = draggable; }.bind(this), draggable.options.delay); } else { window.focus(); // allows keypress events if window isn't currently focused, fails for Safari this.activeDraggable = draggable; } }, deactivate: function() { this.activeDraggable = null; }, updateDrag: function(event) { if(!this.activeDraggable) return; var pointer = [Event.pointerX(event), Event.pointerY(event)]; // Mozilla-based browsers fire successive mousemove events with // the same coordinates, prevent needless redrawing (moz bug?) if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; this._lastPointer = pointer; this.activeDraggable.updateDrag(event, pointer); }, endDrag: function(event) { if(this._timeout) { clearTimeout(this._timeout); this._timeout = null; } if(!this.activeDraggable) return; this._lastPointer = null; this.activeDraggable.endDrag(event); this.activeDraggable = null; }, keyPress: function(event) { if(this.activeDraggable) this.activeDraggable.keyPress(event); }, addObserver: function(observer) { this.observers.push(observer); this._cacheObserverCallbacks(); }, removeObserver: function(element) { // element instead of observer fixes mem leaks this.observers = this.observers.reject( function(o) { return o.element==element }); this._cacheObserverCallbacks(); }, notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' if(this[eventName+'Count'] > 0) this.observers.each( function(o) { if(o[eventName]) o[eventName](eventName, draggable, event); }); if(draggable.options[eventName]) draggable.options[eventName](draggable, event); }, _cacheObserverCallbacks: function() { ['onStart','onEnd','onDrag'].each( function(eventName) { Draggables[eventName+'Count'] = Draggables.observers.select( function(o) { return o[eventName]; } ).length; }); } }; /*--------------------------------------------------------------------------*/ var Draggable = Class.create({ initialize: function(element) { var defaults = { handle: false, reverteffect: function(element, top_offset, left_offset) { var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, queue: {scope:'_draggable', position:'end'} }); }, endeffect: function(element) { var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0; new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, queue: {scope:'_draggable', position:'end'}, afterFinish: function(){ Draggable._dragging[element] = false } }); }, zindex: 1000, revert: false, quiet: false, scroll: false, scrollSensitivity: 20, scrollSpeed: 15, snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } delay: 0 }; if(!arguments[1] || Object.isUndefined(arguments[1].endeffect)) Object.extend(defaults, { starteffect: function(element) { element._opacity = Element.getOpacity(element); Draggable._dragging[element] = true; new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); } }); var options = Object.extend(defaults, arguments[1] || { }); this.element = $(element); if(options.handle && Object.isString(options.handle)) this.handle = this.element.down('.'+options.handle, 0); if(!this.handle) this.handle = $(options.handle); if(!this.handle) this.handle = this.element; if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { options.scroll = $(options.scroll); this._isScrollChild = Element.childOf(this.element, options.scroll); } Element.makePositioned(this.element); // fix IE this.options = options; this.dragging = false; this.eventMouseDown = this.initDrag.bindAsEventListener(this); Event.observe(this.handle, "mousedown", this.eventMouseDown); Draggables.register(this); }, destroy: function() { Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); Draggables.unregister(this); }, currentDelta: function() { return([ parseInt(Element.getStyle(this.element,'left') || '0'), parseInt(Element.getStyle(this.element,'top') || '0')]); }, initDrag: function(event) { if(!Object.isUndefined(Draggable._dragging[this.element]) && Draggable._dragging[this.element]) return; if(Event.isLeftClick(event)) { // abort on form elements, fixes a Firefox issue var src = Event.element(event); if((tag_name = src.tagName.toUpperCase()) && ( tag_name=='INPUT' || tag_name=='SELECT' || tag_name=='OPTION' || tag_name=='BUTTON' || tag_name=='TEXTAREA')) return; var pointer = [Event.pointerX(event), Event.pointerY(event)]; var pos = Position.cumulativeOffset(this.element); this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); Draggables.activate(this); Event.stop(event); } }, startDrag: function(event) { this.dragging = true; if(!this.delta) this.delta = this.currentDelta(); if(this.options.zindex) { this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); this.element.style.zIndex = this.options.zindex; } if(this.options.ghosting) { this._clone = this.element.cloneNode(true); this._originallyAbsolute = (this.element.getStyle('position') == 'absolute'); if (!this._originallyAbsolute) Position.absolutize(this.element); this.element.parentNode.insertBefore(this._clone, this.element); } if(this.options.scroll) { if (this.options.scroll == window) { var where = this._getWindowScroll(this.options.scroll); this.originalScrollLeft = where.left; this.originalScrollTop = where.top; } else { this.originalScrollLeft = this.options.scroll.scrollLeft; this.originalScrollTop = this.options.scroll.scrollTop; } } Draggables.notify('onStart', this, event); if(this.options.starteffect) this.options.starteffect(this.element); }, updateDrag: function(event, pointer) { if(!this.dragging) this.startDrag(event); if(!this.options.quiet){ Position.prepare(); Droppables.show(pointer, this.element); } Draggables.notify('onDrag', this, event); this.draw(pointer); if(this.options.change) this.options.change(this); if(this.options.scroll) { this.stopScrolling(); var p; if (this.options.scroll == window) { with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } } else { p = Position.page(this.options.scroll); p[0] += this.options.scroll.scrollLeft + Position.deltaX; p[1] += this.options.scroll.scrollTop + Position.deltaY; p.push(p[0]+this.options.scroll.offsetWidth); p.push(p[1]+this.options.scroll.offsetHeight); } var speed = [0,0]; if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); this.startScrolling(speed); } // fix AppleWebKit rendering if(Prototype.Browser.WebKit) window.scrollBy(0,0); Event.stop(event); }, finishDrag: function(event, success) { this.dragging = false; if(this.options.quiet){ Position.prepare(); var pointer = [Event.pointerX(event), Event.pointerY(event)]; Droppables.show(pointer, this.element); } if(this.options.ghosting) { if (!this._originallyAbsolute) Position.relativize(this.element); delete this._originallyAbsolute; Element.remove(this._clone); this._clone = null; } var dropped = false; if(success) { dropped = Droppables.fire(event, this.element); if (!dropped) dropped = false; } if(dropped && this.options.onDropped) this.options.onDropped(this.element); Draggables.notify('onEnd', this, event); var revert = this.options.revert; if(revert && Object.isFunction(revert)) revert = revert(this.element); var d = this.currentDelta(); if(revert && this.options.reverteffect) { if (dropped == 0 || revert != 'failure') this.options.reverteffect(this.element, d[1]-this.delta[1], d[0]-this.delta[0]); } else { this.delta = d; } if(this.options.zindex) this.element.style.zIndex = this.originalZ; if(this.options.endeffect) this.options.endeffect(this.element); Draggables.deactivate(this); Droppables.reset(); }, keyPress: function(event) { if(event.keyCode!=Event.KEY_ESC) return; this.finishDrag(event, false); Event.stop(event); }, endDrag: function(event) { if(!this.dragging) return; this.stopScrolling(); this.finishDrag(event, true); Event.stop(event); }, draw: function(point) { var pos = Position.cumulativeOffset(this.element); if(this.options.ghosting) { var r = Position.realOffset(this.element); pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; } var d = this.currentDelta(); pos[0] -= d[0]; pos[1] -= d[1]; if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; } var p = [0,1].map(function(i){ return (point[i]-pos[i]-this.offset[i]) }.bind(this)); if(this.options.snap) { if(Object.isFunction(this.options.snap)) { p = this.options.snap(p[0],p[1],this); } else { if(Object.isArray(this.options.snap)) { p = p.map( function(v, i) { return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this)); } else { p = p.map( function(v) { return (v/this.options.snap).round()*this.options.snap }.bind(this)); } }} var style = this.element.style; if((!this.options.constraint) || (this.options.constraint=='horizontal')) style.left = p[0] + "px"; if((!this.options.constraint) || (this.options.constraint=='vertical')) style.top = p[1] + "px"; if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering }, stopScrolling: function() { if(this.scrollInterval) { clearInterval(this.scrollInterval); this.scrollInterval = null; Draggables._lastScrollPointer = null; } }, startScrolling: function(speed) { if(!(speed[0] || speed[1])) return; this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; this.lastScrolled = new Date(); this.scrollInterval = setInterval(this.scroll.bind(this), 10); }, scroll: function() { var current = new Date(); var delta = current - this.lastScrolled; this.lastScrolled = current; if(this.options.scroll == window) { with (this._getWindowScroll(this.options.scroll)) { if (this.scrollSpeed[0] || this.scrollSpeed[1]) { var d = delta / 1000; this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); } } } else { this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; } Position.prepare(); Droppables.show(Draggables._lastPointer, this.element); Draggables.notify('onDrag', this); if (this._isScrollChild) { Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; if (Draggables._lastScrollPointer[0] < 0) Draggables._lastScrollPointer[0] = 0; if (Draggables._lastScrollPointer[1] < 0) Draggables._lastScrollPointer[1] = 0; this.draw(Draggables._lastScrollPointer); } if(this.options.change) this.options.change(this); }, _getWindowScroll: function(w) { var T, L, W, H; with (w.document) { if (w.document.documentElement && documentElement.scrollTop) { T = documentElement.scrollTop; L = documentElement.scrollLeft; } else if (w.document.body) { T = body.scrollTop; L = body.scrollLeft; } if (w.innerWidth) { W = w.innerWidth; H = w.innerHeight; } else if (w.document.documentElement && documentElement.clientWidth) { W = documentElement.clientWidth; H = documentElement.clientHeight; } else { W = body.offsetWidth; H = body.offsetHeight; } } return { top: T, left: L, width: W, height: H }; } }); Draggable._dragging = { }; /*--------------------------------------------------------------------------*/ var SortableObserver = Class.create({ initialize: function(element, observer) { this.element = $(element); this.observer = observer; this.lastValue = Sortable.serialize(this.element); }, onStart: function() { this.lastValue = Sortable.serialize(this.element); }, onEnd: function() { Sortable.unmark(); if(this.lastValue != Sortable.serialize(this.element)) this.observer(this.element) } }); var Sortable = { SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, sortables: { }, _findRootElement: function(element) { while (element.tagName.toUpperCase() != "BODY") { if(element.id && Sortable.sortables[element.id]) return element; element = element.parentNode; } }, options: function(element) { element = Sortable._findRootElement($(element)); if(!element) return; return Sortable.sortables[element.id]; }, destroy: function(element){ element = $(element); var s = Sortable.sortables[element.id]; if(s) { Draggables.removeObserver(s.element); s.droppables.each(function(d){ Droppables.remove(d) }); s.draggables.invoke('destroy'); delete Sortable.sortables[s.element.id]; } }, create: function(element) { element = $(element); var options = Object.extend({ element: element, tag: 'li', // assumes li children, override with tag: 'tagname' dropOnEmpty: false, tree: false, treeTag: 'ul', overlap: 'vertical', // one of 'vertical', 'horizontal' constraint: 'vertical', // one of 'vertical', 'horizontal', false containment: element, // also takes array of elements (or id's); or false handle: false, // or a CSS class only: false, delay: 0, hoverclass: null, ghosting: false, quiet: false, scroll: false, scrollSensitivity: 20, scrollSpeed: 15, format: this.SERIALIZE_RULE, // these take arrays of elements or ids and can be // used for better initialization performance elements: false, handles: false, onChange: Prototype.emptyFunction, onUpdate: Prototype.emptyFunction }, arguments[1] || { }); // clear any old sortable with same element this.destroy(element); // build options for the draggables var options_for_draggable = { revert: true, quiet: options.quiet, scroll: options.scroll, scrollSpeed: options.scrollSpeed, scrollSensitivity: options.scrollSensitivity, delay: options.delay, ghosting: options.ghosting, constraint: options.constraint, handle: options.handle }; if(options.starteffect) options_for_draggable.starteffect = options.starteffect; if(options.reverteffect) options_for_draggable.reverteffect = options.reverteffect; else if(options.ghosting) options_for_draggable.reverteffect = function(element) { element.style.top = 0; element.style.left = 0; }; if(options.endeffect) options_for_draggable.endeffect = options.endeffect; if(options.zindex) options_for_draggable.zindex = options.zindex; // build options for the droppables var options_for_droppable = { overlap: options.overlap, containment: options.containment, tree: options.tree, hoverclass: options.hoverclass, onHover: Sortable.onHover }; var options_for_tree = { onHover: Sortable.onEmptyHover, overlap: options.overlap, containment: options.containment, hoverclass: options.hoverclass }; // fix for gecko engine Element.cleanWhitespace(element); options.draggables = []; options.droppables = []; // drop on empty handling if(options.dropOnEmpty || options.tree) { Droppables.add(element, options_for_tree); options.droppables.push(element); } (options.elements || this.findElements(element, options) || []).each( function(e,i) { var handle = options.handles ? $(options.handles[i]) : (options.handle ? $(e).select('.' + options.handle)[0] : e); options.draggables.push( new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); Droppables.add(e, options_for_droppable); if(options.tree) e.treeNode = element; options.droppables.push(e); }); if(options.tree) { (Sortable.findTreeElements(element, options) || []).each( function(e) { Droppables.add(e, options_for_tree); e.treeNode = element; options.droppables.push(e); }); } // keep reference this.sortables[element.id] = options; // for onupdate Draggables.addObserver(new SortableObserver(element, options.onUpdate)); }, // return all suitable-for-sortable elements in a guaranteed order findElements: function(element, options) { return Element.findChildren( element, options.only, options.tree ? true : false, options.tag); }, findTreeElements: function(element, options) { return Element.findChildren( element, options.only, options.tree ? true : false, options.treeTag); }, onHover: function(element, dropon, overlap) { if(Element.isParent(dropon, element)) return; if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { return; } else if(overlap>0.5) { Sortable.mark(dropon, 'before'); if(dropon.previousSibling != element) { var oldParentNode = element.parentNode; element.style.visibility = "hidden"; // fix gecko rendering dropon.parentNode.insertBefore(element, dropon); if(dropon.parentNode!=oldParentNode) Sortable.options(oldParentNode).onChange(element); Sortable.options(dropon.parentNode).onChange(element); } } else { Sortable.mark(dropon, 'after'); var nextElement = dropon.nextSibling || null; if(nextElement != element) { var oldParentNode = element.parentNode; element.style.visibility = "hidden"; // fix gecko rendering dropon.parentNode.insertBefore(element, nextElement); if(dropon.parentNode!=oldParentNode) Sortable.options(oldParentNode).onChange(element); Sortable.options(dropon.parentNode).onChange(element); } } }, onEmptyHover: function(element, dropon, overlap) { var oldParentNode = element.parentNode; var droponOptions = Sortable.options(dropon); if(!Element.isParent(dropon, element)) { var index; var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); var child = null; if(children) { var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); for (index = 0; index < children.length; index += 1) { if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { offset -= Element.offsetSize (children[index], droponOptions.overlap); } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { child = index + 1 < children.length ? children[index + 1] : null; break; } else { child = children[index]; break; } } } dropon.insertBefore(element, child); Sortable.options(oldParentNode).onChange(element); droponOptions.onChange(element); } }, unmark: function() { if(Sortable._marker) Sortable._marker.hide(); }, mark: function(dropon, position) { // mark on ghosting only var sortable = Sortable.options(dropon.parentNode); if(sortable && !sortable.ghosting) return; if(!Sortable._marker) { Sortable._marker = ($('dropmarker') || Element.extend(document.createElement('DIV'))). hide().addClassName('dropmarker').setStyle({position:'absolute'}); document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); } var offsets = Position.cumulativeOffset(dropon); Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); if(position=='after') if(sortable.overlap == 'horizontal') Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); else Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); Sortable._marker.show(); }, _tree: function(element, options, parent) { var children = Sortable.findElements(element, options) || []; for (var i = 0; i < children.length; ++i) { var match = children[i].id.match(options.format); if (!match) continue; var child = { id: encodeURIComponent(match ? match[1] : null), element: element, parent: parent, children: [], position: parent.children.length, container: $(children[i]).down(options.treeTag) }; /* Get the element containing the children and recurse over it */ if (child.container) this._tree(child.container, options, child); parent.children.push (child); } return parent; }, tree: function(element) { element = $(element); var sortableOptions = this.options(element); var options = Object.extend({ tag: sortableOptions.tag, treeTag: sortableOptions.treeTag, only: sortableOptions.only, name: element.id, format: sortableOptions.format }, arguments[1] || { }); var root = { id: null, parent: null, children: [], container: element, position: 0 }; return Sortable._tree(element, options, root); }, /* Construct a [i] index for a particular node */ _constructIndex: function(node) { var index = ''; do { if (node.id) index = '[' + node.position + ']' + index; } while ((node = node.parent) != null); return index; }, sequence: function(element) { element = $(element); var options = Object.extend(this.options(element), arguments[1] || { }); return $(this.findElements(element, options) || []).map( function(item) { return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; }); }, setSequence: function(element, new_sequence) { element = $(element); var options = Object.extend(this.options(element), arguments[2] || { }); var nodeMap = { }; this.findElements(element, options).each( function(n) { if (n.id.match(options.format)) nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; n.parentNode.removeChild(n); }); new_sequence.each(function(ident) { var n = nodeMap[ident]; if (n) { n[1].appendChild(n[0]); delete nodeMap[ident]; } }); }, serialize: function(element) { element = $(element); var options = Object.extend(Sortable.options(element), arguments[1] || { }); var name = encodeURIComponent( (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); if (options.tree) { return Sortable.tree(element, arguments[1]).children.map( function (item) { return [name + Sortable._constructIndex(item) + "[id]=" + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); }).flatten().join('&'); } else { return Sortable.sequence(element, arguments[1]).map( function(item) { return name + "[]=" + encodeURIComponent(item); }).join('&'); } } }; // Returns true if child is contained within element Element.isParent = function(child, element) { if (!child.parentNode || child == element) return false; if (child.parentNode == element) return true; return Element.isParent(child.parentNode, element); }; Element.findChildren = function(element, only, recursive, tagName) { if(!element.hasChildNodes()) return null; tagName = tagName.toUpperCase(); if(only) only = [only].flatten(); var elements = []; $A(element.childNodes).each( function(e) { if(e.tagName && e.tagName.toUpperCase()==tagName && (!only || (Element.classNames(e).detect(function(v) { return only.include(v) })))) elements.push(e); if(recursive) { var grandchildren = Element.findChildren(e, only, recursive, tagName); if(grandchildren) elements.push(grandchildren); } }); return (elements.length>0 ? elements.flatten() : []); }; Element.offsetSize = function (element, type) { return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; };
{ "pile_set_name": "Github" }
{ "name": "map-canvas", "version": "1.0.0", "description": "基于baidu、google、openlayers、arcgis、高德地图、canvas数据可视化", "main": "rollup.config.js", "scripts": { "mini": "npm run build && uglifyjs build/baidu-map-lineGradient.js -c -m -o build/release/baidu-map-lineGradient.min.js", "build": "rollup -c", "watch": "npm-watch", "test": "npm run build" }, "watch": { "build": { "patterns": [ "src", "main.js" ], "extensions": "js,jsx", "ignore": "" } }, "repository": { "type": "git", "url": "git+https://github.com/chengquan223/map-canvas.git" }, "keywords": [ "baidu", "arcgis", "amap", "google", "openlayers", "canvas", "visualization" ], "author": "[email protected]", "license": "ISC", "bugs": { "url": "https://github.com/chengquan223/map-canvas/issues" }, "homepage": "https://github.com/chengquan223/map-canvas#readme", "devDependencies": { "babel-preset-es2015-rollup": "^3.0.0", "npm-watch": "^0.3.0", "rollup": "^0.41.5", "rollup-plugin-babel": "^2.7.1", "uglify-js": "^3.3.8" }, "dependencies": { "lodash": "^4.17.19", "mixin-deep": "^2.0.1", "set-value": "^3.0.1" } }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2019 Infostretch Corporation * * 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 com.qmetry.qaf.automation.ui; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.impl.LogFactoryImpl; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.qmetry.qaf.automation.core.AutomationError; import com.qmetry.qaf.automation.core.ConfigurationManager; import com.qmetry.qaf.automation.core.DriverFactory; import com.qmetry.qaf.automation.core.LoggingBean; import com.qmetry.qaf.automation.core.QAFListener; import com.qmetry.qaf.automation.core.QAFTestBase.STBArgs; import com.qmetry.qaf.automation.keys.ApplicationProperties; import com.qmetry.qaf.automation.ui.selenium.webdriver.SeleniumDriverFactory; import com.qmetry.qaf.automation.ui.webdriver.ChromeDriverHelper; import com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver; import com.qmetry.qaf.automation.ui.webdriver.QAFWebDriverCommandListener; import com.qmetry.qaf.automation.util.StringUtil; /** * com.qmetry.qaf.automation.ui.UiDriverFactory.java * * @author chirag */ public class UiDriverFactory implements DriverFactory<UiDriver> { private static final Log logger = LogFactoryImpl.getLog(UiDriverFactory.class); /* * (non-Javadoc) * * @see com.qmetry.qaf.automation.core.DriverFactory#get(java.lang.String[]) */ @Override public UiDriver get(ArrayList<LoggingBean> commandLog, String[] stb) { WebDriverCommandLogger cmdLogger = new WebDriverCommandLogger(commandLog); String browser = STBArgs.browser_str.getFrom(stb); logger.info("Driver: " + browser); if (browser.toLowerCase().contains("driver") && !browser.startsWith("*")) { return getDriver(cmdLogger, stb); } return new SeleniumDriverFactory().getDriver(cmdLogger, stb); } @Override public void tearDown(UiDriver driver) { try { driver.stop(); logger.info("UI-driver tear down complete..."); } catch (Throwable t) { logger.error(t.getMessage()); } } /** * Utility method to get capability that will be used by factory to create * driver object. It will not include any modification done by * {@link QAFWebDriverCommandListener#beforeInitialize(Capabilities)} * * @param driverName * @return */ public static DesiredCapabilities getDesiredCapabilities(String driverName) { return Browsers.getBrowser(driverName).getDesiredCapabilities(); } public static String[] checkAndStartServer(String... args) { if (!isServerRequired(args)) { return args; } if (isSeverRunning(STBArgs.sel_server.getFrom(args), Integer.parseInt(STBArgs.port.getFrom(args)))) { return args; } // override args values to default args = STBArgs.sel_server.set(STBArgs.sel_server.getDefaultVal(), args); if (isSeverRunning(STBArgs.sel_server.getFrom(args), Integer.parseInt(STBArgs.port.getFrom(args)))) { logger.info("Assigning server running on localhost"); return args; } return args; } private static boolean isServerRequired(String... args) { String browser = STBArgs.browser_str.getFrom(args).toLowerCase(); return browser.contains("*") || browser.contains("remote"); } private static boolean isSeverRunning(String host, int port) { boolean isRunning = false; Socket socket = null; try { socket = new Socket(host, (port)); isRunning = socket.isConnected(); } catch (Exception exp) { logger.error("Error occured while checking Selenium : " + exp.getMessage()); } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { } } return isRunning; } private static void beforeInitialize(Capabilities desiredCapabilities, Collection<QAFWebDriverCommandListener> listners) { if ((listners != null) && !listners.isEmpty()) { for (QAFWebDriverCommandListener listener : listners) { listener.beforeInitialize(desiredCapabilities); } } } private static void onInitializationFailure(Capabilities desiredCapabilities, Throwable e, Collection<QAFWebDriverCommandListener> listners) { if ((listners != null) && !listners.isEmpty()) { for (QAFWebDriverCommandListener listener : listners) { listener.onInitializationFailure(desiredCapabilities, e); } } } private static Collection<QAFWebDriverCommandListener> getDriverListeners() { LinkedHashSet<QAFWebDriverCommandListener> listners = new LinkedHashSet<QAFWebDriverCommandListener>(); String[] clistners = ConfigurationManager.getBundle() .getStringArray(ApplicationProperties.WEBDRIVER_COMMAND_LISTENERS.key); for (String listenr : clistners) { try { QAFWebDriverCommandListener cls = (QAFWebDriverCommandListener) Class.forName(listenr).newInstance(); listners.add(cls); } catch (Exception e) { logger.error("Unable to register listener class " + listenr, e); } } clistners = ConfigurationManager.getBundle().getStringArray(ApplicationProperties.QAF_LISTENERS.key); for (String listener : clistners) { try { QAFListener cls = (QAFListener) Class.forName(listener).newInstance(); if (QAFWebDriverCommandListener.class.isAssignableFrom(cls.getClass())) listners.add((QAFWebDriverCommandListener) cls); } catch (Exception e) { logger.error("Unable to register class as driver listener: " + listener, e); } } return listners; } private static QAFExtendedWebDriver getDriver(WebDriverCommandLogger reporter, String... args) { String b = STBArgs.browser_str.getFrom(args).toLowerCase(); String urlStr = STBArgs.sel_server.getFrom(args).startsWith("http") ? STBArgs.sel_server.getFrom(args) : String.format("http://%s:%s/wd/hub", STBArgs.sel_server.getFrom(args), STBArgs.port.getFrom(args)); Browsers browser = Browsers.getBrowser(b); loadDriverResouces(browser); ConfigurationManager.getBundle().setProperty("driver.desiredCapabilities", browser.getDesiredCapabilities().asMap()); QAFExtendedWebDriver driver = b.contains("remote") ? browser.getDriver(urlStr, reporter) : browser.getDriver(reporter, urlStr); ConfigurationManager.getBundle().setProperty("driver.actualCapabilities", driver.getCapabilities().asMap()); return driver; } private static void loadDriverResouces(Browsers browser) { String driverResourcesKey = String.format(ApplicationProperties.DRIVER_RESOURCES_FORMAT.key, browser.browserName); String driverResources = ConfigurationManager.getBundle().getString(driverResourcesKey, ""); if (StringUtil.isNotBlank(driverResources)) { ConfigurationManager.addBundle(driverResources); } } public static void loadDriverResouces(String driverName) { Browsers browser = Browsers.getBrowser(driverName); loadDriverResouces(browser); } private static WebDriver getDriverObj(Class<? extends WebDriver> of, Capabilities capabilities, String urlStr) { try { //give it first try Constructor<? extends WebDriver> constructor = of.getConstructor(URL.class, Capabilities.class); return constructor.newInstance(new URL(urlStr), capabilities); } catch (Exception ex) { try { Constructor<? extends WebDriver> constructor = of.getConstructor(Capabilities.class); return constructor.newInstance(capabilities); } catch (Exception e) { if (e.getCause() != null && e.getCause() instanceof WebDriverException) { throw (WebDriverException) e.getCause(); } try { return of.newInstance(); } catch (Exception e1) { try { //give it another try Constructor<? extends WebDriver> constructor = of.getConstructor(URL.class, Capabilities.class); return constructor.newInstance(new URL(urlStr), capabilities); } catch (InvocationTargetException e2) { throw new WebDriverException(e2.getTargetException()); } catch (InstantiationException e2) { throw new WebDriverException(e2); } catch (IllegalAccessException e2) { throw new WebDriverException(e2); } catch (IllegalArgumentException e2) { throw new WebDriverException(e2); } catch (MalformedURLException e2) { throw new WebDriverException(e2); } catch (NoSuchMethodException e2) { throw new WebDriverException(e2); } catch (SecurityException e2) { throw new WebDriverException(e2); } } } } } private enum Browsers { edge(DesiredCapabilities.edge(), EdgeDriver.class), firefox(DesiredCapabilities.firefox(), FirefoxDriver.class), iexplorer(DesiredCapabilities.internetExplorer(), InternetExplorerDriver.class), chrome(DesiredCapabilities.chrome(), ChromeDriver.class), opera( DesiredCapabilities.operaBlink(), "com.opera.core.systems.OperaDriver"), android(new DesiredCapabilities("android", "", Platform.ANDROID), "org.openqa.selenium.android.AndroidDriver"), iphone( new DesiredCapabilities("iPhone", "", Platform.MAC), "org.openqa.selenium.iphone.IPhoneDriver"), ipad( new DesiredCapabilities("iPad", "", Platform.MAC), "org.openqa.selenium.iphone.IPhoneDriver"), safari( DesiredCapabilities.safari(), "org.openqa.selenium.safari.SafariDriver"), appium( new DesiredCapabilities(), "io.appium.java_client.AppiumDriver"), perfecto( new DesiredCapabilities()), /** * can with assumption that you have set desired capabilities using * property. This is to provide support for future drivers or custom * drivers if any. You can provide driver class as capability : * driver.class, for example :<br> * driver.class=org.openqa.selenium.safari.SafariDriver */ other(new DesiredCapabilities()); private DesiredCapabilities desiredCapabilities; private Class<? extends WebDriver> driverCls = null; private String browserName = name(); private Browsers(Capabilities desiredCapabilities) { this.desiredCapabilities = new DesiredCapabilities(desiredCapabilities.asMap()); this.desiredCapabilities.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT,true); this.desiredCapabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true); this.desiredCapabilities.setCapability(CapabilityType.SUPPORTS_FINDING_BY_CSS, true); } @SuppressWarnings("unchecked") private Browsers(Capabilities desiredCapabilities, String drivercls) { this(desiredCapabilities); if (null == driverCls) { // not overridden by extra capability try { driverCls = (Class<? extends WebDriver>) Class.forName(drivercls); } catch (Exception e) { // throw new AutomationError(e); } } } private Browsers(Capabilities desiredCapabilities, Class<? extends WebDriver> driver) { this(desiredCapabilities); if (null == driverCls) { // not overridden by extra capability driverCls = driver; } } @SuppressWarnings("unchecked") private DesiredCapabilities getDesiredCapabilities() { Map<String, Object> capabilities = new HashMap<String, Object>(desiredCapabilities.asMap()); Gson gson = new GsonBuilder().create(); // capabilities provided for all driver Map<String, Object> extraCapabilities = gson .fromJson(ApplicationProperties.DRIVER_ADDITIONAL_CAPABILITIES.getStringVal("{}"), Map.class); capabilities.putAll(extraCapabilities); // individual capability property for all driver Configuration config = ConfigurationManager.getBundle() .subset(ApplicationProperties.DRIVER_CAPABILITY_PREFIX.key); capabilities.putAll(new ConfigurationMap(config)); //#332 add default capabilities for standard driver if(!name().equalsIgnoreCase(other.name())){ String driverCapsKey = String.format(ApplicationProperties.DRIVER_ADDITIONAL_CAPABILITIES_FORMAT.key, name()); extraCapabilities = gson.fromJson(ConfigurationManager.getBundle().getString(driverCapsKey, "{}"), Map.class); capabilities.putAll(extraCapabilities); } // capabilities specific to this driver String driverCapsKey = String.format(ApplicationProperties.DRIVER_ADDITIONAL_CAPABILITIES_FORMAT.key, browserName); extraCapabilities = gson.fromJson(ConfigurationManager.getBundle().getString(driverCapsKey, "{}"), Map.class); capabilities.putAll(extraCapabilities); // individual capability property with driver name prefix String driverCapKey = String.format(ApplicationProperties.DRIVER_CAPABILITY_PREFIX_FORMAT.key, browserName); config = ConfigurationManager.getBundle().subset(driverCapKey); capabilities.putAll(new ConfigurationMap(config)); Object driverclass = capabilities.get(ApplicationProperties.CAPABILITY_NAME_DRIVER_CLASS.key); if (null == driverclass) {// backward compatibility only driverclass = capabilities.get("driver.class"); } if (null != driverclass) { try { driverCls = (Class<? extends WebDriver>) Class.forName(String.valueOf(driverclass)); } catch (Exception e) { // throw new AutomationError(e); } } for(String key : capabilities.keySet()){ Object value = capabilities.get(key); if(value instanceof String){ capabilities.put(key, ConfigurationManager.getBundle().getSubstitutor().replace(value)); } } return new DesiredCapabilities(capabilities); } private static Browsers getBrowser(String name) { for (Browsers browser : Browsers.values()) { if (name.contains(browser.name())) { browser.setBrowserName(name); return browser; } } Browsers b = Browsers.other; b.setBrowserName(name); return b; } private void setBrowserName(String name) { // remove driver and remote from name browserName = name.replaceAll("(?i)remote|driver", ""); } private QAFExtendedWebDriver getDriver(WebDriverCommandLogger reporter, String urlstr) { Capabilities desiredCapabilities = getDesiredCapabilities(); Collection<QAFWebDriverCommandListener> listners = getDriverListeners(); beforeInitialize(desiredCapabilities, listners); try { if (this.name().equalsIgnoreCase("chrome")) { return new QAFExtendedWebDriver(ChromeDriverHelper.getService().getUrl(), desiredCapabilities, reporter); } WebDriver driver = getDriverObj(driverCls, desiredCapabilities, urlstr);// driverCls.newInstance(); return new QAFExtendedWebDriver(driver, reporter); } catch (Throwable e) { onInitializationFailure(desiredCapabilities, e, listners); throw new AutomationError("Unable to Create Driver Instance for " + browserName + ": " + e.getMessage(), e); } } private QAFExtendedWebDriver getDriver(String url, WebDriverCommandLogger reporter) { Capabilities desiredCapabilities = getDesiredCapabilities(); Collection<QAFWebDriverCommandListener> listners = getDriverListeners(); beforeInitialize(desiredCapabilities, listners); try { if (StringUtil.isNotBlank(ApplicationProperties.WEBDRIVER_REMOTE_SESSION.getStringVal()) || desiredCapabilities.asMap() .containsKey(ApplicationProperties.WEBDRIVER_REMOTE_SESSION.key)) { Constructor<?> constructor = Class .forName("com.qmetry.qaf.automation.ui.webdriver.LiveIsExtendedWebDriver") .getDeclaredConstructor(URL.class, Capabilities.class, WebDriverCommandLogger.class); return (QAFExtendedWebDriver) constructor.newInstance(new URL(url), desiredCapabilities, reporter); } return new QAFExtendedWebDriver(new URL(url), desiredCapabilities, reporter); } catch (Throwable e) { onInitializationFailure(desiredCapabilities, e, listners); throw new AutomationError("Unable to Create Driver Instance " + e.getMessage(), e); } } } }
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "filename" : "video-play.png", "scale" : "1x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "2x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
import {EventEmitter} from 'events'; /** * Require options for a VM */ export interface VMRequire { /** Array of allowed builtin modules, accepts ["*"] for all (default: none) */ builtin?: string[]; /* * `host` (default) to require modules in host and proxy them to sandbox. `sandbox` to load, compile and * require modules in sandbox. Builtin modules except `events` always required in host and proxied to sandbox */ context?: "host" | "sandbox"; /** `true` or an array of allowed external modules (default: `false`) */ external?: boolean | string[]; /** Array of modules to be loaded into NodeVM on start. */ import?: string[]; /** Restricted path where local modules can be required (default: every path). */ root?: string; /** Collection of mock modules (both external or builtin). */ mock?: any; } /** * A custom compiler function for all of the JS that comes * into the VM */ type CompilerFunction = (code: string, filename: string) => string; /** * Options for creating a VM */ export interface VMOptions { /** * `javascript` (default) or `coffeescript` or custom compiler function (which receives the code, and it's filepath). * The library expects you to have coffee-script pre-installed if the compiler is set to `coffeescript`. */ compiler?: "javascript" | "coffeescript" | CompilerFunction; /** VM's global object. */ sandbox?: any; /** * Script timeout in milliseconds. Timeout is only effective on code you run through `run`. * Timeout is NOT effective on any method returned by VM. */ timeout?: number; } /** * Options for creating a NodeVM */ export interface NodeVMOptions extends VMOptions { /** `inherit` to enable console, `redirect` to redirect to events, `off` to disable console (default: `inherit`). */ console?: "inherit" | "redirect" | "off"; /** `true` or an object to enable `require` optionss (default: `false`). */ require?: true | VMRequire; /** `true` to enable VMs nesting (default: `false`). */ nesting?: boolean; /** `commonjs` (default) to wrap script into CommonJS wrapper, `none` to retrieve value returned by the script. */ wrapper?: "commonjs" | "none"; /** File extensions that the internal module resolver should accept. */ sourceExtensions?: string[] } /** * A VM with behavior more similar to running inside Node. */ export class NodeVM extends EventEmitter { constructor(options?: NodeVMOptions); /** Runs the code */ run(js: string, path: string): any; /** Runs the VMScript object */ run(script: VMScript, path?: string): any; /** Freezes the object inside VM making it read-only. Not available for primitive values. */ freeze(object: any, name: string): any; /** Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values. */ protect(object: any, name: string): any; /** Require a module in VM and return it's exports. */ require(module: string): any; } /** * VM is a simple sandbox, without `require` feature, to synchronously run an untrusted code. * Only JavaScript built-in objects + Buffer are available. Scheduling functions * (`setInterval`, `setTimeout` and `setImmediate`) are not available by default. */ export class VM { constructor(options?: VMOptions); /** Runs the code */ run(js: string): any; /** Runs the VMScript object */ run(script: VMScript): any; /** Freezes the object inside VM making it read-only. Not available for primitive values. */ freeze(object: any, name: string): any; /** Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values */ protect(object: any, name: string): any; /** * Create NodeVM and run code inside it. * * @param {String} script Javascript code. * @param {String} [filename] File name (used in stack traces only). * @param {Object} [options] VM options. */ static code(script: string, filename: string, options: NodeVMOptions): NodeVM; /** * Create NodeVM and run script from file inside it. * * @param {String} [filename] File name (used in stack traces only). * @param {Object} [options] VM options. */ static file(filename: string, options: NodeVMOptions): NodeVM } /** * You can increase performance by using pre-compiled scripts. * The pre-compiled VMScript can be run later multiple times. It is important to note that the code is not bound * to any VM (context); rather, it is bound before each run, just for that run. */ export class VMScript { constructor(code: string, path?: string); /** Wraps the code */ wrap(prefix: string, postfix: string): VMScript; /** Compiles the code. If called multiple times, the code is only compiled once. */ compile(): any; } /** Custom Error class */ export class VMError extends Error {}
{ "pile_set_name": "Github" }
MauvilleCity_BikeShop_Text_180F9F:: @ 8180F9F .string "Well, well, what have we here?\n" .string "A most energetic customer!\p" .string "Me? You may call me RYDEL.\n" .string "I'm the owner of this cycle shop.$" MauvilleCity_BikeShop_Text_181016:: @ 8181016 .string "RYDEL: Your RUNNING SHOES...\n" .string "They're awfully filthy.\p" .string "Did you come from far away?$" MauvilleCity_BikeShop_Text_181067:: @ 8181067 .string "RYDEL: Is that right?\p" .string "Then, I guess you have no need for\n" .string "any of my BIKES.$" MauvilleCity_BikeShop_Text_1810B1:: @ 81810B1 .string "RYDEL: Hm, hm... ... ... ... ...\n" .string "... ... ... ... ... ... ... ...\p" .string "You're saying that you came all this\n" .string "way from LITTLEROOT?\p" .string "My goodness!\n" .string "That's ridiculously far!\p" .string "If you had one of my BIKES, you could\n" .string "go anywhere easily while feeling the\l" .string "gentle caress of the wind!\p" .string "I'll tell you what!\n" .string "I'll give you a BIKE!\p" .string "Oh, wait a second!\p" .string "I forgot to tell you that there are\n" .string "two kinds of BIKES!\p" .string "They are the MACH BIKE and the\n" .string "ACRO BIKE!\p" .string "MACH BIKE is for cyclists who want\n" .string "to feel the wind with their bodies!\p" .string "And an ACRO BIKE is for those who\n" .string "prefer technical rides!\p" .string "I'm a real sweetheart, so you can\n" .string "have whichever one you like!\p" .string "Which one will you choose?$" MauvilleCity_BikeShop_Text_181332:: @ 8181332 .string "{PLAYER} chose the MACH BIKE.$" MauvilleCity_BikeShop_Text_18134A:: @ 818134A .string "{PLAYER} chose the ACRO BIKE.$" MauvilleCity_BikeShop_Text_181362:: @ 8181362 .string "RYDEL: If you get the urge to switch\n" .string "BIKES, just come see me!$" MauvilleCity_BikeShop_Text_1813A0:: @ 81813A0 .string "RYDEL: Oh? Were you thinking about\n" .string "switching BIKES?$" MauvilleCity_BikeShop_Text_1813D4:: @ 81813D4 .string "RYDEL: Okay, no problem!\n" .string "I'll switch BIKES for you!$" MauvilleCity_BikeShop_Text_181408:: @ 8181408 .string "{PLAYER} got the MACH BIKE exchanged\n" .string "for an ACRO BIKE.$" MauvilleCity_BikeShop_Text_181439:: @ 8181439 .string "{PLAYER} got the ACRO BIKE exchanged\n" .string "for a MACH BIKE.$" MauvilleCity_BikeShop_Text_181469:: @ 8181469 .string "RYDEL: Good, good!\n" .string "I'm happy that you like it!$" MauvilleCity_BikeShop_Text_181498:: @ 8181498 .string "Oh? What happened to that BIKE I\n" .string "gave you?\p" .string "Oh, I get it, you stored it using your PC.\p" .string "Well, take it out of PC storage,\n" .string "and I'll be happy to exchange it!\p" .string "May the wind always be at your back\n" .string "on your adventure!$" MauvilleCity_BikeShop_Text_181568:: @ 8181568 .string "I'm learning about BIKES while\n" .string "I work here.\p" .string "If you need advice on how to ride your\n" .string "BIKE, there're a couple handbooks in\l" .string "the back.$" MauvilleCity_BikeShop_Text_1815EA:: @ 81815EA .string "It's a handbook on the MACH BIKE.\p" .string "Which page do you want to read?$" MauvilleCity_BikeShop_Text_18162C:: @ 818162C .string "A BIKE moves in the direction that\n" .string "the + Control Pad is pressed.\p" .string "It will speed up once it gets rolling.\p" .string "To stop, release the + Control Pad.\n" .string "The BIKE will slow to a stop.\p" .string "Want to read a different page?$" MauvilleCity_BikeShop_Text_1816F5:: @ 81816F5 .string "A MACH BIKE is speedy, but it can't\n" .string "stop very quickly.\p" .string "It gets a little tricky to get around\n" .string "a corner.\p" .string "Release the + Control Pad a little\n" .string "before the corner and slow down.\p" .string "Want to read a different page?$" MauvilleCity_BikeShop_Text_1817BF:: @ 81817BF .string "There are small sandy slopes throughout\n" .string "the HOENN region.\p" .string "The loose, crumbly sand makes it\n" .string "impossible to climb normally.\p" .string "But if you have a MACH BIKE, you can\n" .string "zip up a sandy slope.\p" .string "Want to read a different page?$" MauvilleCity_BikeShop_Text_181892:: @ 8181892 .string "It's a handbook on the ACRO BIKE.\p" .string "Which page do you want to read?$" MauvilleCity_BikeShop_Text_1818D4:: @ 81818D4 .string "Press the B Button while riding, and the\n" .string "front wheel lifts up.\p" .string "You can zip around with the front\n" .string "wheel up using the + Control Pad.\p" .string "This technique is called a wheelie.\p" .string "Want to read a different page?$" MauvilleCity_BikeShop_Text_18199A:: @ 818199A .string "Keeping the B Button pressed, your\n" .string "BIKE can hop on the spot.\p" .string "This technique is called a bunny hop.\p" .string "You can ride while hopping, too.\p" .string "Want to read a different page?$" MauvilleCity_BikeShop_Text_181A3D:: @ 8181A3D .string "Press the B Button and the + Control\n" .string "Pad at the same time to jump.\p" .string "Press the + Control Pad to the side\n" .string "to jump sideways.\p" .string "Press it backwards to make the BIKE\n" .string "change directions while jumping.\p" .string "Want to read a different page?$"
{ "pile_set_name": "Github" }
package com.coderising.ood.srp; import com.coderising.ood.srp.utils.DBUtil; import com.coderising.ood.srp.utils.MailUtil; import com.coderising.ood.srp.utils.ArgsUtil; import java.io.IOException; import java.util.*; /** * PromotionMail * * @author Chenpz * @package com.coderising.ood.srp * @date 2017/6/12/23:33 */ public class PromotionMail { private ProductInfo productInfo; private List<MailInfo> mailInfoList = new ArrayList<>(); private static final String NAME_KEY = "NAME"; private static final String EMAIL_KEY = "EMAIL"; public PromotionMail(){} public PromotionMail(ProductInfo productInfo) throws Exception { this.productInfo = productInfo; initMailInfoList(loadMailingList()); } /** * 获取每个型号的手机关注的人员信息列表 * @return * @throws Exception */ private List<Map<String, String>> loadMailingList() throws Exception { String sql = "select name from subscriptions " + "where product_id= '" + productInfo.getProductID() +"' " + "and send_mail=1 "; return DBUtil.query(sql); } /** * 组装促销邮件的内容信息 * @param mailingList */ private void initMailInfoList(List<Map<String, String>> mailingList) { if (ArgsUtil.isNotEmpty(mailingList)){ for (Map<String, String> map : mailingList){ // 初始化 mailInfoList mailInfoList.add(buildMailInfo(map)); } } } /** * 组装邮件内容信息 * @param userInfo * @return */ private MailInfo buildMailInfo(Map<String, String> userInfo){ String name = userInfo.get(NAME_KEY); String subject = "您关注的产品降价了"; String message = "尊敬的 "+name+", 您关注的产品 " + productInfo.getProductDesc() + " 降价了,欢迎购买!" ; String toAddress = userInfo.get(EMAIL_KEY); return new MailInfo(toAddress, subject, message); } /** * 发送促销邮件 * @param debug * @throws IOException */ public void sendEMails(boolean debug) throws IOException { System.out.println("开始发送邮件... ..."); if (ArgsUtil.isNotEmpty(mailInfoList)) { for (MailInfo mailInfo : mailInfoList){ MailUtil.sendEmail(mailInfo.toAddress, mailInfo.subject, mailInfo.message, debug); } }else { System.out.println("没有邮件发送... ..."); } } class MailInfo{ private String toAddress = null; private String subject = null; private String message = null; MailInfo(String toAddress, String subject, String message){ this.toAddress = toAddress; this.subject = subject; this.message = message; } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <message> <name>MFNM14</name> <description>Master File Notification - Site Defined</description> <segments> <segment>MSH</segment> <segment minOccurs="0" maxOccurs="unbounded">SFT</segment> <segment>MFI</segment> <group maxOccurs="unbounded"> <segment>MFE</segment> <segment>ANY</segment> </group> </segments> </message>
{ "pile_set_name": "Github" }
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) (* v * Copyright INRIA, CNRS and contributors *) (* <O___,, * (see version control and CREDITS file for authors & dates) *) (* \VV/ **************************************************************) (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (* * (see LICENSE file for the text of the license) *) (************************************************************************) (** * Hexadecimal numbers *) (** These numbers coded in base 16 will be used for parsing and printing other Coq numeral datatypes in an human-readable way. See the [Numeral Notation] command. We represent numbers in base 16 as lists of hexadecimal digits, in big-endian order (most significant digit comes first). *) Require Import Datatypes Decimal. (** Unsigned integers are just lists of digits. For instance, sixteen is (D1 (D0 Nil)) *) Inductive uint := | Nil | D0 (_:uint) | D1 (_:uint) | D2 (_:uint) | D3 (_:uint) | D4 (_:uint) | D5 (_:uint) | D6 (_:uint) | D7 (_:uint) | D8 (_:uint) | D9 (_:uint) | Da (_:uint) | Db (_:uint) | Dc (_:uint) | Dd (_:uint) | De (_:uint) | Df (_:uint). (** [Nil] is the number terminator. Taken alone, it behaves as zero, but rather use [D0 Nil] instead, since this form will be denoted as [0], while [Nil] will be printed as [Nil]. *) Notation zero := (D0 Nil). (** For signed integers, we use two constructors [Pos] and [Neg]. *) Variant int := Pos (d:uint) | Neg (d:uint). (** For decimal numbers, we use two constructors [Hexadecimal] and [HexadecimalExp], depending on whether or not they are given with an exponent (e.g., 0x1.a2p+01). [i] is the integral part while [f] is the fractional part (beware that leading zeroes do matter). *) Variant hexadecimal := | Hexadecimal (i:int) (f:uint) | HexadecimalExp (i:int) (f:uint) (e:Decimal.int). Declare Scope hex_uint_scope. Delimit Scope hex_uint_scope with huint. Bind Scope hex_uint_scope with uint. Declare Scope hex_int_scope. Delimit Scope hex_int_scope with hint. Bind Scope hex_int_scope with int. Register uint as num.hexadecimal_uint.type. Register int as num.hexadecimal_int.type. Register hexadecimal as num.hexadecimal.type. Fixpoint nb_digits d := match d with | Nil => O | D0 d | D1 d | D2 d | D3 d | D4 d | D5 d | D6 d | D7 d | D8 d | D9 d | Da d | Db d | Dc d | Dd d | De d | Df d => S (nb_digits d) end. (** This representation favors simplicity over canonicity. For normalizing numbers, we need to remove head zero digits, and choose our canonical representation of 0 (here [D0 Nil] for unsigned numbers and [Pos (D0 Nil)] for signed numbers). *) (** [nzhead] removes all head zero digits *) Fixpoint nzhead d := match d with | D0 d => nzhead d | _ => d end. (** [unorm] : normalization of unsigned integers *) Definition unorm d := match nzhead d with | Nil => zero | d => d end. (** [norm] : normalization of signed integers *) Definition norm d := match d with | Pos d => Pos (unorm d) | Neg d => match nzhead d with | Nil => Pos zero | d => Neg d end end. (** A few easy operations. For more advanced computations, use the conversions with other Coq numeral datatypes (e.g. Z) and the operations on them. *) Definition opp (d:int) := match d with | Pos d => Neg d | Neg d => Pos d end. (** For conversions with binary numbers, it is easier to operate on little-endian numbers. *) Fixpoint revapp (d d' : uint) := match d with | Nil => d' | D0 d => revapp d (D0 d') | D1 d => revapp d (D1 d') | D2 d => revapp d (D2 d') | D3 d => revapp d (D3 d') | D4 d => revapp d (D4 d') | D5 d => revapp d (D5 d') | D6 d => revapp d (D6 d') | D7 d => revapp d (D7 d') | D8 d => revapp d (D8 d') | D9 d => revapp d (D9 d') | Da d => revapp d (Da d') | Db d => revapp d (Db d') | Dc d => revapp d (Dc d') | Dd d => revapp d (Dd d') | De d => revapp d (De d') | Df d => revapp d (Df d') end. Definition rev d := revapp d Nil. Definition app d d' := revapp (rev d) d'. Definition app_int d1 d2 := match d1 with Pos d1 => Pos (app d1 d2) | Neg d1 => Neg (app d1 d2) end. (** [nztail] removes all trailing zero digits and return both the result and the number of removed digits. *) Definition nztail d := let fix aux d_rev := match d_rev with | D0 d_rev => let (r, n) := aux d_rev in pair r (S n) | _ => pair d_rev O end in let (r, n) := aux (rev d) in pair (rev r) n. Definition nztail_int d := match d with | Pos d => let (r, n) := nztail d in pair (Pos r) n | Neg d => let (r, n) := nztail d in pair (Neg r) n end. Module Little. (** Successor of little-endian numbers *) Fixpoint succ d := match d with | Nil => D1 Nil | D0 d => D1 d | D1 d => D2 d | D2 d => D3 d | D3 d => D4 d | D4 d => D5 d | D5 d => D6 d | D6 d => D7 d | D7 d => D8 d | D8 d => D9 d | D9 d => Da d | Da d => Db d | Db d => Dc d | Dc d => Dd d | Dd d => De d | De d => Df d | Df d => D0 (succ d) end. (** Doubling little-endian numbers *) Fixpoint double d := match d with | Nil => Nil | D0 d => D0 (double d) | D1 d => D2 (double d) | D2 d => D4 (double d) | D3 d => D6 (double d) | D4 d => D8 (double d) | D5 d => Da (double d) | D6 d => Dc (double d) | D7 d => De (double d) | D8 d => D0 (succ_double d) | D9 d => D2 (succ_double d) | Da d => D4 (succ_double d) | Db d => D6 (succ_double d) | Dc d => D8 (succ_double d) | Dd d => Da (succ_double d) | De d => Dc (succ_double d) | Df d => De (succ_double d) end with succ_double d := match d with | Nil => D1 Nil | D0 d => D1 (double d) | D1 d => D3 (double d) | D2 d => D5 (double d) | D3 d => D7 (double d) | D4 d => D9 (double d) | D5 d => Db (double d) | D6 d => Dd (double d) | D7 d => Df (double d) | D8 d => D1 (succ_double d) | D9 d => D3 (succ_double d) | Da d => D5 (succ_double d) | Db d => D7 (succ_double d) | Dc d => D9 (succ_double d) | Dd d => Db (succ_double d) | De d => Dd (succ_double d) | Df d => Df (succ_double d) end. End Little.
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2011 Hartmut Kaiser 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) ==============================================================================*/ #if !defined(BOOST_SPIRIT_STREAM_MAY_05_2007_1228PM) #define BOOST_SPIRIT_STREAM_MAY_05_2007_1228PM #if defined(_MSC_VER) #pragma once #endif #include <boost/spirit/home/qi/detail/string_parse.hpp> #include <boost/spirit/home/qi/stream/detail/match_manip.hpp> #include <boost/spirit/home/qi/stream/detail/iterator_source.hpp> #include <boost/spirit/home/support/detail/hold_any.hpp> #include <iosfwd> #include <sstream> /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { /////////////////////////////////////////////////////////////////////////// // Enablers /////////////////////////////////////////////////////////////////////////// template <> struct use_terminal<qi::domain, tag::stream> // enables stream : mpl::true_ {}; template <> struct use_terminal<qi::domain, tag::wstream> // enables wstream : mpl::true_ {}; }} /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { namespace qi { #ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS using spirit::stream; using spirit::wstream; #endif using spirit::stream_type; using spirit::wstream_type; template <typename Char = char, typename T = spirit::basic_hold_any<char> > struct stream_parser : primitive_parser<stream_parser<Char, T> > { template <typename Context, typename Iterator> struct attribute { typedef T type; }; template <typename Iterator, typename Context , typename Skipper, typename Attribute> bool parse(Iterator& first, Iterator const& last , Context& /*context*/, Skipper const& skipper , Attribute& attr_) const { typedef qi::detail::iterator_source<Iterator> source_device; typedef boost::iostreams::stream<source_device> instream; qi::skip_over(first, last, skipper); instream in(first, last); // copies 'first' in >> attr_; // use existing operator>>() // advance the iterator if everything is ok if (in) { if (!in.eof()) { std::streamsize pos = in.tellg(); std::advance(first, pos); } else { first = last; } return true; } return false; } template <typename Context> info what(Context& /*context*/) const { return info("stream"); } }; template <typename T, typename Char = char> struct typed_stream : proto::terminal<stream_parser<Char, T> >::type { }; /////////////////////////////////////////////////////////////////////////// // Parser generators: make_xxx function (objects) /////////////////////////////////////////////////////////////////////////// template <typename Char> struct make_stream { typedef stream_parser<Char> result_type; result_type operator()(unused_type, unused_type) const { return result_type(); } }; template <typename Modifiers> struct make_primitive<tag::stream, Modifiers> : make_stream<char> {}; template <typename Modifiers> struct make_primitive<tag::wstream, Modifiers> : make_stream<wchar_t> {}; }}} #endif
{ "pile_set_name": "Github" }
const nest = require('depnest') const Value = require('mutant/value') const onceTrue = require('mutant/once-true') const computed = require('mutant/computed') const resolve = require('mutant/resolve') const pull = require('pull-stream') const sorted = require('sorted-array-functions') const MutantPullCollection = require('../../mutant-pull-collection') exports.needs = nest({ 'sbot.pull.backlinks': 'first', 'sbot.obs.connection': 'first', 'message.sync.root': 'first', 'sbot.pull.stream': 'first', 'message.sync.timestamp': 'first' }) exports.gives = nest({ 'backlinks.obs.for': true, 'backlinks.obs.references': true, 'backlinks.obs.forks': true }) exports.create = function (api) { const cache = {} const collections = {} let loaded = false // cycle remove sets for fast cleanup let newRemove = new Set() let oldRemove = new Set() // run cache cleanup every 5 seconds // an item will be removed from cache between 5 - 10 seconds after release // this ensures that the data is still available for a page reload const timer = setInterval(() => { oldRemove.forEach(id => { if (cache[id]) { unsubscribe(id) delete collections[id] delete cache[id] } }) oldRemove.clear() // cycle const hold = oldRemove oldRemove = newRemove newRemove = hold }, 5e3) if (timer.unref) timer.unref() return nest({ 'backlinks.obs.for': (id) => backlinks(id), 'backlinks.obs.references': references, 'backlinks.obs.forks': forks }) function references (msg) { const id = msg.key return MutantPullCollection((lastMessage) => { return api.sbot.pull.stream((sbot) => sbot.patchwork.backlinks.referencesStream({ id, since: lastMessage && lastMessage.timestamp })) }) } function forks (msg) { const id = msg.key const rooted = !!api.message.sync.root(msg) if (rooted) { return MutantPullCollection((lastMessage) => { return api.sbot.pull.stream((sbot) => sbot.patchwork.backlinks.forksStream({ id, since: lastMessage && lastMessage.timestamp })) }) } else { return [] } } function backlinks (id) { load() if (!cache[id]) { const sync = Value(false) const collection = Value([]) subscribe(id) process.nextTick(() => { pull( api.sbot.pull.backlinks({ query: [{ $filter: { dest: id } }], index: 'DTA' // use asserted timestamps }), pull.drain((msg) => { const value = resolve(collection) sorted.add(value, msg, compareAsserted) collection.set(value) }, () => { sync.set(true) }) ) }) collections[id] = collection cache[id] = computed([collection], x => x, { onListen: () => use(id), onUnlisten: () => release(id) }) cache[id].sync = sync } return cache[id] } function load () { if (!loaded) { pull( api.sbot.pull.stream(sbot => sbot.patchwork.liveBacklinks.stream()), pull.drain(msg => { const collection = collections[msg.dest] if (collection) { const value = resolve(collection) sorted.add(value, msg, compareAsserted) collection.set(value) } }) ) loaded = true } } function use (id) { newRemove.delete(id) oldRemove.delete(id) } function release (id) { newRemove.add(id) } function subscribe (id) { onceTrue(api.sbot.obs.connection(), (sbot) => sbot.patchwork.liveBacklinks.subscribe(id)) } function unsubscribe (id) { onceTrue(api.sbot.obs.connection(), (sbot) => sbot.patchwork.liveBacklinks.unsubscribe(id)) } function compareAsserted (a, b) { if (isReplyTo(a, b)) { return -1 } else if (isReplyTo(b, a)) { return 1 } else { return api.message.sync.timestamp(a) - api.message.sync.timestamp(b) } } } function isReplyTo (maybeReply, msg) { return (includesOrEquals(maybeReply.branch, msg.key)) } function includesOrEquals (array, value) { if (Array.isArray(array)) { return array.includes(value) } else { return array === value } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.ds; import org.postgresql.ds.common.BaseDataSource; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.sql.SQLException; import javax.sql.DataSource; /** * Simple DataSource which does not perform connection pooling. In order to use the DataSource, you * must set the property databaseName. The settings for serverName, portNumber, user, and password * are optional. Note: these properties are declared in the superclass. * * @author Aaron Mulder ([email protected]) */ public class PGSimpleDataSource extends BaseDataSource implements DataSource, Serializable { /** * Gets a description of this DataSource. */ public String getDescription() { return "Non-Pooling DataSource from " + org.postgresql.util.DriverInfo.DRIVER_FULL_NAME; } private void writeObject(ObjectOutputStream out) throws IOException { writeBaseObject(out); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { readBaseObject(in); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isAssignableFrom(getClass()); } public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isAssignableFrom(getClass())) { return iface.cast(this); } throw new SQLException("Cannot unwrap to " + iface.getName()); } }
{ "pile_set_name": "Github" }
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.source.resolve.reference.impl.manipulators; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiPlainTextFile; import com.intellij.psi.AbstractElementManipulator; import com.intellij.util.IncorrectOperationException; import javax.annotation.Nonnull; /** * Created by IntelliJ IDEA. * User: ik * Date: 09.12.2003 * Time: 14:10:35 * To change this template use Options | File Templates. */ public class PlainFileManipulator extends AbstractElementManipulator<PsiPlainTextFile> { @Override public PsiPlainTextFile handleContentChange(@Nonnull PsiPlainTextFile file, @Nonnull TextRange range, String newContent) throws IncorrectOperationException { final Document document = FileDocumentManager.getInstance().getDocument(file.getVirtualFile()); document.replaceString(range.getStartOffset(), range.getEndOffset(), newContent); PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); return file; } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. module internal FSharp.Compiler.InnerLambdasToTopLevelFuncs open FSharp.Compiler open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.CompilerGlobalState open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Detuple.GlobalUsageAnalysis open FSharp.Compiler.Layout open FSharp.Compiler.Lib open FSharp.Compiler.SyntaxTree open FSharp.Compiler.TypedTree open FSharp.Compiler.TypedTreeBasics open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TypedTreeOps.DebugPrint open FSharp.Compiler.TcGlobals open FSharp.Compiler.XmlDoc let verboseTLR = false //------------------------------------------------------------------------- // library helpers //------------------------------------------------------------------------- let internalError str = dprintf "Error: %s\n" str;raise (Failure str) module Zmap = let force k mp (str, soK) = try Zmap.find k mp with e -> dprintf "Zmap.force: %s %s\n" str (soK k) PreserveStackTrace e raise e //------------------------------------------------------------------------- // misc //------------------------------------------------------------------------- /// tree, used to store dec sequence type Tree<'T> = | TreeNode of Tree<'T> list | LeafNode of 'T let fringeTR tr = let rec collect tr acc = match tr with | TreeNode subts -> List.foldBack collect subts acc | LeafNode x -> x :: acc collect tr [] let emptyTR = TreeNode[] //------------------------------------------------------------------------- // misc //------------------------------------------------------------------------- /// Collapse reclinks on app and combine apps if possible /// recursive ids are inside reclinks and maybe be type instanced with a Expr.App // CLEANUP NOTE: mkApps ensures applications are kept in a collapsed // and combined form, so this function should not be needed let destApp (f, fty, tys, args, m) = match stripExpr f with | Expr.App (f2, fty2, tys2, [], _) -> (f2, fty2, tys2 @ tys, args, m) | Expr.App _ -> (f, fty, tys, args, m) (* has args, so not combine ty args *) | f -> (f, fty, tys, args, m) #if DEBUG let showTyparSet tps = showL (commaListL (List.map typarL (Zset.elements tps))) #endif // CLEANUP NOTE: don't like the look of this function - this distinction // should never be needed let isDelayedRepr (f: Val) e = let _tps, vss, _b, _rty = stripTopLambda (e, f.Type) List.length vss>0 // REVIEW: these should just be replaced by direct calls to mkLocal, mkCompGenLocal etc. // REVIEW: However these set an arity whereas the others don't let mkLocalNameTypeArity compgen m name ty topValInfo = Construct.NewVal(name, m, None, ty, Immutable, compgen, topValInfo, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) //------------------------------------------------------------------------- // definitions: TLR, arity, arity-met, arity-short // // DEFN: An f is TLR with arity wf if // (a) it's repr is "LAM tps. lam x1...xN. body" and have N<=wf (i.e. have enough args) // (b) it has no free tps // (c) for g: freevars(repr), both // (1) g is TLR with arity wg, and // (2) g occurs in arity-met occurrence. // (d) if N=0, then further require that body be a TLR-constant. // // Conditions (a-c) are required if f is to have a static method/field representation. // Condition (d) chooses which constants can be lifted. (no effects, non-trivial). // // DEFN: An arity-met occurrence of g is a g application with enough args supplied, // ie. (g tps args) where wg <= |args|. // // DEFN: An arity-short occurrence does not have enough args. // // DEFN: A TLR-constant: // - can have constructors (tuples, datatype, records, exn). // - should be non-trivial (says, causes allocation). // - if calls are allowed, they must be effect free (since eval point is moving). //------------------------------------------------------------------------- //------------------------------------------------------------------------- // OVERVIEW // Overview of passes (over term) and steps (not over term): // // pass1 - decide which f will be TLR and determine their arity. // pass2 - what closures are needed? Finds reqdTypars(f) and reqdItems(f) for TLR f. // Depends on the arity choice, so must follow pass1. // step3 - choose env packing, create fHats. // pass4 - rewrite term fixing up definitions and callsites. // Depends on closure and env packing, so must follow pass2 (and step 3). // pass5 - copyExpr call to topexpr to ensure all bound ids are unique. // For complexity reasons, better to re-recurse over expr once. // pass6 - sanity check, confirm that all TLR marked bindings meet DEFN. // //------------------------------------------------------------------------- //------------------------------------------------------------------------- // pass1: GetValsBoundUnderMustInline (see comment further below) //------------------------------------------------------------------------- let GetValsBoundUnderMustInline xinfo = let accRejectFrom (v: Val) repr rejectS = if v.InlineInfo = ValInline.PseudoVal then Zset.union (GetValsBoundInExpr repr) rejectS else rejectS let rejectS = Zset.empty valOrder let rejectS = Zmap.fold accRejectFrom xinfo.Defns rejectS rejectS //------------------------------------------------------------------------- // pass1: IsRefusedTLR //------------------------------------------------------------------------- let IsRefusedTLR g (f: Val) = let mutableVal = f.IsMutable // things marked ValInline.Never are special let dllImportStubOrOtherNeverInline = (f.InlineInfo = ValInline.Never) // Cannot have static fields of byref type let byrefVal = isByrefLikeTy g f.Range f.Type // Special values are instance methods etc. on .NET types. For now leave these alone let specialVal = f.MemberInfo.IsSome let alreadyChosen = f.ValReprInfo.IsSome let refuseTest = alreadyChosen || mutableVal || byrefVal || specialVal || dllImportStubOrOtherNeverInline refuseTest let IsMandatoryTopLevel (f: Val) = let specialVal = f.MemberInfo.IsSome let isModulBinding = f.IsMemberOrModuleBinding specialVal || isModulBinding let IsMandatoryNonTopLevel g (f: Val) = let byrefVal = isByrefLikeTy g f.Range f.Type byrefVal //------------------------------------------------------------------------- // pass1: decide which f are to be TLR? and if so, arity(f) //------------------------------------------------------------------------- module Pass1_DetermineTLRAndArities = let GetMaxNumArgsAtUses xinfo f = match Zmap.tryFind f xinfo.Uses with | None -> 0 (* no call sites *) | Some sites -> sites |> List.map (fun (_accessors, _tinst, args) -> List.length args) |> List.max let SelectTLRVals g xinfo f e = if IsRefusedTLR g f then None // Exclude values bound in a decision tree else if Zset.contains f xinfo.DecisionTreeBindings then None else // Could the binding be TLR? with what arity? let atTopLevel = Zset.contains f xinfo.TopLevelBindings let tps, vss, _b, _rty = stripTopLambda (e, f.Type) let nFormals = vss.Length let nMaxApplied = GetMaxNumArgsAtUses xinfo f let arity = Operators.min nFormals nMaxApplied if atTopLevel || arity<>0 || not (isNil tps) then Some (f, arity) else None /// Check if f involves any value recursion (so can skip those). /// ValRec considered: recursive && some f in mutual binding is not bound to a lambda let IsValueRecursionFree xinfo f = let hasDelayedRepr f = isDelayedRepr f (Zmap.force f xinfo.Defns ("IsValueRecursionFree - hasDelayedRepr", nameOfVal)) let isRecursive, mudefs = Zmap.force f xinfo.RecursiveBindings ("IsValueRecursionFree", nameOfVal) not isRecursive || List.forall hasDelayedRepr mudefs let DumpArity arityM = let dump f n = dprintf "tlr: arity %50s = %d\n" (showL (valL f)) n Zmap.iter dump arityM let DetermineTLRAndArities g expr = let xinfo = GetUsageInfoOfImplFile g expr let fArities = Zmap.chooseL (SelectTLRVals g xinfo) xinfo.Defns let fArities = List.filter (fst >> IsValueRecursionFree xinfo) fArities // Do not TLR v if it is bound under a mustinline defn // There is simply no point - the original value will be duplicated and TLR'd anyway let rejectS = GetValsBoundUnderMustInline xinfo let fArities = List.filter (fun (v, _) -> not (Zset.contains v rejectS)) fArities (*-*) let tlrS = Zset.ofList valOrder (List.map fst fArities) let topValS = xinfo.TopLevelBindings (* genuinely top level *) let topValS = Zset.filter (IsMandatoryNonTopLevel g >> not) topValS (* restrict *) (* REPORT MISSED CASES *) #if DEBUG if verboseTLR then let missed = Zset.diff xinfo.TopLevelBindings tlrS missed |> Zset.iter (fun v -> dprintf "TopLevel but not TLR = %s\n" v.LogicalName) #endif (* REPORT OVER *) let arityM = Zmap.ofList valOrder fArities #if DEBUG if verboseTLR then DumpArity arityM #endif tlrS, topValS, arityM (* NOTES: For constants, Want to fold in a declaration order, so can make decisions about TLR given TLR-knowledge about prior constants. Assuming ilxgen will fix up initialisations. So, Results to be extended to include some scoping representation. Maybe a telescope tree which can be walked over. *) //------------------------------------------------------------------------- // pass2: determine reqdTypars(f) and envreq(f) - notes //------------------------------------------------------------------------- /// What are the closing types/values for {f1, f2...} mutually defined? /// // Note: arity-met g-applications (g TLR) will translated as: // [[g @ tps ` args]] -> gHAT @ reqdTypars(g) tps ` env(g) args // so they require availability of closing types/values for g. // // If g is free wrt f1, f2... then g's closure must be included. // // Note: mutual definitions have a common closure. // // For f1, f2, ... = fBody1, fbody2... mutual bindings: // // DEFN: The reqdVals0 are the free-values of fBody1, fBody2... // // What are the closure equations? // // reqdTypars(f1, f2..) includes free-tps(f) // reqdTypars(f1, f2..) includes reqdTypars(g) if fBody has arity-met g-occurrence (g TLR). // // reqdItems(f1, f2...) includes ReqdSubEnv(g) if fBody has arity-met g-occurrence (g TLR) // reqdItems(f1, f2...) includes ReqdVal(g) if fBody has arity-short g-occurrence (g TLR) // reqdItems(f1, f2...) includes ReqdVal(g) if fBody has g-occurrence (g not TLR) // // and only collect requirements if g is a generator (see next notes). // // Note: "env-availability" // In the translated code, env(h) will be defined at the h definition point. // So, where-ever h could be called (recursive or not), // the env(h) will be available (in scope). // // Note (subtle): "sub-env-requirement-only-for-reqdVals0" // If have an arity-met call to h inside fBody, but h is not a freevar for f, // then h does not contribute env(h) to env(f), the closure for f. // It is true that env(h) will be required at the h call-site, // but the env(h) will be available there (by "env-availability"), // since h must be bound inside the fBody since h was not a freevar for f. // . // [note, f and h may mutually recurse and formals of f may be in env(h), // so env(f) may be properly inside env(h), // so better not have env(h) in env(f)!!!]. /// The subset of ids from a mutal binding that are chosen to be TLR. /// They share a common env. /// [Each fclass has an env, the fclass are the handles to envs.] type BindingGroupSharingSameReqdItems(bindings: Bindings) = let vals = valsOfBinds bindings let vset = Zset.addList vals (Zset.empty valOrder) member fclass.Vals = vals member fclass.Contains (v: Val) = vset.Contains v member fclass.IsEmpty = isNil vals member fclass.Pairs = vals |> List.map (fun f -> (f, fclass)) override fclass.ToString() = "+" + String.concat "+" (List.map nameOfVal vals) let fclassOrder = Order.orderOn (fun (b: BindingGroupSharingSameReqdItems) -> b.Vals) (List.order valOrder) /// It is required to make the TLR closed wrt it's freevars (the env reqdVals0). /// For gv a generator, /// An arity-met gv occurrence contributes the env required for that gv call. /// Other occurrences contribute the value gv. type ReqdItem = | ReqdSubEnv of Val | ReqdVal of Val override i.ToString() = match i with | ReqdSubEnv f -> "&" + f.LogicalName | ReqdVal f -> f.LogicalName let reqdItemOrder = let rep = function | ReqdSubEnv v -> true, v | ReqdVal v -> false, v Order.orderOn rep (Pair.order (Bool.order, valOrder)) /// An env says what is needed to close the corresponding defn(s). /// The reqdTypars are the free reqdTypars of the defns, and those required by any direct TLR arity-met calls. /// The reqdItems are the ids/subEnvs required from calls to freeVars. type ReqdItemsForDefn = { reqdTypars: Zset<Typar> reqdItems: Zset<ReqdItem> m: Range.range } member env.ReqdSubEnvs = [ for x in env.reqdItems do match x with | ReqdSubEnv f -> yield f | ReqdVal _ -> () ] member env.ReqdVals = [ for x in env.reqdItems do match x with | ReqdSubEnv _ -> () | ReqdVal v -> yield v ] member env.Extend (typars, items) = {env with reqdTypars = Zset.addList typars env.reqdTypars reqdItems = Zset.addList items env.reqdItems} static member Initial typars m = {reqdTypars = Zset.addList typars (Zset.empty typarOrder) reqdItems = Zset.empty reqdItemOrder m = m } override env.ToString() = (showL (commaListL (List.map typarL (Zset.elements env.reqdTypars)))) + "--" + (String.concat ", " (List.map string (Zset.elements env.reqdItems))) (*--debug-stuff--*) //------------------------------------------------------------------------- // pass2: collector - state //------------------------------------------------------------------------- type Generators = Zset<Val> /// check a named function value applied to sufficient arguments let IsArityMet (vref: ValRef) wf (tys: TypeInst) args = (tys.Length = vref.Typars.Length) && (wf <= List.length args) module Pass2_DetermineReqdItems = // IMPLEMENTATION PLAN: // // fold over expr. // // - at an instance g, // - (a) g arity-met, LogRequiredFrom g - ReqdSubEnv(g) -- direct call will require env(g) and reqdTypars(g) // - (b) g arity-short, LogRequiredFrom g - ReqdVal(g) -- remains g call // - (c) g non-TLR, LogRequiredFrom g - ReqdVal(g) -- remains g // where // LogRequiredFrom g ... = logs info into (reqdVals0, env) if g in reqdVals0. // // - at some mu-bindings, f1, f2... = fBody1, fBody2, ... // "note reqdVals0, push (reqdVals0, env), fold-over bodies, pop, fold rest" // // - let fclass = ff1, ... be the fi which are being made TLR. // - required to find an env for these. // - start a new envCollector: // freetps = freetypars of (fBody1, fBody2, ...) // freevs = freevars of .. // initialise: // reqdTypars = freetps // reqdItems = [] -- info collected from generator occurrences in bindings // reqdVals0 = freevs // - fold bodies, collecting info for reqdVals0. // - pop and save env. // - note: - reqdTypars(fclass) are only the freetps // - they need to include reqdTypars(g) for each direct call to g (g a generator for fclass) // - the reqdTypars(g) may not yet be known, // e.g. if we are inside the definition of g and had recursively called it. // - so need to FIX up the reqdTypars(-) function when collected info for all fclass. // - fold rest (after binding) // // fix up reqdTypars(-) according to direct call dependencies. // /// This state collects: /// reqdItemsMap - fclass -> env /// fclassM - f -> fclass /// declist - fclass list /// recShortCallS - the f which are "recursively-called" in arity short instance. /// /// When walking expr, at each mutual binding site, /// push a (generator, env) collector frame on stack. /// If occurrences in body are relevant (for a generator) then it's contribution is logged. /// /// recShortCalls to f will require a binding for f in terms of fHat within the fHatBody. type state = { stack: (BindingGroupSharingSameReqdItems * Generators * ReqdItemsForDefn) list reqdItemsMap: Zmap<BindingGroupSharingSameReqdItems, ReqdItemsForDefn> fclassM: Zmap<Val, BindingGroupSharingSameReqdItems> revDeclist: BindingGroupSharingSameReqdItems list recShortCallS: Zset<Val> } let state0 = { stack = [] reqdItemsMap = Zmap.empty fclassOrder fclassM = Zmap.empty valOrder revDeclist = [] recShortCallS = Zset.empty valOrder } /// PUSH = start collecting for fclass let PushFrame (fclass: BindingGroupSharingSameReqdItems) (reqdTypars0, reqdVals0, m) state = if fclass.IsEmpty then state else {state with revDeclist = fclass :: state.revDeclist stack = (let env = ReqdItemsForDefn.Initial reqdTypars0 m in (fclass, reqdVals0, env) :: state.stack) } /// POP & SAVE = end collecting for fclass and store let SaveFrame (fclass: BindingGroupSharingSameReqdItems) state = if verboseTLR then dprintf "SaveFrame: %A\n" fclass if fclass.IsEmpty then state else match state.stack with | [] -> internalError "trl: popFrame has empty stack" | (fclass, _reqdVals0, env) :: stack -> (* ASSERT: same fclass *) {state with stack = stack reqdItemsMap = Zmap.add fclass env state.reqdItemsMap fclassM = List.fold (fun mp (k, v) -> Zmap.add k v mp) state.fclassM fclass.Pairs } /// Log requirements for gv in the relevant stack frames let LogRequiredFrom gv items state = let logIntoFrame (fclass, reqdVals0: Zset<Val>, env: ReqdItemsForDefn) = let env = if reqdVals0.Contains gv then env.Extend ([], items) else env fclass, reqdVals0, env {state with stack = List.map logIntoFrame state.stack} let LogShortCall gv state = if state.stack |> List.exists (fun (fclass, _reqdVals0, _env) -> fclass.Contains gv) then if verboseTLR then dprintf "shortCall: rec: %s\n" gv.LogicalName // Have short call to gv within it's (mutual) definition(s) {state with recShortCallS = Zset.add gv state.recShortCallS} else if verboseTLR then dprintf "shortCall: not-rec: %s\n" gv.LogicalName state let FreeInBindings bs = List.fold (foldOn (freeInBindingRhs CollectTyparsAndLocals) unionFreeVars) emptyFreeVars bs /// Intercepts selected exprs. /// "letrec f1, f2, ... = fBody1, fBody2, ... in rest" - /// "val v" - free occurrence /// "app (f, tps, args)" - occurrence /// /// On intercepted nodes, must recurseF fold to collect from subexpressions. let ExprEnvIntercept (tlrS, arityM) recurseF noInterceptF z expr = let accInstance z (fvref: ValRef, tps, args) = let f = fvref.Deref match Zmap.tryFind f arityM with | Some wf -> // f is TLR with arity wf if IsArityMet fvref wf tps args then // arity-met call to a TLR g LogRequiredFrom f [ReqdSubEnv f] z else // arity-short instance let z = LogRequiredFrom f [ReqdVal f] z // LogShortCall - logs recursive short calls let z = LogShortCall f z z | None -> // f is non-TLR LogRequiredFrom f [ReqdVal f] z let accBinds m z (binds: Bindings) = let tlrBs, nonTlrBs = binds |> List.partition (fun b -> Zset.contains b.Var tlrS) // For bindings marked TLR, collect implied env let fclass = BindingGroupSharingSameReqdItems tlrBs // what determines env? let frees = FreeInBindings tlrBs // put in env let reqdTypars0 = frees.FreeTyvars.FreeTypars |> Zset.elements // occurrences contribute to env let reqdVals0 = frees.FreeLocals |> Zset.elements // tlrBs are not reqdVals0 for themselves let reqdVals0 = reqdVals0 |> List.filter (fun gv -> not (fclass.Contains gv)) let reqdVals0 = reqdVals0 |> Zset.ofList valOrder // collect into env over bodies let z = PushFrame fclass (reqdTypars0, reqdVals0,m) z let z = (z, tlrBs) ||> List.fold (foldOn (fun b -> b.Expr) recurseF) let z = SaveFrame fclass z // for bindings not marked TRL, collect let z = (z, nonTlrBs) ||> List.fold (foldOn (fun b -> b.Expr) recurseF) z match expr with | Expr.Val (v, _, _) -> accInstance z (v, [], []) | Expr.Op (TOp.LValueOp (_, v), _tys, args, _) -> let z = accInstance z (v, [], []) List.fold recurseF z args | Expr.App (f, fty, tys, args, m) -> let f, _fty, tys, args, _m = destApp (f, fty, tys, args, m) match f with | Expr.Val (f, _, _) -> // YES: APP vspec tps args - log let z = accInstance z (f, tys, args) List.fold recurseF z args | _ -> // NO: app, but function is not val - no log noInterceptF z expr | Expr.LetRec (binds, body, m, _) -> let z = accBinds m z binds recurseF z body | Expr.Let (bind,body,m,_) -> let z = accBinds m z [bind] // tailcall for linear sequences recurseF z body | _ -> noInterceptF z expr /// Initially, reqdTypars(fclass) = freetps(bodies). /// For each direct call to a gv, a generator for fclass, /// Required to include the reqdTypars(gv) in reqdTypars(fclass). let CloseReqdTypars fclassM reqdItemsMap = if verboseTLR then dprintf "CloseReqdTypars------\n" let closeStep reqdItemsMap changed fc (env: ReqdItemsForDefn) = let directCallReqdEnvs = env.ReqdSubEnvs let directCallReqdTypars = directCallReqdEnvs |> List.map (fun f -> let fc = Zmap.force f fclassM ("reqdTyparsFor", nameOfVal) let env = Zmap.force fc reqdItemsMap ("reqdTyparsFor", string) env.reqdTypars) let reqdTypars0 = env.reqdTypars let reqdTypars = List.fold Zset.union reqdTypars0 directCallReqdTypars let changed = changed || (not (Zset.equal reqdTypars0 reqdTypars)) let env = {env with reqdTypars = reqdTypars} #if DEBUG if verboseTLR then dprintf "closeStep: fc=%30A nSubs=%d reqdTypars0=%s reqdTypars=%s\n" fc directCallReqdEnvs.Length (showTyparSet reqdTypars0) (showTyparSet reqdTypars) directCallReqdEnvs |> List.iter (fun f -> dprintf "closeStep: dcall f=%s\n" f.LogicalName) directCallReqdEnvs |> List.iter (fun f -> dprintf "closeStep: dcall fc=%A\n" (Zmap.find f fclassM)) directCallReqdTypars |> List.iter (fun _reqdTypars -> dprintf "closeStep: dcall reqdTypars=%s\n" (showTyparSet reqdTypars0)) #else ignore fc #endif changed, env let rec fixpoint reqdItemsMap = let changed = false let changed, reqdItemsMap = Zmap.foldMap (closeStep reqdItemsMap) changed reqdItemsMap if changed then fixpoint reqdItemsMap else reqdItemsMap fixpoint reqdItemsMap #if DEBUG let DumpReqdValMap reqdItemsMap = for KeyValue(fc, env) in reqdItemsMap do dprintf "CLASS=%A\n env=%A\n" fc env #endif let DetermineReqdItems (tlrS, arityM) expr = if verboseTLR then dprintf "DetermineReqdItems------\n" let folder = {ExprFolder0 with exprIntercept = ExprEnvIntercept (tlrS, arityM)} let z = state0 // Walk the entire assembly let z = FoldImplFile folder z expr // project results from the state let reqdItemsMap = z.reqdItemsMap let fclassM = z.fclassM let declist = List.rev z.revDeclist let recShortCallS = z.recShortCallS // diagnostic dump #if DEBUG if verboseTLR then DumpReqdValMap reqdItemsMap #endif // close the reqdTypars under the subEnv reln let reqdItemsMap = CloseReqdTypars fclassM reqdItemsMap // filter out trivial fclass - with no TLR defns let reqdItemsMap = Zmap.remove (BindingGroupSharingSameReqdItems List.empty) reqdItemsMap // restrict declist to those with reqdItemsMap bindings (the non-trivial ones) let declist = List.filter (Zmap.memberOf reqdItemsMap) declist #if DEBUG // diagnostic dump if verboseTLR then DumpReqdValMap reqdItemsMap declist |> List.iter (fun fc -> dprintf "Declist: %A\n" fc) recShortCallS |> Zset.iter (fun f -> dprintf "RecShortCall: %s\n" f.LogicalName) #endif reqdItemsMap, fclassM, declist, recShortCallS //------------------------------------------------------------------------- // step3: PackedReqdItems //------------------------------------------------------------------------- /// Each env is represented by some carrier values, the aenvs. /// An env packing defines these, and the pack/unpack bindings. /// The bindings are in terms of the fvs directly. /// /// When defining a new TLR f definition, /// the fvs will become bound by the unpack bindings, /// the aenvs will become bound by the new lam, and /// the reqdTypars will become bound by the new LAM. /// For uniqueness of bound ids, /// all these ids (Typar/Val) will need to be freshened up. /// It is OK to break the uniqueness-of-bound-ids rule during the rw, /// provided it is fixed up via a copyExpr call on the final expr. type PackedReqdItems = { /// The actual typars ep_etps: Typars /// The actual env carrier values ep_aenvs: Val list /// Sequentially define the aenvs in terms of the fvs ep_pack: Bindings /// Sequentially define the fvs in terms of the aenvs ep_unpack: Bindings } //------------------------------------------------------------------------- // step3: FlatEnvPacks //------------------------------------------------------------------------- exception AbortTLR of Range.range /// A naive packing of environments. /// Chooses to pass all env values as explicit args (no tupling). /// Note, tupling would cause an allocation, /// so, unless arg lists get very long, this flat packing will be preferable. /// Given (fclass, env). /// Have env = ReqdVal vj, ReqdSubEnv subEnvk -- ranging over j, k /// Define vals(env) = {vj}|j union vals(subEnvk)|k -- trans closure of vals of env. /// Define <vi, aenvi> for each vi in vals(env). /// This is the cmap for the env. /// reqdTypars = env.reqdTypars /// carriers = aenvi|i /// pack = TBIND(aenvi = vi) for each (aenvi, vi) in cmap /// unpack = TBIND(vj = aenvFor(vj)) for each vj in reqvals(env). /// and TBIND(asubEnvi = aenvFor(v)) for each (asubEnvi, v) in cmap(subEnvk) ranging over required subEnvk. /// where /// aenvFor(v) = aenvi where (v, aenvi) in cmap. let FlatEnvPacks g fclassM topValS declist (reqdItemsMap: Zmap<BindingGroupSharingSameReqdItems, ReqdItemsForDefn>) = let fclassOf f = Zmap.force f fclassM ("fclassM", nameOfVal) let packEnv carrierMaps (fc: BindingGroupSharingSameReqdItems) = if verboseTLR then dprintf "\ntlr: packEnv fc=%A\n" fc let env = Zmap.force fc reqdItemsMap ("packEnv", string) // carrierMaps = (fclass, (v, aenv)map)map let carrierMapFor f = Zmap.force (fclassOf f) carrierMaps ("carrierMapFor", string) let valsSubEnvFor f = Zmap.keys (carrierMapFor f) // determine vals(env) - transclosure let vals = env.ReqdVals @ List.collect valsSubEnvFor env.ReqdSubEnvs // list, with repeats let vals = vals |> List.distinctBy (fun v -> v.Stamp) // Remove genuinely toplevel, no need to close over these let vals = vals |> List.filter (IsMandatoryTopLevel >> not) // Remove byrefs, no need to close over these, and would be invalid to do so since their values can change. // // Note that it is normally not OK to skip closing over values, since values given (method) TLR must have implementations // which are truly closed. However, byref values never escape into any lambdas, so are never used in anything // for which we will choose a method TLR. // // For example, consider this (FSharp 1.0 bug 5578): // // let mutable a = 1 // // let resutl1 = // let x = &a // This is NOT given TLR, because it is byref // x <- 111 // let temp = x // This is given a static field TLR, not a method TLR // // let f () = x // This is not allowed, can't capture x // x <- 999 // temp // // Compare with this: // let mutable a = 1 // // let result2 = // let x = a // this is given static field TLR // a <- 111 // let temp = a // let f () = x // This is not allowed, and is given a method TLR // a <- 999 // temp let vals = vals |> List.filter (fun v -> not (isByrefLikeTy g v.Range v.Type)) // Remove values which have been labelled TLR, no need to close over these let vals = vals |> List.filter (Zset.memberOf topValS >> not) // Carrier sets cannot include constrained polymorphic values. We can't just take such a value out, so for the moment // we'll just abandon TLR altogether and give a warning about this condition. match vals |> List.tryFind (IsGenericValWithGenericConstraints g) with | None -> () | Some v -> raise (AbortTLR v.Range) // build cmap for env let cmapPairs = vals |> List.map (fun v -> (v, (mkCompGenLocal env.m v.LogicalName v.Type |> fst))) let cmap = Zmap.ofList valOrder cmapPairs let aenvFor v = Zmap.force v cmap ("aenvFor", nameOfVal) let aenvExprFor v = exprForVal env.m (aenvFor v) // build PackedReqdItems let reqdTypars = env.reqdTypars let aenvs = Zmap.values cmap let pack = cmapPairs |> List.map (fun (v, aenv) -> mkInvisibleBind aenv (exprForVal env.m v)) let unpack = let unpackCarrier (v, aenv) = mkInvisibleBind (setValHasNoArity v) (exprForVal env.m aenv) let unpackSubenv f = let subCMap = carrierMapFor f let vaenvs = Zmap.toList subCMap vaenvs |> List.map (fun (subv, subaenv) -> mkBind NoDebugPointAtInvisibleBinding subaenv (aenvExprFor subv)) List.map unpackCarrier (Zmap.toList cmap) @ List.collect unpackSubenv env.ReqdSubEnvs // extend carrierMaps let carrierMaps = Zmap.add fc cmap carrierMaps // dump if verboseTLR then let bindingL bind = bindingL g bind dprintf "tlr: packEnv envVals =%s\n" (showL (listL valL env.ReqdVals)) dprintf "tlr: packEnv envSubs =%s\n" (showL (listL valL env.ReqdSubEnvs)) dprintf "tlr: packEnv vals =%s\n" (showL (listL valL vals)) dprintf "tlr: packEnv aenvs =%s\n" (showL (listL valL aenvs)) dprintf "tlr: packEnv pack =%s\n" (showL (listL bindingL pack)) dprintf "tlr: packEnv unpack =%s\n" (showL (listL bindingL unpack)) // result (fc, { ep_etps = Zset.elements reqdTypars ep_aenvs = aenvs ep_pack = pack ep_unpack = unpack}), carrierMaps let carriedMaps = Zmap.empty fclassOrder let envPacks, _carriedMaps = List.mapFold packEnv carriedMaps declist (* List.mapFold in dec order *) let envPacks = Zmap.ofList fclassOrder envPacks envPacks //------------------------------------------------------------------------- // step3: chooseEnvPacks //------------------------------------------------------------------------- #if DEBUG let DumpEnvPackM g envPackM = let bindingL bind = bindingL g bind for KeyValue(fc, packedReqdItems) in envPackM do dprintf "packedReqdItems: fc = %A\n" fc dprintf " reqdTypars = %s\n" (showL (commaListL (List.map typarL packedReqdItems.ep_etps))) dprintf " aenvs = %s\n" (showL (commaListL (List.map valL packedReqdItems.ep_aenvs))) dprintf " pack = %s\n" (showL (semiListL (List.map bindingL packedReqdItems.ep_pack))) dprintf " unpack = %s\n" (showL (semiListL (List.map bindingL packedReqdItems.ep_unpack))) dprintf "\n" #endif /// For each fclass, have an env. /// Required to choose an PackedReqdItems, /// e.g. deciding whether to tuple up the environment or not. /// e.g. deciding whether to use known values for required sub environments. /// /// Scope for optimization env packing here. /// For now, pass all environments via arguments since aiming to eliminate allocations. /// Later, package as tuples if arg lists get too long. let ChooseReqdItemPackings g fclassM topValS declist reqdItemsMap = if verboseTLR then dprintf "ChooseReqdItemPackings------\n" let envPackM = FlatEnvPacks g fclassM topValS declist reqdItemsMap #if DEBUG if verboseTLR then DumpEnvPackM g envPackM #endif envPackM //------------------------------------------------------------------------- // step3: CreateNewValuesForTLR //------------------------------------------------------------------------- /// arity info where nothing is untupled // REVIEW: could do better here by preserving names let MakeSimpleArityInfo tps n = ValReprInfo (ValReprInfo.InferTyparInfo tps, List.replicate n ValReprInfo.unnamedTopArg, ValReprInfo.unnamedRetVal) let CreateNewValuesForTLR g tlrS arityM fclassM envPackM = if verboseTLR then dprintf "CreateNewValuesForTLR------\n" let createFHat (f: Val) = let wf = Zmap.force f arityM ("createFHat - wf", (fun v -> showL (valL v))) let fc = Zmap.force f fclassM ("createFHat - fc", nameOfVal) let envp = Zmap.force fc envPackM ("CreateNewValuesForTLR - envp", string) let name = f.LogicalName (* + "_TLR_" + string wf *) let m = f.Range let tps, tau = f.TypeScheme let argtys, res = stripFunTy g tau let newTps = envp.ep_etps @ tps let fHatTy = let newArgtys = List.map typeOfVal envp.ep_aenvs @ argtys mkLambdaTy newTps newArgtys res let fHatArity = MakeSimpleArityInfo newTps (envp.ep_aenvs.Length + wf) let fHatName = // Ensure that we have an g.CompilerGlobalState assert(g.CompilerGlobalState |> Option.isSome) g.CompilerGlobalState.Value.NiceNameGenerator.FreshCompilerGeneratedName(name, m) let fHat = mkLocalNameTypeArity f.IsCompilerGenerated m fHatName fHatTy (Some fHatArity) fHat let fs = Zset.elements tlrS let ffHats = List.map (fun f -> f, createFHat f) fs let fHatM = Zmap.ofList valOrder ffHats fHatM //------------------------------------------------------------------------- // pass4: rewrite - penv //------------------------------------------------------------------------- module Pass4_RewriteAssembly = [<NoEquality; NoComparison>] type RewriteContext = { ccu: CcuThunk g: TcGlobals tlrS: Zset<Val> topValS: Zset<Val> arityM: Zmap<Val, int> fclassM: Zmap<Val, BindingGroupSharingSameReqdItems> recShortCallS: Zset<Val> envPackM: Zmap<BindingGroupSharingSameReqdItems, PackedReqdItems> /// The mapping from 'f' values to 'fHat' values fHatM: Zmap<Val, Val> } //------------------------------------------------------------------------- // pass4: rwstate (z state) //------------------------------------------------------------------------- type IsRecursive = IsRec | NotRec type LiftedDeclaration = IsRecursive * Bindings (* where bool=true if letrec *) /// This state is related to lifting to top-level (which is actually disabled right now) /// This is to ensure the TLR constants get initialised once. /// /// Top-level status ends when stepping inside a lambda, where a lambda is: /// Expr.TyLambda, Expr.Lambda, Expr.Obj (and tmethods). /// [... also, try_catch handlers, and switch targets...] /// /// Top* repr bindings already at top-level do not need moving... /// [and should not be, since they may lift over unmoved defns on which they depend]. /// Any TLR repr bindings under lambdas can be filtered out (and collected), /// giving pre-declarations to insert before the outermost lambda expr. type RewriteState = { rws_mustinline: bool /// counts level of enclosing "lambdas" rws_innerLevel: int /// collected preDecs (fringe is in-order) rws_preDecs: Tree<LiftedDeclaration> } let rewriteState0 = {rws_mustinline=false;rws_innerLevel=0;rws_preDecs=emptyTR} // move in/out of lambdas (or lambda containing construct) let EnterInner z = {z with rws_innerLevel = z.rws_innerLevel + 1} let ExitInner z = {z with rws_innerLevel = z.rws_innerLevel - 1} let EnterMustInline b z f = let orig = z.rws_mustinline let x, z' = f (if b then {z with rws_mustinline = true } else z) {z' with rws_mustinline = orig }, x /// extract PreDecs (iff at top-level) let ExtractPreDecs z = // If level=0, so at top-level, then pop decs, // else keep until get back to a top-level point. if z.rws_innerLevel=0 then // at top-level, extract preDecs let preDecs = fringeTR z.rws_preDecs preDecs, {z with rws_preDecs=emptyTR} else // not yet top-level, keep decs [], z /// pop and set preDecs as "LiftedDeclaration tree" let PopPreDecs z = {z with rws_preDecs=emptyTR}, z.rws_preDecs let SetPreDecs z pdt = {z with rws_preDecs=pdt} /// collect Top* repr bindings - if needed... let LiftTopBinds _isRec _penv z binds = z, binds /// Wrap preDecs (in order) over an expr - use letrec/let as approp let MakePreDec m (isRec, binds: Bindings) expr = if isRec=IsRec then // By definition top level bindings don't refer to non-top level bindings, so we can build them in two parts let topLevelBinds, nonTopLevelBinds = binds |> List.partition (fun bind -> bind.Var.IsCompiledAsTopLevel) mkLetRecBinds m topLevelBinds (mkLetRecBinds m nonTopLevelBinds expr) else mkLetsFromBindings m binds expr /// Must MakePreDecs around every construct that could do EnterInner (which filters TLR decs). /// i.e. let, letrec (bind may...), ilobj, lambda, tlambda. let MakePreDecs m preDecs expr = List.foldBack (MakePreDec m) preDecs expr let RecursivePreDecs pdsA pdsB = let pds = fringeTR (TreeNode[pdsA;pdsB]) let decs = pds |> List.collect snd LeafNode (IsRec, decs) //------------------------------------------------------------------------- // pass4: lowertop - convert_vterm_bind on TopLevel binds //------------------------------------------------------------------------- let ConvertBind g (TBind(v, repr, _) as bind) = match v.ValReprInfo with | None -> v.SetValReprInfo (Some (InferArityOfExprBinding g AllowTypeDirectedDetupling.Yes v repr )) | Some _ -> () bind //------------------------------------------------------------------------- // pass4: transBind (translate) //------------------------------------------------------------------------- // Transform // let f<tps> vss = f_body[<f_freeTypars>, f_freeVars] // To // let f<tps> vss = fHat<f_freeTypars> f_freeVars vss // let fHat<tps> f_freeVars vss = f_body[<f_freeTypars>, f_freeVars] let TransTLRBindings penv (binds: Bindings) = if isNil binds then List.empty, List.empty else let fc = BindingGroupSharingSameReqdItems binds let envp = Zmap.force fc penv.envPackM ("TransTLRBindings", string) let fRebinding (TBind(fOrig, b, letSeqPtOpt)) = let m = fOrig.Range let tps, vss, _b, rty = stripTopLambda (b, fOrig.Type) let aenvExprs = envp.ep_aenvs |> List.map (exprForVal m) let vsExprs = vss |> List.map (mkRefTupledVars penv.g m) let fHat = Zmap.force fOrig penv.fHatM ("fRebinding", nameOfVal) (* REVIEW: is this mutation really, really necessary? *) (* Why are we applying TLR if the thing already has an arity? *) let fOrig = setValHasNoArity fOrig let fBind = mkMultiLambdaBind fOrig letSeqPtOpt m tps vss (mkApps penv.g ((exprForVal m fHat, fHat.Type), [List.map mkTyparTy (envp.ep_etps @ tps)], aenvExprs @ vsExprs, m), rty) fBind let fHatNewBinding (shortRecBinds: Bindings) (TBind(f, b, letSeqPtOpt)) = let wf = Zmap.force f penv.arityM ("fHatNewBinding - arityM", nameOfVal) let fHat = Zmap.force f penv.fHatM ("fHatNewBinding - fHatM", nameOfVal) // Take off the variables let tps, vss, b, rty = stripTopLambda (b, f.Type) // Don't take all the variables - only up to length wf let vssTake, vssDrop = List.splitAt wf vss // put the variables back on let b, rty = mkMultiLambdasCore b.Range vssDrop (b, rty) // fHat, args let m = fHat.Range // Add the type variables to the front let fHat_tps = envp.ep_etps @ tps // Add the 'aenv' and original taken variables to the front let fHat_args = List.map List.singleton envp.ep_aenvs @ vssTake let fHat_body = mkLetsFromBindings m envp.ep_unpack b let fHat_body = mkLetsFromBindings m shortRecBinds fHat_body // bind "f" if have short recursive calls (somewhere) // fHat binding, f rebinding let fHatBind = mkMultiLambdaBind fHat letSeqPtOpt m fHat_tps fHat_args (fHat_body, rty) fHatBind let rebinds = binds |> List.map fRebinding let shortRecBinds = rebinds |> List.filter (fun b -> penv.recShortCallS.Contains(b.Var)) let newBinds = binds |> List.map (fHatNewBinding shortRecBinds) newBinds, rebinds let GetAEnvBindings penv fc = match Zmap.tryFind fc penv.envPackM with | None -> List.empty // no env for this mutual binding | Some envp -> envp.ep_pack // environment pack bindings let TransBindings xisRec penv (binds: Bindings) = let tlrBs, nonTlrBs = binds |> List.partition (fun b -> Zset.contains b.Var penv.tlrS) let fclass = BindingGroupSharingSameReqdItems tlrBs // Trans each TLR f binding into fHat and f rebind let newTlrBinds, tlrRebinds = TransTLRBindings penv tlrBs let aenvBinds = GetAEnvBindings penv fclass // lower nonTlrBs if they are GTL // QUERY: we repeat this logic in LowerCallsAndSeqs. Do we really need to do this here? // QUERY: yes and no - if we don't, we have an unrealizable term, and many decisions must // QUERY: correlate with LowerCallsAndSeqs. let forceTopBindToHaveArity (bind: Binding) = if penv.topValS.Contains(bind.Var) then ConvertBind penv.g bind else bind let nonTlrBs = nonTlrBs |> List.map forceTopBindToHaveArity let tlrRebinds = tlrRebinds |> List.map forceTopBindToHaveArity // assemble into replacement bindings let bindAs, rebinds = match xisRec with | IsRec -> newTlrBinds @ tlrRebinds @ nonTlrBs @ aenvBinds, [] (* note: aenv last, order matters in letrec! *) | NotRec -> aenvBinds @ newTlrBinds, tlrRebinds @ nonTlrBs (* note: aenv go first, they may be used *) bindAs, rebinds //------------------------------------------------------------------------- // pass4: TransApp (translate) //------------------------------------------------------------------------- let TransApp penv (fx, fty, tys, args, m) = // Is it a val app, where the val f is TLR with arity wf? // CLEANUP NOTE: should be using a mkApps to make all applications match fx with | Expr.Val (fvref: ValRef, _, m) when (Zset.contains fvref.Deref penv.tlrS) && (let wf = Zmap.force fvref.Deref penv.arityM ("TransApp - wf", nameOfVal) IsArityMet fvref wf tys args) -> let f = fvref.Deref (* replace by direct call to corresponding fHat (and additional closure args) *) let fc = Zmap.force f penv.fclassM ("TransApp - fc", nameOfVal) let envp = Zmap.force fc penv.envPackM ("TransApp - envp", string) let fHat = Zmap.force f penv.fHatM ("TransApp - fHat", nameOfVal) let tys = (List.map mkTyparTy envp.ep_etps) @ tys let aenvExprs = List.map (exprForVal m) envp.ep_aenvs let args = aenvExprs @ args mkApps penv.g ((exprForVal m fHat, fHat.Type), [tys], args, m) (* change, direct fHat call with closure (reqdTypars, aenvs) *) | _ -> if isNil tys && isNil args then fx else Expr.App (fx, fty, tys, args, m) (* no change, f is expr *) //------------------------------------------------------------------------- // pass4: pass (over expr) //------------------------------------------------------------------------- /// At bindings, fixup any TLR bindings. /// At applications, fixup calls if they are arity-met instances of TLR. /// At free vals, fixup 0-call if it is an arity-met constant. /// Other cases rewrite structurally. let rec TransExpr (penv: RewriteContext) (z: RewriteState) expr: Expr * RewriteState = match expr with // Use TransLinearExpr with a rebuild-continuation for some forms to avoid stack overflows on large terms | LinearOpExpr _ | LinearMatchExpr _ | Expr.LetRec _ // note, Expr.LetRec not normally considered linear, but keeping it here as it's always been here | Expr.Let _ | Expr.Sequential _ -> TransLinearExpr penv z expr (fun res -> res) // app - call sites may require z. // - match the app (collapsing reclinks and type instances). // - patch it. | Expr.App (f, fty, tys, args, m) -> // pass over f, args subexprs let f, z = TransExpr penv z f let args, z = List.mapFold (TransExpr penv) z args // match app, and fixup if needed let f, fty, tys, args, m = destApp (f, fty, tys, args, m) let expr = TransApp penv (f, fty, tys, args, m) expr, z | Expr.Val (v, _, m) -> // consider this a trivial app let fx, fty = expr, v.Type let expr = TransApp penv (fx, fty, [], [], m) expr, z // reclink - suppress | Expr.Link r -> TransExpr penv z (!r) // ilobj - has implicit lambda exprs and recursive/base references | Expr.Obj (_, ty, basev, basecall, overrides, iimpls, m) -> let basecall, z = TransExpr penv z basecall let overrides, z = List.mapFold (TransMethod penv) z overrides let iimpls, z = (z, iimpls) ||> List.mapFold (fun z (tType, objExprs) -> let objExprs', z' = List.mapFold (TransMethod penv) z objExprs (tType, objExprs'), z') let expr = Expr.Obj (newUnique(), ty, basev, basecall, overrides, iimpls, m) let pds, z = ExtractPreDecs z MakePreDecs m pds expr, z (* if TopLevel, lift preDecs over the ilobj expr *) // lambda, tlambda - explicit lambda terms | Expr.Lambda (_, ctorThisValOpt, baseValOpt, argvs, body, m, rty) -> let z = EnterInner z let body, z = TransExpr penv z body let z = ExitInner z let pds, z = ExtractPreDecs z MakePreDecs m pds (rebuildLambda m ctorThisValOpt baseValOpt argvs (body, rty)), z | Expr.TyLambda (_, argtyvs, body, m, rty) -> let z = EnterInner z let body, z = TransExpr penv z body let z = ExitInner z let pds, z = ExtractPreDecs z MakePreDecs m pds (mkTypeLambda m argtyvs (body, rty)), z /// Lifting TLR out over constructs (disabled) /// Lift minimally to ensure the defn is not lifted up and over defns on which it depends (disabled) | Expr.Match (spBind, exprm, dtree, targets, m, ty) -> let targets = Array.toList targets let dtree, z = TransDecisionTree penv z dtree let targets, z = List.mapFold (TransDecisionTreeTarget penv) z targets // TransDecisionTreeTarget wraps EnterInner/exitInnter, so need to collect any top decs let pds,z = ExtractPreDecs z MakePreDecs m pds (mkAndSimplifyMatch spBind exprm m ty dtree targets), z // all others - below - rewrite structurally - so boiler plate code after this point... | Expr.Const _ -> expr,z | Expr.Quote (a,dataCell,isFromQueryExpression,m,ty) -> let doData (typeDefs,argTypes,argExprs,data) z = let argExprs,z = List.mapFold (TransExpr penv) z argExprs (typeDefs,argTypes,argExprs,data), z let data, z = match !dataCell with | Some (data1, data2) -> let data1, z = doData data1 z let data2, z = doData data2 z Some (data1, data2), z | None -> None, z Expr.Quote (a,ref data,isFromQueryExpression,m,ty),z | Expr.Op (c,tyargs,args,m) -> let args,z = List.mapFold (TransExpr penv) z args Expr.Op (c,tyargs,args,m),z | Expr.StaticOptimization (constraints,e2,e3,m) -> let e2,z = TransExpr penv z e2 let e3,z = TransExpr penv z e3 Expr.StaticOptimization (constraints,e2,e3,m),z | Expr.TyChoose (_,_,m) -> error(Error(FSComp.SR.tlrUnexpectedTExpr(),m)) | Expr.WitnessArg (_witnessInfo, _m) -> expr, z /// Walk over linear structured terms in tail-recursive loop, using a continuation /// to represent the rebuild-the-term stack and TransLinearExpr penv z expr (contf: Expr * RewriteState -> Expr * RewriteState) = match expr with | Expr.Sequential (e1, e2, dir, spSeq, m) -> let e1, z = TransExpr penv z e1 TransLinearExpr penv z e2 (contf << (fun (e2, z) -> Expr.Sequential (e1, e2, dir, spSeq, m), z)) // letrec - pass_recbinds does the work | Expr.LetRec (binds, e, m, _) -> let z = EnterInner z // For letrec, preDecs from RHS must mutually recurse with those from the bindings let z, pdsPrior = PopPreDecs z let binds, z = List.mapFold (TransBindingRhs penv) z binds let z, pdsRhs = PopPreDecs z let binds, rebinds = TransBindings IsRec penv binds let z, binds = LiftTopBinds IsRec penv z binds (* factor Top* repr binds *) let z, rebinds = LiftTopBinds IsRec penv z rebinds let z, pdsBind = PopPreDecs z let z = SetPreDecs z (TreeNode [pdsPrior;RecursivePreDecs pdsBind pdsRhs]) let z = ExitInner z let pds, z = ExtractPreDecs z // tailcall TransLinearExpr penv z e (contf << (fun (e, z) -> let e = mkLetsFromBindings m rebinds e MakePreDecs m pds (Expr.LetRec (binds, e, m, Construct.NewFreeVarsCache())), z)) // let - can consider the mu-let bindings as mu-letrec bindings - so like as above | Expr.Let (bind, e, m, _) -> // For let, preDecs from RHS go before those of bindings, which is collection order let bind, z = TransBindingRhs penv z bind let binds, rebinds = TransBindings NotRec penv [bind] // factor Top* repr binds let z, binds = LiftTopBinds NotRec penv z binds let z, rebinds = LiftTopBinds NotRec penv z rebinds // any lifted PreDecs from binding, if so wrap them... let pds, z = ExtractPreDecs z // tailcall TransLinearExpr penv z e (contf << (fun (e, z) -> let e = mkLetsFromBindings m rebinds e MakePreDecs m pds (mkLetsFromBindings m binds e), z)) | LinearMatchExpr (spBind, exprm, dtree, tg1, e2, sp2, m2, ty) -> let dtree, z = TransDecisionTree penv z dtree let tg1, z = TransDecisionTreeTarget penv z tg1 // tailcall TransLinearExpr penv z e2 (contf << (fun (e2, z) -> rebuildLinearMatchExpr (spBind, exprm, dtree, tg1, e2, sp2, m2, ty), z)) | LinearOpExpr (op, tyargs, argsHead, argLast, m) -> let argsHead,z = List.mapFold (TransExpr penv) z argsHead // tailcall TransLinearExpr penv z argLast (contf << (fun (argLast, z) -> rebuildLinearOpExpr (op, tyargs, argsHead, argLast, m), z)) | _ -> // not a linear expression contf (TransExpr penv z expr) and TransMethod penv (z: RewriteState) (TObjExprMethod(slotsig, attribs, tps, vs, e, m)) = let z = EnterInner z let e, z = TransExpr penv z e let z = ExitInner z TObjExprMethod(slotsig, attribs, tps, vs, e, m), z and TransBindingRhs penv z (TBind(v, e, letSeqPtOpt)) : Binding * RewriteState = let mustInline = v.MustInline let z, e = EnterMustInline mustInline z (fun z -> TransExpr penv z e) TBind (v, e, letSeqPtOpt), z and TransDecisionTree penv z x: DecisionTree * RewriteState = match x with | TDSuccess (es, n) -> let es, z = List.mapFold (TransExpr penv) z es TDSuccess(es, n), z | TDBind (bind, rest) -> let bind, z = TransBindingRhs penv z bind let rest, z = TransDecisionTree penv z rest TDBind(bind, rest), z | TDSwitch (e, cases, dflt, m) -> let e, z = TransExpr penv z e let TransDecisionTreeCase penv z (TCase (discrim, dtree)) = let dtree, z = TransDecisionTree penv z dtree TCase(discrim, dtree), z let cases, z = List.mapFold (TransDecisionTreeCase penv) z cases let dflt, z = Option.mapFold (TransDecisionTree penv) z dflt TDSwitch (e, cases, dflt, m), z and TransDecisionTreeTarget penv z (TTarget(vs, e, spTarget)) = let z = EnterInner z let e, z = TransExpr penv z e let z = ExitInner z TTarget(vs, e, spTarget), z and TransValBinding penv z bind = TransBindingRhs penv z bind and TransValBindings penv z binds = List.mapFold (TransValBinding penv) z binds and TransModuleExpr penv z x = match x with | ModuleOrNamespaceExprWithSig(mty, def, m) -> let def, z = TransModuleDef penv z def ModuleOrNamespaceExprWithSig(mty, def, m), z and TransModuleDefs penv z x = List.mapFold (TransModuleDef penv) z x and TransModuleDef penv (z: RewriteState) x: ModuleOrNamespaceExpr * RewriteState = match x with | TMDefRec(isRec, tycons, mbinds, m) -> let mbinds, z = TransModuleBindings penv z mbinds TMDefRec(isRec, tycons, mbinds, m), z | TMDefLet(bind, m) -> let bind, z = TransValBinding penv z bind TMDefLet(bind, m), z | TMDefDo(e, m) -> let _bind, z = TransExpr penv z e TMDefDo(e, m), z | TMDefs defs -> let defs, z = TransModuleDefs penv z defs TMDefs defs, z | TMAbstract mexpr -> let mexpr, z = TransModuleExpr penv z mexpr TMAbstract mexpr, z and TransModuleBindings penv z binds = List.mapFold (TransModuleBinding penv) z binds and TransModuleBinding penv z x = match x with | ModuleOrNamespaceBinding.Binding bind -> let bind, z = TransValBinding penv z bind ModuleOrNamespaceBinding.Binding bind, z | ModuleOrNamespaceBinding.Module(nm, rhs) -> let rhs, z = TransModuleDef penv z rhs ModuleOrNamespaceBinding.Module(nm, rhs), z let TransImplFile penv z (TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = let moduleExpr, z = TransModuleExpr penv z moduleExpr (TImplFile (fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)), z //------------------------------------------------------------------------- // pass5: copyExpr //------------------------------------------------------------------------- let RecreateUniqueBounds g expr = copyImplFile g OnlyCloneExprVals expr //------------------------------------------------------------------------- // entry point //------------------------------------------------------------------------- let MakeTLRDecisions ccu g expr = try // pass1: choose the f to be TLR with arity(f) let tlrS, topValS, arityM = Pass1_DetermineTLRAndArities.DetermineTLRAndArities g expr // pass2: determine the typar/freevar closures, f->fclass and fclass declist let reqdItemsMap, fclassM, declist, recShortCallS = Pass2_DetermineReqdItems.DetermineReqdItems (tlrS, arityM) expr // pass3 let envPackM = ChooseReqdItemPackings g fclassM topValS declist reqdItemsMap let fHatM = CreateNewValuesForTLR g tlrS arityM fclassM envPackM // pass4: rewrite if verboseTLR then dprintf "TransExpr(rw)------\n" let expr, _ = let penv: Pass4_RewriteAssembly.RewriteContext = {ccu=ccu; g=g; tlrS=tlrS; topValS=topValS; arityM=arityM; fclassM=fclassM; recShortCallS=recShortCallS; envPackM=envPackM; fHatM=fHatM} let z = Pass4_RewriteAssembly.rewriteState0 Pass4_RewriteAssembly.TransImplFile penv z expr // pass5: copyExpr to restore "each bound is unique" property // aka, copyExpr if verboseTLR then dprintf "copyExpr------\n" let expr = RecreateUniqueBounds g expr if verboseTLR then dprintf "TLR-done------\n" // Summary: // GTL = genuine top-level // TLR = TopLevelRep = identified by this pass // Note, some GTL are skipped until sort out the initial env... // if verboseTLR then dprintf "note: tlr = %d inner-TLR + %d GenuineTopLevel-TLR + %d GenuineTopLevel skipped TLR (public)\n" // (lengthS (Zset.diff tlrS topValS)) // (lengthS (Zset.inter topValS tlrS)) // (lengthS (Zset.diff topValS tlrS)) // DONE expr with AbortTLR m -> warning(Error(FSComp.SR.tlrLambdaLiftingOptimizationsNotApplied(), m)) expr
{ "pile_set_name": "Github" }
/* * textstyle.c -- text style processing module. * * Copyright (c) 2018, Liu chao <[email protected]> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of LCUI nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string.h> #include <stdlib.h> #include <errno.h> #include <LCUI_Build.h> #include <LCUI/types.h> #include <LCUI/util/math.h> #include <LCUI/util/parse.h> #include <LCUI/util/linkedlist.h> #include <LCUI/font.h> typedef enum LCUI_TextStyleTagType_ { TEXT_STYLE_STYLE, TEXT_STYLE_BOLD, TEXT_STYLE_ITALIC, TEXT_STYLE_SIZE, TEXT_STYLE_COLOR, TEXT_STYLE_BG_COLOR, TEXT_STYLE_TOTAL_NUM } LCUI_TextStyleTagType; typedef struct LCUI_StyleTag { LCUI_TextStyleTagType id; LCUI_StyleRec style; } LCUI_TextStyleTag; void TextStyle_Init(LCUI_TextStyle data) { data->has_style = FALSE; data->has_weight = FALSE; data->has_family = FALSE; data->has_pixel_size = FALSE; data->has_back_color = FALSE; data->has_fore_color = FALSE; data->font_ids = NULL; data->style = FONT_STYLE_NORMAL; data->weight = FONT_WEIGHT_NORMAL; data->fore_color.value = 0xff333333; data->back_color.value = 0xffffffff; data->pixel_size = 13; } int TextStyle_CopyFamily(LCUI_TextStyle dst, LCUI_TextStyle src) { size_t len; if (!src->has_family) { return 0; } for (len = 0; src->font_ids[len]; ++len); len += 1; if (dst->font_ids) { free(dst->font_ids); } dst->font_ids = malloc(len * sizeof(int)); if (!dst->font_ids) { return -ENOMEM; } dst->has_family = TRUE; memcpy(dst->font_ids, src->font_ids, len * sizeof(int)); return 0; } int TextStyle_Copy(LCUI_TextStyle dst, LCUI_TextStyle src) { *dst = *src; dst->font_ids = NULL; return TextStyle_CopyFamily(dst, src); } void TextStyle_Destroy(LCUI_TextStyle data) { if (data->font_ids) { free(data->font_ids); } data->font_ids = NULL; } void TextStyle_Merge(LCUI_TextStyle base, LCUI_TextStyle target) { int *font_ids = NULL; base->has_family = TRUE; TextStyle_CopyFamily(base, target); if (target->has_style && !base->has_style && target->style != FONT_STYLE_NORMAL) { base->has_style = TRUE; base->style = target->style; } if (LCUIFont_UpdateStyle(base->font_ids, base->style, &font_ids) > 0) { free(base->font_ids); base->font_ids = font_ids; } if (target->has_weight && !base->has_weight && target->weight != FONT_WEIGHT_NORMAL) { base->has_weight = TRUE; base->weight = target->weight; } if (LCUIFont_UpdateWeight(base->font_ids, base->weight, &font_ids) > 0) { free(base->font_ids); base->font_ids = font_ids; } } int TextStyle_SetWeight(LCUI_TextStyle ts, LCUI_FontWeight weight) { int *font_ids; ts->weight = weight; ts->has_weight = TRUE; if (LCUIFont_UpdateWeight(ts->font_ids, weight, &font_ids) > 0) { free(ts->font_ids); ts->font_ids = font_ids; return 0; } return -1; } int TextStyle_SetStyle(LCUI_TextStyle ts, LCUI_FontStyle style) { int *font_ids; ts->style = style; ts->has_style = TRUE; if (LCUIFont_UpdateStyle(ts->font_ids, style, &font_ids) > 0) { free(ts->font_ids); ts->font_ids = font_ids; return 0; } return -1; } int TextStyle_SetFont(LCUI_TextStyle ts, const char *str) { size_t count; if (ts->has_family && ts->font_ids) { free(ts->font_ids); } ts->font_ids = NULL; ts->has_family = FALSE; count = LCUIFont_GetIdByNames(&ts->font_ids, ts->style, ts->weight, str); if (count > 0) { ts->has_family = TRUE; return 0; } return -1; } int TextStyle_SetDefaultFont(LCUI_TextStyle ts) { if (ts->has_family && ts->font_ids) { free(ts->font_ids); ts->has_family = FALSE; } ts->font_ids = malloc(sizeof(int) * 2); if (!ts->font_ids) { ts->font_ids = NULL; return -ENOMEM; } ts->has_family = TRUE; ts->font_ids[0] = LCUIFont_GetDefault(); ts->font_ids[1] = 0; return 0; } /*-------------------------- StyleTag --------------------------------*/ void StyleTags_Clear(LinkedList *tags) { LinkedList_Clear(tags, free); } /** 获取当前的文本样式 */ LCUI_TextStyle StyleTags_GetTextStyle(LinkedList *tags) { int count = 0; LinkedListNode *node; LCUI_TextStyleTag *tag; LCUI_TextStyle style; LCUI_BOOL found_tags[TEXT_STYLE_TOTAL_NUM] = { 0 }; if (tags->length <= 0) { return NULL; } style = malloc(sizeof(LCUI_TextStyleRec)); TextStyle_Init(style); /* 根据已经记录的各种样式,生成当前应有的文本样式 */ for (LinkedList_EachReverse(node, tags)) { tag = node->data; switch (tag->id) { case TEXT_STYLE_COLOR: if (found_tags[tag->id]) { break; } style->has_fore_color = TRUE; style->fore_color = tag->style.color; found_tags[tag->id] = TRUE; ++count; break; case TEXT_STYLE_BG_COLOR: if (found_tags[tag->id]) { break; } style->has_back_color = TRUE; style->back_color = tag->style.color; found_tags[tag->id] = TRUE; ++count; break; case TEXT_STYLE_BOLD: if (found_tags[tag->id]) { break; } found_tags[tag->id] = TRUE; TextStyle_SetWeight(style, FONT_WEIGHT_BOLD); ++count; break; case TEXT_STYLE_ITALIC: if (found_tags[tag->id]) { break; } found_tags[tag->id] = TRUE; TextStyle_SetStyle(style, FONT_STYLE_ITALIC); ++count; break; case TEXT_STYLE_SIZE: if (found_tags[tag->id]) { break; } style->has_pixel_size = TRUE; style->pixel_size = iround(tag->style.px); found_tags[tag->id] = TRUE; ++count; break; default: break; } if (count == 4) { break; } } if (count == 0) { free(style); return NULL; } return style; } /** 将指定标签的样式数据从队列中删除,只删除队列尾部第一个匹配的标签 */ static void StyleTags_Delete(LinkedList *tags, int id) { LCUI_TextStyleTag *tag; LinkedListNode *node; DEBUG_MSG("delete start, total tag: %d\n", total); if (tags->length <= 0) { return; } for (LinkedList_Each(node, tags)) { tag = node->data; if (tag->id == id) { free(tag); LinkedList_DeleteNode(tags, node); break; } } DEBUG_MSG("delete end, total tag: %d\n", tags->length); } /** 清除字符串中的空格 */ void clear_space(char *in, char *out) { size_t j, i, len = strlen(in); for (j = i = 0; i < len; ++i) { if (in[i] == ' ') { continue; } out[j] = in[i]; ++j; } out[j] = 0; } /** 在字符串中获取样式的结束标签,输出的是标签名 */ const wchar_t *ScanStyleEndingTag(const wchar_t *wstr, wchar_t *name) { size_t i, j, len; len = wcslen(wstr); if (wstr[0] != '[' || wstr[1] != '/') { return NULL; } /* 匹配标签,获取标签名 */ for (j = 0, i = 2; i < len; ++i) { switch (wstr[i]) { case ' ': break; case ']': ++i; goto end_tag_search; default: if (name) { name[j] = wstr[i]; } ++j; break; } } end_tag_search:; if (name) { name[j] = 0; } if (j < 1) { return NULL; } return wstr + i; } /** 从字符串中获取样式标签的名字及样式属性 */ const wchar_t *ScanStyleTag(const wchar_t *wstr, wchar_t *name, int max_name_len, wchar_t *data) { size_t i, j, len; LCUI_BOOL end_name = FALSE; len = wcslen(wstr); if (wstr[0] != '<') { return NULL; } /* 匹配标签前半部分 */ for (j = 0, i = 1; i < len; ++i) { if (wstr[i] == ' ') { /* 如果上个字符不是空格,说明标签名已经结束 */ if (i > 0 && wstr[i - 1] != ' ') { end_name = TRUE; } /* 标签名首部和尾部可包含空格 */ if (j == 0 || max_name_len == 0 || (max_name_len > 0 && end_name)) { continue; } /* 标签名中间不能包含空格 */ return NULL; } /* 如果标签名部分已经匹配完 */ if (wstr[i] == '=') { ++i; break; } /* 如果标签名已经结束了 */ if (end_name) { return NULL; } if (max_name_len > 0 && data) { name[j] = wstr[i]; } ++j; } if (data) { name[j] = 0; } /* 获取标签后半部分 */ for (j = 0; i < len; ++i) { if (wstr[i] == ' ') { continue; } /* 标签结束,退出 */ if (wstr[i] == '>') { ++i; break; } if (data) { /* 保存标签内的数据 */ data[j] = wstr[i]; } ++j; } if (data) { data[j] = 0; } if (i >= len) { return NULL; } return wstr + i; } /** 在字符串中获取指定样式标签中的数据 */ static const wchar_t *ScanStyleTagByName(const wchar_t *wstr, const wchar_t *name, char *data) { size_t i, j, len, tag_len; len = wcslen(wstr); tag_len = wcslen(name); if (wstr[0] != '[') { return NULL; } /* 匹配标签前半部分 */ for (j = 0, i = 1; i < len; ++i) { if (wstr[i] == ' ') { if (j == 0 || j >= tag_len) { continue; } return NULL; } if (j < tag_len) { if (wstr[i] == name[j]) { ++j; continue; } } else if (wstr[i] == '=') { ++i; break; } else if (wstr[i] == ']') { break; } return NULL; } /* 获取标签后半部分 */ for (j = 0; i < len; ++i) { if (wstr[i] == ' ') { continue; } /* 标签结束,退出 */ if (wstr[i] == ']') { ++i; break; } /* 保存标签内的数据 */ data[j] = (char)wstr[i]; ++j; } data[j] = 0; if (i >= len) { return NULL; } return &wstr[i]; } /** 根据字符串中的标签得到相应的样式数据,并返回指向标签后面字符的指针 */ static const wchar_t *ScanStyleTagData(const wchar_t *wstr, LCUI_TextStyleTag *tag) { const wchar_t *p, *q; char tag_data[256]; p = wstr; if ((q = ScanStyleTagByName(p, L"color", tag_data))) { if (!ParseColor(&tag->style, tag_data)) { return NULL; } tag->id = TEXT_STYLE_COLOR; return q; } if ((q = ScanStyleTagByName(p, L"bgcolor", tag_data))) { if (!ParseColor(&tag->style, tag_data)) { return NULL; } tag->id = TEXT_STYLE_BG_COLOR; return q; } if ((q = ScanStyleTagByName(p, L"size", tag_data))) { if (!ParseNumber(&tag->style, tag_data)) { return NULL; } tag->id = TEXT_STYLE_SIZE; return q; } if ((q = ScanStyleTagByName(p, L"b", tag_data))) { tag->id = TEXT_STYLE_BOLD; return q; } if ((q = ScanStyleTagByName(p, L"i", tag_data))) { tag->id = TEXT_STYLE_ITALIC; return q; } return NULL; } /** 处理样式标签 */ const wchar_t *StyleTags_GetStart(LinkedList *tags, const wchar_t *str) { const wchar_t *q; LCUI_TextStyleTag *tag = NEW(LCUI_TextStyleTag, 1); q = ScanStyleTagData(str, tag); if (q) { /* 将标签样式数据加入队列 */ LinkedList_Insert(tags, 0, tag); } else { free(tag); } return q; } /** 处理样式结束标签 */ const wchar_t* StyleTags_GetEnd(LinkedList *tags, const wchar_t *str) { const wchar_t *p; wchar_t tagname[256]; /* 获取标签名 */ p = ScanStyleEndingTag(str, tagname); if (!p) { return NULL; } /* 删除相应的样式标签 */ if (wcscmp(tagname, L"color") == 0) { StyleTags_Delete(tags, TEXT_STYLE_COLOR); } else if (wcscmp(tagname, L"bgcolor") == 0) { StyleTags_Delete(tags, TEXT_STYLE_BG_COLOR); } else if (wcscmp(tagname, L"size") == 0) { StyleTags_Delete(tags, TEXT_STYLE_SIZE); } else if (wcscmp(tagname, L"b") == 0) { StyleTags_Delete(tags, TEXT_STYLE_BOLD); } else if (wcscmp(tagname, L"i") == 0) { StyleTags_Delete(tags, TEXT_STYLE_ITALIC); } else { return NULL; } return p; } /*------------------------- End StyleTag -----------------------------*/
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <NewsUI2/_TtC7NewsUI217NoopAudioAssembly.h> @interface _TtC7NewsUI217NoopAudioAssembly (NewsUI2) - (void)loadInRegistry:(id)arg1; @end
{ "pile_set_name": "Github" }
/* * Copyright (C) 2004, 2005 Nikolas Zimmermann <[email protected]> * Copyright (C) 2004, 2005 Rob Buis <[email protected]> * Copyright (C) 2006 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ interface SVGTransform { // Transform Types const unsigned short SVG_TRANSFORM_UNKNOWN = 0; const unsigned short SVG_TRANSFORM_MATRIX = 1; const unsigned short SVG_TRANSFORM_TRANSLATE = 2; const unsigned short SVG_TRANSFORM_SCALE = 3; const unsigned short SVG_TRANSFORM_ROTATE = 4; const unsigned short SVG_TRANSFORM_SKEWX = 5; const unsigned short SVG_TRANSFORM_SKEWY = 6; readonly attribute unsigned short type; [ImplementedAs=svgMatrix] readonly attribute SVGMatrix matrix; readonly attribute unrestricted float angle; [StrictTypeChecking] void setMatrix(SVGMatrix matrix); [StrictTypeChecking] void setTranslate(unrestricted float tx, unrestricted float ty); [StrictTypeChecking] void setScale(unrestricted float sx, unrestricted float sy); [StrictTypeChecking] void setRotate(unrestricted float angle, unrestricted float cx, unrestricted float cy); [StrictTypeChecking] void setSkewX(unrestricted float angle); [StrictTypeChecking] void setSkewY(unrestricted float angle); };
{ "pile_set_name": "Github" }
$(function() { $('.navdrawer-nav a[title]').tooltip({ 'html': true, 'placement': 'right', 'boundary': 'viewport' }); });
{ "pile_set_name": "Github" }
"use strict"; /* Generated from: * ap-northeast-1 (https://d33vqc0rt9ld30.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * ap-northeast-2 (https://d1ane3fvebulky.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * ap-northeast-3 (https://d2zq80gdmjim8k.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * ap-south-1 (https://d2senuesg1djtx.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * ap-southeast-1 (https://doigdx0kgq9el.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * ap-southeast-2 (https://d2stg8d246z9di.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * ca-central-1 (https://d2s8ygphhesbe7.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * eu-central-1 (https://d1mta8qj7i28i2.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * eu-west-1 (https://d3teyb21fexa9r.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * eu-west-2 (https://d1742qcu2c1ncx.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * eu-west-3 (https://d2d0mfegowb3wk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * sa-east-1 (https://d3c9jyj3w509b0.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * us-east-1 (https://d1uauaxba7bl26.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * us-east-2 (https://dnwj8swjjbsbt.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * us-west-1 (https://d68hl49wbnanq.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0, * us-west-2 (https://d201a2mn26r7lk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0 */ Object.defineProperty(exports, "__esModule", { value: true }); const simulationApplication_1 = require("./simulationApplication"); const simulationApplicationVersion_1 = require("./simulationApplicationVersion"); const robotApplication_1 = require("./robotApplication"); const fleet_1 = require("./fleet"); const robotApplicationVersion_1 = require("./robotApplicationVersion"); const robot_1 = require("./robot"); var RoboMaker; (function (RoboMaker) { RoboMaker.SimulationApplication = simulationApplication_1.default; RoboMaker.SimulationApplicationVersion = simulationApplicationVersion_1.default; RoboMaker.RobotApplication = robotApplication_1.default; RoboMaker.Fleet = fleet_1.default; RoboMaker.RobotApplicationVersion = robotApplicationVersion_1.default; RoboMaker.Robot = robot_1.default; })(RoboMaker = exports.RoboMaker || (exports.RoboMaker = {}));
{ "pile_set_name": "Github" }
def safe_remove(f): import os try: os.remove(f) except OSError: pass """ Basic logger functionality; replace this with a real logger of your choice """ import imp import sys class VPLogger: def debug(self, s): print '[DEBUG] %s' % s def info(self, s): print '[INFO] %s' % s def warning(self, s): print '[WARNING] %s' % s def error(self, s): print '[ERROR] %s' % s def import_non_local(name, custom_name=None): """Import when you have conflicting names""" custom_name = custom_name or name f, pathname, desc = imp.find_module(name, sys.path[1:]) module = imp.load_module(custom_name, f, pathname, desc) if f: f.close() return module
{ "pile_set_name": "Github" }
<p></p>
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <title>Suave Test Page</title> <script type="text/javascript"> //<![CDATA[ window.addEventListener("load", function () { var sendFiles = function(event) { var fd = new FormData(event.target); fd.append('custom', 1337); var request = new XMLHttpRequest(); request.addEventListener("load", function(event) { if (console && console.log) { console.info('success', event.target.responseText); } }); request.addEventListener("error", function(event) { if (console && console.log) { console.error('error', event); } }); request.open("PUT", event.target.action); request.send(fd); }; document.getElementById("up3").addEventListener("submit", function (event) { event.preventDefault(); sendFiles(event); }); }); //]]> </script> </head> <body> <h1>POST testing</h1> <h2>Simple data POST</h2> <form method="post" action="test.html"> <p> <input type="text" name="edit1" /><br /> <input type="submit" /> </p> </form> <h2>1. File Upload test</h2> <form method="post" action="upload" enctype="multipart/form-data"> <p> <input type="file" name="myfile" /><br /> <input type="submit" /> </p> </form> <h2>2. Multiple File Upload test &ndash; <pre>multipart/form-data</pre></h2> <form method="PUT" action="upload2" enctype="multipart/form-data"> <p> <input type="file" name="myfile1" /><br /> <input type="file" name="myfile2" /><br /> <input type="text" name="edit1" /><br /> <input type="submit" /> </p> </form> <h2>3. Multiple File JavaScript/FormData Upload test</h2> <form id="up3" name="up3" method="PUT" action="upload2"> <p>Will post with <pre>Content-Type: multipart/form-data; boundary=---------------------------15407761691467256857631277098</pre></p> <p> <input type="file" name="myfile1" accept="image/*;capture=camera" required="required" /> *<br /> <input type="file" name="myfile2" accept="image/*;capture=camera" /><br /> <input type="text" name="edit1" /><br /> <input type="submit" /> </p> </form> <h2>Image</h2> <img src="examples.png" /> <h2>4. International Form Fields</h2> <form id="put1" name="put1" method="POST" action="i18nforms" enctype="multipart/form-data"> <p>Will now post a form with a number of funky names</p> <p> <input type="text" name="ödlan" /><br /> <input type="text" name="小" value="small" /><br /> <input type="submit" /> </p> </form> </body> </html>
{ "pile_set_name": "Github" }
#include <stdio.h> #include <string.h> int romanToInt(char *s) { int len = strlen(s); int ans = 0; int i = 0; while (i < len) { switch (s[i]) { case 'M': ans += 1000; break; case 'D': ans += 500; break; case 'C': if (s[i + 1] == 'D' || s[i + 1] == 'M'){ ans -= 100; } else { ans += 100; } break; case 'L': ans += 50; break; case 'X': if (s[i + 1] == 'L' || s[i + 1] == 'C'){ ans -= 10; } else { ans += 10; } break; case 'V': ans += 5; break; case 'I': if (s[i + 1] == 'V' || s[i + 1] == 'X'){ ans -= 1; } else { ans += 1; } break; default: break; } i++; } return ans; } int main() { char s1[] = "MMXIV"; char s2[] = "MMXV"; /* should be 2014 */ printf("%d\n", romanToInt(s1)); /* should be 2015 */ printf("%d\n", romanToInt(s2)); return 0; }
{ "pile_set_name": "Github" }
import { IScheduler } from '../Scheduler'; import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { TeardownLogic } from '../Subscription'; /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export declare class ScalarObservable<T> extends Observable<T> { value: T; private scheduler; static create<T>(value: T, scheduler?: IScheduler): ScalarObservable<T>; static dispatch(state: any): void; _isScalar: boolean; constructor(value: T, scheduler?: IScheduler); protected _subscribe(subscriber: Subscriber<T>): TeardownLogic; }
{ "pile_set_name": "Github" }
package ezy.sdk3rd.social.sdk; /** * Created by ezy on 17/3/18. */ public interface OnSucceed<T> { void onSucceed(T result); }
{ "pile_set_name": "Github" }
package jsoniter import ( "encoding/json" "io" "reflect" "sync" "unsafe" "github.com/modern-go/concurrent" "github.com/modern-go/reflect2" ) // Config customize how the API should behave. // The API is created from Config by Froze. type Config struct { IndentionStep int MarshalFloatWith6Digits bool EscapeHTML bool SortMapKeys bool UseNumber bool DisallowUnknownFields bool TagKey string OnlyTaggedField bool ValidateJsonRawMessage bool ObjectFieldMustBeSimpleString bool CaseSensitive bool } // API the public interface of this package. // Primary Marshal and Unmarshal. type API interface { IteratorPool StreamPool MarshalToString(v interface{}) (string, error) Marshal(v interface{}) ([]byte, error) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) UnmarshalFromString(str string, v interface{}) error Unmarshal(data []byte, v interface{}) error Get(data []byte, path ...interface{}) Any NewEncoder(writer io.Writer) *Encoder NewDecoder(reader io.Reader) *Decoder Valid(data []byte) bool RegisterExtension(extension Extension) DecoderOf(typ reflect2.Type) ValDecoder EncoderOf(typ reflect2.Type) ValEncoder } // ConfigDefault the default API var ConfigDefault = Config{ EscapeHTML: true, }.Froze() // ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior var ConfigCompatibleWithStandardLibrary = Config{ EscapeHTML: true, SortMapKeys: true, ValidateJsonRawMessage: true, }.Froze() // ConfigFastest marshals float with only 6 digits precision var ConfigFastest = Config{ EscapeHTML: false, MarshalFloatWith6Digits: true, // will lose precession ObjectFieldMustBeSimpleString: true, // do not unescape object field }.Froze() type frozenConfig struct { configBeforeFrozen Config sortMapKeys bool indentionStep int objectFieldMustBeSimpleString bool onlyTaggedField bool disallowUnknownFields bool decoderCache *concurrent.Map encoderCache *concurrent.Map encoderExtension Extension decoderExtension Extension extraExtensions []Extension streamPool *sync.Pool iteratorPool *sync.Pool caseSensitive bool } func (cfg *frozenConfig) initCache() { cfg.decoderCache = concurrent.NewMap() cfg.encoderCache = concurrent.NewMap() } func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { cfg.decoderCache.Store(cacheKey, decoder) } func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { cfg.encoderCache.Store(cacheKey, encoder) } func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { decoder, found := cfg.decoderCache.Load(cacheKey) if found { return decoder.(ValDecoder) } return nil } func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { encoder, found := cfg.encoderCache.Load(cacheKey) if found { return encoder.(ValEncoder) } return nil } var cfgCache = concurrent.NewMap() func getFrozenConfigFromCache(cfg Config) *frozenConfig { obj, found := cfgCache.Load(cfg) if found { return obj.(*frozenConfig) } return nil } func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { cfgCache.Store(cfg, frozenConfig) } // Froze forge API from config func (cfg Config) Froze() API { api := &frozenConfig{ sortMapKeys: cfg.SortMapKeys, indentionStep: cfg.IndentionStep, objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, onlyTaggedField: cfg.OnlyTaggedField, disallowUnknownFields: cfg.DisallowUnknownFields, caseSensitive: cfg.CaseSensitive, } api.streamPool = &sync.Pool{ New: func() interface{} { return NewStream(api, nil, 512) }, } api.iteratorPool = &sync.Pool{ New: func() interface{} { return NewIterator(api) }, } api.initCache() encoderExtension := EncoderExtension{} decoderExtension := DecoderExtension{} if cfg.MarshalFloatWith6Digits { api.marshalFloatWith6Digits(encoderExtension) } if cfg.EscapeHTML { api.escapeHTML(encoderExtension) } if cfg.UseNumber { api.useNumber(decoderExtension) } if cfg.ValidateJsonRawMessage { api.validateJsonRawMessage(encoderExtension) } api.encoderExtension = encoderExtension api.decoderExtension = decoderExtension api.configBeforeFrozen = cfg return api } func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig { api := getFrozenConfigFromCache(cfg) if api != nil { return api } api = cfg.Froze().(*frozenConfig) for _, extension := range extraExtensions { api.RegisterExtension(extension) } addFrozenConfigToCache(cfg, api) return api } func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { rawMessage := *(*json.RawMessage)(ptr) iter := cfg.BorrowIterator([]byte(rawMessage)) defer cfg.ReturnIterator(iter) iter.Read() if iter.Error != nil && iter.Error != io.EOF { stream.WriteRaw("null") } else { stream.WriteRaw(string(rawMessage)) } }, func(ptr unsafe.Pointer) bool { return len(*((*json.RawMessage)(ptr))) == 0 }} extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder } func (cfg *frozenConfig) useNumber(extension DecoderExtension) { extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { exitingValue := *((*interface{})(ptr)) if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { iter.ReadVal(exitingValue) return } if iter.WhatIsNext() == NumberValue { *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) } else { *((*interface{})(ptr)) = iter.Read() } }} } func (cfg *frozenConfig) getTagKey() string { tagKey := cfg.configBeforeFrozen.TagKey if tagKey == "" { return "json" } return tagKey } func (cfg *frozenConfig) RegisterExtension(extension Extension) { cfg.extraExtensions = append(cfg.extraExtensions, extension) copied := cfg.configBeforeFrozen cfg.configBeforeFrozen = copied } type lossyFloat32Encoder struct { } func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat32Lossy(*((*float32)(ptr))) } func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float32)(ptr)) == 0 } type lossyFloat64Encoder struct { } func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat64Lossy(*((*float64)(ptr))) } func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float64)(ptr)) == 0 } // EnableLossyFloatMarshalling keeps 10**(-6) precision // for float variables for better performance. func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { // for better performance extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} } type htmlEscapedStringEncoder struct { } func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { str := *((*string)(ptr)) stream.WriteStringWithHTMLEscaped(str) } func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*string)(ptr)) == "" } func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} } func (cfg *frozenConfig) cleanDecoders() { typeDecoders = map[string]ValDecoder{} fieldDecoders = map[string]ValDecoder{} *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) } func (cfg *frozenConfig) cleanEncoders() { typeEncoders = map[string]ValEncoder{} fieldEncoders = map[string]ValEncoder{} *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) } func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) { stream := cfg.BorrowStream(nil) defer cfg.ReturnStream(stream) stream.WriteVal(v) if stream.Error != nil { return "", stream.Error } return string(stream.Buffer()), nil } func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { stream := cfg.BorrowStream(nil) defer cfg.ReturnStream(stream) stream.WriteVal(v) if stream.Error != nil { return nil, stream.Error } result := stream.Buffer() copied := make([]byte, len(result)) copy(copied, result) return copied, nil } func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { if prefix != "" { panic("prefix is not supported") } for _, r := range indent { if r != ' ' { panic("indent can only be space") } } newCfg := cfg.configBeforeFrozen newCfg.IndentionStep = len(indent) return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v) } func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { data := []byte(str) iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.ReadVal(v) c := iter.nextToken() if c == 0 { if iter.Error == io.EOF { return nil } return iter.Error } iter.ReportError("Unmarshal", "there are bytes left after unmarshal") return iter.Error } func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) return locatePath(iter, path) } func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.ReadVal(v) c := iter.nextToken() if c == 0 { if iter.Error == io.EOF { return nil } return iter.Error } iter.ReportError("Unmarshal", "there are bytes left after unmarshal") return iter.Error } func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder { stream := NewStream(cfg, writer, 512) return &Encoder{stream} } func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder { iter := Parse(cfg, reader, 512) return &Decoder{iter} } func (cfg *frozenConfig) Valid(data []byte) bool { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.Skip() return iter.Error == nil }
{ "pile_set_name": "Github" }
#region Copyright notice and license // Copyright 2019 The gRPC 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. #endregion using Microsoft.Extensions.DependencyInjection; namespace Grpc.AspNetCore.Server.Internal { /// <summary> /// A marker class used to determine if all the required gRPC services were added /// to the <see cref="IServiceCollection"/>. /// </summary> internal class GrpcMarkerService { } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.cxf.systests</groupId> <artifactId>cxf-systests-container-integration</artifactId> <version>3.4.1-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>cxf-systests-ci-webapp</artifactId> <name>Apache CXF Container Integration Test Webapp</name> <description>Apache CXF Container Integration Test Webapp</description> <packaging>war</packaging> <properties> <cxf.module.name>org.apache.cxf.systests.ci.webapp</cxf.module.name> </properties> <dependencies> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> </dependencies> </project>
{ "pile_set_name": "Github" }
H 514 // -0.003071 0xFF9B // 0.000000 0x0000 // 0.000837 0x001B // 0.000460 0x000F // -0.000172 0xFFFA // 0.004224 0x008A // 0.001067 0x0023 // -0.000172 0xFFFA // -0.000591 0xFFED // 0.001196 0x0027 // 0.000749 0x0019 // -0.002649 0xFFA9 // -0.002541 0xFFAD // 0.000919 0x001E // 0.001236 0x0028 // 0.002534 0x0053 // -0.000219 0xFFF9 // 0.002971 0x0061 // -0.000512 0xFFEF // -0.001688 0xFFC9 // -0.003583 0xFF8B // -0.001090 0xFFDC // 0.000593 0x0013 // 0.003065 0x0064 // -0.000524 0xFFEF // -0.001371 0xFFD3 // 0.001801 0x003B // 0.001528 0x0032 // -0.002660 0xFFA9 // -0.002455 0xFFB0 // 0.002330 0x004C // -0.000900 0xFFE3 // -0.002564 0xFFAC // -0.000514 0xFFEF // -0.001033 0xFFDE // 0.000281 0x0009 // 0.000469 0x000F // -0.002239 0xFFB7 // -0.002356 0xFFB3 // 0.000554 0x0012 // -0.002421 0xFFB1 // -0.000130 0xFFFC // -0.000562 0xFFEE // 0.001396 0x002E // -0.002489 0xFFAE // 0.000426 0x000E // 0.002256 0x004A // 0.002442 0x0050 // 0.001776 0x003A // 0.000518 0x0011 // -0.001811 0xFFC5 // 0.000621 0x0014 // -0.000363 0xFFF4 // -0.000726 0xFFE8 // 0.002774 0x005B // 0.000604 0x0014 // 0.001582 0x0034 // -0.003577 0xFF8B // -0.005167 0xFF57 // -0.000674 0xFFEA // 0.001228 0x0028 // 0.005169 0x00A9 // -0.002550 0xFFAC // 0.000948 0x001F // -0.000272 0xFFF7 // -0.348433 0xD367 // 0.000003 0x0000 // -0.002993 0xFF9E // -0.003208 0xFF97 // 0.000343 0x000B // -0.004114 0xFF79 // 0.001893 0x003E // -0.000575 0xFFED // -0.002274 0xFFB5 // -0.001288 0xFFD6 // 0.004634 0x0098 // 0.001951 0x0040 // 0.000565 0x0013 // 0.004877 0x00A0 // -0.004819 0xFF62 // -0.001148 0xFFDA // -0.003033 0xFF9D // 0.000542 0x0012 // 0.002940 0x0060 // 0.002456 0x0050 // 0.003269 0x006B // 0.000090 0x0003 // 0.003598 0x0076 // -0.000852 0xFFE4 // -0.001671 0xFFC9 // 0.003703 0x0079 // 0.000302 0x000A // 0.001622 0x0035 // -0.001162 0xFFDA // 0.000454 0x000F // -0.003371 0xFF92 // 0.005582 0x00B7 // 0.000520 0x0011 // 0.000053 0x0002 // 0.000482 0x0010 // -0.000753 0xFFE7 // -0.002900 0xFFA1 // -0.002337 0xFFB3 // -0.000990 0xFFE0 // 0.000336 0x000B // -0.002012 0xFFBE // 0.002787 0x005B // 0.002887 0x005F // -0.000504 0xFFEF // -0.002794 0xFFA4 // -0.002083 0xFFBC // 0.002852 0x005D // -0.003867 0xFF81 // -0.003583 0xFF8B // 0.004177 0x0089 // 0.003345 0x006E // -0.001919 0xFFC1 // -0.001362 0xFFD3 // -0.001385 0xFFD3 // 0.000467 0x000F // 0.000274 0x0009 // 0.002044 0x0043 // 0.002510 0x0052 // -0.002230 0xFFB7 // 0.001917 0x003F // -0.002398 0xFFB1 // 0.000628 0x0015 // -0.003740 0xFF85 // 0.001128 0x0025 // -0.000604 0xFFEC // -0.000438 0xFFF2 // -0.001033 0xFFDE // 0.000429 0x000E // -0.002321 0xFFB4 // 0.001635 0x0036 // -0.000327 0xFFF5 // 0.000236 0x0008 // 0.002720 0x0059 // -0.000609 0xFFEC // -0.001582 0xFFCC // 0.003225 0x006A // -0.002813 0xFFA4 // -0.000369 0xFFF4 // -0.001834 0xFFC4 // 0.000031 0x0001 // 0.000185 0x0006 // 0.000105 0x0003 // -0.000179 0xFFFA // -0.000319 0xFFF6 // -0.000499 0xFFF0 // 0.002246 0x004A // 0.000977 0x0020 // -0.001249 0xFFD7 // 0.002727 0x0059 // -0.000492 0xFFF0 // 0.000821 0x001B // -0.000651 0xFFEB // -0.002319 0xFFB4 // 0.000045 0x0001 // 0.001755 0x003A // 0.002297 0x004B // -0.003476 0xFF8E // -0.002343 0xFFB3 // -0.000240 0xFFF8 // 0.001105 0x0024 // 0.001331 0x002C // 0.001400 0x002E // -0.000242 0xFFF8 // -0.001631 0xFFCB // -0.003229 0xFF96 // 0.002528 0x0053 // -0.001220 0xFFD8 // -0.002878 0xFFA2 // -0.001199 0xFFD9 // 0.002841 0x005D // -0.003089 0xFF9B // -0.005334 0xFF51 // 0.003751 0x007B // 0.000436 0x000E // -0.003199 0xFF97 // -0.000197 0xFFFA // 0.001792 0x003B // 0.000881 0x001D // -0.001966 0xFFC0 // 0.004552 0x0095 // 0.002998 0x0062 // 0.000748 0x0019 // 0.003216 0x0069 // -0.003147 0xFF99 // 0.005147 0x00A9 // 0.000788 0x001A // 0.000820 0x001B // 0.000375 0x000C // 0.001903 0x003E // 0.000857 0x001C // -0.003591 0xFF8A // 0.003376 0x006F // -0.000117 0xFFFC // 0.003477 0x0072 // -0.003027 0xFF9D // -0.000599 0xFFEC // 0.002421 0x004F // 0.000433 0x000E // -0.001123 0xFFDB // 0.000505 0x0011 // 0.000744 0x0018 // -0.003798 0xFF84 // -0.001847 0xFFC3 // -0.002098 0xFFBB // -0.000777 0xFFE7 // -0.002058 0xFFBD // 0.002545 0x0053 // 0.000802 0x001A // -0.001445 0xFFD1 // -0.000326 0xFFF5 // -0.001832 0xFFC4 // 0.001094 0x0024 // -0.001218 0xFFD8 // -0.000015 0x0000 // -0.000504 0xFFEF // 0.000501 0x0010 // 0.001190 0x0027 // 0.002021 0x0042 // 0.000211 0x0007 // 0.000260 0x0009 // 0.003467 0x0072 // -0.001353 0xFFD4 // -0.000851 0xFFE4 // 0.001836 0x003C // -0.001909 0xFFC1 // -0.000302 0xFFF6 // 0.000067 0x0002 // 0.004263 0x008C // -0.000206 0xFFF9 // -0.000589 0xFFED // 0.001973 0x0041 // -0.002440 0xFFB0 // 0.002888 0x005F // -0.000674 0xFFEA // 0.003050 0x0064 // -0.002185 0xFFB8 // -0.001720 0xFFC8 // -0.000264 0xFFF7 // 0.000836 0x001B // 0.002070 0x0044 // -0.000217 0xFFF9 // 0.002208 0x0048 // 0.003916 0x0080 // 0.003070 0x0065 // -0.001858 0xFFC3 // 0.001215 0x0028 // -0.002186 0xFFB8 // 0.000399 0x000D // 0.001567 0x0033 // 0.002489 0x0052 // -0.004808 0xFF62 // 0.005828 0x00BF // 0.000000 0x0000 // 0.002489 0x0052 // 0.004808 0x009E // 0.000399 0x000D // -0.001567 0xFFCD // 0.001215 0x0028 // 0.002186 0x0048 // 0.003070 0x0065 // 0.001858 0x003D // 0.002208 0x0048 // -0.003916 0xFF80 // 0.002070 0x0044 // 0.000217 0x0007 // -0.000264 0xFFF7 // -0.000836 0xFFE5 // -0.002185 0xFFB8 // 0.001720 0x0038 // -0.000674 0xFFEA // -0.003050 0xFF9C // -0.002440 0xFFB0 // -0.002888 0xFFA1 // -0.000589 0xFFED // -0.001973 0xFFBF // 0.004263 0x008C // 0.000206 0x0007 // -0.000302 0xFFF6 // -0.000067 0xFFFE // 0.001836 0x003C // 0.001909 0x003F // -0.001353 0xFFD4 // 0.000851 0x001C // 0.000260 0x0009 // -0.003467 0xFF8E // 0.002021 0x0042 // -0.000211 0xFFF9 // 0.000501 0x0010 // -0.001190 0xFFD9 // -0.000015 0x0000 // 0.000504 0x0011 // 0.001094 0x0024 // 0.001218 0x0028 // -0.000326 0xFFF5 // 0.001832 0x003C // 0.000802 0x001A // 0.001445 0x002F // -0.002058 0xFFBD // -0.002545 0xFFAD // -0.002098 0xFFBB // 0.000777 0x0019 // -0.003798 0xFF84 // 0.001847 0x003D // 0.000505 0x0011 // -0.000744 0xFFE8 // 0.000433 0x000E // 0.001123 0x0025 // -0.000599 0xFFEC // -0.002421 0xFFB1 // 0.003477 0x0072 // 0.003027 0x0063 // 0.003376 0x006F // 0.000117 0x0004 // 0.000857 0x001C // 0.003591 0x0076 // 0.000375 0x000C // -0.001903 0xFFC2 // 0.000788 0x001A // -0.000820 0xFFE5 // -0.003147 0xFF99 // -0.005147 0xFF57 // 0.000748 0x0019 // -0.003216 0xFF97 // 0.004552 0x0095 // -0.002998 0xFF9E // 0.000881 0x001D // 0.001966 0x0040 // -0.000197 0xFFFA // -0.001792 0xFFC5 // 0.000436 0x000E // 0.003199 0x0069 // -0.005334 0xFF51 // -0.003751 0xFF85 // 0.002841 0x005D // 0.003089 0x0065 // -0.002878 0xFFA2 // 0.001199 0x0027 // 0.002528 0x0053 // 0.001220 0x0028 // -0.001631 0xFFCB // 0.003229 0x006A // 0.001400 0x002E // 0.000242 0x0008 // 0.001105 0x0024 // -0.001331 0xFFD4 // -0.002343 0xFFB3 // 0.000240 0x0008 // 0.002297 0x004B // 0.003476 0x0072 // 0.000045 0x0001 // -0.001755 0xFFC6 // -0.000651 0xFFEB // 0.002319 0x004C // -0.000492 0xFFF0 // -0.000821 0xFFE5 // -0.001249 0xFFD7 // -0.002727 0xFFA7 // 0.002246 0x004A // -0.000977 0xFFE0 // -0.000319 0xFFF6 // 0.000499 0x0010 // 0.000105 0x0003 // 0.000179 0x0006 // 0.000031 0x0001 // -0.000185 0xFFFA // -0.000369 0xFFF4 // 0.001834 0x003C // 0.003225 0x006A // 0.002813 0x005C // -0.000609 0xFFEC // 0.001582 0x0034 // 0.000236 0x0008 // -0.002720 0xFFA7 // 0.001635 0x0036 // 0.000327 0x000B // 0.000429 0x000E // 0.002321 0x004C // -0.000438 0xFFF2 // 0.001033 0x0022 // 0.001128 0x0025 // 0.000604 0x0014 // 0.000628 0x0015 // 0.003740 0x007B // 0.001917 0x003F // 0.002398 0x004F // 0.002510 0x0052 // 0.002230 0x0049 // 0.000274 0x0009 // -0.002044 0xFFBD // -0.001385 0xFFD3 // -0.000467 0xFFF1 // -0.001919 0xFFC1 // 0.001362 0x002D // 0.004177 0x0089 // -0.003345 0xFF92 // -0.003867 0xFF81 // 0.003583 0x0075 // -0.002083 0xFFBC // -0.002852 0xFFA3 // -0.000504 0xFFEF // 0.002794 0x005C // 0.002787 0x005B // -0.002887 0xFFA1 // 0.000336 0x000B // 0.002012 0x0042 // -0.002337 0xFFB3 // 0.000990 0x0020 // -0.000753 0xFFE7 // 0.002900 0x005F // 0.000053 0x0002 // -0.000482 0xFFF0 // 0.005582 0x00B7 // -0.000520 0xFFEF // 0.000454 0x000F // 0.003371 0x006E // 0.001622 0x0035 // 0.001162 0x0026 // 0.003703 0x0079 // -0.000302 0xFFF6 // -0.000852 0xFFE4 // 0.001671 0x0037 // 0.000090 0x0003 // -0.003598 0xFF8A // 0.002456 0x0050 // -0.003269 0xFF95 // 0.000542 0x0012 // -0.002940 0xFFA0 // -0.001148 0xFFDA // 0.003033 0x0063 // 0.004877 0x00A0 // 0.004819 0x009E // 0.001951 0x0040 // -0.000565 0xFFED // -0.001288 0xFFD6 // -0.004634 0xFF68 // -0.000575 0xFFED // 0.002274 0x004B // -0.004114 0xFF79 // -0.001893 0xFFC2 // -0.003208 0xFF97 // -0.000343 0xFFF5 // 0.000003 0x0000 // 0.002993 0x0062 // -0.000272 0xFFF7 // 0.348433 0x2C99 // -0.002550 0xFFAC // -0.000948 0xFFE1 // 0.001228 0x0028 // -0.005169 0xFF57 // -0.005167 0xFF57 // 0.000674 0x0016 // 0.001582 0x0034 // 0.003577 0x0075 // 0.002774 0x005B // -0.000604 0xFFEC // -0.000363 0xFFF4 // 0.000726 0x0018 // -0.001811 0xFFC5 // -0.000621 0xFFEC // 0.001776 0x003A // -0.000518 0xFFEF // 0.002256 0x004A // -0.002442 0xFFB0 // -0.002489 0xFFAE // -0.000426 0xFFF2 // -0.000562 0xFFEE // -0.001396 0xFFD2 // -0.002421 0xFFB1 // 0.000130 0x0004 // -0.002356 0xFFB3 // -0.000554 0xFFEE // 0.000469 0x000F // 0.002239 0x0049 // -0.001033 0xFFDE // -0.000281 0xFFF7 // -0.002564 0xFFAC // 0.000514 0x0011 // 0.002330 0x004C // 0.000900 0x001D // -0.002660 0xFFA9 // 0.002455 0x0050 // 0.001801 0x003B // -0.001528 0xFFCE // -0.000524 0xFFEF // 0.001371 0x002D // 0.000593 0x0013 // -0.003065 0xFF9C // -0.003583 0xFF8B // 0.001090 0x0024 // -0.000512 0xFFEF // 0.001688 0x0037 // -0.000219 0xFFF9 // -0.002971 0xFF9F // 0.001236 0x0028 // -0.002534 0xFFAD // -0.002541 0xFFAD // -0.000919 0xFFE2 // 0.000749 0x0019 // 0.002649 0x0057 // -0.000591 0xFFED // -0.001196 0xFFD9 // 0.001067 0x0023 // 0.000172 0x0006 // -0.000172 0xFFFA // -0.004224 0xFF76 // 0.000837 0x001B // -0.000460 0xFFF1 // 0.000000 0x0000 // 0.000000 0x0000
{ "pile_set_name": "Github" }
'use strict'; module.exports = function (str, sep) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } sep = typeof sep === 'undefined' ? '_' : sep; return str .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') .toLowerCase(); };
{ "pile_set_name": "Github" }
<?php /* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_Spanner_Binding extends Google_Collection { protected $collection_key = 'members'; public $members; public $role; public function setMembers($members) { $this->members = $members; } public function getMembers() { return $this->members; } public function setRole($role) { $this->role = $role; } public function getRole() { return $this->role; } }
{ "pile_set_name": "Github" }
{ "id": "biancas-poster", "name": "Bianca's Poster", "games": { "nh": { "sellPrice": { "currency": "bells", "value": 250 }, "buyPrices": [ { "currency": "bells", "value": 1000 } ] } }, "category": "Photos" }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <!--[if IE]><![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Class OculusManifestPreprocessor | XRTK-Core </title> <meta name="viewport" content="width=device-width"> <meta name="title" content="Class OculusManifestPreprocessor | XRTK-Core "> <meta name="generator" content="docfx 2.52.0.0"> <link rel="shortcut icon" href="../favicon.png"> <link rel="stylesheet" href="../styles/docfx.vendor.css"> <link rel="stylesheet" href="../styles/docfx.css"> <link rel="stylesheet" href="../styles/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <meta property="docfx:navrel" content="../toc.html"> <meta property="docfx:tocrel" content="toc.html"> </head> <body data-spy="scroll" data-target="#affix" data-offset="120"> <div id="wrapper"> <header> <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"> <img id="logo" class="svg" src="../logo.png" alt=""> </a> </div> <div class="collapse navbar-collapse" id="navbar"> <form class="navbar-form navbar-right" role="search" id="search"> <div class="form-group"> <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off"> </div> </form> </div> </div> </nav> <div class="subnav navbar navbar-default"> <div class="container hide-when-search" id="breadcrumb"> <ul class="breadcrumb"> <li></li> </ul> </div> </div> </header> <div role="main" class="container body-content hide-when-search"> <div class="sidenav hide-when-search"> <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a> <div class="sidetoggle collapse" id="sidetoggle"> <div id="sidetoc"></div> </div> </div> <div class="article row grid-right"> <div class="col-md-10"> <article class="content wrap" id="_content" data-uid="XRTK.Oculus.OculusManifestPreprocessor"> <h1 id="XRTK_Oculus_OculusManifestPreprocessor" data-uid="XRTK.Oculus.OculusManifestPreprocessor" class="text-break">Class OculusManifestPreprocessor </h1> <div class="markdown level0 summary"></div> <div class="markdown level0 conceptual"></div> <div class="inheritance"> <h5>Inheritance</h5> <div class="level0"><a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object">Object</a></div> <div class="level1"><span class="xref">OculusManifestPreprocessor</span></div> </div> <div class="inheritedMembers"> <h5>Inherited Members</h5> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.equals#System_Object_Equals_System_Object_">Object.Equals(Object)</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.equals#System_Object_Equals_System_Object_System_Object_">Object.Equals(Object, Object)</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.gethashcode#System_Object_GetHashCode">Object.GetHashCode()</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.gettype#System_Object_GetType">Object.GetType()</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.memberwiseclone#System_Object_MemberwiseClone">Object.MemberwiseClone()</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.referenceequals#System_Object_ReferenceEquals_System_Object_System_Object_">Object.ReferenceEquals(Object, Object)</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.tostring#System_Object_ToString">Object.ToString()</a> </div> </div> <h6><strong>Namespace</strong>: <a class="xref" href="XRTK.Oculus.html">XRTK.Oculus</a></h6> <h6><strong>Assembly</strong>: XRTK.Oculus.Editor.dll</h6> <h5 id="XRTK_Oculus_OculusManifestPreprocessor_syntax">Syntax</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public class OculusManifestPreprocessor</code></pre> </div> <h3 id="methods">Methods </h3> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/XRTK/XRTK-Core/new/development/docs-ref-overwrite/new?filename=XRTK_Oculus_OculusManifestPreprocessor_GenerateManifestForSubmission.md&amp;value=---%0Auid%3A%20XRTK.Oculus.OculusManifestPreprocessor.GenerateManifestForSubmission%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/XRTK/XRTK-Core/blob/master/XRTK-Core/Packages/com.xrtk.oculus/Editor/OculusManifestPreprocessor.cs/#L30">View Source</a> </span> <a id="XRTK_Oculus_OculusManifestPreprocessor_GenerateManifestForSubmission_" data-uid="XRTK.Oculus.OculusManifestPreprocessor.GenerateManifestForSubmission*"></a> <h4 id="XRTK_Oculus_OculusManifestPreprocessor_GenerateManifestForSubmission" data-uid="XRTK.Oculus.OculusManifestPreprocessor.GenerateManifestForSubmission">GenerateManifestForSubmission()</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">[MenuItem(&quot;Mixed Reality Toolkit/Tools/Create Oculus Quest compatible AndroidManifest.xml&quot;, false, 100000)] public static void GenerateManifestForSubmission()</code></pre> </div> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/XRTK/XRTK-Core/new/development/docs-ref-overwrite/new?filename=XRTK_Oculus_OculusManifestPreprocessor_RemoveAndroidManifest.md&amp;value=---%0Auid%3A%20XRTK.Oculus.OculusManifestPreprocessor.RemoveAndroidManifest%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/XRTK/XRTK-Core/blob/master/XRTK-Core/Packages/com.xrtk.oculus/Editor/OculusManifestPreprocessor.cs/#L98">View Source</a> </span> <a id="XRTK_Oculus_OculusManifestPreprocessor_RemoveAndroidManifest_" data-uid="XRTK.Oculus.OculusManifestPreprocessor.RemoveAndroidManifest*"></a> <h4 id="XRTK_Oculus_OculusManifestPreprocessor_RemoveAndroidManifest" data-uid="XRTK.Oculus.OculusManifestPreprocessor.RemoveAndroidManifest">RemoveAndroidManifest()</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">[MenuItem(&quot;Mixed Reality Toolkit/Tools/Remove AndroidManifest.xml&quot;, false, 100001)] public static void RemoveAndroidManifest()</code></pre> </div> <h3 id="extensionmethods">Extension Methods</h3> <div> <a class="xref" href="XRTK.Extensions.ConverterExtensions.html#XRTK_Extensions_ConverterExtensions_GetBuiltInTypeBytes__1___0_">ConverterExtensions.GetBuiltInTypeBytes&lt;T&gt;(T)</a> </div> <div> <a class="xref" href="XRTK.Utilities.Async.Awaiters.html#XRTK_Utilities_Async_Awaiters_WaitUntil__1___0_System_Func___0_System_Boolean__System_Int32_">Awaiters.WaitUntil&lt;T&gt;(T, Func&lt;T, Boolean&gt;, Int32)</a> </div> </article> </div> <div class="hidden-sm col-md-2" role="complementary"> <div class="sideaffix"> <div class="contribution"> <ul class="nav"> <li> <a href="https://github.com/XRTK/XRTK-Core/new/development/docs-ref-overwrite/new?filename=XRTK_Oculus_OculusManifestPreprocessor.md&amp;value=---%0Auid%3A%20XRTK.Oculus.OculusManifestPreprocessor%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A" class="contribution-link">Improve this Doc</a> </li> <li> <a href="https://github.com/XRTK/XRTK-Core/blob/master/XRTK-Core/Packages/com.xrtk.oculus/Editor/OculusManifestPreprocessor.cs/#L28" class="contribution-link">View Source</a> </li> </ul> </div> <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix"> <!-- <p><a class="back-to-top" href="#top">Back to top</a><p> --> </nav> </div> </div> </div> </div> <footer> <div class="grad-bottom"></div> <div class="footer"> <div class="container"> <span class="pull-right"> <a href="#top">Back to top</a> </span> (c) XRTK </div> </div> </footer> </div> <script type="text/javascript" src="../styles/docfx.vendor.js"></script> <script type="text/javascript" src="../styles/docfx.js"></script> <script type="text/javascript" src="../styles/main.js"></script> </body> </html>
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <SAObjects/AceObject.h> #import <SAObjects/SAAceSerializable-Protocol.h> @class NSString; @interface SAUITemplateEdgeInsets : AceObject <SAAceSerializable> { } + (id)edgeInsetsWithDictionary:(id)arg1 context:(id)arg2; + (id)edgeInsets; @property(nonatomic) float top; @property(nonatomic) float right; @property(nonatomic) float left; @property(nonatomic) float bottom; - (id)encodedClassName; - (id)groupIdentifier; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
{ "pile_set_name": "Github" }
//===== eAthena Script ======================================= //= Lighthalzen Dungeon(Biolabs) Monster Spawn Script //===== By: ================================================== // The Prometheus Project, eAthena dev team //===== Current Version: ===================================== //= 1.8 //===== Compatible With: ===================================== //= Any Athena //===== Additional Comments: ================================= //= 08/24/05 : Added 1st version. [Muad_Dib] //= 1.1: Some corrections to level 1, 2 as pointed out by //= MasterofMuppets. [Skotlex] //= 1.3: Some fixes based on kRO's "RO Map" [Poki#3] //= I also made the place more Moby ^^ //= 1.4: Adjusted spawns according to own info from iRO [MasterOfMuppets] //= 1.5: More accurate spawn numbers and iRO names thanks to Tharis [Playtester] //= 1.6: Official X.3 spawns [Playtester] //= 1.7 Corrected MVP spawn function to be standard to iRO. [L0ne_W0lf] //= - A random 99 will now be spawned when the MVP spawns. //= - Spare spawn and MVP spawn now spawn in official locations. //= - Expandeded timer to allow for varying spawn times. //= 1.7a Added dummy event to keep from causnig warnings. [L0ne_W0lf] //= 1.8 Corrected MVP spawn variance (Labs2 MVP). [L0ne_W0lf] //============================================================ //======================================================================================== // lhz_dun01 - Bio-life Labs 1F //======================================================================================== lhz_dun01,0,0,0,0 monster Metaling 1613,50,0,0,0 lhz_dun01,0,0,0,0 monster Anopheles 1627,70,0,0,0 lhz_dun01,0,0,0,0 monster Remover 1682,100,0,0,0 lhz_dun01,0,0,0,0 monster Egnigem Cenia 1652,1,0,0,0 lhz_dun01,0,0,0,0 monster Wickebine Tres 1653,1,0,0,0 lhz_dun01,0,0,0,0 monster Armeyer Dinze 1654,1,0,0,0 lhz_dun01,0,0,0,0 monster Errende Ebecee 1655,1,0,0,0 lhz_dun01,0,0,0,0 monster Kavach Icarus 1656,1,0,0,0 lhz_dun01,0,0,0,0 monster Laurell Weinder 1657,1,0,0,0 lhz_dun01,150,50,16,18 monster Egnigem Cenia 1652,1,900000,800000,1 lhz_dun01,150,50,16,18 monster Wickebine Tres 1653,1,900000,800000,1 lhz_dun01,150,50,16,18 monster Armeyer Dinze 1654,1,900000,800000,1 lhz_dun01,150,50,16,18 monster Errende Ebecee 1655,5,900000,800000,1 lhz_dun01,150,50,16,18 monster Kavach Icarus 1656,5,600000,300000,1 lhz_dun01,150,50,16,18 monster Laurell Weinder 1657,5,600000,300000,1 lhz_dun01,250,150,18,30 monster Egnigem Cenia 1652,4,900000,800000,1 lhz_dun01,250,150,18,30 monster Wickebine Tres 1653,4,600000,300000,1 lhz_dun01,250,150,18,30 monster Armeyer Dinze 1654,4,900000,800000,1 lhz_dun01,250,150,18,30 monster Errende Ebecee 1655,2,900000,800000,1 lhz_dun01,250,150,18,30 monster Kavach Icarus 1656,2,900000,800000,1 lhz_dun01,250,150,18,30 monster Laurell Weinder 1657,2,600000,300000,1 lhz_dun01,50,150,11,35 monster Egnigem Cenia 1652,1,600000,300000,1 lhz_dun01,50,150,11,35 monster Wickebine Tres 1653,4,900000,800000,1 lhz_dun01,50,150,11,35 monster Armeyer Dinze 1654,1,900000,800000,1 lhz_dun01,50,150,11,35 monster Errende Ebecee 1655,4,900000,800000,1 lhz_dun01,50,150,11,35 monster Kavach Icarus 1656,4,900000,800000,1 lhz_dun01,50,150,11,35 monster Laurell Weinder 1657,2,600000,300000,1 lhz_dun01,192,61,18,30 monster Egnigem Cenia 1652,1,900000,800000,1 lhz_dun01,192,61,18,30 monster Wickebine Tres 1653,1,900000,800000,1 lhz_dun01,192,61,18,30 monster Armeyer Dinze 1654,1,900000,800000,1 lhz_dun01,192,61,18,30 monster Errende Ebecee 1655,1,900000,800000,1 lhz_dun01,192,61,18,30 monster Kavach Icarus 1656,1,900000,800000,1 lhz_dun01,192,61,18,30 monster Laurell Weinder 1657,1,900000,800000,1 lhz_dun01,0,0,0,0 monster Gemini-S58 1681,1,7200000,5400000,0 //======================================================================================== // lhz_dun02 - Bio-life Labs 2F //======================================================================================== lhz_dun02,0,0,0,0 monster Egnigem Cenia 1652,26,0,0,0 lhz_dun02,0,0,0,0 monster Wickebine Tres 1653,26,0,0,0 lhz_dun02,0,0,0,0 monster Armeyer Dinze 1654,26,0,0,0 lhz_dun02,0,0,0,0 monster Errende Ebecee 1655,26,0,0,0 lhz_dun02,0,0,0,0 monster Kavach Icarus 1656,26,0,0,0 lhz_dun02,0,0,0,0 monster Laurell Weinder 1657,26,0,0,0 lhz_dun02,150,150,56,54 monster Egnigem Cenia 1652,4,120000,60000,1 lhz_dun02,150,150,56,54 monster Wickebine Tres 1653,4,120000,60000,1 lhz_dun02,150,150,56,54 monster Armeyer Dinze 1654,4,120000,60000,1 lhz_dun02,150,150,56,54 monster Errende Ebecee 1655,4,120000,60000,1 lhz_dun02,150,150,56,54 monster Kavach Icarus 1656,4,120000,60000,1 lhz_dun02,150,150,56,54 monster Laurell Weinder 1657,4,120000,60000,1 lhz_dun02,150,150,105,90 monster Egnigem Cenia 1652,10,120000,60000,1 lhz_dun02,150,150,105,90 monster Wickebine Tres 1653,10,120000,60000,1 lhz_dun02,150,150,105,90 monster Armeyer Dinze 1654,10,120000,60000,1 lhz_dun02,150,150,105,90 monster Errende Ebecee 1655,10,120000,60000,1 lhz_dun02,150,150,105,90 monster Kavach Icarus 1656,10,120000,60000,1 lhz_dun02,150,150,105,90 monster Laurell Weinder 1657,10,120000,60000,1 lhz_dun02,0,0,0,0 monster Egnigem Cenia 1652,10,300000,150000,1 lhz_dun02,0,0,0,0 monster Wickebine Tres 1653,10,300000,150000,1 lhz_dun02,0,0,0,0 monster Armeyer Dinze 1654,10,300000,150000,1 lhz_dun02,0,0,0,0 monster Errende Ebecee 1655,10,300000,150000,1 lhz_dun02,0,0,0,0 monster Kavach Icarus 1656,10,300000,150000,1 lhz_dun02,0,0,0,0 monster Laurell Weinder 1657,10,300000,150000,1 lhz_dun02,0,0,0,0 monster Remover 1682,20,300000,150000,1 lhz_dun02,0,0,0,0 monster Eremes Guile 1635,1,180000,120000,0 lhz_dun02,0,0,0,0 monster Gemini-S58 1681,10,5400000,180000,0 lhz_dun02,0,0,0,0 boss_monster Egnigem Cenia 1658,1,7200000,600000,1 //======================================================================================== // lhz_dun03 - Bio-life Labs 3F //======================================================================================== lhz_dun03,140,235,116,30 monster Seyren Windsor 1634,4,180000,120000,0 lhz_dun03,140,235,116,30 monster Eremes Guile 1635,4,180000,120000,0 lhz_dun03,140,235,116,30 monster Howard Alt-Eisen 1636,4,180000,120000,0 lhz_dun03,140,235,116,30 monster Margaretha Sorin 1637,4,180000,120000,0 lhz_dun03,140,235,116,30 monster Cecil Damon 1638,4,180000,120000,0 lhz_dun03,140,235,116,30 monster Kathryne Keyron 1639,4,180000,120000,0 lhz_dun03,40,214,16,16 monster Seyren Windsor 1634,1,120000,60000,0 lhz_dun03,40,214,16,16 monster Eremes Guile 1635,1,120000,60000,0 lhz_dun03,40,214,16,16 monster Howard Alt-Eisen 1636,1,120000,60000,0 lhz_dun03,40,214,16,16 monster Margaretha Sorin 1637,1,120000,60000,0 lhz_dun03,40,214,16,16 monster Cecil Damon 1638,1,120000,60000,0 lhz_dun03,40,214,16,16 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,240,213,16,17 monster Seyren Windsor 1634,1,120000,60000,0 lhz_dun03,240,213,16,17 monster Eremes Guile 1635,1,120000,60000,0 lhz_dun03,240,213,16,17 monster Howard Alt-Eisen 1636,1,120000,60000,0 lhz_dun03,240,213,16,17 monster Margaretha Sorin 1637,1,120000,60000,0 lhz_dun03,240,213,16,17 monster Cecil Damon 1638,1,120000,60000,0 lhz_dun03,240,213,16,17 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,140,65,108,38 monster Seyren Windsor 1634,7,120000,160000,0 lhz_dun03,140,65,108,38 monster Eremes Guile 1635,7,120000,160000,0 lhz_dun03,140,65,108,38 monster Howard Alt-Eisen 1636,7,120000,160000,0 lhz_dun03,140,65,108,38 monster Margaretha Sorin 1637,7,120000,160000,0 lhz_dun03,140,65,108,38 monster Cecil Damon 1638,7,120000,60000,0 lhz_dun03,140,65,108,38 monster Kathryne Keyron 1639,7,120000,60000,0 lhz_dun03,140,31,8,15 monster Seyren Windsor 1634,1,600000,540000,0 lhz_dun03,140,31,8,15 monster Eremes Guile 1635,1,540000,480000,0 lhz_dun03,140,31,8,15 monster Howard Alt-Eisen 1636,1,600000,540000,0 lhz_dun03,140,31,8,15 monster Margaretha Sorin 1637,1,540000,480000,0 lhz_dun03,140,31,8,15 monster Cecil Damon 1638,1,600000,540000,0 lhz_dun03,140,31,8,15 monster Kathryne Keyron 1639,1,540000,480000,0 lhz_dun03,40,66,16,16 monster Seyren Windsor 1634,1,120000,60000,0 lhz_dun03,40,66,16,16 monster Eremes Guile 1635,1,120000,60000,0 lhz_dun03,40,66,16,16 monster Howard Alt-Eisen 1636,1,120000,60000,0 lhz_dun03,40,66,16,16 monster Margaretha Sorin 1637,1,120000,60000,0 lhz_dun03,40,66,16,16 monster Cecil Damon 1638,1,120000,60000,0 lhz_dun03,40,66,16,16 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,240,66,16,16 monster Seyren Windsor 1634,1,120000,60000,0 lhz_dun03,240,66,16,16 monster Eremes Guile 1635,1,120000,60000,0 lhz_dun03,240,66,16,16 monster Howard Alt-Eisen 1636,1,120000,60000,0 lhz_dun03,240,66,16,16 monster Margaretha Sorin 1637,1,120000,60000,0 lhz_dun03,240,66,16,16 monster Cecil Damon 1638,1,120000,60000,0 lhz_dun03,240,66,16,16 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,54,131,35,39 monster Seyren Windsor 1634,5,180000,120000,0 lhz_dun03,54,131,35,39 monster Eremes Guile 1635,5,180000,120000,0 lhz_dun03,54,131,35,39 monster Howard Alt-Eisen 1636,5,180000,120000,0 lhz_dun03,54,131,35,39 monster Margaretha Sorin 1637,5,180000,120000,0 lhz_dun03,54,131,35,39 monster Cecil Damon 1638,5,120000,60000,0 lhz_dun03,54,131,35,39 monster Kathryne Keyron 1639,5,120000,60000,0 lhz_dun03,228,137,35,39 monster Seyren Windsor 1634,5,180000,120000,0 lhz_dun03,228,137,35,39 monster Eremes Guile 1635,5,180000,120000,0 lhz_dun03,228,137,35,39 monster Howard Alt-Eisen 1636,5,180000,120000,0 lhz_dun03,228,137,35,39 monster Margaretha Sorin 1637,5,180000,120000,0 lhz_dun03,228,137,35,39 monster Cecil Damon 1638,5,120000,60000,0 lhz_dun03,228,137,35,39 monster Kathryne Keyron 1639,5,120000,60000,0 lhz_dun03,138,138,36,34 monster Seyren Windsor 1634,3,120000,60000,0 lhz_dun03,138,138,36,34 monster Eremes Guile 1635,3,120000,60000,0 lhz_dun03,138,138,36,34 monster Howard Alt-Eisen 1636,3,120000,60000,0 lhz_dun03,138,138,36,34 monster Margaretha Sorin 1637,3,180000,120000,0 lhz_dun03,138,138,36,34 monster Cecil Damon 1638,4,0,0,0 lhz_dun03,138,138,36,34 monster Kathryne Keyron 1639,4,0,0,0 lhz_dun03,140,192,66,21 monster Seyren Windsor 1634,7,120000,60000,0 lhz_dun03,140,192,66,21 monster Eremes Guile 1635,7,180000,120000,0 lhz_dun03,140,192,66,21 monster Howard Alt-Eisen 1636,7,120000,60000,0 lhz_dun03,140,192,66,21 monster Margaretha Sorin 1637,7,180000,120000,0 lhz_dun03,140,192,66,21 monster Cecil Damon 1638,7,120000,60000,0 lhz_dun03,140,192,66,21 monster Kathryne Keyron 1639,7,120000,60000,0 lhz_dun03,89,164,4,8 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,89,164,4,8 monster Cecil Damon 1638,3,120000,60000,0 lhz_dun03,107,167,4,5 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,107,167,4,5 monster Cecil Damon 1638,3,120000,60000,0 lhz_dun03,171,167,4,5 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,171,167,4,5 monster Cecil Damon 1638,3,120000,60000,0 lhz_dun03,189,164,4,8 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,189,164,4,8 monster Cecil Damon 1638,3,120000,60000,0 lhz_dun03,89,113,4,9 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,89,113,4,9 monster Cecil Damon 1638,3,120000,60000,0 lhz_dun03,107,109,4,5 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,107,109,4,5 monster Cecil Damon 1638,3,120000,60000,0 lhz_dun03,171,109,4,5 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,171,109,4,5 monster Cecil Damon 1638,3,120000,60000,0 lhz_dun03,189,113,4,9 monster Kathryne Keyron 1639,1,120000,60000,0 lhz_dun03,189,113,4,9 monster Cecil Damon 1638,3,120000,60000,0 lhz_dun03,96,164,13,8 monster Seyren Windsor 1634,2,300000,120000,0 lhz_dun03,96,164,13,8 monster Eremes Guile 1635,2,300000,120000,0 lhz_dun03,96,164,13,8 monster Margaretha Sorin 1637,2,300000,120000,0 lhz_dun03,96,164,13,8 monster Cecil Damon 1638,5,0,0,0 lhz_dun03,96,164,13,8 monster Kathryne Keyron 1639,3,0,0,0 lhz_dun03,180,164,13,8 monster Seyren Windsor 1634,2,300000,120000,0 lhz_dun03,180,164,13,8 monster Howard Alt-Eisen 1636,2,300000,120000,0 lhz_dun03,180,164,13,8 monster Margaretha Sorin 1637,2,300000,120000,0 lhz_dun03,180,164,13,8 monster Cecil Damon 1638,5,0,0,0 lhz_dun03,180,164,13,8 monster Kathryne Keyron 1639,3,0,0,0 lhz_dun03,98,113,13,9 monster Seyren Windsor 1634,2,300000,120000,0 lhz_dun03,98,113,13,9 monster Eremes Guile 1635,2,300000,120000,0 lhz_dun03,98,113,13,9 monster Howard Alt-Eisen 1636,2,300000,120000,0 lhz_dun03,98,113,13,9 monster Cecil Damon 1638,5,0,0,0 lhz_dun03,98,113,13,9 monster Kathryne Keyron 1639,3,0,0,0 lhz_dun03,180,113,13,9 monster Eremes Guile 1635,2,300000,120000,0 lhz_dun03,180,113,13,9 monster Howard Alt-Eisen 1636,2,300000,120000,0 lhz_dun03,180,113,13,9 monster Margaretha Sorin 1637,2,300000,120000,0 lhz_dun03,180,113,13,9 monster Cecil Damon 1638,5,0,0,0 lhz_dun03,180,113,13,9 monster Kathryne Keyron 1639,3,0,0,0 lhz_dun03,114,138,12,16 monster Lord Knight Seyren 1640,1,2700000,2400000,1 lhz_dun03,163,138,12,16 monster Whitesmith Howard 1642,1,3000000,2700000,1 lhz_dun03,139,158,20,11 monster Assassin Cross Eremes 1641,1,2580000,2340000,1 lhz_dun03,139,117,20,11 monster Sniper Cecil 1644,1,2700000,2500000,1 lhz_dun03,138,138,36,34 monster High Priest Margaretha 1643,1,3300000,3000000,1 lhz_dun03,138,138,36,34 monster High Wizard Kathryne 1645,1,2580000,2460000,1 lhz_dun03,2,2,0 script summon_boss_lt -1,{ OnInit: initnpctimer; end; OnTimer6000000: if (rand(1,6) == 1) { donpcevent "summon_boss_lt::Onsummon"; stopnpctimer; } end; OnTimer6300000: if (rand(1,6) == 2) { donpcevent "summon_boss_lt::Onsummon"; stopnpctimer; } end; OnTimer6600000: if (rand(1,6) == 3) { donpcevent "summon_boss_lt::Onsummon"; stopnpctimer; } end; OnTimer6900000: if (rand(1,6) == 4) { donpcevent "summon_boss_lt::Onsummon"; stopnpctimer; } end; OnTimer7200000: if (rand(1,6) == 5) { donpcevent "summon_boss_lt::Onsummon"; stopnpctimer; } end; OnTimer7500000: if (rand(1,6) == 6) { donpcevent "summon_boss_lt::Onsummon"; stopnpctimer; } end; OnTimer7800000: donpcevent "summon_boss_lt::Onsummon"; stopnpctimer; end; Onsummon: // Select Coordinates to summon a random MVP on switch(rand(1,6)) { case 1: set .@x,140; set .@y,232; break; case 2: set .@x,75; set .@y,138; break; case 3: set .@x,140; set .@y,87; break; case 4: set .@x,205; set .@y,140; break; case 5: set .@x,123; set .@y,137; break; case 6: set .@x,175; set .@y,137; break; } set .@mob,rand(1646,1651); monster "lhz_dun03",.@x,.@y,strmobinfo(1,.@mob),.@mob,1,"summon_boss_lt::OnMyMvPDead"; // Select Coordinates to summon a random 99 on switch(rand(1,6)) { case 1: set .@x2,183; set .@y2,97; break; case 2: set .@x2,97; set .@y2,96; break; case 3: set .@x2,47; set .@y2,139; break; case 4: set .@x2,231; set .@y2,140; break; case 5: set .@x2,139; set .@y2,211; break; case 6: set .@x2,139; set .@y2,259; break; } set .@mob2,rand(1640,1645); monster "lhz_dun03",.@x2,.@y2,strmobinfo(1,.@mob2),.@mob2,1,"summon_boss_lt::OnMVP"; end; OnMyMvPDead: killmonster "lhz_dun03","summon_boss_lt::OnMVP"; initnpctimer; end; //Required to keep from erroring OnMVP: end; }
{ "pile_set_name": "Github" }
/* * Copyright 2019 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.igor.model; public interface RetryableStageDefinition { int getConsecutiveErrors(); }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from globaleaks.handlers.admin import l10n as admin_l10n from globaleaks.tests import helpers from twisted.internet.defer import inlineCallbacks empty_texts = {} custom_texts1 = { '12345': '54321' } custom_texts2 = { '12345': '54321' } class TestAdminL10NHandler(helpers.TestHandler): _handler = admin_l10n.AdminL10NHandler @inlineCallbacks def test_get(self): handler = self.request(role='admin') response = yield handler.get(lang=u'en') self.assertEqual(response, {}) @inlineCallbacks def test_put(self): check = yield admin_l10n.get(1, 'en') self.assertEqual(empty_texts, check) handler = self.request(custom_texts1, role='admin') yield handler.put(lang=u'en') check = yield admin_l10n.get(1, 'en') self.assertEqual(custom_texts1, check) handler = self.request(custom_texts1, role='admin') yield handler.put(lang=u'en') check = yield admin_l10n.get(1, 'en') self.assertEqual(custom_texts2, check) @inlineCallbacks def test_delete(self): yield self.test_put() check = yield admin_l10n.get(1, 'en') self.assertEqual(custom_texts1, check) handler = self.request({}, role='admin') handler.delete(lang=u'en') check = yield admin_l10n.get(1, 'en') self.assertEqual(empty_texts, check)
{ "pile_set_name": "Github" }
+++ title = "Pangram checker" description = "" date = 2019-10-17T23:32:31Z aliases = [] [extra] id = 5383 [taxonomies] categories = [] tags = [] +++ {{task}} [[Category:String manipulation]] {{omit from|Lilypond}} A pangram is a sentence that contains all the letters of the English alphabet at least once. For example: ''The quick brown fox jumps over the lazy dog''. ;Task: Write a function or method to check a sentence to see if it is a [[wp:Pangram|pangram]] (or not) and show its use. ## 360 Assembly ```360asm * Pangram RC 11/08/2015 PANGRAM CSECT USING PANGRAM,R12 LR R12,R15 BEGIN LA R9,SENTENCE LA R6,4 LOOPI LA R10,ALPHABET loop on sentences LA R7,26 LOOPJ LA R5,0 loop on letters LR R11,R9 LA R8,60 LOOPK MVC BUFFER+1(1),0(R10) loop in sentence CLC 0(1,R10),0(R11) if alphabet[j=sentence[i] BNE NEXTK LA R5,1 found NEXTK LA R11,1(R11) next character BCT R8,LOOPK LTR R5,R5 if found BNZ NEXTJ MVI BUFFER,C'?' not found B PRINT NEXTJ LA R10,1(R10) next letter BCT R7,LOOPJ MVC BUFFER(2),=CL2'OK' PRINT MVC BUFFER+3(60),0(R9) XPRNT BUFFER,80 NEXTI LA R9,60(R9) next sentence BCT R6,LOOPI RETURN XR R15,R15 BR R14 ALPHABET DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ' SENTENCE DC CL60'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.' DC CL60'THE FIVE BOXING WIZARDS DUMP QUICKLY.' DC CL60'HEAVY BOXES PERFORM WALTZES AND JIGS.' DC CL60'PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.' BUFFER DC CL80' ' YREGS END PANGRAM ``` {{out}} ```txt OK THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. ?J THE FIVE BOXING WIZARDS DUMP QUICKLY. ?C HEAVY BOXES PERFORM WALTZES AND JIGS. OK PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS. ``` ## ACL2 ```Lisp (defun contains-each (needles haystack) (if (endp needles) t (and (member (first needles) haystack) (contains-each (rest needles) haystack)))) (defun pangramp (str) (contains-each (coerce "abcdefghijklmnopqrstuvwxyz" 'list) (coerce (string-downcase str) 'list))) ``` ## ActionScript {{works with|ActionScript|2.0}} ```ActionScript function pangram(k:string):Boolean { var lowerK:String = k.toLowerCase(); var has:Object = {} for (var i:Number=0; i<=k.length-1; i++) { has[lowerK.charAt(i)] = true; } var result:Boolean = true; for (var ch:String='a'; ch <= 'z'; ch=String.fromCharCode(ch.charCodeAt(0)+1)) { result = result && has[ch] } return result || false; } ``` ## Ada ### Using character sets ```Ada with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Characters.Handling; use Ada.Characters.Handling; procedure pangram is function ispangram(txt: String) return Boolean is (Is_Subset(To_Set(Span => ('a','z')), To_Set(To_Lower(txt)))); begin put_line(Boolean'Image(ispangram("This is a test"))); put_line(Boolean'Image(ispangram("The quick brown fox jumps over the lazy dog"))); put_line(Boolean'Image(ispangram("NOPQRSTUVWXYZ abcdefghijklm"))); put_line(Boolean'Image(ispangram("abcdefghijklopqrstuvwxyz"))); --Missing m, n end pangram; ``` ### Using quantified expressions ```Ada with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters.Handling; use Ada.Characters.Handling; procedure pangram is function ispangram(txt : in String) return Boolean is (for all Letter in Character range 'a'..'z' => (for some Char of txt => To_Lower(Char) = Letter)); begin put_line(Boolean'Image(ispangram("This is a test"))); put_line(Boolean'Image(ispangram("The quick brown fox jumps over the lazy dog"))); put_line(Boolean'Image(ispangram("NOPQRSTUVWXYZ abcdefghijklm"))); put_line(Boolean'Image(ispangram("abcdefghijklopqrstuvwxyz"))); --Missing m, n end pangram; ``` {{out}} ```txt FALSE TRUE TRUE FALSE ``` ## ALGOL 68 {{works with|ALGOL 68|Standard - no extensions to language used}} {{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}} {{works with|ELLA ALGOL 68|Any (with appropriate job cards)}} ```algol68 # init pangram: # INT la = ABS "a", lz = ABS "z"; INT ua = ABS "A", uz = ABS "Z"; IF lz-la+1 > bits width THEN put(stand error, "Exception: insufficient bits in word for task"); stop FI; PROC is a pangram = (STRING test)BOOL: ( BITS a2z := BIN(ABS(2r1 SHL (lz-la))-1); # assume: ASCII & Binary # FOR i TO UPB test WHILE INT c = ABS test[i]; IF la <= c AND c <= lz THEN a2z := a2z AND NOT(2r1 SHL (c-la)) ELIF ua <= c AND c <= uz THEN a2z := a2z AND NOT(2r1 SHL (c-ua)) FI; # WHILE # a2z /= 2r0 DO SKIP OD; a2z = 2r0 ); main:( []STRING test list = ( "Big fjiords vex quick waltz nymph", "The quick brown fox jumps over a lazy dog", "A quick brown fox jumps over a lazy dog" ); FOR key TO UPB test list DO STRING test = test list[key]; IF is a pangram(test) THEN print(("""",test,""" is a pangram!", new line)) FI OD ) ``` {{out}} ```txt "Big fjiords vex quick waltz nymph" is a pangram! "The quick brown fox jumps over a lazy dog" is a pangram! ``` ## APL ```apl a←'abcdefghijklmnopqrstuvwxyz' A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ' Panagram←{∧/ ∨⌿ 2 26⍴(a,A) ∊ ⍵} Panagram 'This should fail' 0 Panagram 'The quick brown fox jumps over the lazy dog' 1 ``` ## AppleScript Out of the box, AppleScript lacks many library basics – no regex, no higher order functions, not even string functions for mapping to upper or lower case. From OSX 10.10 onwards, we can, however, use ObjC functions from AppleScript by importing the Foundation framework. We do this below to get a toLowerCase() function. If we also add generic filter and map functions, we can write and test a simple isPangram() function as follows: ```AppleScript use framework "Foundation" -- ( for case conversion function ) -- PANGRAM CHECK ------------------------------------------------------------- -- isPangram :: String -> Bool on isPangram(s) script charUnUsed property lowerCaseString : my toLower(s) on |λ|(c) lowerCaseString does not contain c end |λ| end script length of filter(charUnUsed, "abcdefghijklmnopqrstuvwxyz") = 0 end isPangram -- TEST ---------------------------------------------------------------------- on run map(isPangram, {¬ "is this a pangram", ¬ "The quick brown fox jumps over the lazy dog"}) --> {false, true} end run -- GENERIC FUNCTIONS --------------------------------------------------------- -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn -- toLower :: String -> String on toLower(str) set ca to current application ((ca's NSString's stringWithString:(str))'s ¬ lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text end toLower ``` {{Out}} ```AppleScript {false, true} ``` ## ATS ```ATS (* ****** ****** *) // #include "share/atspre_staload.hats" #include "share/HATS/atspre_staload_libats_ML.hats" // (* ****** ****** *) // fun letter_check ( cs: string, c0: char ) : bool = cs.exists()(lam(c) => c0 = c) // (* ****** ****** *) fun Pangram_check (text: string): bool = let // val alphabet = "abcdefghijklmnopqrstuvwxyz" val ((*void*)) = assertloc(length(alphabet) = 26) // in alphabet.forall()(lam(c) => letter_check(text, c) || letter_check(text, toupper(c))) end // end of [Pangram_check] (* ****** ****** *) implement main0 () = { // val text0 = "The quick brown fox jumps over the lazy dog." // val-true = Pangram_check(text0) val-false = Pangram_check("This is not a pangram sentence.") // } (* end of [main0] *) (* ****** ****** *) ``` An alternate implementation that makes a single pass through the string: ```ATS fn is_pangram{n:nat}(s: string(n)): bool = loop(s, i2sz(0)) where { val letters: arrayref(bool, 26) = arrayref_make_elt<bool>(i2sz(26), false) fn check(): bool = loop(0) where { fun loop{i:int | i >= 0 && i <= 26}(i: int(i)) = if i < 26 then if letters[i] then loop(i+1) else false else true } fun add{c:int}(c: char(c)): void = if (c >= 'A') * (c <= 'Z') then letters[char2int1(c) - char2int1('A')] := true else if (c >= 'a') * (c <= 'z') then letters[char2int1(c) - char2int1('a')] := true fun loop{i:nat | i <= n}.<n-i>.(s: string(n), i: size_t(i)): bool = if string_is_atend(s, i) then check() else begin add(s[i]); loop(s, succ(i)) end } ``` ## AutoHotkey ```autohotkey Gui, -MinimizeBox Gui, Add, Edit, w300 r5 vText Gui, Add, Button, x105 w100 Default, Check Pangram Gui, Show,, Pangram Checker Return GuiClose: ExitApp Return ButtonCheckPangram: Gui, Submit, NoHide Loop, 26 If Not InStr(Text, Char := Chr(64 + A_Index)) { MsgBox,, Pangram, Character %Char% is missing! Return } MsgBox,, Pangram, OK`, this is a Pangram! Return ``` ## AutoIt ```autoit Pangram("The quick brown fox jumps over the lazy dog") Func Pangram($s_String) For $i = 1 To 26 IF Not StringInStr($s_String, Chr(64 + $i)) Then Return MsgBox(0,"No Pangram", "Character " & Chr(64 + $i) &" is missing") EndIf Next Return MsgBox(0,"Pangram", "Sentence is a Pangram") EndFunc ``` ## AWK ===Solution using string-operations=== ```AWK #!/usr/bin/awk -f BEGIN { allChars="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; print isPangram("The quick brown fox jumps over the lazy dog."); print isPangram("The quick brown fo."); } function isPangram(string) { delete X; for (k=1; k<length(string); k++) { X[toupper(substr(string,k,1))]++; # histogram } for (k=1; k<=length(allChars); k++) { if (!X[substr(allChars,k,1)]) return 0; } return 1; } ``` {{out}} ```txt 1 0 ``` ### Solution using associative arrays and split {{Works with|gawk|4.1.0}} {{Works with|mawk|1.3.3}} ```AWK # usage: awk -f pangram.awk -v p="The five boxing wizards dump quickly." input.txt # # Pangram-checker, using associative arrays and split BEGIN { alfa="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; ac=split(alfa,A,"") print "# Checking for all",ac,"chars in '" alfa "' :" print testPangram("The quick brown fox jumps over the lazy dog."); print testPangram(p); } { print testPangram($0) } function testPangram(str, c,i,S,H,hit,miss) { print str ## split( toupper(str), S, "") for (c in S) { H[ S[c] ]++ #print c, S[c], H[ S[c] ] ## } for (i=1; i<=ac; i++) { c = A[i] #printf("%2d %c : %4d\n", i, c, H[c] ) ## if (H[c]) { hit=hit c } else { miss=miss c } } print "# hit:",hit, "# miss:",miss, "." ## if (miss) return 0 return 1 } ``` {{out}} ```txt # Checking for all 26 chars in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' : The quick brown fox jumps over the lazy dog. # hit: ABCDEFGHIJKLMNOPQRSTUVWXYZ # miss: . 1 The five boxing wizards dump quickly. # hit: ABCDEFGHIKLMNOPQRSTUVWXYZ # miss: J . 0 Heavy boxes perform waltzes and jigs # hit: ABDEFGHIJLMNOPRSTVWXYZ # miss: CKQU . 0 The quick onyx goblin jumps over the lazy dwarf. # hit: ABCDEFGHIJKLMNOPQRSTUVWXYZ # miss: . 1 Pack my box with five dozen liquor jugs # hit: ABCDEFGHIJKLMNOPQRSTUVWXYZ # miss: . 1 ``` ## BASIC {{works with|QBasic}} ```qbasic DECLARE FUNCTION IsPangram! (sentence AS STRING) DIM x AS STRING x = "My dog has fleas." GOSUB doIt x = "The lazy dog jumps over the quick brown fox." GOSUB doIt x = "Jackdaws love my big sphinx of quartz." GOSUB doIt x = "What's a jackdaw?" GOSUB doIt END doIt: PRINT IsPangram!(x), x RETURN FUNCTION IsPangram! (sentence AS STRING) 'returns -1 (true) if sentence is a pangram, 0 (false) otherwise DIM l AS INTEGER, s AS STRING, t AS INTEGER DIM letters(25) AS INTEGER FOR l = 1 TO LEN(sentence) s = UCASE$(MID$(sentence, l, 1)) SELECT CASE s CASE "A" TO "Z" t = ASC(s) - 65 letters(t) = 1 END SELECT NEXT FOR l = 0 TO 25 IF letters(l) < 1 THEN IsPangram! = 0 EXIT FUNCTION END IF NEXT IsPangram! = -1 END FUNCTION ``` {{out}} ```txt 0 My dog has fleas. -1 The quick brown fox jumps over the lazy dog. -1 Jackdaws love my big sphinx of quartz. 0 What's a jackdaw? ``` = ## Sinclair ZX81 BASIC = Works (just) with the 1k RAM model. The "37" that crops up a couple of times stops being a mystery if we remember that the ZX81 character code for <code>A</code> is 38 and that strings (like arrays) are indexed from 1, not from 0. ```basic 10 LET A$="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 20 LET L=26 30 INPUT P$ 40 IF LEN P$<26 THEN GOTO 170 50 FAST 60 LET C=1 70 IF P$(C)<"A" OR P$(C)>"Z" THEN GOTO 120 80 IF A$(CODE P$(C)-37)=" " THEN GOTO 120 90 LET A$(CODE P$(C)-37)=" " 100 LET L=L-1 110 IF L=0 THEN GOTO 150 120 IF C=LEN P$ THEN GOTO 170 130 LET C=C+1 140 GOTO 70 150 PRINT "PANGRAM" 160 GOTO 180 170 PRINT "NOT A PANGRAM" 180 SLOW ``` {{in}} ```txt THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. ``` {{out}} ```txt PANGRAM ``` {{in}} ```txt AND DARK THE SUN AND MOON, AND THE ALMANACH DE GOTHA ``` {{out}} ```txt NOT A PANGRAM ``` ## Batch File ```dos @echo off setlocal enabledelayedexpansion % ### The Main Thing % call :pangram "The quick brown fox jumps over the lazy dog." call :pangram "The quick brown fox jumped over the lazy dog." echo. pause exit /b 0 % ### The Function % :pangram set letters=abcdefgihjklmnopqrstuvwxyz set cnt=0 set inp=%~1 set str=!inp: =! :loop set chr=!str:~%cnt%,1! if "!letters!"=="" ( echo %1 is a pangram^^! goto :EOF ) if "!chr!"=="" ( echo %1 is not a pangram. goto :EOF ) set letters=!letters:%chr%=! set /a cnt+=1 goto loop ``` {{Out}} ```txt "The quick brown fox jumps over the lazy dog." is a pangram! "The quick brown fox jumped over the lazy dog." is not a pangram. Press any key to continue . . . ``` ## BBC BASIC ```bbcbasic FOR test% = 1 TO 2 READ test$ PRINT """" test$ """ " ; IF FNpangram(test$) THEN PRINT "is a pangram" ELSE PRINT "is not a pangram" ENDIF NEXT test% END DATA "The quick brown fox jumped over the lazy dog" DATA "The five boxing wizards jump quickly" DEF FNpangram(A$) LOCAL C% A$ = FNlower(A$) FOR C% = ASC("a") TO ASC("z") IF INSTR(A$, CHR$(C%)) = 0 THEN = FALSE NEXT = TRUE DEF FNlower(A$) LOCAL A%, C% FOR A% = 1 TO LEN(A$) C% = ASCMID$(A$,A%) IF C% >= 65 IF C% <= 90 MID$(A$,A%,1) = CHR$(C%+32) NEXT = A$ ``` {{out}} ```txt "The quick brown fox jumped over the lazy dog" is not a pangram "The five boxing wizards jump quickly" is a pangram ``` ## Befunge Reads the sentence to test from stdin. ```befunge> ~>:65*`!#v_:"`"`48*v>g+04p1\4p ^#*`\*93\`0<::-"@"-*<^40!%2g4:_ "pangram."<v*84<_v#-":"g40\" a" >>:#,_55+,@>"ton">48*>"si tahT" ``` {{in}} ```txt The quick brown fox jumps over the lazy dog. ``` {{out}} ```txt That is a pangram. ``` ## Bracmat ```bracmat (isPangram= k . low$!arg:?arg & a:?k & whl ' ( @(!arg:? !k ?) & chr$(1+asc$!k):?k:~>z ) & !k:>z & ); ``` Some examples: ```txt isPangram$("the Quick brown FOX jumps over the lazy do") no isPangram$("the Quick brown FOX jumps over the lazy dog") yes isPangram$"My dog has fleas." no isPangram$"The quick brown fox jumps over the lazy dog." yes isPangram$"Jackdaws love my big sphinx of quartz." yes isPangram$"What's a jackdaw?" no isPangram$"Lynx c.q. vos prikt bh: dag zwemjuf!" yes ``` ## Brat ```brat pangram? = { sentence | letters = [:a :b :c :d :e :f :g :h :i :j :k :l :m :n :o :p :q :r :s :t :u :v :w :x :y :z] sentence.downcase! letters.reject! { l | sentence.include? l } letters.empty? } p pangram? 'The quick brown fox jumps over the lazy dog.' #Prints true p pangram? 'Probably not a pangram.' #Prints false ``` Alternative version: ```brat pangram? = { sentence | sentence.downcase.dice.unique.select(:alpha?).length == 26 } ``` ## C ```c #include <stdio.h> int is_pangram(const char *s) { const char *alpha = "" "abcdefghjiklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char ch, wasused[26] = {0}; int total = 0; while ((ch = *s++) != '\0') { const char *p; int idx; if ((p = strchr(alpha, ch)) == NULL) continue; idx = (p - alpha) % 26; total += !wasused[idx]; wasused[idx] = 1; if (total == 26) return 1; } return 0; } int main(void) { int i; const char *tests[] = { "The quick brown fox jumps over the lazy dog.", "The qu1ck brown fox jumps over the lazy d0g." }; for (i = 0; i < 2; i++) printf("\"%s\" is %sa pangram\n", tests[i], is_pangram(tests[i])?"":"not "); return 0; } ``` ### Using bitmask Assumes an execution environment using the ASCII character set (will invoke undefined behavior on other systems). ```c #include <stdio.h> int pangram(const char *s) { int c, mask = (1 << 26) - 1; while ((c = (*s++)) != '\0') /* 0x20 converts lowercase to upper */ if ((c &= ~0x20) <= 'Z' && c >= 'A') mask &= ~(1 << (c - 'A')); return !mask; } int main() { int i; const char *s[] = { "The quick brown fox jumps over lazy dogs.", "The five boxing wizards dump quickly.", }; for (i = 0; i < 2; i++) printf("%s: %s\n", pangram(s[i]) ? "yes" : "no ", s[i]); return 0; } ``` {{out}} ```txt yes: The quick brown fox jumps over lazy dogs. no : The five boxing wizards dump quickly. ``` ## C# C# 3.0 or higher (.NET Framework 3.5 or higher) ```c# using System; using System.Linq; static class Program { static bool IsPangram(this string text, string alphabet = "abcdefghijklmnopqrstuvwxyz") { return alphabet.All(text.ToLower().Contains); } static void Main(string[] arguments) { Console.WriteLine(arguments.Any() && arguments.First().IsPangram()); } } ``` Any version of C# language and .NET Framework ```c# using System; namespace PangrammChecker { public class PangrammChecker { public static bool IsPangram(string str) { bool[] isUsed = new bool[26]; int ai = (int)'a'; int total = 0; for (CharEnumerator en = str.ToLower().GetEnumerator(); en.MoveNext(); ) { int d = (int)en.Current - ai; if (d >= 0 && d < 26) if (!isUsed[d]) { isUsed[d] = true; total++; } } return (total == 26); } } class Program { static void Main(string[] args) { string str1 = "The quick brown fox jumps over the lazy dog."; string str2 = "The qu1ck brown fox jumps over the lazy d0g."; Console.WriteLine("{0} is {1}a pangram", str1, PangrammChecker.IsPangram(str1)?"":"not "); Console.WriteLine("{0} is {1}a pangram", str2, PangrammChecker.IsPangram(str2)?"":"not "); Console.WriteLine("Press Return to exit"); Console.ReadLine(); } } } ``` ## C++ ```cpp #include <algorithm> #include <cctype> #include <string> #include <iostream> const std::string alphabet("abcdefghijklmnopqrstuvwxyz"); bool is_pangram(std::string s) { std::transform(s.begin(), s.end(), s.begin(), ::tolower); std::sort(s.begin(), s.end()); return std::includes(s.begin(), s.end(), alphabet.begin(), alphabet.end()); } int main() { const auto examples = {"The quick brown fox jumps over the lazy dog", "The quick white cat jumps over the lazy dog"}; std::cout.setf(std::ios::boolalpha); for (auto& text : examples) { std::cout << "Is \"" << text << "\" a pangram? - " << is_pangram(text) << std::endl; } } ``` ## Ceylon ```ceylon shared void run() { function pangram(String sentence) => let(alphabet = set('a'..'z'), letters = set(sentence.lowercased.filter(alphabet.contains))) letters == alphabet; value sentences = [ "The quick brown fox jumps over the lazy dog", """Watch "Jeopardy!", Alex Trebek's fun TV quiz game.""", "Pack my box with five dozen liquor jugs.", "blah blah blah" ]; for(sentence in sentences) { print("\"``sentence``\" is a pangram? ``pangram(sentence)``"); } } ``` ## Clojure ```lisp (defn pangram? [s] (let [letters (into #{} "abcdefghijklmnopqrstuvwxyz")] (= (->> s .toLowerCase (filter letters) (into #{})) letters))) ``` ## COBOL ```COBOL identification division. program-id. pan-test. data division. working-storage section. 1 text-string pic x(80). 1 len binary pic 9(4). 1 trailing-spaces binary pic 9(4). 1 pangram-flag pic x value "n". 88 is-not-pangram value "n". 88 is-pangram value "y". procedure division. begin. display "Enter text string:" accept text-string set is-not-pangram to true initialize trailing-spaces len inspect function reverse (text-string) tallying trailing-spaces for leading space len for characters after space call "pangram" using pangram-flag len text-string cancel "pangram" if is-pangram display "is a pangram" else display "is not a pangram" end-if stop run . end program pan-test. identification division. program-id. pangram. data division. 1 lc-alphabet pic x(26) value "abcdefghijklmnopqrstuvwxyz". linkage section. 1 pangram-flag pic x. 88 is-not-pangram value "n". 88 is-pangram value "y". 1 len binary pic 9(4). 1 text-string pic x(80). procedure division using pangram-flag len text-string. begin. inspect lc-alphabet converting function lower-case (text-string (1:len)) to space if lc-alphabet = space set is-pangram to true end-if exit program . end program pangram. ``` ## CoffeeScript ```coffeescript is_pangram = (s) -> # This is optimized for longish strings--as soon as all 26 letters # are encountered, we will be done. Our worst case scenario is a really # long non-pangram, or a really long pangram with at least one letter # only appearing toward the end of the string. a_code = 'a'.charCodeAt(0) required_letters = {} for i in [a_code...a_code+26] required_letters[String.fromCharCode(i)] = true cnt = 0 for c in s c = c.toLowerCase() if required_letters[c] cnt += 1 return true if cnt == 26 delete required_letters[c] false do -> tests = [ ["is this a pangram", false] ["The quick brown fox jumps over the lazy dog", true] ] for test in tests [s, exp_value] = test throw Error("fail") if is_pangram(s) != exp_value # try long strings long_str = '' for i in [1..500000] long_str += s throw Error("fail") if is_pangram(long_str) != exp_value console.log "Passed tests: #{s}" ``` ## Common Lisp ```lisp (defun pangramp (s) (null (set-difference (loop for c from (char-code #\A) upto (char-code #\Z) collect (code-char c)) (coerce (string-upcase s) 'list)))) ``` ## Component Pascal BlackBox Component Builder ```oberon2 MODULE BbtPangramChecker; IMPORT StdLog,DevCommanders,TextMappers; PROCEDURE Check(str: ARRAY OF CHAR): BOOLEAN; CONST letters = 26; VAR i,j: INTEGER; status: ARRAY letters OF BOOLEAN; resp : BOOLEAN; BEGIN FOR i := 0 TO LEN(status) -1 DO status[i] := FALSE END; FOR i := 0 TO LEN(str) - 1 DO j := ORD(CAP(str[i])) - ORD('A'); IF (0 <= j) & (25 >= j) & ~status[j] THEN status[j] := TRUE END END; resp := TRUE; FOR i := 0 TO LEN(status) - 1 DO; resp := resp & status[i] END; RETURN resp; END Check; PROCEDURE Do*; VAR params: DevCommanders.Par; s: TextMappers.Scanner; BEGIN params := DevCommanders.par; s.ConnectTo(params.text); s.SetPos(params.beg); s.Scan; WHILE (~s.rider.eot) DO IF (s.type = TextMappers.char) & (s.char = '~') THEN RETURN ELSIF (s.type # TextMappers.string) THEN StdLog.String("Invalid parameter");StdLog.Ln ELSE StdLog.Char("'");StdLog.String(s.string + "' is pangram?:> "); StdLog.Bool(Check(s.string));StdLog.Ln END; s.Scan END END Do; END BbtPangramChecker. ``` Execute: ^Q BbtPangramChecker.Do "The quick brown fox jumps over the lazy dog"~ <br/> ^Q BbtPangramChecker.Do "abcdefghijklmnopqrstuvwxyz"~<br/> ^Q BbtPangramChecker.Do "A simple text"~<br/> {{out}} ```txt 'The quick brown fox jumps over the lazy dog' is pangram?:> $TRUE 'abcdefghijklmnopqrstuvwxyz' is pangram?:> $TRUE 'A simple text' is pangram?:> $FALSE ``` ## D ### ASCII Bitmask version ```d bool isPangram(in string text) pure nothrow @safe @nogc { uint bitset; foreach (immutable c; text) { if (c >= 'a' && c <= 'z') bitset |= (1u << (c - 'a')); else if (c >= 'A' && c <= 'Z') bitset |= (1u << (c - 'A')); } return bitset == 0b11_11111111_11111111_11111111; } void main() { assert("the quick brown fox jumps over the lazy dog".isPangram); assert(!"ABCDEFGHIJKLMNOPQSTUVWXYZ".isPangram); assert(!"ABCDEFGHIJKL.NOPQRSTUVWXYZ".isPangram); assert("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ".isPangram); } ``` ### Unicode version ```d import std.string, std.traits, std.uni; // Do not compile with -g (debug info). enum Alphabet : dstring { DE = "abcdefghijklmnopqrstuvwxyzßäöü", EN = "abcdefghijklmnopqrstuvwxyz", SV = "abcdefghijklmnopqrstuvwxyzåäö" } bool isPangram(S)(in S s, dstring alpha = Alphabet.EN) pure /*nothrow*/ if (isSomeString!S) { foreach (dchar c; alpha) if (indexOf(s, c) == -1 && indexOf(s, std.uni.toUpper(c)) == -1) return false; return true; } void main() { assert(isPangram("the quick brown fox jumps over the lazy dog".dup, Alphabet.EN)); assert(isPangram("Falsches Üben von Xylophonmusik quält jeden größeren Zwerg"d, Alphabet.DE)); assert(isPangram("Yxskaftbud, ge vår wczonmö iqhjälp"w, Alphabet.SV)); } ``` ## Delphi ```Delphi program PangramChecker; {$APPTYPE CONSOLE} uses StrUtils; function IsPangram(const aString: string): Boolean; var c: char; begin for c := 'a' to 'z' do if not ContainsText(aString, c) then Exit(False); Result := True; end; begin Writeln(IsPangram('The quick brown fox jumps over the lazy dog')); // true Writeln(IsPangram('Not a panagram')); // false end. ``` ## E ```e def isPangram(sentence :String) { return ("abcdefghijklmnopqrstuvwxyz".asSet() &! sentence.toLowerCase().asSet()).size() == 0 } ``` <code>&amp;!</code> is the “but-not” or set difference operator. ## Elixir ```elixir defmodule Pangram do def checker(str) do unused = Enum.to_list(?a..?z) -- to_char_list(String.downcase(str)) Enum.empty?(unused) end end text = "The quick brown fox jumps over the lazy dog." IO.puts "#{Pangram.checker(text)}\t#{text}" text = (Enum.to_list(?A..?Z) -- 'Test') |> to_string IO.puts "#{Pangram.checker(text)}\t#{text}" ``` {{out}} ```txt true The quick brown fox jumps over the lazy dog. false ABCDEFGHIJKLMNOPQRSUVWXYZ ``` ## Erlang ```Erlang -module(pangram). -export([is_pangram/1]). is_pangram(String) -> ordsets:is_subset(lists:seq($a, $z), ordsets:from_list(string:to_lower(String))). ``` =={{header|F Sharp|F#}}== If the difference between the set of letters in the alphabet and the set of letters in the given string (after conversion to lower case) is the empty set then every letter appears somewhere in the given string: ```fsharp let isPangram (str: string) = (set['a'..'z'] - set(str.ToLower())).IsEmpty ``` ## Factor {{trans|E}} ```factor : pangram? ( str -- ? ) [ "abcdefghijklmnopqrstuvwxyz" ] dip >lower diff length 0 = ; "How razorback-jumping frogs can level six piqued gymnasts!" pangram? . ``` =={{header|Fōrmulæ}}== In [http://wiki.formulae.org/Pangram_checker this] page you can see the solution of this task. Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition. The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code. ## Forth ```forth : pangram? ( addr len -- ? ) 0 -rot bounds do i c@ 32 or [char] a - dup 0 26 within if 1 swap lshift or else drop then loop 1 26 lshift 1- = ; s" The five boxing wizards jump quickly." pangram? . \ -1 ``` ## Fortran {{works with|Fortran|90 and later}} ```fortran module pangram implicit none private public :: is_pangram character (*), parameter :: lower_case = 'abcdefghijklmnopqrstuvwxyz' character (*), parameter :: upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' contains function to_lower_case (input) result (output) implicit none character (*), intent (in) :: input character (len (input)) :: output integer :: i integer :: j output = input do i = 1, len (output) j = index (upper_case, output (i : i)) if (j /= 0) then output (i : i) = lower_case (j : j) end if end do end function to_lower_case function is_pangram (input) result (output) implicit none character (*), intent (in) :: input character (len (input)) :: lower_case_input logical :: output integer :: i lower_case_input = to_lower_case (input) output = .true. do i = 1, len (lower_case) if (index (lower_case_input, lower_case (i : i)) == 0) then output = .false. exit end if end do end function is_pangram end module pangram ``` Example: ```fortran program test use pangram, only: is_pangram implicit none character (256) :: string string = 'This is a sentence.' write (*, '(a)') trim (string) write (*, '(l1)') is_pangram (string) string = 'The five boxing wizards jumped quickly.' write (*, '(a)') trim (string) write (*, '(l1)') is_pangram (string) end program test ``` {{out}} ```txt This is a sentence. F The five boxing wizards jumped quickly. T ``` ## FreeBASIC ```freebasic ' FB 1.05.0 Win64 Function isPangram(s As Const String) As Boolean Dim As Integer length = Len(s) If length < 26 Then Return False Dim p As String = LCase(s) For i As Integer = 97 To 122 If Instr(p, Chr(i)) = 0 Then Return False Next Return True End Function Dim s(1 To 3) As String = _ { _ "The quick brown fox jumps over the lazy dog", _ "abbdefghijklmnopqrstuVwxYz", _ '' no c! "How vexingly quick daft zebras jump!" _ } For i As Integer = 1 To 3: Print "'"; s(i); "' is "; IIf(isPangram(s(i)), "a", "not a"); " pangram" Print Next Print Print "Press nay key to quit" Sleep ``` {{out}} ```txt 'The quick brown fox jumps over the lazy dog' is a pangram 'abbdefghijklmnopqrstuVwxYz' is not a pangram 'How vexingly quick daft zebras jump!' is a pangram ``` ## Go ```go package main import "fmt" func main() { for _, s := range []string{ "The quick brown fox jumps over the lazy dog.", `Watch "Jeopardy!", Alex Trebek's fun TV quiz game.`, "Not a pangram.", } { if pangram(s) { fmt.Println("Yes:", s) } else { fmt.Println("No: ", s) } } } func pangram(s string) bool { var missing uint32 = (1 << 26) - 1 for _, c := range s { var index uint32 if 'a' <= c && c <= 'z' { index = uint32(c - 'a') } else if 'A' <= c && c <= 'Z' { index = uint32(c - 'A') } else { continue } missing &^= 1 << index if missing == 0 { return true } } return false } ``` {{out}} ```txt Yes: The quick brown fox jumps over the lazy dog. Yes: Watch "Jeopardy!", Alex Trebek's fun TV quiz game. No: Not a pangram. ``` ## Haskell ```haskell import Data.Char (toLower) import Data.List ((\\)) pangram :: String -> Bool pangram = null . (['a' .. 'z'] \\) . map toLower main = print $ pangram "How razorback-jumping frogs can level six piqued gymnasts!" ``` ## HicEst ```HicEst PangramBrokenAt("This is a Pangram.") ! => 2 (b is missing) PangramBrokenAt("The quick Brown Fox jumps over the Lazy Dog") ! => 0 (OK) FUNCTION PangramBrokenAt(string) CHARACTER string, Alfabet="abcdefghijklmnopqrstuvwxyz" PangramBrokenAt = INDEX(Alfabet, string, 64) ! option 64: verify = 1st letter of string not in Alfabet END ``` =={{header|Icon}} and {{header|Unicon}}== A panagram procedure: ```Icon procedure panagram(s) #: return s if s is a panagram and fail otherwise if (map(s) ** &lcase) === &lcase then return s end ``` And a main to drive it: ```Icon procedure main(arglist) if *arglist > 0 then every ( s := "" ) ||:= !arglist || " " else s := "The quick brown fox jumps over the lazy dog." writes(image(s), " -- is") writes(if not panagram(s) then "n't") write(" a panagram.") end ``` ## Io ```Io Sequence isPangram := method( letters := " " repeated(26) ia := "a" at(0) foreach(ichar, if(ichar isLetter, letters atPut((ichar asLowercase) - ia, ichar) ) ) letters contains(" " at(0)) not // true only if no " " in letters ) "The quick brown fox jumps over the lazy dog." isPangram println // --> true "The quick brown fox jumped over the lazy dog." isPangram println // --> false "ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ" isPangram println // --> true ``` ## Ioke ```ioke Text isPangram? = method( letters = "abcdefghijklmnopqrstuvwxyz" chars text = self lower chars letters map(x, text include?(x)) reduce(&&) ) ``` Here is an example of it's use in the Ioke REPL: ```ioke iik> "The quick brown fox jumps over the lazy dog" isPangram? "The quick brown fox jumps over the lazy dog" isPangram? +> true iik> "The quick brown fox jumps over the" isPangram? "The quick brown fox jumps over the" isPangram? +> false ``` ## J '''Solution:''' ```j require 'strings' isPangram=: (a. {~ 97+i.26) */@e. tolower ``` '''Example use:''' ```j isPangram 'The quick brown fox jumps over the lazy dog.' 1 isPangram 'The quick brown fox falls over the lazy dog.' 0 ``` ## Java {{works with|Java|1.5+}} ```java5 public class Pangram { public static boolean isPangram(String test){ for (char a = 'A'; a <= 'Z'; a++) if ((test.indexOf(a) < 0) && (test.indexOf((char)(a + 32)) < 0)) return false; return true; } public static void main(String[] args){ System.out.println(isPangram("the quick brown fox jumps over the lazy dog"));//true System.out.println(isPangram("the quick brown fox jumped over the lazy dog"));//false, no s System.out.println(isPangram("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));//true System.out.println(isPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ"));//false, no r System.out.println(isPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ"));//false, no m System.out.println(isPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ"));//true System.out.println(isPangram(""));//false } } ``` {{out}} ```txt true false true false false true false ``` ## JavaScript ### ES5 ### =Iterative= ```javascript function isPangram(s) { var letters = "zqxjkvbpygfwmucldrhsnioate" // sorted by frequency ascending (http://en.wikipedia.org/wiki/Letter_frequency) s = s.toLowerCase().replace(/[^a-z]/g,'') for (var i = 0; i < 26; i++) if (s.indexOf(letters[i]) < 0) return false return true } console.log(isPangram("is this a pangram")) // false console.log(isPangram("The quick brown fox jumps over the lazy dog")) // true ``` ### ES6 ### =Functional= ```JavaScript (() => { 'use strict'; // isPangram :: String -> Bool let isPangram = s => { let lc = s.toLowerCase(); return 'abcdefghijklmnopqrstuvwxyz' .split('') .filter(c => lc.indexOf(c) === -1) .length === 0; }; // TEST return [ 'is this a pangram', 'The quick brown fox jumps over the lazy dog' ].map(isPangram); })(); ``` {{Out}} ```txt [false, true] ``` ## jq ```jq def is_pangram: explode | map( if 65 <= . and . <= 90 then . + 32 # uppercase elif 97 <= . and . <= 122 then . # lowercase else empty end ) | unique | length == 26; # Example: "The quick brown fox jumps over the lazy dog" | is_pangram ``` {{Out}} $ jq -M -n -f pangram.jq true ## Julia <tt>makepangramchecker</tt> creates a function to test for pangramity based upon the contents of its input string, allowing one to create arbitrary pangram checkers. ```Julia function makepangramchecker(alphabet) alphabet = Set(uppercase.(alphabet)) function ispangram(s) lengthcheck = length(s) ≥ length(alphabet) return lengthcheck && all(c in uppercase(s) for c in alphabet) end return ispangram end const tests = ["Pack my box with five dozen liquor jugs.", "The quick brown fox jumps over a lazy dog.", "The quick brown fox jumps\u2323over the lazy dog.", "The five boxing wizards jump quickly.", "This sentence contains A-Z but not the whole alphabet."] is_english_pangram = makepangramchecker('a':'z') for s in tests println("The sentence \"", s, "\" is ", is_english_pangram(s) ? "" : "not ", "a pangram.") end ``` {{out}} ```txt The sentence "Pack my box with five dozen liquor jugs." is a pangram. The sentence "The quick brown fox jumps over a lazy dog." is a pangram. The sentence "The quick brown fox jumps⌣over the lazy dog." is a pangram. The sentence "The five boxing wizards jump quickly." is a pangram. The sentence "This sentence contains A-Z but not the whole alphabet." is not a pangram. ``` ## K ```k lcase : _ci 97+!26 ucase : _ci 65+!26 tolower : {@[x;p;:;lcase@n@p:&26>n:ucase?/:x]} panagram: {&/lcase _lin tolower x} ``` Example: ```k panagram "The quick brown fox jumps over the lazy dog" 1 panagram "Panagram test" 0 ``` ## Kotlin ```scala // version 1.0.6 fun isPangram(s: String): Boolean { if (s.length < 26) return false val t = s.toLowerCase() for (c in 'a' .. 'z') if (c !in t) return false return true } fun main(args: Array<String>) { val candidates = arrayOf( "The quick brown fox jumps over the lazy dog", "New job: fix Mr. Gluck's hazy TV, PDQ!", "A very bad quack might jinx zippy fowls", "A very mad quack might jinx zippy fowls" // no 'b' now! ) for (candidate in candidates) println("'$candidate' is ${if (isPangram(candidate)) "a" else "not a"} pangram") } ``` {{out}} ```txt 'The quick brown fox jumps over the lazy dog' is a pangram 'New job: fix Mr. Gluck's hazy TV, PDQ!' is a pangram 'A very bad quack might jinx zippy fowls' is a pangram 'A very mad quack might jinx zippy fowls' is not a pangram ``` ## Liberty BASIC ```lb 'Returns 0 if the string is NOT a pangram or >0 if it IS a pangram string$ = "The quick brown fox jumps over the lazy dog." Print isPangram(string$) Function isPangram(string$) string$ = Lower$(string$) For i = Asc("a") To Asc("z") isPangram = Instr(string$, chr$(i)) If isPangram = 0 Then Exit Function Next i End Function ``` ## Logo ```logo to remove.all :s :set if empty? :s [output :set] if word? :s [output remove.all butfirst :s remove first :s :set] output remove.all butfirst :s remove.all first :s :set end to pangram? :s output empty? remove.all :s "abcdefghijklmnopqrstuvwxyz end show pangram? [The five boxing wizards jump quickly.] ; true ``` ## Lua ```lua require"lpeg" S, C = lpeg.S, lpeg.C function ispangram(s) return #(C(S(s)^0):match"abcdefghijklmnopqrstuvwxyz") == 26 end print(ispangram"waltz, bad nymph, for quick jigs vex") print(ispangram"bobby") print(ispangram"long sentence") ``` ## Maple ```Maple #Used built-in StringTools package is_pangram := proc(str) local present := StringTools:-LowerCase~(select(StringTools:-HasAlpha, StringTools:-Explode(str))); local alphabets := {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}; present := convert(present, set); return evalb(present = alphabets); end proc; ``` {{out|Usage}} <lang>is_pangram("The quick brown fox jumps over the lazy dog."); is_pangram("The 2 QUIck brown foxes jumped over the lazy DOG!!"); is_pangram(""The quick brown fox jumps over the lay dog."); ``` {{out|Output}} ```txt true true false ``` ## Mathematica ```Mathematica pangramQ[msg_]:=Complement[CharacterRange["a", "z"], Characters[ToLowerCase[msg]]]=== {} ``` Usage: ```txt pangramQ["The quick brown fox jumps over the lazy dog."] True ``` Or a slightly more verbose version that outputs the missing characters if the string is not a pangram: ```Mathematica pangramQ[msg_] := Function[If[# === {}, Print["The string is a pangram!"], Print["The string is not a pangram. It's missing the letters " <> ToString[#]]]][ Complement[CharacterRange["a", "z"], Characters[ToLowerCase[msg]]]] ``` Usage: ```txt pangramQ["The quick brown fox jumps over the lazy dog."] The string is a pangram! ``` ```txt pangramQ["Not a pangram"] The string is not a pangram. It's missing the letters {b, c, d, e, f, h, i, j, k, l, q, s, u, v, w, x, y, z} ``` ## MATLAB ```MATLAB function trueFalse = isPangram(string) %This works by histogramming the ascii character codes for lower case %letters contained in the string (which is first converted to all %lower case letters). Then it finds the index of the first letter that %is not contained in the string (this is faster than using the find %without the second parameter). If the find returns an empty array then %the original string is a pangram, if not then it isn't. trueFalse = isempty(find( histc(lower(string),(97:122))==0,1 )); end ``` {{out}} ```MATLAB isPangram('The quick brown fox jumps over the lazy dog.') ans = 1 ``` ## MiniScript ```MiniScript sentences = ["The quick brown fox jumps over the lazy dog.", "Peter Piper picked a peck of pickled peppers.", "Waltz job vexed quick frog nymphs."] alphabet = "abcdefghijklmnopqrstuvwxyz" pangram = function (toCheck) sentence = toCheck.lower fail = false for c in alphabet if sentence.indexOf(c) == null then return false end for return true end function for sentence in sentences if pangram(sentence) then print """" + sentence + """ is a Pangram" else print """" + sentence + """ is not a Pangram" end if end for ``` {{out}} ```txt "The quick brown fox jumps over the lazy dog." is a Pangram "Peter Piper picked a peck of pickled peppers." is not a Pangram "Waltz job vexed quick frog nymphs." is a Pangram ``` ## NetRexx NetRexx's <code>verify</code> built&ndash;in method is all you need! ```NetRexx /* NetRexx */ options replace format comments java crossref savelog symbols nobinary A2Z = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' pangrams = create_samples loop p_ = 1 to pangrams[0] pangram = pangrams[p_] q_ = A2Z.verify(pangram.upper) -- <= it basically all happens in this function call! say pangram.left(64)'\-' if q_ == 0 then - say ' [OK, a pangram]' else - say ' [Not a pangram. Missing:' A2Z.substr(q_, 1)']' end p_ method create_samples public static returns Rexx pangrams = '' x_ = 0 x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumps over a lazy dog.' -- best/shortest pangram x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumps over the lazy dog.' -- not as short but at least it's still a pangram x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumped over the lazy dog.' -- common misquote; not a pangram x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick onyx goblin jumps over the lazy dwarf.' x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'Bored? Craving a pub quiz fix? Why, just come to the Royal Oak!' -- (Used to advertise a pub quiz in Bowness-on-Windermere) return pangrams ``` {{out}} <pre style="overflow:scroll"> The quick brown fox jumps over a lazy dog. [OK, a pangram] The quick brown fox jumps over the lazy dog. [OK, a pangram] The quick brown fox jumped over the lazy dog. [Not a pangram. Missing: S] The quick onyx goblin jumps over the lazy dwarf. [OK, a pangram] Bored? Craving a pub quiz fix? Why, just come to the Royal Oak! [OK, a pangram] ``` ## NewLISP ```newlisp (context 'PGR) ;; Switch to context (say namespace) PGR (define (is-pangram? str) (setf chars (explode (upper-case str))) ;; Uppercase + convert string into a list of chars (setf is-pangram-status true) ;; Default return value of function (for (c (char "A") (char "Z") 1 (nil? is-pangram-status)) ;; For loop with break condition (if (not (find (char c) chars)) ;; If char not found in list, "is-pangram-status" becomes "nil" (setf is-pangram-status nil) ) ) is-pangram-status ;; Return current value of symbol "is-pangram-status" ) (context 'MAIN) ;; Back to MAIN context ;; - - - - - - - - - - (println (PGR:is-pangram? "abcdefghijklmnopqrstuvwxyz")) ;; Print true (println (PGR:is-pangram? "abcdef")) ;; Print nil (exit) ``` ## Nim ```nim import rdstdin proc isPangram(sentence: string, alphabet = {'a'..'z'}): bool = var sentset: set[char] = {} for c in sentence: sentset.incl c alphabet <= sentset echo isPangram(readLineFromStdin "Sentence: ") ``` Example usage: ```txt Sentence: The quick brown fox jumps over the lazy dog true ``` ## Objeck {{trans|Java}} ```objeck bundle Default { class Pangram { function : native : IsPangram(test : String) ~ Bool { for(a := 'A'; a <= 'Z'; a += 1;) { if(test->Find(a) < 0 & test->Find(a->ToLower()) < 0) { return false; }; }; return true; } function : Main(args : String[]) ~ Nil { IsPangram("the quick brown fox jumps over the lazy dog")->PrintLine(); # true IsPangram("the quick brown fox jumped over the lazy dog")->PrintLine(); # false, no s IsPangram("ABCDEFGHIJKLMNOPQRSTUVWXYZ")->PrintLine(); # true IsPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ")->PrintLine(); # false, no r IsPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ")->PrintLine(); # false, no m IsPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ")->PrintLine(); # true IsPangram("")->PrintLine(); # false } } } ``` ## OCaml ```ocaml let pangram str = let ar = Array.make 26 false in String.iter (function | 'a'..'z' as c -> ar.(Char.code c - Char.code 'a') <- true | _ -> () ) (String.lowercase str); Array.fold_left ( && ) true ar ``` ```ocaml let check str = Printf.printf " %b -- %s\n" (pangram str) str let () = check "this is a sentence"; check "The quick brown fox jumps over the lazy dog."; ;; ``` {{out}} false -- this is a sentence true -- The quick brown fox jumps over the lazy dog. =={{header|MATLAB}} / {{header|Octave}}== ```matlab function trueFalse = isPangram(string) % X is a histogram of letters X = sparse(abs(lower(string)),1,1,128,1); trueFalse = full(all(X('a':'z') > 0)); end ``` {{out}} ```txt >>isPangram('The quick brown fox jumps over the lazy dog.') ans = 1 ``` ## min {{works with|min|0.19.3}} ```min "abcdefghijklmnopqrstuvwxyz" "" split =alphabet ('alphabet dip lowercase (swap match) prepend all?) :pangram? "The quick brown fox jumps over the lazy dog." pangram? puts ``` ## ML = ## mLite = ```ocaml fun to_locase s = implode ` map (c_downcase) ` explode s fun is_pangram (h :: t, T) = let val flen = len (filter (fn c = c eql h) T) in if (flen = 0) then false else is_pangram (t, T) end | ([], T) = true | S = is_pangram (explode "abcdefghijklmnopqrstuvwxyz", explode ` to_locase S) fun is_pangram_i (h :: t, T) = let val flen = len (filter (fn c = c eql h) T) in if (flen = 0) then false else is_pangram (t, T) end | ([], T) = true | (A,S) = is_pangram (explode A, explode ` to_locase S) fun test (f, arg, res, ok, notok) = if (f arg eql res) then ("'" @ arg @ "' " @ ok) else ("'" @ arg @ "' " @ notok) fun test2 (f, arg, res, ok, notok) = if (f arg eql res) then ("'" @ ref (arg,1) @ "' " @ ok) else ("'" @ ref (arg,1) @ "' " @ notok) ; println ` test (is_pangram, "The quick brown fox jumps over the lazy dog", true, "is a pangram", "is not a pangram"); println ` test (is_pangram, "abcdefghijklopqrstuvwxyz", true, "is a pangram", "is not a pangram"); val SValphabet = "abcdefghijklmnopqrstuvwxyzåäö"; val SVsentence = "Yxskaftbud, ge vår wczonmö iq hjälp"; println ` test2 (is_pangram_i, (SValphabet, SVsentence), true, "is a Swedish pangram", "is not a Swedish pangram"); ``` {{out}} ```txt 'The quick brown fox jumps over the lazy dog' is a pangram 'abcdefghijklopqrstuvwxyz' is not a pangram 'Yxskaftbud, ge vår wczonmö iq hjälp' is a Swedish pangram ``` ## Oz ```oz declare fun {IsPangram Xs} {List.sub {List.number &a &z 1} {Sort {Map Xs Char.toLower} Value.'<'}} end in {Show {IsPangram "The quick brown fox jumps over the lazy dog."}} ``` ## PARI/GP ```parigp pangram(s)={ s=vecsort(Vec(s),,8); for(i=97,122, if(!setsearch(s,Strchr(i)) && !setsearch(s,Strchr(i-32)), return(0) ) ); 1 }; pangram("The quick brown fox jumps over the lazy dog.") pangram("The quick brown fox jumps over the lazy doe.") ``` ## Pascal See [[Pangram_checker#Delphi | Delphi]] ## Perl Get an answer with a module, or without. ```perl use strict; use warnings; use feature 'say'; sub pangram1 { my($str,@set) = @_; use List::MoreUtils 'all'; all { $str =~ /$_/i } @set; } sub pangram2 { my($str,@set) = @_; '' eq (join '',@set) =~ s/[$str]//gir; } my @alpha = 'a' .. 'z'; for ( 'Cozy Lummox Gives Smart Squid Who Asks For Job Pen.', 'Crabby Lummox Gives Smart Squid Who Asks For Job Pen.' ) { say pangram1($_,@alpha) ? 'Yes' : 'No'; say pangram2($_,@alpha) ? 'Yes' : 'No'; } ``` {{out}} ```txt Yes Yes No No ``` ## Perl 6 ```perl6 constant Eng = set 'a' .. 'z'; constant Cyr = set <а б в г д е ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я ё>; constant Hex = set 'a' .. 'f'; sub pangram($str, Set $alpha = Eng) { $alpha ⊆ $str.lc.comb; } say pangram("The quick brown fox jumps over the lazy dog."); say pangram("My dog has fleas."); say pangram("My dog has fleas.", Hex); say pangram("My dog backs fleas.", Hex); say pangram "Съешь же ещё этих мягких французских булок, да выпей чаю", Cyr; ``` {{out}} ```txt True False False True True ``` ## Phix ```Phix function pangram(string s) sequence az = repeat(false,26) integer count = 0 for i=1 to length(s) do integer ch = lower(s[i]) if ch>='a' and ch<='z' and not az[ch-96] then count += 1 if count=26 then return {true,0} end if az[ch-96] = true end if end for return {false,find(false,az)+96} end function sequence checks = {"The quick brown fox jumped over the lazy dog", "The quick brown fox jumps over the lazy dog", ".!$\"AbCdEfghijklmnoprqstuvwxyz", "THE FIVE BOXING WIZARDS DUMP QUICKLY.", "THE FIVE BOXING WIZARDS JUMP QUICKLY.", "HEAVY BOXES PERFORM WALTZES AND JIGS.", "PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.", "Big fjiords vex quick waltz nymph", "The quick onyx goblin jumps over the lazy dwarf.", "no"} for i=1 to length(checks) do string ci = checks[i] integer {r,ch} = pangram(ci) printf(1,"%-50s - %s\n",{ci,iff(r?"yes":"no "&ch)}) end for ``` {{out}} ```txt The quick brown fox jumped over the lazy dog - no s The quick brown fox jumps over the lazy dog - yes .!$"AbCdEfghijklmnoprqstuvwxyz - yes THE FIVE BOXING WIZARDS DUMP QUICKLY. - no j THE FIVE BOXING WIZARDS JUMP QUICKLY. - yes HEAVY BOXES PERFORM WALTZES AND JIGS. - no c PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS. - yes Big fjiords vex quick waltz nymph - yes The quick onyx goblin jumps over the lazy dwarf. - yes no - no a ``` ## PicoLisp ```PicoLisp (de isPangram (Str) (not (diff '`(chop "abcdefghijklmnopqrstuvwxyz") (chop (lowc Str)) ) ) ) ``` ## PHP {{trans|D}} ```php function isPangram($text) { foreach (str_split($text) as $c) { if ($c >= 'a' && $c <= 'z') $bitset |= (1 << (ord($c) - ord('a'))); else if ($c >= 'A' && $c <= 'Z') $bitset |= (1 << (ord($c) - ord('A'))); } return $bitset == 0x3ffffff; } $test = array( "the quick brown fox jumps over the lazy dog", "the quick brown fox jumped over the lazy dog", "ABCDEFGHIJKLMNOPQSTUVWXYZ", "ABCDEFGHIJKL.NOPQRSTUVWXYZ", "ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ" ); foreach ($test as $str) echo "$str : ", isPangram($str) ? 'T' : 'F', '</br>'; ``` ```txt the quick brown fox jumps over the lazy dog : T the quick brown fox jumped over the lazy dog : F ABCDEFGHIJKLMNOPQSTUVWXYZ : F ABCDEFGHIJKL.NOPQRSTUVWXYZ : F ABC.D.E.FGHI*J/KL-M+NO*PQ R STUVWXYZ : T ``` Using array ```php function is_pangram( $sentence ) { // define "alphabet" $alpha = range( 'a', 'z' ); // split lowercased string into array $a_sentence = str_split( strtolower( $sentence ) ); // check that there are no letters present in alpha not in sentence return empty( array_diff( $alpha, $a_sentence ) ); } $tests = array( "The quick brown fox jumps over the lazy dog.", "The brown fox jumps over the lazy dog.", "ABCDEFGHIJKL.NOPQRSTUVWXYZ", "ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ", "How vexingly quick daft zebras jump", "Is hotdog?", "How razorback-jumping frogs can level six piqued gymnasts!" ); foreach ( $tests as $txt ) { echo '"', $txt, '"', PHP_EOL; echo is_pangram( $txt ) ? "Yes" : "No", PHP_EOL, PHP_EOL; } ``` {{Out}} ```txt "The quick brown fox jumps over the lazy dog." Yes "The brown fox jumps over the lazy dog." No "ABCDEFGHIJKL.NOPQRSTUVWXYZ" No "ABC.D.E.FGHI*J/KL-M+NO*PQ R STUVWXYZ" Yes "How vexingly quick daft zebras jump" Yes "Is hotdog?" No "How razorback-jumping frogs can level six piqued gymnasts!" Yes ``` ## PL/I ```PL/I test_pangram: procedure options (main); is_pangram: procedure() returns (bit(1) aligned); declare text character (200) varying; declare c character (1); get edit (text) (L); put skip list (text); text = lowercase(text); do c = 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'; if index(text, c) = 0 then return ('0'b); end; return ('1'b); end is_pangram; put skip list ('Please type a sentence'); if is_pangram() then put skip list ('The sentence is a pangram.'); else put skip list ('The sentence is not a pangram.'); end test_pangram; ``` {{out}} ```txt Please type a sentence the quick brown fox jumps over the lazy dog The sentence is a pangram. ``` ## PowerShell Cyrillic test sample borrowed from Perl 6. {{works with|PowerShell|2}} ```PowerShell function Test-Pangram ( [string]$Text, [string]$Alphabet = 'abcdefghijklmnopqrstuvwxyz' ) { $Text = $Text.ToLower() $Alphabet = $Alphabet.ToLower() $IsPangram = @( $Alphabet.ToCharArray() | Where-Object { $Text.Contains( $_ ) } ).Count -eq $Alphabet.Length return $IsPangram } Test-Pangram 'The quick brown fox jumped over the lazy dog.' Test-Pangram 'The quick brown fox jumps over the lazy dog.' Test-Pangram 'Съешь же ещё этих мягких французских булок, да выпей чаю' 'абвгдежзийклмнопрстуфхцчшщъыьэюяё' ``` {{out}} ```txt False True True ``` A faster version can be created using .Net HashSet to do what the F# version does: ```PowerShell Function Test-Pangram ( [string]$Text, [string]$Alphabet = 'abcdefghijklmnopqrstuvwxyz' ) { $alSet = [Collections.Generic.HashSet[char]]::new($Alphabet.ToLower()) $textSet = [Collections.Generic.HashSet[char]]::new($Text.ToLower()) $alSet.ExceptWith($textSet) # remove text chars from the alphabet return $alSet.Count -eq 0 # any alphabet letters still remaining? } ``` ## Prolog Works with SWI-Prolog ```Prolog pangram(L) :- numlist(0'a, 0'z, Alphabet), forall(member(C, Alphabet), member(C, L)). pangram_example :- L1 = "the quick brown fox jumps over the lazy dog", ( pangram(L1) -> R1= ok; R1 = ko), format('~s --> ~w ~n', [L1,R1]), L2 = "the quick brown fox jumped over the lazy dog", ( pangram(L2) -> R2 = ok; R2 = ko), format('~s --> ~w ~n', [L2, R2]). ``` {{out}} ```txt ?- pangram_example. the quick brown fox jumps over the lazy dog --> ok the quick brown fox jumped over the lazy dog --> ko true. ``` ## PureBasic ```PureBasic Procedure IsPangram_fast(String$) String$ = LCase(string$) char_a=Asc("a") ; sets bits in a variable if a letter is found, reads string only once For a = 1 To Len(string$) char$ = Mid(String$, a, 1) pos = Asc(char$) - char_a check.l | 1 << pos Next If check & $3FFFFFF = $3FFFFFF ProcedureReturn 1 EndIf ProcedureReturn 0 EndProcedure Procedure IsPangram_simple(String$) String$ = LCase(string$) found = 1 For a = Asc("a") To Asc("z") ; searches for every letter in whole string If FindString(String$, Chr(a), 0) = 0 found = 0 EndIf Next ProcedureReturn found EndProcedure Debug IsPangram_fast("The quick brown fox jumps over lazy dogs.") Debug IsPangram_simple("The quick brown fox jumps over lazy dogs.") Debug IsPangram_fast("No pangram") Debug IsPangram_simple("No pangram") ``` ## Python Using set arithmetic: ```python import string, sys if sys.version_info[0] < 3: input = raw_input def ispangram(sentence, alphabet=string.ascii_lowercase): alphaset = set(alphabet) return alphaset <= set(sentence.lower()) print ( ispangram(input('Sentence: ')) ) ``` {{out}} ```txt Sentence: The quick brown fox jumps over the lazy dog True ``` ## R Using the built-in R vector "letters": ```R checkPangram <- function(sentence){ my.letters <- tolower(unlist(strsplit(sentence, ""))) is.pangram <- all(letters %in% my.letters) if (is.pangram){ cat("\"", sentence, "\" is a pangram! \n", sep="") } else { cat("\"", sentence, "\" is not a pangram! \n", sep="") } } ``` {{out}} ```txt s1 <- "The quick brown fox jumps over the lazy dog" s2 <- "The quick brown fox jumps over the sluggish dog" checkPangram(s1) "The quick brown fox jumps over the lazy dog" is a pangram! checkPangram(s2) "The quick brown fox jumps over the sluggish dog" is not a pangram! ``` ## Racket ```Racket #lang racket (define (pangram? str) (define chars (regexp-replace* #rx"[^a-z]+" (string-downcase str) "")) (= 26 (length (remove-duplicates (string->list chars))))) (pangram? "The quick Brown Fox jumps over the Lazy Dog") ``` ## Retro ```Retro : isPangram? ( $-f ) ^strings'toLower heap [ 27 allot ] preserve [ @ 'a - dup 0 25 within [ [ 'a + ] [ here + ] bi ! ] &drop if ] ^types'STRING each@ here "abcdefghijklmnopqrstuvwxyz" compare ; ``` ## REXX ```REXX /*REXX program verifies if an entered/supplied string (sentence) is a pangram. */ @abc= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*a list of all (Latin) capital letters*/ do forever; say /*keep promoting 'til null (or blanks).*/ say '──────── Please enter a pangramic sentence (or a blank to quit):'; say pull y /*this also uppercases the Y variable.*/ if y='' then leave /*if nothing entered, then we're done.*/ absent= space( translate( @abc, , y), 0) /*obtain a list of any absent letters. */ if absent=='' then say "──────── Sentence is a pangram." else say "──────── Sentence isn't a pangram, missing: " absent say end /*forever*/ say '──────── PANGRAM program ended. ────────' /*stick a fork in it, we're all done. */ ``` {{out|output|:}} ```txt ──────── Please enter a pangramic sentence (or a blank to quit): The quick brown fox jumped over the lazy dog. ◄■■■■■■■■■■ user input. ──────── Sentence isn't a pangram, missing: S ──────── Please enter a pangramic sentence (or a blank to quit): The quick brown fox JUMPS over the lazy dog!!! ◄■■■■■■■■■■ user input. ──────── Sentence is a pangram. ──────── Please enter a pangramic sentence (or a blank to quit): ◄■■■■■■■■■■ user input (null or some blanks). ──────── PANGRAM program ended. ──────── ``` ## Ring ```ring pangram = 0 s = "The quick brown fox jumps over the lazy dog." see "" + pangram(s) + " " + s + nl s = "My dog has fleas." see "" + pangram(s) + " " + s + nl func pangram str str = lower(str) for i = ascii("a") to ascii("z") bool = substr(str, char(i)) > 0 pangram = pangram + bool next pan = (pangram = 26) return pan ``` ## Ruby ```ruby def pangram?(sentence) ('a'..'z').all? {|chars| sentence.downcase.include? (chars) } end p pangram?('this is a sentence') # ==> false p pangram?('The quick brown fox jumps over the lazy dog.') # ==> true ``` ## Run BASIC ```runbasic s$ = "The quick brown fox jumps over the lazy dog." Print pangram(s$);" ";s$ s$ = "My dog has fleas." Print pangram(s$);" ";s$ function pangram(str$) str$ = lower$(str$) for i = asc("a") to asc("z") pangram = pangram + (instr(str$, chr$(i)) <> 0) next i pangram = (pangram = 26) end function ``` ```txt 1 The quick brown fox jumps over the lazy dog. 0 My dog has fleas. ``` ## Rust ```rust #![feature(test)] extern crate test; use std::collections::HashSet; pub fn is_pangram_via_bitmask(s: &str) -> bool { // Create a mask of set bits and convert to false as we find characters. let mut mask = (1 << 26) - 1; for chr in s.chars() { let val = chr as u32 & !0x20; /* 0x20 converts lowercase to upper */ if val <= 'Z' as u32 && val >= 'A' as u32 { mask = mask & !(1 << (val - 'A' as u32)); } } mask == 0 } pub fn is_pangram_via_hashset(s: &str) -> bool { // Insert lowercase letters into a HashSet, then check if we have at least 26. let letters = s.chars() .flat_map(|chr| chr.to_lowercase()) .filter(|&chr| chr >= 'a' && chr <= 'z') .fold(HashSet::new(), |mut letters, chr| { letters.insert(chr); letters }); letters.len() == 26 } pub fn is_pangram_via_sort(s: &str) -> bool { // Copy chars into a vector, convert to lowercase, sort, and remove duplicates. let mut chars: Vec<char> = s.chars() .flat_map(|chr| chr.to_lowercase()) .filter(|&chr| chr >= 'a' && chr <= 'z') .collect(); chars.sort(); chars.dedup(); chars.len() == 26 } fn main() { let examples = ["The quick brown fox jumps over the lazy dog", "The quick white cat jumps over the lazy dog"]; for &text in examples.iter() { let is_pangram_sort = is_pangram_via_sort(text); println!("Is \"{}\" a pangram via sort? - {}", text, is_pangram_sort); let is_pangram_bitmask = is_pangram_via_bitmask(text); println!("Is \"{}\" a pangram via bitmask? - {}", text, is_pangram_bitmask); let is_pangram_hashset = is_pangram_via_hashset(text); println!("Is \"{}\" a pangram via bitmask? - {}", text, is_pangram_hashset); } } ``` ## Scala ```scala def is_pangram(sentence: String) = sentence.toLowerCase.filter(c => c >= 'a' && c <= 'z').toSet.size == 26 ``` ```scala scala> is_pangram("This is a sentence") res0: Boolean = false scala> is_pangram("The quick brown fox jumps over the lazy dog") res1: Boolean = true ``` ## Seed7 ```seed7 $ include "seed7_05.s7i"; const func boolean: isPangram (in string: stri) is func result var boolean: isPangram is FALSE; local var char: ch is ' '; var set of char: usedChars is (set of char).value; begin for ch range lower(stri) do if ch in {'a' .. 'z'} then incl(usedChars, ch); end if; end for; isPangram := usedChars = {'a' .. 'z'}; end func; const proc: main is func begin writeln(isPangram("This is a test")); writeln(isPangram("The quick brown fox jumps over the lazy dog")); writeln(isPangram("NOPQRSTUVWXYZ abcdefghijklm")); writeln(isPangram("abcdefghijklopqrstuvwxyz")); # Missing m, n end func; ``` {{out}} ```txt FALSE TRUE TRUE FALSE ``` ## Sidef {{trans|Perl 6}} ```ruby define Eng = 'a'..'z'; define Hex = 'a'..'f'; define Cyr = %w(а б в г д е ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я ё); func pangram(str, alpha=Eng) { var lstr = str.lc; alpha.all {|c| lstr.contains(c) }; } say pangram("The quick brown fox jumps over the lazy dog."); say pangram("My dog has fleas."); say pangram("My dog has fleas.", Hex); say pangram("My dog backs fleas.", Hex); say pangram("Съешь же ещё этих мягких французских булок, да выпей чаю", Cyr); ``` {{out}} ```txt true false false true true ``` ## Smalltalk ```smalltalk !String methodsFor: 'testing'! isPangram ^((self collect: [:c | c asUppercase]) select: [:c | c >= $A and: [c <= $Z]]) asSet size = 26 ``` ```smalltalk 'The quick brown fox jumps over the lazy dog.' isPangram ``` ## SNOBOL4 {{works with|Macro Spitbol}} {{works with|Snobol4+}} {{works with|CSnobol}} ```SNOBOL4 define('pangram(str)alfa,c') :(pangram_end) pangram str = replace(str,&ucase,&lcase) alfa = &lcase pgr_1 alfa len(1) . c = :f(return) str c :s(pgr_1)f(freturn) pangram_end define('panchk(str)tf') :(panchk_end) panchk output = str tf = 'False'; tf = pangram(str) 'True' output = 'Pangram: ' tf :(return) panchk_end * # Test and display panchk("The quick brown fox jumped over the lazy dogs.") panchk("My girl wove six dozen plaid jackets before she quit.") panchk("This 41-character string: it's a pangram!") end ``` {{out}} ```txt The quick brown fox jumped over the lazy dogs. Pangram: True My girl wove six dozen plaid jackets before she quit. Pangram: True This 41-character string: it's a pangram! Pangram: False ``` ## Swift ```Swift import Foundation let str = "the quick brown fox jumps over the lazy dog" func isPangram(str:String) -> Bool { let stringArray = Array(str.lowercaseString) for char in "abcdefghijklmnopqrstuvwxyz" { if (find(stringArray, char) == nil) { return false } } return true } isPangram(str) // True isPangram("Test string") // False ``` Swift 2.0: ```swift func isPangram(str: String) -> Bool { let (char, alph) = (Set(str.characters), "abcdefghijklmnopqrstuvwxyz".characters) return !alph.contains {!char.contains($0)} } ``` ## Tcl ```tcl proc pangram? {sentence} { set letters [regexp -all -inline {[a-z]} [string tolower $sentence]] expr { [llength [lsort -unique $letters]] == 26 } } puts [pangram? "This is a sentence"]; # ==> false puts [pangram? "The quick brown fox jumps over the lazy dog."]; # ==> true ``` =={{header|TI-83 BASIC}}== ```ti83b :Prompt Str1 :For(L,1,26 :If not(inString(Str1,sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",L,1)) :L=28 :End :If L<28 :Disp "IS A PANGRAM" ``` (not tested yet) ## TUSCRIPT ```tuscript $$ MODE TUSCRIPT,{} alfabet="abcdefghijklmnopqrstuvwxyz" sentences = * DATA The quick brown fox jumps over the lazy dog DATA the quick brown fox falls over the lazy dog LOOP s=sentences getchars =STRINGS (s," {&a} ") sortchars =ALPHA_SORT (getchars) reducechars =REDUCE (sortchars) chars_in_s =EXCHANGE (reducechars," ' ") IF (chars_in_s==alfabet) PRINT " pangram: ",s IF (chars_in_s!=alfabet) PRINT "no pangram: ",s ENDLOOP ``` {{out}} ```txt pangram: The quick brown fox jumps over the lazy dog no pangram: the quick brown fox falls over the lazy dog ``` ## TXR ```txr @/.*[Aa].*&.*[Bb].*&.*[Cc].*&.*[Dd].*& \ .*[Ee].*&.*[Ff].*&.*[Gg].*&.*[Hh].*& \ .*[Ii].*&.*[Jj].*&.*[Kk].*&.*[Ll].*& \ .*[Mm].*&.*[Nn].*&.*[Oo].*&.*[Pp].*& \ .*[Qq].*&.*[Rr].*&.*[Ss].*&.*[Tt].*& \ .*[Uu].*&.*[Vv].*&.*[Ww].*&.*[Xx].*& \ .*[Yy].*&.*[Zz].*/ ``` {{out|Run}} ```txt $ echo "The quick brown fox jumped over the lazy dog." | txr is-pangram.txr - $echo $? # failed termination 1 $ echo "The quick brown fox jumped over the lazy dogs." | txr is-pangram.txr - $ echo $? # successful termination 0 ``` ## UNIX Shell {{works with|Bourne Again SHell}} ```bash function pangram? { local alphabet=abcdefghijklmnopqrstuvwxyz local string="$*" string="${string,,}" while [[ -n "$string" && -n "$alphabet" ]]; do local ch="${string%%${string#?}}" string="${string#?}" alphabet="${alphabet/$ch}" done [[ -z "$alphabet" ]] } ``` ## Ursala ```Ursala #import std is_pangram = ^jZ^(!@l,*+ @rlp -:~&) ~=`A-~ letters ``` example usage: ```Ursala #cast %bL test = is_pangram* < 'The quick brown fox jumps over the lazy dog', 'this is not a pangram'> ``` {{out}} ```txt <true,false> ``` ## VBA The function pangram() in the VBScript section below will do just fine. Here is an alternative version: ```vb Function pangram2(s As String) As Boolean Const sKey As String = "abcdefghijklmnopqrstuvwxyz" Dim sLow As String Dim i As Integer sLow = LCase(s) For i = 1 To 26 If InStr(sLow, Mid(sKey, i, 1)) = 0 Then pangram2 = False Exit Function End If Next pangram2 = True End Function ``` Invocation e.g. (typed in the Immediate window): ```txt print pangram2("the quick brown dog jumps over a lazy fox") print pangram2("it is time to say goodbye!") ``` ## VBScript ### =Implementation= ```vb function pangram( s ) dim i dim sKey dim sChar dim nOffset sKey = "abcdefghijklmnopqrstuvwxyz" for i = 1 to len( s ) sChar = lcase(mid(s,i,1)) if sChar <> " " then if instr(sKey, sChar) then nOffset = asc( sChar ) - asc("a") + 1 if nOffset > 1 then sKey = left(sKey, nOffset - 1) & " " & mid( sKey, nOffset + 1) else sKey = " " & mid( sKey, nOffset + 1) end if end if end if next pangram = ( ltrim(sKey) = vbnullstring ) end function function eef( bCond, exp1, exp2 ) if bCond then eef = exp1 else eef = exp2 end if end function ``` ### =Invocation= ```vb wscript.echo eef(pangram("a quick brown fox jumps over the lazy dog"), "is a pangram", "is not a pangram") wscript.echo eef(pangram(""), "is a pangram", "is not a pangram")" ``` ## XPL0 ```XPL0 include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings func StrLen(Str); \Return number of characters in an ASCIIZ string char Str; int I; for I:= 0 to -1>>1-1 do if Str(I) = 0 then return I; func Pangram(S); char S; int A, I, C; [A:= 0; for I:= 0 to StrLen(S)-1 do [C:= S(I); if C>=^A & C<=^Z then C:= C or $20; if C>=^a & C<=^z then [C:= C - ^a; A:= A or 1<<C]; ]; return A = $3FFFFFF; ]; \Pangram int Sentence, I; [Sentence:= ["The quick brown fox jumps over the lazy dog.", "Pack my box with five dozen liquor jugs.", "Now is the time for all good men to come to the aid of their country."]; for I:= 0 to 3-1 do [Text(0, if Pangram(Sentence(I)) then "yes" else "no"); CrLf(0); ]; ] ``` {{out}} ```txt yes yes no ``` ## Yabasic ```Yabasic sub isPangram$(t$, l1$) local lt, ll, r$, i, cc, ic if numparams = 1 then l1$ = "abcdefghijklmnopqrstuvwxyz" end if t$ = lower$(t$) ll = len(l1$) for i = 1 to ll r$ = r$ + " " next lt = len(t$) cc = asc("a") for i = 1 to lt ic = asc(mid$(t$, i, 1)) - cc + 1 if ic > 0 and ic <= ll then mid$(r$, ic, 1) = chr$(ic + cc - 1) end if next i if l1$ = r$ then return "true" else return "false" end if end sub print isPangram$("The quick brown fox jumps over the lazy dog.") // --> true print isPangram$("The quick brown fox jumped over the lazy dog.") // --> false print isPangram$("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ") // --> true ``` ## zkl ```zkl var letters=["a".."z"].pump(String); //-->"abcdefghijklmnopqrstuvwxyz" fcn isPangram(text){(not (letters-text.toLower()))} ``` {{out}} ```txt isPangram("The quick brown fox jumps over the lazy dog.") True isPangram("Pack my box with five dozen liquor jugs.") True isPangram("Now is the time for all good men to come to the aid of their country.") False ```
{ "pile_set_name": "Github" }
<!--index.wxml--> <view class="index"> <view class="index-profile"> <open-data type="userAvatarUrl" class="index-profile__img"></open-data> </view> <view class="index-title"> {{ title }} </view> <view class="index-books"> <view class="index-books__showLayer"> <view class="index-books__item" wx:for="{{ bookList }}" wx:key="{{ index }}"> <view class="index-books__title">书目:</view> <view class="index-books__controls--show" wx:if="{{ !item.isEditing }}">{{ item.bookName }} </view> <view class="index-books__controls--edit-area" wx:else> <input type="text" value="{{ item.bookName }}" confirm-type="完成" data-book-id="{{ item.id }}" bindinput="bindEditBookNameInput" /> </view> <button class="index-books__controls--edit-btn btn" type="primary" data-book-id="{{ item.id }}" data-index="{{index}}" bindtap="{{ item.isEditing ? 'updateBook' : 'editBookButtonClicked' }}" > {{ item.isEditing ? '保存' : '编辑' }} </button> <button class="index-books__controls--delete btn" type="warn" data-book-id="{{ item.id }}" bindtap="deleteBook" > 删除 </button> </view> </view> <view class="index-books__input"> <input type="text" placeholder="我的床头书" value="{{ createBookValue }}" confirm-type="完成" bindinput="bindCreateBookNameInput" /> </view> <view class="index-books__controls"> <button class="index-books__controls--create" bindtap="createBook" type="primary" > 添加 </button> </view> </view> </view>
{ "pile_set_name": "Github" }
[ { "EventCode": "0xE8", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "BPU_CLEARS.EARLY", "SampleAfterValue": "2000000", "BriefDescription": "Early Branch Prediciton Unit clears" }, { "EventCode": "0xE8", "Counter": "0,1,2,3", "UMask": "0x2", "EventName": "BPU_CLEARS.LATE", "SampleAfterValue": "2000000", "BriefDescription": "Late Branch Prediction Unit clears" }, { "EventCode": "0xE5", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "BPU_MISSED_CALL_RET", "SampleAfterValue": "2000000", "BriefDescription": "Branch prediction unit missed call or return" }, { "EventCode": "0xD5", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "ES_REG_RENAMES", "SampleAfterValue": "2000000", "BriefDescription": "ES segment renames" }, { "EventCode": "0x6C", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "IO_TRANSACTIONS", "SampleAfterValue": "2000000", "BriefDescription": "I/O transactions" }, { "EventCode": "0x80", "Counter": "0,1,2,3", "UMask": "0x4", "EventName": "L1I.CYCLES_STALLED", "SampleAfterValue": "2000000", "BriefDescription": "L1I instruction fetch stall cycles" }, { "EventCode": "0x80", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "L1I.HITS", "SampleAfterValue": "2000000", "BriefDescription": "L1I instruction fetch hits" }, { "EventCode": "0x80", "Counter": "0,1,2,3", "UMask": "0x2", "EventName": "L1I.MISSES", "SampleAfterValue": "2000000", "BriefDescription": "L1I instruction fetch misses" }, { "EventCode": "0x80", "Counter": "0,1,2,3", "UMask": "0x3", "EventName": "L1I.READS", "SampleAfterValue": "2000000", "BriefDescription": "L1I Instruction fetches" }, { "EventCode": "0x82", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "LARGE_ITLB.HIT", "SampleAfterValue": "200000", "BriefDescription": "Large ITLB hit" }, { "EventCode": "0x13", "Counter": "0,1,2,3", "UMask": "0x7", "EventName": "LOAD_DISPATCH.ANY", "SampleAfterValue": "2000000", "BriefDescription": "All loads dispatched" }, { "EventCode": "0x13", "Counter": "0,1,2,3", "UMask": "0x4", "EventName": "LOAD_DISPATCH.MOB", "SampleAfterValue": "2000000", "BriefDescription": "Loads dispatched from the MOB" }, { "EventCode": "0x13", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "LOAD_DISPATCH.RS", "SampleAfterValue": "2000000", "BriefDescription": "Loads dispatched that bypass the MOB" }, { "EventCode": "0x13", "Counter": "0,1,2,3", "UMask": "0x2", "EventName": "LOAD_DISPATCH.RS_DELAYED", "SampleAfterValue": "2000000", "BriefDescription": "Loads dispatched from stage 305" }, { "EventCode": "0x7", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "PARTIAL_ADDRESS_ALIAS", "SampleAfterValue": "200000", "BriefDescription": "False dependencies due to partial address aliasing" }, { "EventCode": "0xD2", "Counter": "0,1,2,3", "UMask": "0xf", "EventName": "RAT_STALLS.ANY", "SampleAfterValue": "2000000", "BriefDescription": "All RAT stall cycles" }, { "EventCode": "0xD2", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "RAT_STALLS.FLAGS", "SampleAfterValue": "2000000", "BriefDescription": "Flag stall cycles" }, { "EventCode": "0xD2", "Counter": "0,1,2,3", "UMask": "0x2", "EventName": "RAT_STALLS.REGISTERS", "SampleAfterValue": "2000000", "BriefDescription": "Partial register stall cycles" }, { "EventCode": "0xD2", "Counter": "0,1,2,3", "UMask": "0x4", "EventName": "RAT_STALLS.ROB_READ_PORT", "SampleAfterValue": "2000000", "BriefDescription": "ROB read port stalls cycles" }, { "EventCode": "0xD2", "Counter": "0,1,2,3", "UMask": "0x8", "EventName": "RAT_STALLS.SCOREBOARD", "SampleAfterValue": "2000000", "BriefDescription": "Scoreboard stall cycles" }, { "EventCode": "0x4", "Counter": "0,1,2,3", "UMask": "0x7", "EventName": "SB_DRAIN.ANY", "SampleAfterValue": "200000", "BriefDescription": "All Store buffer stall cycles" }, { "EventCode": "0xD4", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "SEG_RENAME_STALLS", "SampleAfterValue": "2000000", "BriefDescription": "Segment rename stall cycles" }, { "EventCode": "0xB8", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "SNOOP_RESPONSE.HIT", "SampleAfterValue": "100000", "BriefDescription": "Thread responded HIT to snoop" }, { "EventCode": "0xB8", "Counter": "0,1,2,3", "UMask": "0x2", "EventName": "SNOOP_RESPONSE.HITE", "SampleAfterValue": "100000", "BriefDescription": "Thread responded HITE to snoop" }, { "EventCode": "0xB8", "Counter": "0,1,2,3", "UMask": "0x4", "EventName": "SNOOP_RESPONSE.HITM", "SampleAfterValue": "100000", "BriefDescription": "Thread responded HITM to snoop" }, { "EventCode": "0xF6", "Counter": "0,1,2,3", "UMask": "0x1", "EventName": "SQ_FULL_STALL_CYCLES", "SampleAfterValue": "2000000", "BriefDescription": "Super Queue full stall cycles" } ]
{ "pile_set_name": "Github" }
### ### DO NOT MODIFY THIS FILE. THIS FILE HAS BEEN AUTOGENERATED ### FROM openjdk:15-ea-10-jdk-buster # It's DynamoDB, in Docker! # # Check for details on how to run DynamoDB locally.: # # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html # # This Dockerfile essentially replicates those instructions. # Create our main application folder. RUN mkdir -p opt/dynamodb WORKDIR /opt/dynamodb # Download and unpack dynamodb. RUN wget http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gz -q -O - | tar -xz || curl -L http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gz | tar xz # The entrypoint is the dynamodb jar. ENTRYPOINT ["java", "-Xmx1G", "-jar", "DynamoDBLocal.jar"] # Default port for "DynamoDB Local" is 8000. EXPOSE 8000
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab * Copyright (C) 2009 - DIGITEO - Vincent COUVERT * * Copyright (C) 2012 - 2016 - Scilab Enterprises * * This file is hereby licensed under the terms of the GNU GPL v2.0, * pursuant to article 5.3.4 of the CeCILL v.2.1. * This file was originally licensed under the terms of the CeCILL v2.1, * and continues to be available under such terms. * For more information, see the COPYING file which you should have received * along with this program. * --> <refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svg="http://www.w3.org/2000/svg" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:db="http://docbook.org/ns/docbook" xmlns:scilab="http://www.scilab.org" xml:id="m2sci_besselj"> <refnamediv> <refname>besselj (Matlab function)</refname> <refpurpose>Bessel functions of the first kind </refpurpose> </refnamediv> <refsection> <title>Matlab/Scilab equivalent</title> <informaltable border="1" width="100%"> <tr> <td align="center"> <emphasis role="bold">Matlab</emphasis> </td> <td align="center"> <emphasis role="bold">Scilab</emphasis> </td> </tr> <tr> <td> <programlisting role="example"><![CDATA[ besselj ]]></programlisting> </td> <td> <programlisting role="example"><![CDATA[ besselj ]]></programlisting> </td> </tr> </informaltable> </refsection> <refsection> <title>Particular cases</title> <para> Scilab <emphasis role="bold">besselj</emphasis> function can work with only one output argument, but the Matlab function can work with two outputs arguments. </para> </refsection> <refsection> <title>Examples</title> <informaltable border="1" width="100%"> <tr> <td align="center"> <emphasis role="bold">Matlab</emphasis> </td> <td align="center"> <emphasis role="bold">Scilab</emphasis> </td> </tr> <tr> <td> <programlisting role="example"><![CDATA[ y = besselj(alpha,x) y = besselj(alpha,x,1) [y,ierr] = besselj(alpha,...) ]]></programlisting> </td> <td> <programlisting role="example"><![CDATA[ y = besselj(alpha,x) y = besselj(alpha,x,ice),ice = 1 or ice = 2 ]]></programlisting> </td> </tr> </informaltable> </refsection> </refentry>
{ "pile_set_name": "Github" }
#%RAML 0.8 title: test API traits: - tr: body: application/json: schemas: - MyType: | { "$schema": "http://json-schema.org/draft-04/", "type": "object", "properties": { "arrayProp": { "items": { "type": "object", "properties": { "prop1": { "type": "number" }, "prop2": { "type": "boolean" } }, "additionalProperties": false } } } } /res1: post: body: application/json: schema: MyType example: | { "arrayProp": [ { "prop1": 13, "prop2" : true }, { "prop1": 13, "prop2": false } ] } /res2: post: body: application/json: schema: MyType example: | { "arrayProp": [ { "prop1": 13 "prop2": false } , { "prop1": 13, "prop2": false } ] }
{ "pile_set_name": "Github" }
/* * CRIS helper routines * * Copyright (c) 2007 AXIS Communications * Written by Edgar E. Iglesias * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #include "cpu.h" #include "dyngen-exec.h" #include "mmu.h" #include "helper.h" #include "host-utils.h" //#define CRIS_OP_HELPER_DEBUG #ifdef CRIS_OP_HELPER_DEBUG #define D(x) x #define D_LOG(...) qemu_log(__VA__ARGS__) #else #define D(x) #define D_LOG(...) do { } while (0) #endif #if !defined(CONFIG_USER_ONLY) #include "softmmu_exec.h" #define MMUSUFFIX _mmu #define SHIFT 0 #include "softmmu_template.h" #define SHIFT 1 #include "softmmu_template.h" #define SHIFT 2 #include "softmmu_template.h" #define SHIFT 3 #include "softmmu_template.h" /* Try to fill the TLB and return an exception if error. If retaddr is NULL, it means that the function was called in C code (i.e. not from generated code or from helper.c) */ /* XXX: fix it to restore all registers */ void tlb_fill(CPUState *env1, target_ulong addr, int is_write, int mmu_idx, void *retaddr) { TranslationBlock *tb; CPUState *saved_env; unsigned long pc; int ret; saved_env = env; env = env1; D_LOG("%s pc=%x tpc=%x ra=%x\n", __func__, env->pc, env->debug1, retaddr); ret = cpu_cris_handle_mmu_fault(env, addr, is_write, mmu_idx); if (unlikely(ret)) { if (retaddr) { /* now we have a real cpu fault */ pc = (unsigned long)retaddr; tb = tb_find_pc(pc); if (tb) { /* the PC is inside the translated code. It means that we have a virtual CPU fault */ cpu_restore_state(tb, env, pc); /* Evaluate flags after retranslation. */ helper_top_evaluate_flags(); } } cpu_loop_exit(env); } env = saved_env; } #endif void helper_raise_exception(uint32_t index) { env->exception_index = index; cpu_loop_exit(env); } void helper_tlb_flush_pid(uint32_t pid) { #if !defined(CONFIG_USER_ONLY) pid &= 0xff; if (pid != (env->pregs[PR_PID] & 0xff)) cris_mmu_flush_pid(env, env->pregs[PR_PID]); #endif } void helper_spc_write(uint32_t new_spc) { #if !defined(CONFIG_USER_ONLY) tlb_flush_page(env, env->pregs[PR_SPC]); tlb_flush_page(env, new_spc); #endif } void helper_dump(uint32_t a0, uint32_t a1, uint32_t a2) { qemu_log("%s: a0=%x a1=%x\n", __func__, a0, a1); } /* Used by the tlb decoder. */ #define EXTRACT_FIELD(src, start, end) \ (((src) >> start) & ((1 << (end - start + 1)) - 1)) void helper_movl_sreg_reg (uint32_t sreg, uint32_t reg) { uint32_t srs; srs = env->pregs[PR_SRS]; srs &= 3; env->sregs[srs][sreg] = env->regs[reg]; #if !defined(CONFIG_USER_ONLY) if (srs == 1 || srs == 2) { if (sreg == 6) { /* Writes to tlb-hi write to mm_cause as a side effect. */ env->sregs[SFR_RW_MM_TLB_HI] = env->regs[reg]; env->sregs[SFR_R_MM_CAUSE] = env->regs[reg]; } else if (sreg == 5) { uint32_t set; uint32_t idx; uint32_t lo, hi; uint32_t vaddr; int tlb_v; idx = set = env->sregs[SFR_RW_MM_TLB_SEL]; set >>= 4; set &= 3; idx &= 15; /* We've just made a write to tlb_lo. */ lo = env->sregs[SFR_RW_MM_TLB_LO]; /* Writes are done via r_mm_cause. */ hi = env->sregs[SFR_R_MM_CAUSE]; vaddr = EXTRACT_FIELD(env->tlbsets[srs-1][set][idx].hi, 13, 31); vaddr <<= TARGET_PAGE_BITS; tlb_v = EXTRACT_FIELD(env->tlbsets[srs-1][set][idx].lo, 3, 3); env->tlbsets[srs - 1][set][idx].lo = lo; env->tlbsets[srs - 1][set][idx].hi = hi; D_LOG("tlb flush vaddr=%x v=%d pc=%x\n", vaddr, tlb_v, env->pc); if (tlb_v) { tlb_flush_page(env, vaddr); } } } #endif } void helper_movl_reg_sreg (uint32_t reg, uint32_t sreg) { uint32_t srs; env->pregs[PR_SRS] &= 3; srs = env->pregs[PR_SRS]; #if !defined(CONFIG_USER_ONLY) if (srs == 1 || srs == 2) { uint32_t set; uint32_t idx; uint32_t lo, hi; idx = set = env->sregs[SFR_RW_MM_TLB_SEL]; set >>= 4; set &= 3; idx &= 15; /* Update the mirror regs. */ hi = env->tlbsets[srs - 1][set][idx].hi; lo = env->tlbsets[srs - 1][set][idx].lo; env->sregs[SFR_RW_MM_TLB_HI] = hi; env->sregs[SFR_RW_MM_TLB_LO] = lo; } #endif env->regs[reg] = env->sregs[srs][sreg]; } static void cris_ccs_rshift(CPUState *env) { uint32_t ccs; /* Apply the ccs shift. */ ccs = env->pregs[PR_CCS]; ccs = (ccs & 0xc0000000) | ((ccs & 0x0fffffff) >> 10); if (ccs & U_FLAG) { /* Enter user mode. */ env->ksp = env->regs[R_SP]; env->regs[R_SP] = env->pregs[PR_USP]; } env->pregs[PR_CCS] = ccs; } void helper_rfe(void) { int rflag = env->pregs[PR_CCS] & R_FLAG; D_LOG("rfe: erp=%x pid=%x ccs=%x btarget=%x\n", env->pregs[PR_ERP], env->pregs[PR_PID], env->pregs[PR_CCS], env->btarget); cris_ccs_rshift(env); /* RFE sets the P_FLAG only if the R_FLAG is not set. */ if (!rflag) env->pregs[PR_CCS] |= P_FLAG; } void helper_rfn(void) { int rflag = env->pregs[PR_CCS] & R_FLAG; D_LOG("rfn: erp=%x pid=%x ccs=%x btarget=%x\n", env->pregs[PR_ERP], env->pregs[PR_PID], env->pregs[PR_CCS], env->btarget); cris_ccs_rshift(env); /* Set the P_FLAG only if the R_FLAG is not set. */ if (!rflag) env->pregs[PR_CCS] |= P_FLAG; /* Always set the M flag. */ env->pregs[PR_CCS] |= M_FLAG; } uint32_t helper_lz(uint32_t t0) { return clz32(t0); } uint32_t helper_btst(uint32_t t0, uint32_t t1, uint32_t ccs) { /* FIXME: clean this up. */ /* des ref: The N flag is set according to the selected bit in the dest reg. The Z flag is set if the selected bit and all bits to the right are zero. The X flag is cleared. Other flags are left untouched. The destination reg is not affected.*/ unsigned int fz, sbit, bset, mask, masked_t0; sbit = t1 & 31; bset = !!(t0 & (1 << sbit)); mask = sbit == 31 ? -1 : (1 << (sbit + 1)) - 1; masked_t0 = t0 & mask; fz = !(masked_t0 | bset); /* Clear the X, N and Z flags. */ ccs = ccs & ~(X_FLAG | N_FLAG | Z_FLAG); if (env->pregs[PR_VR] < 32) ccs &= ~(V_FLAG | C_FLAG); /* Set the N and Z flags accordingly. */ ccs |= (bset << 3) | (fz << 2); return ccs; } static inline uint32_t evaluate_flags_writeback(uint32_t flags, uint32_t ccs) { unsigned int x, z, mask; /* Extended arithmetics, leave the z flag alone. */ x = env->cc_x; mask = env->cc_mask | X_FLAG; if (x) { z = flags & Z_FLAG; mask = mask & ~z; } flags &= mask; /* all insn clear the x-flag except setf or clrf. */ ccs &= ~mask; ccs |= flags; return ccs; } uint32_t helper_evaluate_flags_muls(uint32_t ccs, uint32_t res, uint32_t mof) { uint32_t flags = 0; int64_t tmp; int dneg; dneg = ((int32_t)res) < 0; tmp = mof; tmp <<= 32; tmp |= res; if (tmp == 0) flags |= Z_FLAG; else if (tmp < 0) flags |= N_FLAG; if ((dneg && mof != -1) || (!dneg && mof != 0)) flags |= V_FLAG; return evaluate_flags_writeback(flags, ccs); } uint32_t helper_evaluate_flags_mulu(uint32_t ccs, uint32_t res, uint32_t mof) { uint32_t flags = 0; uint64_t tmp; tmp = mof; tmp <<= 32; tmp |= res; if (tmp == 0) flags |= Z_FLAG; else if (tmp >> 63) flags |= N_FLAG; if (mof) flags |= V_FLAG; return evaluate_flags_writeback(flags, ccs); } uint32_t helper_evaluate_flags_mcp(uint32_t ccs, uint32_t src, uint32_t dst, uint32_t res) { uint32_t flags = 0; src = src & 0x80000000; dst = dst & 0x80000000; if ((res & 0x80000000L) != 0L) { flags |= N_FLAG; if (!src && !dst) flags |= V_FLAG; else if (src & dst) flags |= R_FLAG; } else { if (res == 0L) flags |= Z_FLAG; if (src & dst) flags |= V_FLAG; if (dst | src) flags |= R_FLAG; } return evaluate_flags_writeback(flags, ccs); } uint32_t helper_evaluate_flags_alu_4(uint32_t ccs, uint32_t src, uint32_t dst, uint32_t res) { uint32_t flags = 0; src = src & 0x80000000; dst = dst & 0x80000000; if ((res & 0x80000000L) != 0L) { flags |= N_FLAG; if (!src && !dst) flags |= V_FLAG; else if (src & dst) flags |= C_FLAG; } else { if (res == 0L) flags |= Z_FLAG; if (src & dst) flags |= V_FLAG; if (dst | src) flags |= C_FLAG; } return evaluate_flags_writeback(flags, ccs); } uint32_t helper_evaluate_flags_sub_4(uint32_t ccs, uint32_t src, uint32_t dst, uint32_t res) { uint32_t flags = 0; src = (~src) & 0x80000000; dst = dst & 0x80000000; if ((res & 0x80000000L) != 0L) { flags |= N_FLAG; if (!src && !dst) flags |= V_FLAG; else if (src & dst) flags |= C_FLAG; } else { if (res == 0L) flags |= Z_FLAG; if (src & dst) flags |= V_FLAG; if (dst | src) flags |= C_FLAG; } flags ^= C_FLAG; return evaluate_flags_writeback(flags, ccs); } uint32_t helper_evaluate_flags_move_4(uint32_t ccs, uint32_t res) { uint32_t flags = 0; if ((int32_t)res < 0) flags |= N_FLAG; else if (res == 0L) flags |= Z_FLAG; return evaluate_flags_writeback(flags, ccs); } uint32_t helper_evaluate_flags_move_2(uint32_t ccs, uint32_t res) { uint32_t flags = 0; if ((int16_t)res < 0L) flags |= N_FLAG; else if (res == 0) flags |= Z_FLAG; return evaluate_flags_writeback(flags, ccs); } /* TODO: This is expensive. We could split things up and only evaluate part of CCR on a need to know basis. For now, we simply re-evaluate everything. */ void helper_evaluate_flags(void) { uint32_t src, dst, res; uint32_t flags = 0; src = env->cc_src; dst = env->cc_dest; res = env->cc_result; if (env->cc_op == CC_OP_SUB || env->cc_op == CC_OP_CMP) src = ~src; /* Now, evaluate the flags. This stuff is based on Per Zander's CRISv10 simulator. */ switch (env->cc_size) { case 1: if ((res & 0x80L) != 0L) { flags |= N_FLAG; if (((src & 0x80L) == 0L) && ((dst & 0x80L) == 0L)) { flags |= V_FLAG; } else if (((src & 0x80L) != 0L) && ((dst & 0x80L) != 0L)) { flags |= C_FLAG; } } else { if ((res & 0xFFL) == 0L) { flags |= Z_FLAG; } if (((src & 0x80L) != 0L) && ((dst & 0x80L) != 0L)) { flags |= V_FLAG; } if ((dst & 0x80L) != 0L || (src & 0x80L) != 0L) { flags |= C_FLAG; } } break; case 2: if ((res & 0x8000L) != 0L) { flags |= N_FLAG; if (((src & 0x8000L) == 0L) && ((dst & 0x8000L) == 0L)) { flags |= V_FLAG; } else if (((src & 0x8000L) != 0L) && ((dst & 0x8000L) != 0L)) { flags |= C_FLAG; } } else { if ((res & 0xFFFFL) == 0L) { flags |= Z_FLAG; } if (((src & 0x8000L) != 0L) && ((dst & 0x8000L) != 0L)) { flags |= V_FLAG; } if ((dst & 0x8000L) != 0L || (src & 0x8000L) != 0L) { flags |= C_FLAG; } } break; case 4: if ((res & 0x80000000L) != 0L) { flags |= N_FLAG; if (((src & 0x80000000L) == 0L) && ((dst & 0x80000000L) == 0L)) { flags |= V_FLAG; } else if (((src & 0x80000000L) != 0L) && ((dst & 0x80000000L) != 0L)) { flags |= C_FLAG; } } else { if (res == 0L) flags |= Z_FLAG; if (((src & 0x80000000L) != 0L) && ((dst & 0x80000000L) != 0L)) flags |= V_FLAG; if ((dst & 0x80000000L) != 0L || (src & 0x80000000L) != 0L) flags |= C_FLAG; } break; default: break; } if (env->cc_op == CC_OP_SUB || env->cc_op == CC_OP_CMP) flags ^= C_FLAG; env->pregs[PR_CCS] = evaluate_flags_writeback(flags, env->pregs[PR_CCS]); } void helper_top_evaluate_flags(void) { switch (env->cc_op) { case CC_OP_MCP: env->pregs[PR_CCS] = helper_evaluate_flags_mcp( env->pregs[PR_CCS], env->cc_src, env->cc_dest, env->cc_result); break; case CC_OP_MULS: env->pregs[PR_CCS] = helper_evaluate_flags_muls( env->pregs[PR_CCS], env->cc_result, env->pregs[PR_MOF]); break; case CC_OP_MULU: env->pregs[PR_CCS] = helper_evaluate_flags_mulu( env->pregs[PR_CCS], env->cc_result, env->pregs[PR_MOF]); break; case CC_OP_MOVE: case CC_OP_AND: case CC_OP_OR: case CC_OP_XOR: case CC_OP_ASR: case CC_OP_LSR: case CC_OP_LSL: switch (env->cc_size) { case 4: env->pregs[PR_CCS] = helper_evaluate_flags_move_4( env->pregs[PR_CCS], env->cc_result); break; case 2: env->pregs[PR_CCS] = helper_evaluate_flags_move_2( env->pregs[PR_CCS], env->cc_result); break; default: helper_evaluate_flags(); break; } break; case CC_OP_FLAGS: /* live. */ break; case CC_OP_SUB: case CC_OP_CMP: if (env->cc_size == 4) env->pregs[PR_CCS] = helper_evaluate_flags_sub_4( env->pregs[PR_CCS], env->cc_src, env->cc_dest, env->cc_result); else helper_evaluate_flags(); break; default: { switch (env->cc_size) { case 4: env->pregs[PR_CCS] = helper_evaluate_flags_alu_4( env->pregs[PR_CCS], env->cc_src, env->cc_dest, env->cc_result); break; default: helper_evaluate_flags(); break; } } break; } }
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.jeecms.cms.entity.assist"> <class name="CmsGuestbookExt" table="jc_guestbook_ext"> <meta attribute="sync-DAO">false</meta> <cache usage="read-write"/> <id name="id" type="java.lang.Integer" column="guestbook_id"> <generator class="foreign"><param name="property">guestbook</param></generator> </id> <property name="title" column="title" type="string" not-null="false" length="255"/> <property name="content" column="content" type="string" not-null="false"/> <property name="reply" column="reply" type="string" not-null="false"/> <property name="email" column="email" type="string" not-null="false" length="100"/> <property name="phone" column="phone" type="string" not-null="false" length="100"/> <property name="qq" column="qq" type="string" not-null="false" length="50"/> <one-to-one name="guestbook" class="CmsGuestbook" constrained="true"/> </class> </hibernate-mapping>
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- import six from bson import ObjectId from easydict import EasyDict as edict from tornado.concurrent import return_future from motorengine import ASCENDING from motorengine.query_builder.transform import update class BaseAggregation(object): def __init__(self, field, alias): self._field = field self.alias = alias @property def field(self): return self._field class PipelineOperation(object): def __init__(self, aggregation): self.aggregation = aggregation def to_query(self): return {} class GroupBy(PipelineOperation): def __init__(self, aggregation, first_group_by, *groups): super(GroupBy, self).__init__(aggregation) self.first_group_by = first_group_by self.groups = groups def to_query(self): group_obj = {'$group': {'_id': {}}} for group in self.groups: if isinstance(group, BaseAggregation): group_obj['$group'].update(group.to_query(self.aggregation)) continue if isinstance(group, six.string_types): field_name = group else: field_name = self.aggregation.get_field(group).db_field if self.first_group_by: group_obj['$group']['_id'][field_name] = "$%s" % field_name else: group_obj['$group']['_id'][field_name] = "$_id.%s" % field_name return group_obj class Match(PipelineOperation): def __init__(self, aggregation, **filters): super(Match, self).__init__(aggregation) self.filters = filters def to_query(self): from motorengine import Q match_obj = {'$match': {}} query = self.aggregation.queryset.get_query_from_filters(Q(**self.filters)) update(match_obj['$match'], query) return match_obj class Unwind(PipelineOperation): def __init__(self, aggregation, field): super(Unwind, self).__init__(aggregation) self.field = self.aggregation.get_field(field) def to_query(self): return {'$unwind': '$%s' % self.field.db_field} class OrderBy(PipelineOperation): def __init__(self, aggregation, field, direction): super(OrderBy, self).__init__(aggregation) self.field = self.aggregation.get_field(field) self.direction = direction def to_query(self): return {'$sort': {self.field.db_field: self.direction}} class Aggregation(object): def __init__(self, queryset): self.first_group_by = True self.queryset = queryset self.pipeline = [] self.ids = [] self.raw_query = None def get_field_name(self, field): if isinstance(field, six.string_types): return field return field.db_field def get_field(self, field): return field def raw(self, steps): self.raw_query = steps return self def group_by(self, *args): self.pipeline.append(GroupBy(self, self.first_group_by, *args)) self.first_group_by = False return self def match(self, **kw): self.pipeline.append(Match(self, **kw)) return self def unwind(self, field): self.pipeline.append(Unwind(self, field)) return self def order_by(self, field, direction=ASCENDING): self.pipeline.append(OrderBy(self, field, direction)) return self def fill_ids(self, item): if not '_id' in item: return if isinstance(item['_id'], (dict,)): for id_name, id_value in list(item['_id'].items()): item[id_name] = id_value def get_instance(self, item): return self.queryset.__klass__.from_son(item) def handle_aggregation(self, callback): def handle(*arguments, **kw): if arguments[1]: raise RuntimeError('Aggregation failed due to: %s' % str(arguments[1])) results = [] for item in arguments[0]: self.fill_ids(item) results.append(edict(item)) callback(results) return handle @return_future def fetch(self, callback=None, alias=None): coll = self.queryset.coll(alias) coll.aggregate(self.to_query()).to_list(None, callback=self.handle_aggregation(callback)) @classmethod def avg(cls, field, alias=None): from motorengine.aggregation.avg import AverageAggregation return AverageAggregation(field, alias) @classmethod def sum(cls, field, alias=None): from motorengine.aggregation.sum import SumAggregation return SumAggregation(field, alias) def to_query(self): if self.raw_query is not None: return self.raw_query query = [] for pipeline_step in self.pipeline: query_steps = pipeline_step.to_query() if isinstance(query_steps, (tuple, set, list)): for step in query_steps: query.append(step) else: query.append(query_steps) return query
{ "pile_set_name": "Github" }
<div class="subblock"> <h3><%= t('.owner_tools') %></h3> <div> <%= link_to t('.force_update'), act_content_path(action_name: 'manual_refresh'), method: :put, class: "btn info" %> <%= link_to t('.purge_children'), act_content_path(action_name: 'delete_children'), method: :put, class: "btn info" %> </div> </div>
{ "pile_set_name": "Github" }
package org.intellij.markdown.parser.sequentialparsers.impl import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.sequentialparsers.LocalParsingResult import org.intellij.markdown.parser.sequentialparsers.RangesListBuilder import org.intellij.markdown.parser.sequentialparsers.SequentialParser import org.intellij.markdown.parser.sequentialparsers.TokensCache class ReferenceLinkParser : SequentialParser { override fun parse(tokens: TokensCache, rangesToGlue: List<IntRange>): SequentialParser.ParsingResult { var result = SequentialParser.ParsingResultBuilder() val delegateIndices = RangesListBuilder() var iterator: TokensCache.Iterator = tokens.RangesListIterator(rangesToGlue) while (iterator.type != null) { if (iterator.type == MarkdownTokenTypes.LBRACKET) { val referenceLink = parseReferenceLink(iterator) if (referenceLink != null) { iterator = referenceLink.iteratorPosition.advance() result = result.withOtherParsingResult(referenceLink) continue } } delegateIndices.put(iterator.index) iterator = iterator.advance() } return result.withFurtherProcessing(delegateIndices.get()) } companion object { fun parseReferenceLink(iterator: TokensCache.Iterator): LocalParsingResult? { return parseFullReferenceLink(iterator) ?: parseShortReferenceLink(iterator) } private fun parseFullReferenceLink(iterator: TokensCache.Iterator): LocalParsingResult? { val startIndex = iterator.index val linkText = LinkParserUtil.parseLinkText(iterator) ?: return null var it = linkText.iteratorPosition.advance() if (it.type == MarkdownTokenTypes.EOL) { it = it.advance() } val linkLabel = LinkParserUtil.parseLinkLabel(it) ?: return null it = linkLabel.iteratorPosition return LocalParsingResult(it, linkText.parsedNodes + linkLabel.parsedNodes + SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.FULL_REFERENCE_LINK), linkText.rangesToProcessFurther + linkLabel.rangesToProcessFurther) } private fun parseShortReferenceLink(iterator: TokensCache.Iterator): LocalParsingResult? { val startIndex = iterator.index val linkLabel = LinkParserUtil.parseLinkLabel(iterator) ?: return null var it = linkLabel.iteratorPosition val shortcutLinkEnd = it it = it.advance() if (it.type == MarkdownTokenTypes.EOL) { it = it.advance() } if (it.type == MarkdownTokenTypes.LBRACKET && it.rawLookup(1) == MarkdownTokenTypes.RBRACKET) { it = it.advance() } else { it = shortcutLinkEnd } return LocalParsingResult(it, linkLabel.parsedNodes + SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.SHORT_REFERENCE_LINK), linkLabel.rangesToProcessFurther) } } }
{ "pile_set_name": "Github" }
var mkdirp = require('../'); var path = require('path'); var fs = require('fs'); var test = require('tap').test; test('root', function (t) { // '/' on unix, 'c:/' on windows. var file = path.resolve('/'); mkdirp(file, 0755, function (err) { if (err) throw err fs.stat(file, function (er, stat) { if (er) throw er t.ok(stat.isDirectory(), 'target is a directory'); t.end(); }) }); });
{ "pile_set_name": "Github" }
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="#FF000000" android:pathData="M20,6h-8l-2,-2L4,4c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,8c0,-1.1 -0.9,-2 -2,-2zM17.94,17L15,15.28 12.06,17l0.78,-3.33 -2.59,-2.24 3.41,-0.29L15,8l1.34,3.14 3.41,0.29 -2.59,2.24 0.78,3.33z"/> </vector>
{ "pile_set_name": "Github" }
<#-- /** * Copyright 2000-present Liferay, 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. */ --> <#assign aui = PortletJspTagLibs["/META-INF/liferay-aui.tld"] /> <#assign liferay_portlet = PortletJspTagLibs["/META-INF/liferay-portlet-ext.tld"] /> <#assign liferay_security = PortletJspTagLibs["/META-INF/liferay-security.tld"] /> <#assign liferay_theme = PortletJspTagLibs["/META-INF/liferay-theme.tld"] /> <#assign liferay_ui = PortletJspTagLibs["/META-INF/liferay-ui.tld"] /> <#assign liferay_util = PortletJspTagLibs["/META-INF/liferay-util.tld"] /> <#assign portlet = PortletJspTagLibs["/META-INF/liferay-portlet.tld"] /> <@liferay_theme["defineObjects"] /> <@portlet["defineObjects"] />
{ "pile_set_name": "Github" }
#ifndef PARDENSEMATRIX_H #define PARDENSEMATRIX_H #include "MatrixDef.h" #include "DenseMatrix.h" #include "DenseVector.h" #include "MPI_Wrappers.h" #include "ATC_Error.h" using ATC::ATC_Error; #include <algorithm> #include <sstream> namespace ATC_matrix { /** * @class ParDenseMatrix * @brief Parallelized version of DenseMatrix class. */ template <typename T> class ParDenseMatrix : public DenseMatrix<T> { public: MPI_Comm _comm; ParDenseMatrix(MPI_Comm comm, INDEX rows=0, INDEX cols=0, bool z=1) : DenseMatrix<T>(rows, cols, z), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const DenseMatrix<T>& c) : DenseMatrix<T>(c), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const SparseMatrix<T>& c) : DenseMatrix<T>(c), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const Matrix<T>& c) : DenseMatrix<T>(c), _comm(comm) {} ////////////////////////////////////////////////////////////////////////////// //* performs a matrix-vector multiply void ParMultMv(const Vector<T> &v, DenseVector<T> &c, const bool At, T a, T b) { // We can't generically support parallel multiplication because the data // types must be specified when using MPI MultMv(*this, v, c, At, a, b); } }; template<> class ParDenseMatrix<double> : public DenseMatrix<double> { public: MPI_Comm _comm; ParDenseMatrix(MPI_Comm comm, INDEX rows=0, INDEX cols=0, bool z=1) : DenseMatrix<double>(rows, cols, z), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const DenseMatrix<double>& c) : DenseMatrix<double>(c), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const SparseMatrix<double>& c) : DenseMatrix<double>(c), _comm(comm) {} ParDenseMatrix(MPI_Comm comm, const Matrix<double>& c) : DenseMatrix<double>(c), _comm(comm) {} void ParMultMv(const Vector<double> &v, DenseVector<double> &c, const bool At, double a, double b) const { // We don't support parallel vec-Mat multiplication yet if (At) { MultMv(*this, v, c, At, a, b); return; } const INDEX nRows = this->nRows(); const INDEX nCols = this->nCols(); if (c.size() != nRows) { c.resize(nRows); // set size of C c.zero(); // do not add result to C } else c *= b; // Determine how many rows will be handled on each processor int nProcs = MPI_Wrappers::size(_comm); int myRank = MPI_Wrappers::rank(_comm); int *majorCounts = new int[nProcs]; int *offsets = new int[nProcs]; #ifdef COL_STORAGE // Column-major storage int nMajor = nCols; int nMinor = nRows; int ParDenseMatrix::*majorField = &ParDenseMatrix::_nCols; int ParDenseMatrix::*minorField = &ParDenseMatrix::_nRows; #else // Row-major storage int nMajor = nRows; int nMinor = nCols; int ParDenseMatrix::*majorField = &ParDenseMatrix::_nRows; int ParDenseMatrix::*minorField = &ParDenseMatrix::_nCols; #endif for (int i = 0; i < nProcs; i++) { // If we have an uneven row-or-col/processors number, or too few rows // or cols, some processors will need to receive fewer rows/cols. offsets[i] = (i * nMajor) / nProcs; majorCounts[i] = (((i + 1) * nMajor) / nProcs) - offsets[i]; } int myNMajor = majorCounts[myRank]; int myMajorOffset = offsets[myRank]; // Take data from an offset version of A ParDenseMatrix<double> A_local(_comm); A_local._data = this->_data + myMajorOffset * nMinor; A_local.*majorField = myNMajor; A_local.*minorField = nMinor; #ifdef COL_STORAGE // Column-major storage // When splitting by columns, we split the vector as well, and sum the // results. DenseVector<double> v_local(myNMajor); for (int i = 0; i < myNMajor; i++) v_local(i) = v(myMajorOffset + i); // Store results in a local vector DenseVector<double> c_local = A_local * v_local; // Sum all vectors onto each processor MPI_Wrappers::allsum(_comm, c_local.ptr(), c.ptr(), c_local.size()); #else // Row-major storage // When splitting by rows, we use the whole vector and concatenate the // results. // Store results in a small local vector DenseVector<double> c_local(myNMajor); for (int i = 0; i < myNMajor; i++) c_local(i) = c(myMajorOffset + i); MultMv(A_local, v, c_local, At, a, b); // Gather the results onto each processor allgatherv(_comm, c_local.ptr(), c_local.size(), c.ptr(), majorCounts, offsets); #endif // Clear out the local matrix's pointer so we don't double-free A_local._data = nullptr; delete [] majorCounts; delete [] offsets; } }; // Operator for dense Matrix - dense vector product template<typename T> DenseVector<T> operator*(const ParDenseMatrix<T> &A, const Vector<T> &b) { DenseVector<T> c; A.ParMultMv(b, c, 0, 1.0, 0.0); return c; } } // end namespace #endif
{ "pile_set_name": "Github" }
# Application to the Class of 2020🎓 This pull request template helps you complete an application to the **Class of 2020**. Use the checklist below to verify you have followed the instructions correctly. ## Checklist ✅ - [ ] I have read the instructions on the README file before submitting my application. - [ ] I made my submission by creating a folder on the `_data` folder and followed the naming convention mentioned in the instructions (`<username>`), added my profile picture and markdown file. - [ ] I have used the Markdown file template to add my information to the Year Book. - [ ] I understand that a reviewer will merge my pull request after examining it or ask for changes in case needed. - [ ] I understand I should not tag or add a reviewer to this Pull Request. - [ ] I understand the photo added to the template will be used in the ceremony "Graduate Walk". - [ ] I have [added the event](http://www.google.com/calendar/event?action=TEMPLATE&dates=20200615T160000Z%2F20200615T183000Z&text=%24%20git%20remote%20%3Cgraduation%3E%20%F0%9F%8E%93&location=https%3A%2F%2Fwww.twitch.tv%2Fgithubeducation&details=) to my Calendar.
{ "pile_set_name": "Github" }
// Copyright (C) 2014 Yasuhiro Matsumoto <[email protected]>. // Copyright (C) 2018 G.J.R. Timmer <[email protected]>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build sqlite_secure_delete_fast package sqlite3 /* #cgo CFLAGS: -DSQLITE_SECURE_DELETE=FAST #cgo LDFLAGS: -lm */ import "C"
{ "pile_set_name": "Github" }
// +build acceptance package k8s import ( "fmt" "testing" "github.com/kyma-project/kyma/tests/console-backend-service/internal/domain/shared/auth" "github.com/kyma-project/kyma/tests/console-backend-service/internal/graphql" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type selfSubjectRulesQueryResponse struct { SelfSubjectRules []*selfSubjectRule `json:"selfSubjectRules"` } type selfSubjectRule struct { Verbs []string `json:"verbs"` APIGroups []string `json:"apiGroups"` Resources []string `json:"resources"` } func TestSelfSubjectRules(t *testing.T) { c, err := graphql.New() require.NoError(t, err) t.Log("Querying for SelfSubjectRules...") var selfSubjectRulesRes selfSubjectRulesQueryResponse err = c.Do(fixSelfSubjectRulesQuery(), &selfSubjectRulesRes) require.NoError(t, err) assert.True(t, len(selfSubjectRulesRes.SelfSubjectRules) > 0) err = c.Do(fixNamespacedSelfSubjectRulesQuery("foo"), &selfSubjectRulesRes) require.NoError(t, err) assert.True(t, len(selfSubjectRulesRes.SelfSubjectRules) > 0) t.Log("Checking authorization directives...") ops := &auth.OperationsInput{ auth.CreateSelfSubjectRulesReview: {fixSelfSubjectRulesQuery(), fixNamespacedSelfSubjectRulesQuery("foo")}, } AuthSuite.Run(t, ops) } func fixSelfSubjectRulesQuery() *graphql.Request { query := fmt.Sprintf( `query { selfSubjectRules { verbs resources apiGroups } }`) return graphql.NewRequest(query) } func fixNamespacedSelfSubjectRulesQuery(namespace string) *graphql.Request { query := fmt.Sprintf( `query ($namespace: String){ selfSubjectRules (namespace: $namespace){ verbs resources apiGroups } }`) req := graphql.NewRequest(query) req.SetVar("namespace", namespace) return req }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from .common import *
{ "pile_set_name": "Github" }
sizeof_1_ = 8; aggr _1_ { 'U' 0 lo; 'U' 4 hi; }; defn _1_(addr) { complex _1_ addr; print(" lo ", addr.lo, "\n"); print(" hi ", addr.hi, "\n"); }; sizeofFPdbleword = 8; aggr FPdbleword { 'F' 0 x; { 'U' 0 lo; 'U' 4 hi; }; }; defn FPdbleword(addr) { complex FPdbleword addr; print(" x ", addr.x, "\n"); print("_1_ {\n"); _1_(addr+0); print("}\n"); }; UTFmax = 3; Runesync = 128; Runeself = 128; Runeerror = 128; sizeofFmt = 48; aggr Fmt { 'b' 0 runes; 'X' 4 start; 'X' 8 to; 'X' 12 stop; 'X' 16 flush; 'X' 20 farg; 'D' 24 nfmt; 'X' 28 args; 'D' 32 r; 'D' 36 width; 'D' 40 prec; 'U' 44 flags; }; defn Fmt(addr) { complex Fmt addr; print(" runes ", addr.runes, "\n"); print(" start ", addr.start\X, "\n"); print(" to ", addr.to\X, "\n"); print(" stop ", addr.stop\X, "\n"); print(" flush ", addr.flush\X, "\n"); print(" farg ", addr.farg\X, "\n"); print(" nfmt ", addr.nfmt, "\n"); print(" args ", addr.args\X, "\n"); print(" r ", addr.r, "\n"); print(" width ", addr.width, "\n"); print(" prec ", addr.prec, "\n"); print(" flags ", addr.flags, "\n"); }; FmtWidth = 1; FmtLeft = 2; FmtPrec = 4; FmtSharp = 8; FmtSpace = 16; FmtSign = 32; FmtZero = 64; FmtUnsigned = 128; FmtShort = 256; FmtLong = 512; FmtVLong = 1024; FmtComma = 2048; FmtByte = 4096; FmtFlag = 8192; sizeofTm = 40; aggr Tm { 'D' 0 sec; 'D' 4 min; 'D' 8 hour; 'D' 12 mday; 'D' 16 mon; 'D' 20 year; 'D' 24 wday; 'D' 28 yday; 'a' 32 zone; 'D' 36 tzoff; }; defn Tm(addr) { complex Tm addr; print(" sec ", addr.sec, "\n"); print(" min ", addr.min, "\n"); print(" hour ", addr.hour, "\n"); print(" mday ", addr.mday, "\n"); print(" mon ", addr.mon, "\n"); print(" year ", addr.year, "\n"); print(" wday ", addr.wday, "\n"); print(" yday ", addr.yday, "\n"); print(" zone ", addr.zone, "\n"); print(" tzoff ", addr.tzoff, "\n"); }; PNPROC = 1; PNGROUP = 2; sizeofLock = 4; aggr Lock { 'D' 0 val; }; defn Lock(addr) { complex Lock addr; print(" val ", addr.val, "\n"); }; sizeofQLp = 12; aggr QLp { 'D' 0 inuse; 'A' QLp 4 next; 'C' 8 state; }; defn QLp(addr) { complex QLp addr; print(" inuse ", addr.inuse, "\n"); print(" next ", addr.next\X, "\n"); print(" state ", addr.state, "\n"); }; sizeofQLock = 16; aggr QLock { Lock 0 lock; 'D' 4 locked; 'A' QLp 8 $head; 'A' QLp 12 $tail; }; defn QLock(addr) { complex QLock addr; print("Lock lock {\n"); Lock(addr.lock); print("}\n"); print(" locked ", addr.locked, "\n"); print(" $head ", addr.$head\X, "\n"); print(" $tail ", addr.$tail\X, "\n"); }; sizeofRWLock = 20; aggr RWLock { Lock 0 lock; 'D' 4 readers; 'D' 8 writer; 'A' QLp 12 $head; 'A' QLp 16 $tail; }; defn RWLock(addr) { complex RWLock addr; print("Lock lock {\n"); Lock(addr.lock); print("}\n"); print(" readers ", addr.readers, "\n"); print(" writer ", addr.writer, "\n"); print(" $head ", addr.$head\X, "\n"); print(" $tail ", addr.$tail\X, "\n"); }; sizeofRendez = 12; aggr Rendez { 'A' QLock 0 l; 'A' QLp 4 $head; 'A' QLp 8 $tail; }; defn Rendez(addr) { complex Rendez addr; print(" l ", addr.l\X, "\n"); print(" $head ", addr.$head\X, "\n"); print(" $tail ", addr.$tail\X, "\n"); }; sizeofNetConnInfo = 28; aggr NetConnInfo { 'X' 0 dir; 'X' 4 root; 'X' 8 spec; 'X' 12 lsys; 'X' 16 lserv; 'X' 20 rsys; 'X' 24 rserv; }; defn NetConnInfo(addr) { complex NetConnInfo addr; print(" dir ", addr.dir\X, "\n"); print(" root ", addr.root\X, "\n"); print(" spec ", addr.spec\X, "\n"); print(" lsys ", addr.lsys\X, "\n"); print(" lserv ", addr.lserv\X, "\n"); print(" rsys ", addr.rsys\X, "\n"); print(" rserv ", addr.rserv\X, "\n"); }; RFNAMEG = 1; RFENVG = 2; RFFDG = 4; RFNOTEG = 8; RFPROC = 16; RFMEM = 32; RFNOWAIT = 64; RFCNAMEG = 1024; RFCENVG = 2048; RFCFDG = 4096; RFREND = 8192; RFNOMNT = 16384; sizeofQid = 16; aggr Qid { 'W' 0 path; 'U' 8 vers; 'b' 12 type; }; defn Qid(addr) { complex Qid addr; print(" path ", addr.path, "\n"); print(" vers ", addr.vers, "\n"); print(" type ", addr.type, "\n"); }; sizeofDir = 60; aggr Dir { 'u' 0 type; 'U' 4 dev; Qid 8 qid; 'U' 24 mode; 'U' 28 atime; 'U' 32 mtime; 'V' 36 length; 'X' 44 name; 'X' 48 uid; 'X' 52 gid; 'X' 56 muid; }; defn Dir(addr) { complex Dir addr; print(" type ", addr.type, "\n"); print(" dev ", addr.dev, "\n"); print("Qid qid {\n"); Qid(addr.qid); print("}\n"); print(" mode ", addr.mode, "\n"); print(" atime ", addr.atime, "\n"); print(" mtime ", addr.mtime, "\n"); print(" length ", addr.length, "\n"); print(" name ", addr.name\X, "\n"); print(" uid ", addr.uid\X, "\n"); print(" gid ", addr.gid\X, "\n"); print(" muid ", addr.muid\X, "\n"); }; sizeofWaitmsg = 20; aggr Waitmsg { 'D' 0 pid; 'a' 4 time; 'X' 16 msg; }; defn Waitmsg(addr) { complex Waitmsg addr; print(" pid ", addr.pid, "\n"); print(" time ", addr.time, "\n"); print(" msg ", addr.msg\X, "\n"); }; sizeofIOchunk = 8; aggr IOchunk { 'X' 0 addr; 'U' 4 len; }; defn IOchunk(addr) { complex IOchunk addr; print(" addr ", addr.addr\X, "\n"); print(" len ", addr.len, "\n"); }; MaxFragSize = 9216; VtScoreSize = 20; VtMaxStringSize = 1024; VtMaxFileSize = 281474976710655; VtMaxLumpSize = 57344; VtPointerDepth = 7; VtDataType = 0; VtDirType = 8; VtRootType = 16; VtMaxType = 17; VtTypeDepthMask = 7; VtEntryActive = 1; VtEntryDir = 2; VtEntryDepthShift = 2; VtEntryDepthMask = 28; VtEntryLocal = 32; VtEntrySize = 40; sizeofVtEntry = 40; aggr VtEntry { 'U' 0 gen; 'u' 4 psize; 'u' 6 dsize; 'b' 8 type; 'b' 9 flags; 'W' 12 size; 'a' 20 score; }; defn VtEntry(addr) { complex VtEntry addr; print(" gen ", addr.gen, "\n"); print(" psize ", addr.psize, "\n"); print(" dsize ", addr.dsize, "\n"); print(" type ", addr.type, "\n"); print(" flags ", addr.flags, "\n"); print(" size ", addr.size, "\n"); print(" score ", addr.score, "\n"); }; sizeofVtRoot = 300; aggr VtRoot { 'a' 0 name; 'a' 128 type; 'a' 256 score; 'u' 276 blocksize; 'a' 278 prev; }; defn VtRoot(addr) { complex VtRoot addr; print(" name ", addr.name, "\n"); print(" type ", addr.type, "\n"); print(" score ", addr.score, "\n"); print(" blocksize ", addr.blocksize, "\n"); print(" prev ", addr.prev, "\n"); }; VtRootSize = 300; VtRootVersion = 2; VtCryptoStrengthNone = 0; VtCryptoStrengthAuth = 1; VtCryptoStrengthWeak = 2; VtCryptoStrengthStrong = 3; VtCryptoNone = 0; VtCryptoSSL3 = 1; VtCryptoTLS1 = 2; VtCryptoMax = 3; VtCodecNone = 0; VtCodecDeflate = 1; VtCodecThwack = 2; VtCodecMax = 3; VtRerror = 1; VtTping = 2; VtRping = 3; VtThello = 4; VtRhello = 5; VtTgoodbye = 6; VtRgoodbye = 7; VtTauth0 = 8; VtRauth0 = 9; VtTauth1 = 10; VtRauth1 = 11; VtTread = 12; VtRread = 13; VtTwrite = 14; VtRwrite = 15; VtTsync = 16; VtRsync = 17; VtTmax = 18; sizeofVtFcall = 80; aggr VtFcall { 'b' 0 type; 'b' 1 tag; 'X' 4 error; 'X' 8 version; 'X' 12 uid; 'b' 16 strength; 'X' 20 crypto; 'U' 24 ncrypto; 'X' 28 codec; 'U' 32 ncodec; 'X' 36 sid; 'b' 40 rcrypto; 'b' 41 rcodec; 'X' 44 auth; 'U' 48 nauth; 'a' 52 score; 'b' 72 dtype; 'u' 74 count; 'X' 76 data; }; defn VtFcall(addr) { complex VtFcall addr; print(" type ", addr.type, "\n"); print(" tag ", addr.tag, "\n"); print(" error ", addr.error\X, "\n"); print(" version ", addr.version\X, "\n"); print(" uid ", addr.uid\X, "\n"); print(" strength ", addr.strength, "\n"); print(" crypto ", addr.crypto\X, "\n"); print(" ncrypto ", addr.ncrypto, "\n"); print(" codec ", addr.codec\X, "\n"); print(" ncodec ", addr.ncodec, "\n"); print(" sid ", addr.sid\X, "\n"); print(" rcrypto ", addr.rcrypto, "\n"); print(" rcodec ", addr.rcodec, "\n"); print(" auth ", addr.auth\X, "\n"); print(" nauth ", addr.nauth, "\n"); print(" score ", addr.score, "\n"); print(" dtype ", addr.dtype, "\n"); print(" count ", addr.count, "\n"); print(" data ", addr.data\X, "\n"); }; VtStateAlloc = 0; VtStateConnected = 1; VtStateClosed = 2; sizeofVtConn = 1148; aggr VtConn { QLock 0 lk; QLock 16 inlk; QLock 32 outlk; 'D' 48 debug; 'D' 52 infd; 'D' 56 outfd; 'D' 60 muxer; 'X' 64 writeq; 'X' 68 readq; 'D' 72 state; 'a' 76 wait; 'U' 1100 ntag; 'U' 1104 nsleep; 'X' 1108 part; Rendez 1112 tagrend; Rendez 1124 rpcfork; 'X' 1136 version; 'X' 1140 uid; 'X' 1144 sid; }; defn VtConn(addr) { complex VtConn addr; print("QLock lk {\n"); QLock(addr.lk); print("}\n"); print("QLock inlk {\n"); QLock(addr.inlk); print("}\n"); print("QLock outlk {\n"); QLock(addr.outlk); print("}\n"); print(" debug ", addr.debug, "\n"); print(" infd ", addr.infd, "\n"); print(" outfd ", addr.outfd, "\n"); print(" muxer ", addr.muxer, "\n"); print(" writeq ", addr.writeq\X, "\n"); print(" readq ", addr.readq\X, "\n"); print(" state ", addr.state, "\n"); print(" wait ", addr.wait, "\n"); print(" ntag ", addr.ntag, "\n"); print(" nsleep ", addr.nsleep, "\n"); print(" part ", addr.part\X, "\n"); print("Rendez tagrend {\n"); Rendez(addr.tagrend); print("}\n"); print("Rendez rpcfork {\n"); Rendez(addr.rpcfork); print("}\n"); print(" version ", addr.version\X, "\n"); print(" uid ", addr.uid\X, "\n"); print(" sid ", addr.sid\X, "\n"); }; NilBlock = -1; sizeofVtBlock = 88; aggr VtBlock { 'X' 0 c; QLock 4 lk; 'X' 20 data; 'a' 24 score; 'b' 44 type; 'D' 48 nlock; 'D' 52 iostate; 'D' 56 ref; 'U' 60 heap; 'A' VtBlock 64 next; 'A' VtBlock 68 prev; 'U' 72 used; 'U' 76 used2; 'U' 80 addr; 'D' 84 decrypted; }; defn VtBlock(addr) { complex VtBlock addr; print(" c ", addr.c\X, "\n"); print("QLock lk {\n"); QLock(addr.lk); print("}\n"); print(" data ", addr.data\X, "\n"); print(" score ", addr.score, "\n"); print(" type ", addr.type, "\n"); print(" nlock ", addr.nlock, "\n"); print(" iostate ", addr.iostate, "\n"); print(" ref ", addr.ref, "\n"); print(" heap ", addr.heap, "\n"); print(" next ", addr.next\X, "\n"); print(" prev ", addr.prev\X, "\n"); print(" used ", addr.used, "\n"); print(" used2 ", addr.used2, "\n"); print(" addr ", addr.addr, "\n"); print(" decrypted ", addr.decrypted, "\n"); }; VtOREAD = 0; VtOWRITE = 1; VtORDWR = 2; VtOCREATE = 256; BioLocal = 1; BioVenti = 2; BioReading = 3; BioWriting = 4; BioEmpty = 5; BioVentiError = 6; BadHeap = -1; sizeofVtCache = 60; aggr VtCache { QLock 0 lk; 'A' VtConn 16 z; 'U' 20 blocksize; 'U' 24 now; 'A' VtBlock 28 hash; 'D' 32 nhash; 'A' VtBlock 36 heap; 'D' 40 nheap; 'A' VtBlock 44 block; 'D' 48 nblock; 'X' 52 mem; 'D' 56 mode; }; defn VtCache(addr) { complex VtCache addr; print("QLock lk {\n"); QLock(addr.lk); print("}\n"); print(" z ", addr.z\X, "\n"); print(" blocksize ", addr.blocksize, "\n"); print(" now ", addr.now, "\n"); print(" hash ", addr.hash\X, "\n"); print(" nhash ", addr.nhash, "\n"); print(" heap ", addr.heap\X, "\n"); print(" nheap ", addr.nheap, "\n"); print(" block ", addr.block\X, "\n"); print(" nblock ", addr.nblock, "\n"); print(" mem ", addr.mem\X, "\n"); print(" mode ", addr.mode, "\n"); }; complex VtConn vtcachealloc:z; complex VtCache vtcachealloc:c; complex VtBlock vtcachealloc:b; complex VtCache vtcachefree:c; complex VtCache vtcachedump:c; complex VtBlock vtcachedump:b; complex VtCache cachecheck:c; complex VtBlock cachecheck:b; complex VtBlock upheap:b; complex VtBlock upheap:bb; complex VtCache upheap:c; complex VtBlock downheap:b; complex VtBlock downheap:bb; complex VtCache downheap:c; complex VtBlock heapdel:b; complex VtCache heapdel:c; complex VtBlock heapins:b; complex VtCache vtcachebumpblock:c; complex VtBlock vtcachebumpblock:b; complex VtCache vtcachelocal:c; complex VtBlock vtcachelocal:b; complex VtCache vtcacheallocblock:c; complex VtBlock vtcacheallocblock:b; complex VtCache vtcacheglobal:c; complex VtBlock vtcacheglobal:b; complex VtBlock vtblockduplock:b; complex VtBlock vtblockput:b; complex VtCache vtblockput:c; complex VtBlock vtblockwrite:b; complex VtCache vtblockwrite:c; complex VtCache vtcacheblocksize:c; complex VtBlock vtblockcopy:b; complex VtBlock vtblockcopy:bb;
{ "pile_set_name": "Github" }
@using System.Globalization @using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Extensions @using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Helpers @using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Models @using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Helpers @using GlobalResources @model Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Models.DeviceDetailModel @{ DateTime? resolvedDate; var tags = Model.DevicePropertyValueModels.Where(m => m.Name.StartsWith("tags.") && !m.Name.IsReservedTwinName()); var desiredProperties = Model.DevicePropertyValueModels.Where(m => m.Name.StartsWith("properties.desired.") && !m.Name.IsReservedTwinName()); var reportedProperties = Model.DevicePropertyValueModels.Where(m => m.Name.StartsWith("properties.reported.") && !m.Name.IsReservedTwinName()); var deviceProperties = Model.DevicePropertyValueModels.Except(tags).Except(desiredProperties).Except(reportedProperties).Where(m => !m.Name.IsReservedTwinName()); var utcNow = DateTime.UtcNow; } <div class="header_grid header_grid_general"> <h3 class="grid_subheadhead_detail grid_subheadhead">@Strings.DeviceTwin</h3> <img src="~/Content/img/icon_info_gray.svg" class="details_grid_info" title="@Strings.DeviceTwinHeader" /> @Html.ActionLink(@Strings.DownloadTwinJson, "DownloadTwinJson", "Device", new { deviceId = Model.DeviceID }, new { id = "download_link", @class = "link_grid_subheadhead_detail", @style = "margin-top: 1ch;" }) </div> <hr class="details_grid_twin_begin_line" /> <div class="header_grid_left_space"> <div class="header_grid header_grid_general"> <img id="tagClose" src="~/Content/img/expanded.svg" class="details_grid_info pull-left cursor_pointer tag_toggle_target tag_toggle_source" /> <img id="tagOpen" src="~/Content/img/collapsed.svg" class="details_grid_info pull-left cursor_pointer display_none tag_toggle_target tag_toggle_source" /> <h3 class="grid_subheadhead_detail_collapsable cursor_pointer tag_toggle_source">@Strings.Tags</h3> @if (Model.IsDeviceEditEnabled) { @Html.ActionLink(@Strings.Edit, "EditTags", "Device", new { deviceId = Model.DeviceID }, new { id = "edit_tags_link", @class = "link_grid_subheadhead_detail", }) } </div> <section class="details_grid_general tag_toggle_target" id="tagsGrid"> @if (tags.Any()) { foreach (var val in tags) { <h4 class="grid_subhead_detail_label">@val.Name.Substring(5)</h4> if (val.PropertyType == PropertyType.DateTime && (resolvedDate = DynamicValuesHelper.ConvertToDateTime(CultureInfo.InvariantCulture, val.Value)).HasValue) { <p class="grid_detail_value" name="[email protected]">@resolvedDate.Value.ToString()</p> } else { <p class="grid_detail_value" name="[email protected]">@val.Value</p> } } } else { <p class="grid_detail_value">@Strings.NoTags</p> } </section> <div class="header_grid header_grid_general"> <img id="desiredPropertyClose" src="~/Content/img/expanded.svg" class="details_grid_info pull-left cursor_pointer desiredproperty_toggle_target desiredproperty_toggle_source" /> <img id="desiredPropertyOpen" src="~/Content/img/collapsed.svg" class="details_grid_info pull-left cursor_pointer display_none desiredproperty_toggle_target desiredproperty_toggle_source" /> <h3 class="grid_subheadhead_detail_collapsable cursor_pointer desiredproperty_toggle_source">@Strings.DesiredProperties</h3> @if (Model.IsDeviceEditEnabled) { @Html.ActionLink(@Strings.Edit, "EditDesiredProperties", "Device", new { deviceId = Model.DeviceID }, new { id = "edit_desiredProperties_link", @class = "link_grid_subheadhead_detail", }) } </div> <section class="details_grid_general desiredproperty_toggle_target" id="desiredPropertiesGrid"> @if (desiredProperties.Any()) { foreach (var val in desiredProperties) { <h4 class="grid_subhead_detail_label">@val.Name.Substring(19)</h4> <div> <p class="grid_detail_value" name="[email protected]"> @if (val.PropertyType == PropertyType.DateTime && (resolvedDate = DynamicValuesHelper.ConvertToDateTime(CultureInfo.InvariantCulture, val.Value)).HasValue) { @resolvedDate.Value.ToString() } else { @val.Value } <span class="grid_detail_lastUpdated pull-right" name="[email protected]">@TimeSpanExtension.ToFloorShortString(utcNow - val.LastUpdatedUtc, Strings.LastUpdatedFormatString)</span> </p> </div> } } else { <p class="grid_detail_value">@Strings.NoDesiredProperties</p> } </section> @if (reportedProperties.Any()) { <div class="header_grid header_grid_general"> <img id="reportedPropertyClose" src="~/Content/img/expanded.svg" class="details_grid_info pull-left cursor_pointer reportedproperty_toggle_target reportedproperty_toggle_source" /> <img id="reportedPropertyOpen" src="~/Content/img/collapsed.svg" class="details_grid_info pull-left cursor_pointer display_none reportedproperty_toggle_target reportedproperty_toggle_source" /> <h3 class="grid_subheadhead_detail_collapsable cursor_pointer reportedproperty_toggle_source">@Strings.ReportedProperties</h3> </div> <section class="details_grid_general reportedproperty_toggle_target" id="reportedPropertiesGrid"> @foreach (var val in reportedProperties) { <h4 class="grid_subhead_detail_label">@val.Name.Substring(20)</h4> <div> <p class="grid_detail_value" name="[email protected]"> @if (val.PropertyType == PropertyType.DateTime && (resolvedDate = DynamicValuesHelper.ConvertToDateTime(CultureInfo.InvariantCulture, val.Value)).HasValue) { @resolvedDate.Value.ToString() } else { @val.Value } <span class="grid_detail_lastUpdated pull-right" name="[email protected]">@TimeSpanExtension.ToFloorShortString(utcNow - val.LastUpdatedUtc, Strings.LastUpdatedFormatString)</span> </p> </div> } </section> } </div> <hr class="details_grid_twin_end_line" /> <div class="grid_subheadhead_left_space"> <div class="header_grid header_grid_general"> <img id="deviceDetailsClose" src="~/Content/img/expanded.svg" class="details_grid_info cursor_pointer devicedetails_toggle_target devicedetails_toggle_source" /> <img id="deviceDetailsOpen" src="~/Content/img/collapsed.svg" class="details_grid_info cursor_pointer display_none devicedetails_toggle_target devicedetails_toggle_source" /> <h3 class="grid_subheadhead cursor_pointer devicedetails_toggle_source">@Strings.DeviceProperties</h3> </div> <section class="details_grid_general devicedetails_toggle_target" id="deviceDetailsGrid"> @foreach (var propVal in deviceProperties) { <h4 class="grid_subhead_detail_label">@DeviceDisplayHelper.GetDevicePropertyFieldLocalName(propVal.Name)</h4> if (DeviceDisplayHelper.GetIsCopyControlPropertyName(propVal.Name)) { string classname = "text_copy_container__input--details_grid"; string class_styles_modifier = "text_copy_container--details_grid"; string button_style_modifier = "details_grid_general__copy_button"; @IoTHelpers.TextCopy(propVal.Name, classname, propVal.Value, class_styles_modifier, button_style_modifier); } else { if ((propVal.PropertyType == PropertyType.DateTime) && (resolvedDate = DynamicValuesHelper.ConvertToDateTime(CultureInfo.InvariantCulture, propVal.Value)).HasValue) { <p class="grid_detail_value" name="[email protected]">@resolvedDate.Value.ToString()</p> } else { <p class="grid_detail_value" name="[email protected]">@propVal.Value</p> } } } @if (Model.HasKeyViewingPerm) { <p class="grid_detail_value"> <a href="#" id="deviceExplorer_authKeys" class="not_disable">@Strings.ViewAuthenticationKeys</a> </p> } </section> <div class="header_grid header_grid_general"> <img id="jobClose" src="~/Content/img/expanded.svg" class="details_grid_info cursor_pointer job_toggle_target job_toggle_source" /> <img id="jobOpen" src="~/Content/img/collapsed.svg" class="details_grid_info cursor_pointer display_none job_toggle_target job_toggle_source" /> <h3 class="grid_subheadhead cursor_pointer job_toggle_source">@Strings.RecentJobs</h3> </div> <section class="details_grid_general job_toggle_target" id="deviceJobGrid"> <div id="deviceJobLoadingElement" class="loader_container_panel"> <div class="loader_container__loader loader_container__loader--large_top_margin" /> </div> </section> </div> <script type="text/javascript"> (function () { 'use strict'; IoTApp.DeviceDetails.loadDeviceJobs("@Model.DeviceID"); })(); </script>
{ "pile_set_name": "Github" }
package org.spigotmc; /** * FINDME * * @author Hexeption [email protected] * @since 11/11/2019 - 08:06 am */ public interface FINDME { }
{ "pile_set_name": "Github" }
[Unit] Description=Network Connectivity Wants=network.target Before=network.target [Service] Type=oneshot RemainAfterExit=yes # lo is brought up earlier, which will cause the upcoming "ifup -a" to fail # with exit code 1, due to an "ip: RTNETLINK answers: File exists" error during # its "ip addr add ..." command, subsequently causing this unit to fail even # though it is a benign error. Flushing the lo address with the command below # before ifup prevents this failure. ExecStart=/sbin/ip addr flush dev lo ExecStart=/sbin/ifup -a ExecStop=/sbin/ifdown -a [Install] WantedBy=multi-user.target
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (11.0.3) on Sun Mar 29 22:42:10 IST 2020 --> <title>Uses of Class com.googlecode.cqengine.quantizer.BigDecimalQuantizer (CQEngine 3.5.0 API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2020-03-29"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../../jquery/jquery-3.3.1.js"></script> <script type="text/javascript" src="../../../../../jquery/jquery-migrate-3.0.1.js"></script> <script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.googlecode.cqengine.quantizer.BigDecimalQuantizer (CQEngine 3.5.0 API)"; } } catch(err) { } //--> var pathtoroot = "../../../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../BigDecimalQuantizer.html" title="class in com.googlecode.cqengine.quantizer">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <main role="main"> <div class="header"> <h2 title="Uses of Class com.googlecode.cqengine.quantizer.BigDecimalQuantizer" class="title">Uses of Class<br>com.googlecode.cqengine.quantizer.BigDecimalQuantizer</h2> </div> <div class="classUseContainer">No usage of com.googlecode.cqengine.quantizer.BigDecimalQuantizer</div> </main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../BigDecimalQuantizer.html" title="class in com.googlecode.cqengine.quantizer">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small>Copyright &#169; 2020. All rights reserved.</small></p> </footer> </body> </html>
{ "pile_set_name": "Github" }
<section class="notice-previous"> <div class="container text-center"> <a href="http://select2.github.io/select2/">Looking for the Select2 3.5.2 docs?</a> We have moved them to a new location <a href="announcements-4.0.html">while we push forward with Select2 4.0</a>. </div> </section>
{ "pile_set_name": "Github" }
within Buildings.Electrical.DC.Storage; model Battery "Simple model of a battery" parameter Modelica.SIunits.Efficiency etaCha(max=1) = 0.9 "Efficiency during charging"; parameter Modelica.SIunits.Efficiency etaDis(max=1) = 0.9 "Efficiency during discharging"; parameter Real SOC_start(min=0, max=1, unit="1")=0.1 "Initial state of charge"; parameter Modelica.SIunits.Energy EMax(min=0, displayUnit="kWh") "Maximum available charge"; parameter Modelica.SIunits.Voltage V_nominal "Nominal voltage (V_nominal >= 0)"; Modelica.Blocks.Interfaces.RealInput P(unit="W") "Power stored in battery (if positive), or extracted from battery (if negative)" annotation (Placement(transformation(extent={{-20,-20},{20,20}}, rotation=270, origin={0,108}), iconTransformation(extent={{-20,-20},{20,20}}, rotation=270, origin={0,100}))); Modelica.Blocks.Interfaces.RealOutput SOC(min=0, max=1, unit="1") "State of charge" annotation (Placement(transformation(extent={{100,50},{120,70}}))); Buildings.Electrical.DC.Interfaces.Terminal_p terminal "Generalized terminal" annotation (Placement(transformation(extent={{-110,-10},{-90,10}}))); protected Buildings.Electrical.DC.Storage.BaseClasses.Charge cha( final EMax=EMax, final SOC_start=SOC_start, final etaCha=etaCha, final etaDis=etaDis) "Charge model" annotation (Placement(transformation(extent={{40,50},{60,70}}))); Loads.Conductor bat( final mode=Buildings.Electrical.Types.Load.VariableZ_P_input, final V_nominal=V_nominal) "Power exchanged with battery pack" annotation (Placement(transformation(extent={{40,-10},{60,10}}))); Modelica.Blocks.Math.Gain gain(final k=-1) annotation (Placement(transformation(extent={{22,10},{42,30}}))); equation connect(cha.SOC, SOC) annotation (Line( points={{61,60},{110,60}}, color={0,0,127}, smooth=Smooth.None)); connect(cha.P, P) annotation (Line( points={{38,60},{0,60},{0,108},{8.88178e-16,108}}, color={0,0,127}, smooth=Smooth.None)); connect(bat.terminal, terminal) annotation (Line( points={{40,0},{-100,0}}, color={0,0,255}, smooth=Smooth.None)); connect(P, gain.u) annotation (Line( points={{8.88178e-16,108},{8.88178e-16,20},{20,20}}, color={0,0,127}, smooth=Smooth.None)); connect(gain.y, bat.Pow) annotation (Line( points={{43,20},{68,20},{68,8.88178e-16},{60,8.88178e-16}}, color={0,0,127}, smooth=Smooth.None)); annotation ( Icon(coordinateSystem( preserveAspectRatio=false, extent={{-100,-100},{100,100}}), graphics={ Polygon( points={{-62,40},{-62,-40},{72,-40},{72,40},{-62,40}}, smooth=Smooth.None, fillColor={215,215,215}, fillPattern=FillPattern.Solid, pattern=LinePattern.None, lineColor={0,0,0}), Polygon( points={{58,32},{58,-30},{32,-30},{10,32},{58,32}}, smooth=Smooth.None, pattern=LinePattern.None, lineColor={0,0,0}, fillColor={0,127,0}, fillPattern=FillPattern.Solid), Polygon( points={{-34,32},{-12,-30},{-32,-30},{-54,32},{-34,32}}, smooth=Smooth.None, pattern=LinePattern.None, lineColor={0,0,0}, fillColor={0,127,0}, fillPattern=FillPattern.Solid), Polygon( points={{-2,32},{20,-30},{0,-30},{-22,32},{-2,32}}, smooth=Smooth.None, pattern=LinePattern.None, lineColor={0,0,0}, fillColor={0,127,0}, fillPattern=FillPattern.Solid), Polygon( points={{-74,12},{-74,-12},{-62,-12},{-62,12},{-74,12}}, smooth=Smooth.None, fillColor={215,215,215}, fillPattern=FillPattern.Solid, pattern=LinePattern.None, lineColor={0,0,0}), Text( extent={{-50,68},{-20,100}}, lineColor={0,0,0}, fillColor={215,215,215}, fillPattern=FillPattern.Solid, textString="P"), Line( points={{-74,0},{-100,0},{-100,0}}, color={0,0,0}, smooth=Smooth.None), Text( extent={{-150,70},{-50,20}}, lineColor={0,0,0}, textString="+"), Text( extent={{-150,-12},{-50,-62}}, lineColor={0,0,0}, textString="-"), Text( extent={{44,70},{100,116}}, lineColor={0,0,0}, fillColor={215,215,215}, fillPattern=FillPattern.Solid, textString="SOC"), Text( extent={{44,154},{134,112}}, lineColor={0,0,255}, textString="%name")}), Documentation(info="<html> <p> Simple model of a battery. </p> <p> This model takes as an input the power that should be stored in the battery (if <i>P &gt; 0</i>) or that should be extracted from the battery. The model uses a fictitious conductance (see <a href=\"modelica://Buildings.Electrical.DC.Loads.Conductor\">Buildings.Electrical.DC.Loads.Conductor</a>) <i>G</i> such that <i>P = u &nbsp; i</i> and <i>i = u &nbsp; G,</i> where <i>u</i> is the voltage difference across the pins and <i>i</i> is the current at the positive pin. </p> <p> The output connector <code>SOC</code> is the state of charge of the battery. This model does not enforce that the state of charge is between zero and one. However, each time the state of charge crosses zero or one, a warning will be written to the simulation log file. The model also does not limit the current through the battery. The user should provide a control so that only a reasonable amount of power is exchanged, and that the state of charge remains between zero and one. </p> </html>", revisions="<html> <ul> <li> September 24, 2015 by Michael Wetter:<br/> Removed binding of <code>P_nominal</code> as this parameter is disabled and assigned a value in the <code>initial equation</code> section. This is for <a href=\"https://github.com/lbl-srg/modelica-buildings/issues/426\">issue 426</a>. </li> <li> March 19, 2015, by Michael Wetter:<br/> Removed redeclaration of phase system in <code>Terminal_n</code> and <code>Terminal_p</code> as it is already declared to the be the same phase system, and it is not declared to be replaceable. This avoids a translation error in OpenModelica. </li> <li> June 2, 2014, by Marco Bonvini:<br/> Revised documentation. </li> <li> January 8, 2013, by Michael Wetter:<br/> First implementation. </li> </ul> </html>")); end Battery;
{ "pile_set_name": "Github" }