text
stringlengths
2
100k
meta
dict
/** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = { moduleType: 'locale', name: 'ar', dictionary: {}, format: { days: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], shortDays: [ 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت' ], months: [ 'كانون الثاني', 'شباط', 'آذار', 'نيسان', 'آذار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول' ], shortMonths: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], date: '%d/%m/%Y' } };
{ "pile_set_name": "Github" }
/* Copyright (c) 2019-2019, David Anderson 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> /* for printf */ #include <stdlib.h> #include <string.h> #include "dwarfstring.h" #ifndef TRUE #define TRUE 1 #endif /* TRUE */ #ifndef FALSE #define FALSE 0 #endif /* FALSE */ static int errcount; static void check_string(const char *msg,char *exp, char *actual,int line) { if(!strcmp(exp,actual)) { return; } printf("FAIL %s expected \"%s\" got \"%s\" test line %d\n", msg,exp,actual,line); ++errcount; } static void check_value(const char *msg,unsigned long exp, unsigned long actual,int line) { if(exp == actual) { return; } printf("FAIL %s expected %lu got %lu test line %d\n", msg,exp,actual,line); ++errcount; } static int test1(int tnum) { struct dwarfstring_s g; char *d = 0; const char *expstr = ""; int res = 0; unsigned long biglen = 0; char *bigstr = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "ccccccbbbbbbbbbbbbbbbbbbbbbccc" "ccccccbbbbbbbbbbbbbbbbbbbbbccc" "ccccccbbbbbbbbbbbbbbbbbbbbbccc" "ccccccbbbbbyyyybbbbbbbbbbbbccc"; dwarfstring_constructor(&g); d = dwarfstring_string(&g); check_string("expected empty string",(char *)expstr,d,__LINE__); res = dwarfstring_append(&g,"abc"); check_value("expected TRUE ",TRUE,res,__LINE__); d = dwarfstring_string(&g); check_string("expected abc ",(char *)"abc",d,__LINE__); res = dwarfstring_append(&g,"xy"); check_value("expected TRUE ",TRUE,res,__LINE__); d = dwarfstring_string(&g); check_string("expected abcxy ",(char *)"abcxy",d,__LINE__); dwarfstring_destructor(&g); dwarfstring_constructor(&g); res = dwarfstring_append(&g,bigstr); check_value("expected TRUE ",TRUE,res,__LINE__); d = dwarfstring_string(&g); check_string("expected bigstring ",bigstr,d,__LINE__); biglen = dwarfstring_strlen(&g); check_value("expected 120 ",strlen(bigstr),biglen,__LINE__); dwarfstring_append_length(&g,"xxyyzz",3); biglen = dwarfstring_strlen(&g); check_value("expected 123 ",strlen(bigstr)+3,biglen,__LINE__); dwarfstring_destructor(&g); return 0; } static int test2(int tnum) { struct dwarfstring_s g; char *d = 0; const char *expstr = ""; int res = 0; unsigned long biglen = 0; char *bigstr = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "ccccccbbbbbbbbbbbbbbbbbbbbbccc" "ccccccbbbbbbbbbbbbbbbbbbbbbccc" "ccccccbbbbbbbbbbbbbbbbbbbbbccc" "ccccccbbbbbyyyybbbbbbbbbbbbccc"; dwarfstring_constructor_fixed(&g,10); d = dwarfstring_string(&g); check_string("expected empty string",(char *)expstr,d,__LINE__); res = dwarfstring_append(&g,"abc"); check_value("expected TRUE ",TRUE,res,__LINE__); d = dwarfstring_string(&g); check_string("expected abc ",(char *)"abc",d,__LINE__); res = dwarfstring_append(&g,"xy"); check_value("expected TRUE ",TRUE,res,__LINE__); d = dwarfstring_string(&g); check_string("expected abcxy ",(char *)"abcxy",d,__LINE__); dwarfstring_destructor(&g); dwarfstring_constructor_fixed(&g,3); res = dwarfstring_append(&g,bigstr); check_value("expected TRUE ",TRUE,res,__LINE__); d = dwarfstring_string(&g); check_string("expected bigstring ",bigstr,d,__LINE__); biglen = dwarfstring_strlen(&g); check_value("expected 120 ",strlen(bigstr),biglen,__LINE__); dwarfstring_destructor(&g); return 0; } static int test3(int tnum) { struct dwarfstring_s g; char *d = 0; const char *expstr = ""; int res = 0; unsigned long biglen = 0; char *bigstr = "a012345"; char *targetbigstr = "a012345xy"; dwarfstring_constructor_fixed(&g,10); d = dwarfstring_string(&g); check_string("expected empty string",(char *)expstr,d,__LINE__); res = dwarfstring_append(&g,bigstr); check_value("expected TRUE ",TRUE,res,__LINE__); d = dwarfstring_string(&g); check_string("expected a012345 ",(char *)bigstr,d,__LINE__); res = dwarfstring_append_length(&g,"xyzzz",2); check_value("expected TRUE ",TRUE,res,__LINE__); check_value("expected 9 ", 9,(unsigned)dwarfstring_strlen(&g), __LINE__); d = dwarfstring_string(&g); check_string("expected a012345xy ", (char *)targetbigstr,d,__LINE__); dwarfstring_destructor(&g); return 0; } static int test4(int tnum) { struct dwarfstring_s g; char *d = 0; const char *expstr = ""; int res = 0; unsigned long biglen = 0; char *mystr = "a01234"; char *targetmystr = "a01234xyz"; char fixedarea[7]; dwarfstring_constructor_static(&g,fixedarea,sizeof(fixedarea)); d = dwarfstring_string(&g); check_string("expected empty string",(char *)expstr,d,__LINE__); res = dwarfstring_append(&g,mystr); check_value("expected TRUE ",TRUE,res,__LINE__); d = dwarfstring_string(&g); check_string("expected a01234 ",(char *)mystr,d,__LINE__); if (d != fixedarea) { printf(" FAIL reallocated but should not line %d ", __LINE__); ++errcount; } res = dwarfstring_append(&g,"xyz"); d = dwarfstring_string(&g); check_string("expected a01234xyz ",(char *)targetmystr, d,__LINE__); check_value("expected 9",9,dwarfstring_strlen(&g),__LINE__); if (d == fixedarea) { printf(" FAIL not reallocated but should be! line %d ", __LINE__); ++errcount; } dwarfstring_destructor(&g); return 0; } static int test5(int tnum) { struct dwarfstring_s g; char *d = 0; const char *expstr = ""; int res = 0; unsigned long biglen = 0x654a; signed long lminus= -55; char *mystr = "a01234"; char *targetmystr = "a01234xyz"; dwarfstring_constructor(&g); dwarfstring_append_printf_s(&g,"initialstring-%s-finalstring", mystr); d = dwarfstring_string(&g); expstr = "initialstring-a01234-finalstring"; check_string("from pct-s",(char *)expstr,d,__LINE__); dwarfstring_destructor(&g); dwarfstring_constructor(&g); dwarfstring_append_printf_u(&g,"initialstring--0x%x-finalstring", biglen); d = dwarfstring_string(&g); expstr = "initialstring--0x654a-finalstring"; check_string("from pct-s",(char *)expstr,d,__LINE__); dwarfstring_destructor(&g); dwarfstring_constructor(&g); dwarfstring_append_printf_i(&g,"initialstring: %d (", lminus); dwarfstring_append_printf_u(&g,"0x%08x) -finalstring", lminus); d = dwarfstring_string(&g); expstr = "initialstring: -55 (0xffffffffffffffc9) -finalstring"; check_string("from pct-s",(char *)expstr,d,__LINE__); dwarfstring_destructor(&g); dwarfstring_constructor(&g); dwarfstring_append_printf_u(&g,"smallhex (0x%08x) -finalstring", biglen); d = dwarfstring_string(&g); expstr = "smallhex (0x0000654a) -finalstring"; check_string("from pct-s",(char *)expstr,d,__LINE__); dwarfstring_destructor(&g); dwarfstring_constructor(&g); dwarfstring_append_printf_u(&g,"longlead (%08u) -end", 20); d = dwarfstring_string(&g); expstr = "longlead (00000020) -end"; check_string("from pct-s",(char *)expstr,d,__LINE__); dwarfstring_destructor(&g); return 0; return 0; } int main() { test1(1); test2(2); test3(3); test4(3); test5(3); if (errcount) { exit(1); } exit(0); }
{ "pile_set_name": "Github" }
"use strict" var bomHandling = require('./bom-handling'), iconv = module.exports; // All codecs and aliases are kept here, keyed by encoding name/alias. // They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. iconv.encodings = null; // Characters emitted in case of error. iconv.defaultCharUnicode = '�'; iconv.defaultCharSingleByte = '?'; // Public API. iconv.encode = function encode(str, encoding, options) { str = "" + (str || ""); // Ensure string. var encoder = iconv.getEncoder(encoding, options); var res = encoder.write(str); var trail = encoder.end(); return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; } iconv.decode = function decode(buf, encoding, options) { if (typeof buf === 'string') { if (!iconv.skipDecodeWarning) { console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); iconv.skipDecodeWarning = true; } buf = new Buffer("" + (buf || ""), "binary"); // Ensure buffer. } var decoder = iconv.getDecoder(encoding, options); var res = decoder.write(buf); var trail = decoder.end(); return trail ? (res + trail) : res; } iconv.encodingExists = function encodingExists(enc) { try { iconv.getCodec(enc); return true; } catch (e) { return false; } } // Legacy aliases to convert functions iconv.toEncoding = iconv.encode; iconv.fromEncoding = iconv.decode; // Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. iconv._codecDataCache = {}; iconv.getCodec = function getCodec(encoding) { if (!iconv.encodings) iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. var enc = (''+encoding).toLowerCase().replace(/[^0-9a-z]|:\d{4}$/g, ""); // Traverse iconv.encodings to find actual codec. var codecOptions = {}; while (true) { var codec = iconv._codecDataCache[enc]; if (codec) return codec; var codecDef = iconv.encodings[enc]; switch (typeof codecDef) { case "string": // Direct alias to other encoding. enc = codecDef; break; case "object": // Alias with options. Can be layered. for (var key in codecDef) codecOptions[key] = codecDef[key]; if (!codecOptions.encodingName) codecOptions.encodingName = enc; enc = codecDef.type; break; case "function": // Codec itself. if (!codecOptions.encodingName) codecOptions.encodingName = enc; // The codec function must load all tables and return object with .encoder and .decoder methods. // It'll be called only once (for each different options object). codec = new codecDef(codecOptions, iconv); iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. return codec; default: throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); } } } iconv.getEncoder = function getEncoder(encoding, options) { var codec = iconv.getCodec(encoding), encoder = new codec.encoder(options, codec); if (codec.bomAware && options && options.addBOM) encoder = new bomHandling.PrependBOM(encoder, options); return encoder; } iconv.getDecoder = function getDecoder(encoding, options) { var codec = iconv.getCodec(encoding), decoder = new codec.decoder(options, codec); if (codec.bomAware && !(options && options.stripBOM === false)) decoder = new bomHandling.StripBOM(decoder, options); return decoder; } // Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; if (nodeVer) { // Load streaming support in Node v0.10+ var nodeVerArr = nodeVer.split(".").map(Number); if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { require("./streams")(iconv); } // Load Node primitive extensions. require("./extend-node")(iconv); }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello World! &mdash; REGoth documentation</title> <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <script src="../_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="../index.html" class="icon icon-home"> REGoth </a> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <p class="caption"><span class="caption-text">Contents:</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="extending-docs.html">Extending the Documentation</a></li> <li class="toctree-l1"><a class="reference internal" href="setting-up-app.html">Setting up a Test-Application</a></li> <li class="toctree-l1"><a class="reference internal" href="world.html">World</a></li> <li class="toctree-l1"><a class="reference internal" href="waynet.html">Waynet</a></li> <li class="toctree-l1"><a class="reference internal" href="characters.html">Characters</a></li> <li class="toctree-l1"><a class="reference internal" href="create-component.html">Creating a new Component</a></li> <li class="toctree-l1"><a class="reference internal" href="case-study-object-kinds.html">Case-Study: Kinds of Objects in Gothic</a></li> <li class="toctree-l1"><a class="reference internal" href="case-study-scene-structure.html">Case-Study: Scene Structure</a></li> <li class="toctree-l1"><a class="reference internal" href="case-study-character-statemachine.html">Case-Study: Character Statemachine</a></li> <li class="toctree-l1"><a class="reference internal" href="case-study-daedalus-vm.html">Case-Study: Daedalus VM</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../index.html">REGoth</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../index.html">Docs</a> &raquo;</li> <li>Hello World!</li> <li class="wy-breadcrumbs-aside"> <a href="../_sources/content/hello-world.rst.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="hello-world"> <h1>Hello World!<a class="headerlink" href="#hello-world" title="Permalink to this headline">¶</a></h1> </div> </div> </div> <footer> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2019, The REGoth-Team </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script type="text/javascript" src="../_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.Navigation.enable(true); }); </script> </body> </html>
{ "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. //! Data source traits use std::sync::Arc; use crate::arrow::datatypes::SchemaRef; use crate::error::Result; use crate::physical_plan::ExecutionPlan; /// Source table pub trait TableProvider { /// Get a reference to the schema for this table fn schema(&self) -> SchemaRef; /// Create an ExecutionPlan that will scan the table. fn scan( &self, projection: &Option<Vec<usize>>, batch_size: usize, ) -> Result<Arc<dyn ExecutionPlan>>; }
{ "pile_set_name": "Github" }
az: ադրբեջաներեն az_AZ: 'ադրբեջաներեն (Ադրբեջան)' az_Latn_AZ: 'ադրբեջաներեն (լատինական, Ադրբեջան)' az_Latn: 'ադրբեջաներեն (լատինական)' az_Cyrl_AZ: 'ադրբեջաներեն (կյուրեղագիր, Ադրբեջան)' az_Cyrl: 'ադրբեջաներեն (կյուրեղագիր)' sq: ալբաներեն sq_AL: 'ալբաներեն (Ալբանիա)' sq_XK: 'ալբաներեն (Կոսովո)' sq_MK: 'ալբաներեն (Մակեդոնիա)' am: ամհարերեն am_ET: 'ամհարերեն (Եթովպիա)' en: անգլերեն en_US: 'անգլերեն (Ամերիկայի Միացյալ Նահանգներ)' en_AS: 'անգլերեն (Ամերիկյան Սամոա)' en_VI: 'անգլերեն (Ամերիկյան Վիրջինյան կղզիներ)' en_AI: 'անգլերեն (Անգիլիա)' en_AG: 'անգլերեն (Անտիգուա և Բարբուդա)' en_AU: 'անգլերեն (Ավստրալիա)' en_UM: 'անգլերեն (Արտաքին կղզիներ (ԱՄՆ))' en_BS: 'անգլերեն (Բահամյան կղզիներ)' en_BB: 'անգլերեն (Բարբադոս)' en_BE: 'անգլերեն (Բելգիա)' en_BZ: 'անգլերեն (Բելիզ)' en_BM: 'անգլերեն (Բերմուդյան կղզիներ)' en_BW: 'անգլերեն (Բոտսվանա)' en_VG: 'անգլերեն (Բրիտանական Վիրջինյան կղզիներ)' en_GM: 'անգլերեն (Գամբիա)' en_GY: 'անգլերեն (Գայանա)' en_GH: 'անգլերեն (Գանա)' en_GG: 'անգլերեն (Գերնսի)' en_GU: 'անգլերեն (Գուամ)' en_GD: 'անգլերեն (Գրենադա)' en_DG: 'անգլերեն (Դիեգո Գարսիա)' en_DM: 'անգլերեն (Դոմինիկա)' en_ZM: 'անգլերեն (Զամբիա)' en_ZW: 'անգլերեն (Զիմբաբվե)' en_ER: 'անգլերեն (Էրիտրեա)' en_IE: 'անգլերեն (Իռլանդիա)' en_LS: 'անգլերեն (Լեսոտո)' en_LR: 'անգլերեն (Լիբերիա)' en_CX: 'անգլերեն (Ծննդյան կղզի)' en_CM: 'անգլերեն (Կամերուն)' en_KY: 'անգլերեն (Կայմանյան կղզիներ)' en_CA: 'անգլերեն (Կանադա)' en_KI: 'անգլերեն (Կիրիբատի)' en_CC: 'անգլերեն (Կոկոսյան (Քիլինգ) կղզիներ)' en_CK: 'անգլերեն (Կուկի կղզիներ)' en_SS: 'անգլերեն (Հարավային Սուդան)' en_ZA: 'անգլերեն (Հարավաֆրիկյան Հանրապետություն)' en_MP: 'անգլերեն (Հյուսիսային Մարիանյան կղզիներ)' en_IO: 'անգլերեն (Հնդկական Օվկիանոսում Բրիտանական Տարածք)' en_IN: 'անգլերեն (Հնդկաստան)' en_HK: 'անգլերեն (Հոնկոնգի ՀՎՇ)' en_MG: 'անգլերեն (Մադագասկար)' en_MY: 'անգլերեն (Մալայզիա)' en_MW: 'անգլերեն (Մալավի)' en_MT: 'անգլերեն (Մալթա)' en_MU: 'անգլերեն (Մավրիկիոս)' en_MH: 'անգլերեն (Մարշալյան կղզիներ)' en_IM: 'անգլերեն (Մեն կղզի)' en_GB: 'անգլերեն (Միացյալ Թագավորություն)' en_FM: 'անգլերեն (Միկրոնեզիա)' en_MS: 'անգլերեն (Մոնտսերատ)' en_NA: 'անգլերեն (Նամիբիա)' en_NR: 'անգլերեն (Նաուրու)' en_NG: 'անգլերեն (Նիգերիա)' en_NU: 'անգլերեն (Նիուե)' en_NZ: 'անգլերեն (Նոր Զելանդիա)' en_NF: 'անգլերեն (Նորֆոլկ կղզի)' en_UG: 'անգլերեն (Ուգանդա)' en_MO: 'անգլերեն (Չինաստանի Մակաո ՀՎՇ)' en_PW: 'անգլերեն (Պալաու)' en_PK: 'անգլերեն (Պակիստան)' en_PG: 'անգլերեն (Պապուա Նոր Գվինեա)' en_PN: 'անգլերեն (Պիտկեռն կղզիներ)' en_PR: 'անգլերեն (Պուերտո Ռիկո)' en_JM: 'անգլերեն (Ջամայկա)' en_JE: 'անգլերեն (Ջերսի)' en_GI: 'անգլերեն (Ջիբրալթար)' en_RW: 'անգլերեն (Ռուանդա)' en_WS: 'անգլերեն (Սամոա)' en_SC: 'անգլերեն (Սեյշելյան կղզիներ)' en_LC: 'անգլերեն (Սենթ Լյուսիա)' en_VC: 'անգլերեն (Սենթ Վիսենտ և Գրենադիններ)' en_KN: 'անգլերեն (Սենթ Քիթս և Նևիս)' en_SG: 'անգլերեն (Սինգապուր)' en_SX: 'անգլերեն (Սինտ Մարտեն)' en_SL: 'անգլերեն (Սյերա-Լեոնե)' en_SB: 'անգլերեն (Սողոմոնյան կղզիներ)' en_SD: 'անգլերեն (Սուդան)' en_SH: 'անգլերեն (Սուրբ Հեղինեի կղզի)' en_SZ: 'անգլերեն (Սվազիլենդ)' en_VU: 'անգլերեն (Վանուատու)' en_TZ: 'անգլերեն (Տանզանիա)' en_TC: 'անգլերեն (Տերկս և Կայկոս կղզիներ)' en_TK: 'անգլերեն (Տոկելաու)' en_TO: 'անգլերեն (Տոնգա)' en_TV: 'անգլերեն (Տուվալու)' en_TT: 'անգլերեն (Տրինիդադ և Տոբագո)' en_KE: 'անգլերեն (Քենիա)' en_PH: 'անգլերեն (Ֆիլիպիններ)' en_FJ: 'անգլերեն (Ֆիջի)' en_FK: 'անգլերեն (Ֆոլկլենդյան կղզիներ)' as: ասամերեն as_IN: 'ասամերեն (Հնդկաստան)' ar: արաբերեն ar_DZ: 'արաբերեն (Ալժիր)' ar_EH: 'արաբերեն (Արևմտյան Սահարա)' ar_BH: 'արաբերեն (Բահրեյն)' ar_EG: 'արաբերեն (Եգիպտոս)' ar_YE: 'արաբերեն (Եմեն)' ar_ER: 'արաբերեն (Էրիտրեա)' ar_TN: 'արաբերեն (Թունիս)' ar_IL: 'արաբերեն (Իսրայել)' ar_IQ: 'արաբերեն (Իրաք)' ar_LB: 'արաբերեն (Լիբանան)' ar_LY: 'արաբերեն (Լիբիա)' ar_QA: 'արաբերեն (Կատար)' ar_KM: 'արաբերեն (Կոմորյան կղզիներ)' ar_SS: 'արաբերեն (Հարավային Սուդան)' ar_JO: 'արաբերեն (Հորդանան)' ar_MR: 'արաբերեն (Մավրիտանիա)' ar_MA: 'արաբերեն (Մարոկո)' ar_AE: 'արաբերեն (Միացյալ Արաբական Էմիրություններ)' ar_TD: 'արաբերեն (Չադ)' ar_PS: 'արաբերեն (Պաղեստինյան տարածքներ)' ar_DJ: 'արաբերեն (Ջիբուտի)' ar_SA: 'արաբերեն (Սաուդյան Արաբիա)' ar_SY: 'արաբերեն (Սիրիա)' ar_SO: 'արաբերեն (Սոմալի)' ar_SD: 'արաբերեն (Սուդան)' ar_KW: 'արաբերեն (Քուվեյթ)' ar_OM: 'արաբերեն (Օման)' fy: 'արևմտյան ֆրիզերեն' fy_NL: 'արևմտյան ֆրիզերեն (Նիդերլանդեր)' ak: աքաներեն ak_GH: 'աքաներեն (Գանա)' af: աֆրիկաանս af_ZA: 'աֆրիկաանս (Հարավաֆրիկյան Հանրապետություն)' af_NA: 'աֆրիկաանս (Նամիբիա)' bm: բամբարա bm_Latn_ML: 'բամբարա (լատինական, Մալի)' bm_Latn: 'բամբարա (լատինական)' eu: բասկերեն eu_ES: 'բասկերեն (Իսպանիա)' be: բելառուսերեն be_BY: 'բելառուսերեն (Բելառուս)' bn: բենգալերեն bn_BD: 'բենգալերեն (Բանգլադեշ)' bn_IN: 'բենգալերեն (Հնդկաստան)' my: բիրմայերեն my_MM: 'բիրմայերեն (Մյանմա (Բիրմա))' bs: բոսնիերեն bs_BA: 'բոսնիերեն (Բոսնիա և Հերցեգովինա)' bs_Latn_BA: 'բոսնիերեն (լատինական, Բոսնիա և Հերցեգովինա)' bs_Latn: 'բոսնիերեն (լատինական)' bs_Cyrl_BA: 'բոսնիերեն (կյուրեղագիր, Բոսնիա և Հերցեգովինա)' bs_Cyrl: 'բոսնիերեն (կյուրեղագիր)' bg: բուլղարերեն bg_BG: 'բուլղարերեն (Բուլղարիա)' br: բրետոներեն br_FR: 'բրետոներեն (Ֆրանսիա)' gl: գալիսերեն gl_ES: 'գալիսերեն (Իսպանիա)' lg: գանդա lg_UG: 'գանդա (Ուգանդա)' de: գերմաներեն de_AT: 'գերմաներեն (Ավստրիա)' de_BE: 'գերմաներեն (Բելգիա)' de_DE: 'գերմաներեն (Գերմանիա)' de_LI: 'գերմաներեն (Լիխտենշտեյն)' de_LU: 'գերմաներեն (Լյուքսեմբուրգ)' de_CH: 'գերմաներեն (Շվեյցարիա)' gu: գուջարաթի gu_IN: 'գուջարաթի (Հնդկաստան)' da: դանիերեն da_GL: 'դանիերեն (Գրենլանդիա)' da_DK: 'դանիերեն (Դանիա)' he: եբրայերեն he_IL: 'եբրայերեն (Իսրայել)' zu: զուլուսերեն zu_ZA: 'զուլուսերեն (Հարավաֆրիկյան Հանրապետություն)' eo: էսպերանտո et: էստոներեն et_EE: 'էստոներեն (Էստոնիա)' ee: էվե ee_GH: 'էվե (Գանա)' ee_TG: 'էվե (Տոգո)' ta: թամիլերեն ta_IN: 'թամիլերեն (Հնդկաստան)' ta_MY: 'թամիլերեն (Մալայզիա)' ta_LK: 'թամիլերեն (Շրի Լանկա)' ta_SG: 'թամիլերեն (Սինգապուր)' th: թայերեն th_TH: 'թայերեն (Թաիլանդ)' te: թելուգու te_IN: 'թելուգու (Հնդկաստան)' ti: թիգրինիա ti_ET: 'թիգրինիա (Եթովպիա)' ti_ER: 'թիգրինիա (Էրիտրեա)' tr: թուրքերեն tr_TR: 'թուրքերեն (Թուրքիա)' tr_CY: 'թուրքերեն (Կիպրոս)' ig: իգբո ig_NG: 'իգբո (Նիգերիա)' id: ինդոնեզերեն id_ID: 'ինդոնեզերեն (Ինդոնեզիա)' ga: իռլանդերեն ga_IE: 'իռլանդերեն (Իռլանդիա)' is: իսլանդերեն is_IS: 'իսլանդերեն (Իսլանդիա)' es: իսպաներեն es_US: 'իսպաներեն (Ամերիկայի Միացյալ Նահանգներ)' es_AR: 'իսպաներեն (Արգենտինա)' es_BO: 'իսպաներեն (Բոլիվիա)' es_GT: 'իսպաներեն (Գվատեմալա)' es_DO: 'իսպաներեն (Դոմինիկյան Հանրապետություն)' es_EC: 'իսպաներեն (Էկվադոր)' es_ES: 'իսպաներեն (Իսպանիա)' es_IC: 'իսպաներեն (Կանարյան կղզիներ)' es_CO: 'իսպաներեն (Կոլումբիա)' es_CR: 'իսպաներեն (Կոստա-Ռիկա)' es_CU: 'իսպաներեն (Կուբա)' es_GQ: 'իսպաներեն (Հասարակածային Գվինեա)' es_HN: 'իսպաներեն (Հոնդուրաս)' es_MX: 'իսպաներեն (Մեքսիկա)' es_NI: 'իսպաներեն (Նիկարագուա)' es_UY: 'իսպաներեն (Ուրուգվայ)' es_CL: 'իսպաներեն (Չիլի)' es_PA: 'իսպաներեն (Պանամա)' es_PY: 'իսպաներեն (Պարագվայ)' es_PE: 'իսպաներեն (Պերու)' es_PR: 'իսպաներեն (Պուերտո Ռիկո)' es_SV: 'իսպաներեն (Սալվադոր)' es_EA: 'իսպաներեն (Սեուտա և Մելիլյա)' es_VE: 'իսպաներեն (Վենեսուելա)' es_PH: 'իսպաներեն (Ֆիլիպիններ)' it: իտալերեն it_IT: 'իտալերեն (Իտալիա)' it_CH: 'իտալերեն (Շվեյցարիա)' it_SM: 'իտալերեն (Սան Մարինո)' lo: լաոսերեն lo_LA: 'լաոսերեն (Լաոս)' lv: լատվիերեն lv_LV: 'լատվիերեն (Լատվիա)' pl: լեհերեն pl_PL: 'լեհերեն (Լեհաստան)' ln: լինգալա ln_AO: 'լինգալա (Անգոլա)' ln_CF: 'լինգալա (Կենտրոնական Աֆրիկյան Հանրապետություն)' ln_CG: 'լինգալա (Կոնգո - Բրազավիլ)' ln_CD: 'լինգալա (Կոնգո - Կինշասա)' lt: լիտվերեն lt_LT: 'լիտվերեն (Լիտվա)' lb: լյուքսեմբուրգերեն lb_LU: 'լյուքսեմբուրգերեն (Լյուքսեմբուրգ)' lu: լուբա-կատանգա lu_CD: 'լուբա-կատանգա (Կոնգո - Կինշասա)' hr: խորվաթերեն hr_BA: 'խորվաթերեն (Բոսնիա և Հերցեգովինա)' hr_HR: 'խորվաթերեն (Խորվաթիա)' kl: կալաալիսուտ kl_GL: 'կալաալիսուտ (Գրենլանդիա)' kn: կաննադա kn_IN: 'կաննադա (Հնդկաստան)' ca: կատալաներեն ca_AD: 'կատալաներեն (Անդորա)' ca_ES: 'կատալաներեն (Իսպանիա)' ca_IT: 'կատալաներեն (Իտալիա)' ca_FR: 'կատալաներեն (Ֆրանսիա)' ki: կիկույու ki_KE: 'կիկույու (Քենիա)' kw: կոռներեն kw_GB: 'կոռներեն (Միացյալ Թագավորություն)' ko: կորեերեն ko_KR: 'կորեերեն (Հարավային Կորեա)' ko_KP: 'կորեերեն (Հյուսիսային Կորեա)' hy: հայերեն hy_AM: 'հայերեն (Հայաստան)' ha: հաուսա ha_GH: 'հաուսա (Գանա)' ha_Latn_GH: 'հաուսա (լատինական, Գանա)' ha_Latn_NE: 'հաուսա (լատինական, Նիգեր)' ha_Latn_NG: 'հաուսա (լատինական, Նիգերիա)' ha_Latn: 'հաուսա (լատինական)' ha_NE: 'հաուսա (Նիգեր)' ha_NG: 'հաուսա (Նիգերիա)' hi: հինդի hi_IN: 'հինդի (Հնդկաստան)' nd: 'հյուսիսային նդեբելե' nd_ZW: 'հյուսիսային նդեբելե (Զիմբաբվե)' se: 'հյուսիսային սամի' se_NO: 'հյուսիսային սամի (Նորվեգիա)' se_SE: 'հյուսիսային սամի (Շվեդիա)' se_FI: 'հյուսիսային սամի (Ֆինլանդիա)' nl: հոլանդերեն nl_AW: 'հոլանդերեն (Արուբա)' nl_BE: 'հոլանդերեն (Բելգիա)' nl_BQ: 'հոլանդերեն (Կարիբյան Նիդերլանդներ)' nl_CW: 'հոլանդերեն (Կյուրասաո)' nl_NL: 'հոլանդերեն (Նիդերլանդեր)' nl_SX: 'հոլանդերեն (Սինտ Մարտեն)' nl_SR: 'հոլանդերեն (Սուրինամ)' el: հունարեն el_CY: 'հունարեն (Կիպրոս)' el_GR: 'հունարեն (Հունաստան)' hu: հունգարերեն hu_HU: 'հունգարերեն (Հունգարիա)' kk: ղազախերեն kk_Cyrl_KZ: 'ղազախերեն (կյուրեղագիր, Ղազախստան)' kk_Cyrl: 'ղազախերեն (կյուրեղագիր)' kk_KZ: 'ղազախերեն (Ղազախստան)' ky: ղրղզերեն ky_Cyrl_KG: 'ղրղզերեն (կյուրեղագիր, Ղրղզստան)' ky_Cyrl: 'ղրղզերեն (կյուրեղագիր)' ky_KG: 'ղրղզերեն (Ղրղզստան)' ja: ճապոներեն ja_JP: 'ճապոներեն (Ճապոնիա)' mg: մալագասերեն mg_MG: 'մալագասերեն (Մադագասկար)' ml: մալայալամ ml_IN: 'մալայալամ (Հնդկաստան)' ms: մալայերեն ms_BN: 'մալայերեն (Բրունեյ)' ms_Latn_BN: 'մալայերեն (լատինական, Բրունեյ)' ms_Latn_MY: 'մալայերեն (լատինական, Մալայզիա)' ms_Latn_SG: 'մալայերեն (լատինական, Սինգապուր)' ms_Latn: 'մալայերեն (լատինական)' ms_MY: 'մալայերեն (Մալայզիա)' ms_SG: 'մալայերեն (Սինգապուր)' mt: մալթերեն mt_MT: 'մալթերեն (Մալթա)' mk: մակեդոներեն mk_MK: 'մակեդոներեն (Մակեդոնիա)' mr: մարաթի mr_IN: 'մարաթի (Հնդկաստան)' gv: մեներեն gv_IM: 'մեներեն (Մեն կղզի)' mn: մոնղոլերեն mn_Cyrl_MN: 'մոնղոլերեն (կյուրեղագիր, Մոնղոլիա)' mn_Cyrl: 'մոնղոլերեն (կյուրեղագիր)' mn_MN: 'մոնղոլերեն (Մոնղոլիա)' yo: յորուբա yo_BJ: 'յորուբա (Բենին)' yo_NG: 'յորուբա (Նիգերիա)' ne: նեպալերեն ne_IN: 'նեպալերեն (Հնդկաստան)' ne_NP: 'նեպալերեն (Նեպալ)' nb: 'նորվեգերեն բուկմոլ' nb_NO: 'նորվեգերեն բուկմոլ (Նորվեգիա)' nb_SJ: 'նորվեգերեն բուկմոլ (Սվալբարդ և Յան-Մայեն)' nn: 'նորվեգերեն նյունորսկ' nn_NO: 'նորվեգերեն նյունորսկ (Նորվեգիա)' sn: շոնա sn_ZW: 'շոնա (Զիմբաբվե)' sv: շվեդերեն sv_AX: 'շվեդերեն (Ալանդյան կղզիներ)' sv_SE: 'շվեդերեն (Շվեդիա)' sv_FI: 'շվեդերեն (Ֆինլանդիա)' cy: ուելսերեն cy_GB: 'ուելսերեն (Միացյալ Թագավորություն)' uz: ուզբեկերեն uz_Arab_AF: 'ուզբեկերեն (արաբական, Աֆղանստան)' uz_Arab: 'ուզբեկերեն (արաբական)' uz_AF: 'ուզբեկերեն (Աֆղանստան)' uz_Latn_UZ: 'ուզբեկերեն (լատինական, Ուզբեկստան)' uz_Latn: 'ուզբեկերեն (լատինական)' uz_Cyrl_UZ: 'ուզբեկերեն (կյուրեղագիր, Ուզբեկստան)' uz_Cyrl: 'ուզբեկերեն (կյուրեղագիր)' uz_UZ: 'ուզբեկերեն (Ուզբեկստան)' uk: ուկրաիներեն uk_UA: 'ուկրաիներեն (Ուկրաինա)' ug: ույղուրերեն ug_Arab_CN: 'ույղուրերեն (արաբական, Չինաստան)' ug_Arab: 'ույղուրերեն (արաբական)' ug_CN: 'ույղուրերեն (Չինաստան)' ur: ուրդու ur_IN: 'ուրդու (Հնդկաստան)' ur_PK: 'ուրդու (Պակիստան)' cs: չեխերեն cs_CZ: 'չեխերեն (Չեխիա)' zh: չինարեն zh_Hant_TW: 'չինարեն (ավանդական չինական, Թայվան)' zh_Hant_HK: 'չինարեն (ավանդական չինական, Հոնկոնգի ՀՎՇ)' zh_Hant_MO: 'չինարեն (ավանդական չինական, Չինաստանի Մակաո ՀՎՇ)' zh_Hant: 'չինարեն (ավանդական չինական)' zh_TW: 'չինարեն (Թայվան)' zh_HK: 'չինարեն (Հոնկոնգի ՀՎՇ)' zh_CN: 'չինարեն (Չինաստան)' zh_MO: 'չինարեն (Չինաստանի Մակաո ՀՎՇ)' zh_Hans_HK: 'չինարեն (պարզեցված չինական, Հոնկոնգի ՀՎՇ)' zh_Hans_CN: 'չինարեն (պարզեցված չինական, Չինաստան)' zh_Hans_MO: 'չինարեն (պարզեցված չինական, Չինաստանի Մակաո ՀՎՇ)' zh_Hans_SG: 'չինարեն (պարզեցված չինական, Սինգապուր)' zh_Hans: 'չինարեն (պարզեցված չինական)' zh_SG: 'չինարեն (Սինգապուր)' fa: պարսկերեն fa_AF: 'պարսկերեն (Աֆղանստան)' fa_IR: 'պարսկերեն (Իրան)' pt: պորտուգալերեն pt_AO: 'պորտուգալերեն (Անգոլա)' pt_BR: 'պորտուգալերեն (Բրազիլիա)' pt_GW: 'պորտուգալերեն (Գվինեա-Բիսաու)' pt_TL: 'պորտուգալերեն (Թիմոր-Լեստե)' pt_CV: 'պորտուգալերեն (Կաբո Վերդե)' pt_MZ: 'պորտուգալերեն (Մոզամբիկ)' pt_MO: 'պորտուգալերեն (Չինաստանի Մակաո ՀՎՇ)' pt_PT: 'պորտուգալերեն (Պորտուգալիա)' pt_ST: 'պորտուգալերեն (Սան Տոմե և Պրինսիպի)' dz: ջոնգքհա dz_BT: 'ջոնգքհա (Բութան)' rm: ռոմանշերեն rm_CH: 'ռոմանշերեն (Շվեյցարիա)' ro: ռումիներեն ro_MD: 'ռումիներեն (Մոլդովա)' ro_RO: 'ռումիներեն (Ռումինիա)' rn: ռունդի rn_BI: 'ռունդի (Բուրունդի)' ru: ռուսերեն ru_BY: 'ռուսերեն (Բելառուս)' ru_KZ: 'ռուսերեն (Ղազախստան)' ru_KG: 'ռուսերեն (Ղրղզստան)' ru_MD: 'ռուսերեն (Մոլդովա)' ru_UA: 'ռուսերեն (Ուկրաինա)' ru_RU: 'ռուսերեն (Ռուսաստան)' sg: սանգո sg_CF: 'սանգո (Կենտրոնական Աֆրիկյան Հանրապետություն)' sr: սերբերեն sr_BA: 'սերբերեն (Բոսնիա և Հերցեգովինա)' sr_Latn_BA: 'սերբերեն (լատինական, Բոսնիա և Հերցեգովինա)' sr_Latn_XK: 'սերբերեն (լատինական, Կոսովո)' sr_Latn_ME: 'սերբերեն (լատինական, Չեռնոգորիա)' sr_Latn_RS: 'սերբերեն (լատինական, Սերբիա)' sr_Latn: 'սերբերեն (լատինական)' sr_Cyrl_BA: 'սերբերեն (կյուրեղագիր, Բոսնիա և Հերցեգովինա)' sr_Cyrl_XK: 'սերբերեն (կյուրեղագիր, Կոսովո)' sr_Cyrl_ME: 'սերբերեն (կյուրեղագիր, Չեռնոգորիա)' sr_Cyrl_RS: 'սերբերեն (կյուրեղագիր, Սերբիա)' sr_Cyrl: 'սերբերեն (կյուրեղագիր)' sr_XK: 'սերբերեն (Կոսովո)' sr_ME: 'սերբերեն (Չեռնոգորիա)' sr_RS: 'սերբերեն (Սերբիա)' ii: 'սիխուան յի' ii_CN: 'սիխուան յի (Չինաստան)' si: սինհալերեն si_LK: 'սինհալերեն (Շրի Լանկա)' sk: սլովակերեն sk_SK: 'սլովակերեն (Սլովակիա)' sl: սլովեներեն sl_SI: 'սլովեներեն (Սլովենիա)' so: սոմալիերեն so_ET: 'սոմալիերեն (Եթովպիա)' so_DJ: 'սոմալիերեն (Ջիբուտի)' so_SO: 'սոմալիերեն (Սոմալի)' so_KE: 'սոմալիերեն (Քենիա)' sw: սուահիլի sw_UG: 'սուահիլի (Ուգանդա)' sw_TZ: 'սուահիլի (Տանզանիա)' sw_KE: 'սուահիլի (Քենիա)' vi: վիետնամերեն vi_VN: 'վիետնամերեն (Վիետնամ)' ka: վրացերեն ka_GE: 'վրացերեն (Վրաստան)' bo: տիբեթերեն bo_IN: 'տիբեթերեն (Հնդկաստան)' bo_CN: 'տիբեթերեն (Չինաստան)' to: տոնգա to_TO: 'տոնգա (Տոնգա)' pa: փենջաբերեն pa_Arab_PK: 'փենջաբերեն (արաբական, Պակիստան)' pa_Arab: 'փենջաբերեն (արաբական)' pa_Guru_IN: 'փենջաբերեն (գուրմուխի, Հնդկաստան)' pa_Guru: 'փենջաբերեն (գուրմուխի)' pa_IN: 'փենջաբերեն (Հնդկաստան)' pa_PK: 'փենջաբերեն (Պակիստան)' ps: փուշթու ps_AF: 'փուշթու (Աֆղանստան)' ks: քաշմիրերեն ks_Arab_IN: 'քաշմիրերեն (արաբական, Հնդկաստան)' ks_Arab: 'քաշմիրերեն (արաբական)' ks_IN: 'քաշմիրերեն (Հնդկաստան)' qu: քեչուա qu_BO: 'քեչուա (Բոլիվիա)' qu_EC: 'քեչուա (Էկվադոր)' qu_PE: 'քեչուա (Պերու)' rw: քինյարվանդա rw_RW: 'քինյարվանդա (Ռուանդա)' km: քմերերեն km_KH: 'քմերերեն (Կամբոջա)' or: օրիյա or_IN: 'օրիյա (Հնդկաստան)' om: օրոմո om_ET: 'օրոմո (Եթովպիա)' om_KE: 'օրոմո (Քենիա)' fo: ֆարյորերեն fo_FO: 'ֆարյորերեն (Ֆարերյան կղզիներ)' fi: ֆիններեն fi_FI: 'ֆիններեն (Ֆինլանդիա)' fr: ֆրանսերեն fr_DZ: 'ֆրանսերեն (Ալժիր)' fr_BE: 'ֆրանսերեն (Բելգիա)' fr_BJ: 'ֆրանսերեն (Բենին)' fr_BF: 'ֆրանսերեն (Բուրկինա Ֆասո)' fr_BI: 'ֆրանսերեն (Բուրունդի)' fr_GA: 'ֆրանսերեն (Գաբոն)' fr_GP: 'ֆրանսերեն (Գվադելուպա)' fr_GN: 'ֆրանսերեն (Գվինեա)' fr_TN: 'ֆրանսերեն (Թունիս)' fr_LU: 'ֆրանսերեն (Լյուքսեմբուրգ)' fr_CM: 'ֆրանսերեն (Կամերուն)' fr_CA: 'ֆրանսերեն (Կանադա)' fr_CF: 'ֆրանսերեն (Կենտրոնական Աֆրիկյան Հանրապետություն)' fr_KM: 'ֆրանսերեն (Կոմորյան կղզիներ)' fr_CG: 'ֆրանսերեն (Կոնգո - Բրազավիլ)' fr_CD: 'ֆրանսերեն (Կոնգո - Կինշասա)' fr_HT: 'ֆրանսերեն (Հաիթի)' fr_GQ: 'ֆրանսերեն (Հասարակածային Գվինեա)' fr_MG: 'ֆրանսերեն (Մադագասկար)' fr_ML: 'ֆրանսերեն (Մալի)' fr_YT: 'ֆրանսերեն (Մայոտ)' fr_MU: 'ֆրանսերեն (Մավրիկիոս)' fr_MR: 'ֆրանսերեն (Մավրիտանիա)' fr_MA: 'ֆրանսերեն (Մարոկո)' fr_MQ: 'ֆրանսերեն (Մարտինիկա)' fr_MC: 'ֆրանսերեն (Մոնակո)' fr_NE: 'ֆրանսերեն (Նիգեր)' fr_NC: 'ֆրանսերեն (Նոր Կալեդոնիա)' fr_CH: 'ֆրանսերեն (Շվեյցարիա)' fr_WF: 'ֆրանսերեն (Ուոլիս և Ֆուտունա)' fr_TD: 'ֆրանսերեն (Չադ)' fr_DJ: 'ֆրանսերեն (Ջիբուտի)' fr_RE: 'ֆրանսերեն (Ռեյունիոն)' fr_RW: 'ֆրանսերեն (Ռուանդա)' fr_SC: 'ֆրանսերեն (Սեյշելյան կղզիներ)' fr_MF: 'ֆրանսերեն (Սեն Մարտեն)' fr_PM: 'ֆրանսերեն (Սեն Պիեր և Միկելոն)' fr_SN: 'ֆրանսերեն (Սենեգալ)' fr_SY: 'ֆրանսերեն (Սիրիա)' fr_BL: 'ֆրանսերեն (Սուրբ Բարթողոմեոսի կղզի)' fr_VU: 'ֆրանսերեն (Վանուատու)' fr_TG: 'ֆրանսերեն (Տոգո)' fr_CI: 'ֆրանսերեն (Փղոսկրի Ափ)' fr_FR: 'ֆրանսերեն (Ֆրանսիա)' fr_GF: 'ֆրանսերեն (Ֆրանսիական Գվիանա)' fr_PF: 'ֆրանսերեն (Ֆրանսիական Պոլինեզիա)' ff: Fulah ff_CM: 'Fulah (Cameroon)' ff_GN: 'Fulah (Guinea)' ff_MR: 'Fulah (Mauritania)' ff_SN: 'Fulah (Senegal)' 'no': Norwegian no_NO: 'Norwegian (Norway)' os: Ossetic os_GE: 'Ossetic (Georgia)' os_RU: 'Ossetic (Russia)' gd: 'Scottish Gaelic' gd_GB: 'Scottish Gaelic (United Kingdom)' sh: Serbo-Croatian sh_BA: 'Serbo-Croatian (Bosnia & Herzegovina)' tl: Tagalog tl_PH: 'Tagalog (Philippines)' yi: Yiddish
{ "pile_set_name": "Github" }
#!/bin/sh # Copyright (C) 2011 OpenWrt.org . /lib/functions.sh include /lib/network get_ifname() { local interface="$1" local cfgt scan_interfaces config_get cfgt "$interface" TYPE [ "$cfgt" == "interface" ] && config_get "$interface" ifname } config_cb() { config_get TYPE "$CONFIG_SECTION" TYPE [ "interface" == "$TYPE" ] && { config_get device "$CONFIG_SECTION" ifname [ -z "$device" ] && device="$(get_ifname ${CONFIG_SECTION})" config_set "$CONFIG_SECTION" device "$device" } } config_load qos print_comments() { echo '' echo '# Interface: '"$1" echo '# Direction: '"$2" echo '# Stats: '"$3" echo '' } get_device() { ( config_load network; scan_interfaces; config_get "$1" ifname ) } interface_stats() { local interface="$1" local device device="$(get_device "$interface")" [ -z "$device" ] && config_get device "$interface" device config_get_bool enabled "$interface" enabled 1 [ -z "$device" -o 1 -ne "$enabled" ] && { return 1 } config_get_bool halfduplex "$interface" halfduplex 0 if [ 1 -ne "$halfduplex" ]; then unset halfduplex print_comments "$interface" "Egress" "Start" tc -s class show dev "$device" print_comments "$interface" "Egress" "End" id="root" else id="" fi print_comments "$interface" "Ingress${halfduplex:+/Egress}" "Start" tc -s class show dev "$(tc filter show dev $device $id | grep mirred | sed -e 's,.*\(ifb.*\)).*,\1,')" print_comments "$interface" "Ingress${halfduplex:+/Egress}" "End" } [ -z "$1" ] && config_foreach interface_stats interface || interface_stats "$1"
{ "pile_set_name": "Github" }
const parse = require('./parse') const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid
{ "pile_set_name": "Github" }
/** * Parent for all Overlay types. The core concept with an Overlay is that of its `location`, which is specified * as follows: * * ###### Connectors * - a value between 0 and 1 inclusive is a proportional value, relative to the length of the Connector's path. * - a value greater than 1 or less than 0 is an absolute value (travel along the path inscribed by the Connector) * * For Connectors, the default value is `0.5`. * * ###### Endpoints * - An array of two values which are proportional to the width and height of the Endpoint. * * For Endpoints, the default value is `[0.5, 0.5]`. * @class Overlay */ /** * Draws an arrow, using four points: the head and two tail points, and a `foldback` point, which permits the tail of the arrow to be indented. * @class Overlays.Arrow * @constructor * @param {Object} params Constructor parameters * @param {Integer} [params.width=20] Width of the tail of the arrow * @param {Integer} [params.length=20] Distance from the tail of the arrow to the head * @param {Float} [params.location=0.5] Where, either as a proportional value from 0 to 1 inclusive, or as an absolute value (negative values mean distance from target; positive values greater than 1 mean distance from source) the Arrow should appear on the Connector * @param {Integer} [params.direction=1] Which way to point. Allowed values are 1 (the default, meaning forwards) and -1, meaning backwards * @param {Float} [params.foldback=0.623] How far along the axis of the arrow the tail points foldback in to. * @param {Object} [params.paintStyle] A style object in the form used for paintStyle values for Endpoints and Connectors. */ /** * This is just a specialized instance of Arrow in which jsPlumb hardcodes `foldback` to 1, meaning the tail of the Arrow is a flat edge * @class Overlays.PlainArrow * @constructor * @param {Object} params Constructor parameters * @param {Integer} [params.width=20] Width of the tail of the arrow * @param {Integer} [params.length=20] Distance from the tail of the arrow to the head * @param {Float} [params.location=0.5] Where, either as a proportional value from 0 to 1 inclusive, or as an absolute value (negative values mean distance from target; positive values greater than 1 mean distance from source) the PlainArrow should appear on the Connector * @param {Integer} [params.direction=1] Which way to point. Allowed values are 1 (the default, meaning forwards) and -1, meaning backwards * @param {Object} [params.paintStyle] A style object in the form used for paintStyle values for Endpoints and Connectors. */ /** * This is a specialized instance of Arrow in which jsPlumb hardcodes `foldback` to 2, meaning the Arrow turns into a Diamond * @class Overlays.Diamond * @param {Object} params Constructor parameters * @param {Integer} [params.width=20] Width of the diamond. * @param {Integer} [params.length=20] Length of the diamond. * @param {Float} [params.location=0.5] Where, either as a proportional value from 0 to 1 inclusive, or as an absolute value (negative values mean distance from target; positive values greater than 1 mean distance from source) the Diamond should appear on the Connector * @param {Object} [params.paintStyle] A style object in the form used for paintStyle values for Endpoints and Connectors. */ /** * Provides a text label with which to decorate Connectors or Endpoints. jsPlumb draws a Label overlay as a styled DIV. You can style a Label * using the `cssClass` parameter, or - if you need to programmatically generate the appearance - the `labelStyle` parameter. * @class Overlays.Label * @constructor * @param {Object} params Constructor parameters * @param {String|Function} label - The text to display. You can provide a function here instead of plain text: it is passed the component as an argument, and it should return a String. * @param {String} [cssClass] Optional css class to use for the Label. * @param {Float} [location=0.5] Where, either as a proportional value from 0 to 1 inclusive, or as an absolute value (negative values mean distance from target; positive values greater than 1 mean distance from source) the Label should appear on the Connector * @param {Object} [labelStyle] Optional object containing properties for the label's style. Use this if you need to prgrammatically generate the label's appearance. * @param {String} [labelStyle.cssClass] css class for the label (you can also use the `cssClass` parameter on the label; this exists for historical reasons) * @param {String} [labelStyle.font] A string specifying a font to use, in valid CSS format. * @param {String} [labelStyle.color] A string specifying a font color to use, in valid CSS format. * @param {String} [labelStyle.fill] A string specifying the background for the label, in valid CSS format. * @param {String} [labelStyle.borderStyle] A string specifying the border color for the label, in valid CSS format. * @param {Integer} [labelStyle.borderWidth] Width of the border's label * @param {Integer} [labelStyle.padding] Padding for the label. */
{ "pile_set_name": "Github" }
if TARGET_VME8349 config SYS_BOARD default "vme8349" config SYS_VENDOR default "esd" config SYS_CONFIG_NAME default "vme8349" endif
{ "pile_set_name": "Github" }
// Rewrite of Pugna Life Drain // Author: Noya // Date: April 5, 2015 "pugna_life_drain_datadriven" { // General //------------------------------------------------------------------------------------------------------------- "BaseClass" "ability_datadriven" "AbilityType" "DOTA_ABILITY_TYPE_ULTIMATE" "AbilityBehavior" "DOTA_ABILITY_BEHAVIOR_UNIT_TARGET | DOTA_ABILITY_BEHAVIOR_CHANNELLED | DOTA_ABILITY_BEHAVIOR_IGNORE_BACKSWING" "AbilityUnitTargetTeam" "DOTA_UNIT_TARGET_TEAM_BOTH" "AbilityUnitTargetType" "DOTA_UNIT_TARGET_HERO | DOTA_UNIT_TARGET_BASIC" "AbilityUnitTargetFlags" "DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES | DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE" "SpellImmunityType" "SPELL_IMMUNITY_ENEMIES_YES" "AbilityUnitDamageType" "DAMAGE_TYPE_MAGICAL" "FightRecapLevel" "1" "AbilityTextureName" "pugna_life_drain" // Casting //------------------------------------------------------------------------------------------------------------- "AbilityCastRange" "1100" "AbilityCastPoint" "0.2 0.2 0.2" "AbilityChannelTime" "10.0" // Time //------------------------------------------------------------------------------------------------------------- "AbilityCooldown" "22.0 22.0 22.0" // Cost //------------------------------------------------------------------------------------------------------------- "AbilityManaCost" "125 175 225" // Stats //------------------------------------------------------------------------------------------------------------- "AbilityModifierSupportValue" "0.0" // All about the damage // Special //------------------------------------------------------------------------------------------------------------- "AbilitySpecial" { "01" { "var_type" "FIELD_INTEGER" "health_drain" "120 160 200" } "02" { "var_type" "FIELD_INTEGER" "cast_range_tooltip" "850" } "03" { "var_type" "FIELD_INTEGER" "duration_tooltip" "10" } "04" { "var_type" "FIELD_INTEGER" "health_drain_scepter" "180 240 300" } "05" { "var_type" "FIELD_FLOAT" "scepter_cooldown" "0.0 0.0 0.0" } "06" { "var_type" "FIELD_FLOAT" "tick_rate" "0.25 0.25 0.25" } "07" { "var_type" "FIELD_INTEGER" "bonus_range_scepter" "50" } "08" { "var_type" "FIELD_INTEGER" "cast_range_scepter_tooltip" "900" } } "precache" { "particle" "particles/units/heroes/hero_pugna/pugna_life_drain.vpcf" "soundfile" "soundevents/game_sounds_heroes/game_sounds_pugna.vsndevts" } "OnSpellStart" { "ApplyModifier" { "ModifierName" "modifier_life_drain" "Target" "TARGET" } "FireSound" { "EffectName" "Hero_Pugna.LifeDrain.Target" "Target" "CASTER" } } "OnChannelFinish" { "RemoveModifier" { "ModifierName" "modifier_life_drain" "Target" "TARGET" } } "Modifiers" { "modifier_life_drain" { "IsDebuff" "1" "OnCreated" { "RunScript" { "ScriptFile" "heroes/hero_pugna/life_drain.lua" "Function" "LifeDrainParticle" } } "OnDestroy" { "RunScript" { "ScriptFile" "heroes/hero_pugna/life_drain.lua" "Function" "LifeDrainParticleEnd" } } "ThinkInterval" "%tick_rate" "OnIntervalThink" { "RunScript" { "ScriptFile" "heroes/hero_pugna/life_drain.lua" "Function" "LifeDrainHealthTransfer" } } } } }
{ "pile_set_name": "Github" }
#!/bin/sh # # ccat.sh 4.1 83/02/11 # for file in $* do /usr/ucb/uncompact < $file done
{ "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. */ define(function(require){ 'use strict'; var Backbone = require('backbone'); var App = require('App'); var XALinks = require('modules/XALinks'); var XAUtil = require('utils/XAUtils'); var XAEnums = require('utils/XAEnums'); var localization = require('utils/XALangSupport'); var UserTableLayout = require('views/users/UserTableLayout'); var VXRoleList = require('collections/VXRoleList'); var RoleForm = require('views/users/RoleForm'); var RolecreateTmpl = require('hbs!tmpl/users/RoleCreate_tmpl'); var SessionMgr = require('mgrs/SessionMgr'); var RoleCreate = Backbone.Marionette.Layout.extend( /** @lends RoleCreate */ { _viewName : 'RoleCreate', template: RolecreateTmpl, breadCrumbs :function(){ return this.model.isNew() ? [XALinks.get('Roles'),XALinks.get('RoleCreate')] : [XALinks.get('Roles'),XALinks.get('RoleEdit')]; }, /** Layout sub regions */ regions: { 'rForm' :'div[data-id="r_form"]' }, /** ui selector cache */ ui: { 'btnSave' : '[data-id="save"]', 'btnCancel' : '[data-id="cancel"]' }, /** ui events hash */ events: function() { var events = {}; //events['change ' + this.ui.input] = 'onInputChange'; events['click ' + this.ui.btnSave] = 'onSave'; events['click ' + this.ui.btnCancel] = 'onCancel'; return events; }, /** * intialize a new RoleCreate Layout * @constructs */ initialize: function(options) { console.log("initialized a RoleCreate Layout"); _.extend(this, _.pick(options, '')); this.editRole = this.model.has('id') ? true : false; this.bindEvents(); this.form = new RoleForm({ template : require('hbs!tmpl/users/RoleForm_tmpl'), model : this.model }); }, /** all events binding here */ bindEvents : function(){ /*this.listenTo(this.model, "change:foo", this.modelChanged, this);*/ /*this.listenTo(communicator.vent,'someView:someEvent', this.someEventHandler, this)'*/ }, /** on render callback */ onRender: function() { var that = this this.initializePlugins(); this.rForm.show(this.form); // this.rForm.$el.dirtyFields(); // XAUtil.preventNavigation(localization.tt('dialogMsg.preventNavGroupForm'),this.rForm.$el); }, /** all post render plugin initialization */ initializePlugins: function(){ }, onSave: function(){ var that = this, usersDetails = [], groupsDetails = [], rolesDetails = [] ; var errors = this.form.commit({validate : false}); if(! _.isEmpty(errors)){ return; } XAUtil.blockUI(); if(!this.form.beforeSave()){ XAUtil.blockUI('unblock'); return } this.form.usersColl.models.filter(function(m){ usersDetails.push ({'name' : m.get('name') , 'isAdmin' : m.get('isAdmin')}); }) this.form.groupsColl.models.filter(function(m){ groupsDetails.push ({'name' : m.get('name') , 'isAdmin' : m.get('isAdmin')}); }) this.form.rolesColl.models.filter(function(m){ rolesDetails.push ({'name' : m.get('name') , 'isAdmin' : m.get('isAdmin')}); }) this.model.set('users', usersDetails); this.model.set('groups', groupsDetails); this.model.set('roles', rolesDetails); this.model.save({},{ success: function () { XAUtil.blockUI('unblock'); XAUtil.allowNavigation(); Backbone.fetchCache._cache = {} var msg = that.editRole ? 'Role updated successfully' :'Role created successfully'; XAUtil.notifySuccess('Success', msg); App.usersGroupsListing = {'showLastPage' : true} App.appRouter.navigate("#!/users/Roletab",{trigger: true}); }, error : function (model, response, options) { XAUtil.blockUI('unblock'); if ( response && response.responseJSON && response.responseJSON.msgDesc){ if(response.responseJSON.msgDesc == "XRole already exists"){ XAUtil.notifyError('Error', "Role name already exists"); } else { XAUtil.notifyError('Error', response.responseJSON.msgDesc); } }else { XAUtil.notifyError('Error', 'Error occurred while creating/updating Role!'); } } }); }, onCancel : function(){ XAUtil.allowNavigation(); App.appRouter.navigate("#!/users/roletab",{trigger: true}); }, /** on close */ onClose: function(){ } }); return RoleCreate; });
{ "pile_set_name": "Github" }
package khipu.vm import akka.util.ByteString import khipu.DataWord import khipu.crypto import khipu.domain.Address import khipu.domain.TxLogEntry import scala.collection.mutable object OpCodes { val LogOpCodes: List[OpCode[_]] = List( LOG0, LOG1, LOG2, LOG3, LOG4 ) val SwapOpCodes: List[OpCode[_]] = List( SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16 ) val DupOpCodes: List[OpCode[_]] = List( DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16 ) val PushOpCodes: List[OpCode[_]] = List( PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32 ) val FrontierOpCodes: List[OpCode[_]] = LogOpCodes ++ SwapOpCodes ++ PushOpCodes ++ DupOpCodes ++ List( STOP, ADD, MUL, SUB, DIV, SDIV, MOD, SMOD, ADDMOD, MULMOD, EXP, SIGNEXTEND, LT, GT, SLT, SGT, EQ, ISZERO, AND, OR, XOR, NOT, BYTE, SHA3, ADDRESS, BALANCE, ORIGIN, CALLER, CALLVALUE, CALLDATALOAD, CALLDATASIZE, CALLDATACOPY, CODESIZE, CODECOPY, GASPRICE, EXTCODESIZE, EXTCODECOPY, BLOCKHASH, COINBASE, TIMESTAMP, NUMBER, DIFFICULTY, GASLIMIT, POP, MLOAD, MSTORE, MSTORE8, SLOAD, SSTORE, JUMP, JUMPI, PC, MSIZE, GAS, JUMPDEST, CREATE, CALL, CALLCODE, RETURN, INVALID, SELFDESTRUCT ) val HomesteadOpCodes: List[OpCode[_]] = FrontierOpCodes ++ List( DELEGATECALL ) val ByzantiumOpCodes: List[OpCode[_]] = HomesteadOpCodes ++ List( REVERT, RETURNDATASIZE, RETURNDATACOPY, STATICCALL ) val ConstantinopleCodes: List[OpCode[_]] = ByzantiumOpCodes ++ List( SHL, SHR, SAR, CREATE2, EXTCODEHASH ) val IstanbulCodes: List[OpCode[_]] = ConstantinopleCodes ++ List( SELFBALANCE, CHAINID ) } object OpCode { def sliceBytes(bytes: ByteString, offset: Int, size: Int): ByteString = sliceBytes(bytes.toArray, offset, size) def sliceBytes(bytes: Array[Byte], offset: Int, size: Int): ByteString = { if (offset >= 0 && offset <= Int.MaxValue && size > 0) { val slice = Array.ofDim[Byte](size) // auto filled with 0 if (offset < bytes.length) { System.arraycopy(bytes, offset, slice, 0, math.min(size, bytes.length - offset)) } ByteString(slice) } else { ByteString() } } } /** * Base class for all the opcodes of the EVM * * @tparam type of params * @param code Opcode byte representation * @param delta number of words to be popped from stack * @param alpha number of words to be pushed to stack */ sealed abstract class OpCode[P](val code: Byte, val delta: Int, val alpha: Int) { def this(code: Int, pop: Int, push: Int) = this(code.toByte, pop, push) final def execute[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]): ProgramState[W, S] = { if (state.stack.size < delta) { state.withError(StackUnderflow) } else if (state.stack.size - delta + alpha > state.stack.maxSize) { state.withError(StackOverflow) } else { val params = getParams(state) if (state.error.isEmpty) { // error is checked during getParams val baseGas = constGas(state.config.feeSchedule) val moreGas = variableGas(state, params) val spendingGas = baseGas + moreGas //println(s"spendingGas: $spendingGas, state.gas ${state.gas}, OOG? ${spendingGas > state.gas}") // TODO since we use Long (signed number type) to calculate gas, how to // make sure the value is always > 0 and < Long.MaxValue to avoid it becoming // negative value if (moreGas < 0 || spendingGas < 0 || spendingGas > state.gas) { state.withGas(0).withError(OutOfGas) } else { exec(state, params).spendGas(spendingGas) } } else { state } } } protected def constGas(s: FeeSchedule): Long protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: P): Long protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: P): ProgramState[W, S] protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]): P } sealed trait ConstGas[P] { self: OpCode[P] => protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: P): Long = 0 } case object STOP extends OpCode[Unit](0x00, 0, 0) with ConstGas[Unit] { protected def constGas(s: FeeSchedule) = s.G_zero protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = state.halt } sealed abstract class BinaryOp(code: Int) extends OpCode[(DataWord, DataWord)](code, 2, 1) { protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(a, b) = state.stack.pop(2) (a, b) } final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): ProgramState[W, S] = { val (a, b) = params val res = f(a, b) state.stack.push(res) state.step() } protected def f(x: DataWord, y: DataWord): DataWord } case object ADD extends BinaryOp(0x01) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = x + y } case object MUL extends BinaryOp(0x02) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_low protected def f(x: DataWord, y: DataWord) = x * y } case object SUB extends BinaryOp(0x03) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = x - y } case object DIV extends BinaryOp(0x04) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_low protected def f(x: DataWord, y: DataWord) = x div y } case object SDIV extends BinaryOp(0x05) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_low protected def f(x: DataWord, y: DataWord) = x sdiv y } case object MOD extends BinaryOp(0x06) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_low protected def f(x: DataWord, y: DataWord) = x mod y } case object SMOD extends BinaryOp(0x07) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_low protected def f(x: DataWord, y: DataWord) = x smod y } case object EXP extends BinaryOp(0x0a) { protected def constGas(s: FeeSchedule) = s.G_exp protected def f(x: DataWord, y: DataWord) = x ** y protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): Long = { val (_, m) = params state.config.feeSchedule.G_expbyte * m.byteSize } } case object SIGNEXTEND extends BinaryOp(0x0b) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_low protected def f(x: DataWord, y: DataWord) = y signExtend x } case object LT extends BinaryOp(0x10) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = DataWord(x < y) } case object GT extends BinaryOp(0x11) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = DataWord(x > y) } case object SLT extends BinaryOp(0x12) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = DataWord(x slt y) } case object SGT extends BinaryOp(0x13) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = DataWord(x sgt y) } case object EQ extends BinaryOp(0x14) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = DataWord(x.n.compareTo(y.n) == 0) } case object AND extends BinaryOp(0x16) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = x & y } case object OR extends BinaryOp(0x17) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = x | y } case object XOR extends BinaryOp(0x18) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = x ^ y } case object BYTE extends BinaryOp(0x1a) with ConstGas[(DataWord, DataWord)] { override protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(a, b) = state.stack.pop(2) if (a.compareTo(DataWord.MaxInt) > 0) { state.withError(ArithmeticException) } (a, b) } protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = y getByte x } case object SHL extends BinaryOp(0x1b) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = y shiftLeft x } case object SHR extends BinaryOp(0x1c) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = y shiftRight x } case object SAR extends BinaryOp(0x1d) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord, y: DataWord) = y shiftRightSigned x } sealed abstract class UnaryOp(code: Int) extends OpCode[DataWord](code, 1, 1) with ConstGas[DataWord] { final protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(a) = state.stack.pop() a } final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): ProgramState[W, S] = { val a = params val res = f(a) state.stack.push(res) state.step() } protected def f(x: DataWord): DataWord } case object ISZERO extends UnaryOp(0x15) { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord) = DataWord(x.isZero) } case object NOT extends UnaryOp(0x19) { protected def constGas(s: FeeSchedule) = s.G_verylow protected def f(x: DataWord) = ~x } sealed abstract class TernaryOp(code: Int) extends OpCode[(DataWord, DataWord, DataWord)](code, 3, 1) { final protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(a, b, c) = state.stack.pop(3) (a, b, c) } final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): ProgramState[W, S] = { val (a, b, c) = params val res = f(a, b, c) state.stack.push(res) state.step() } protected def f(x: DataWord, y: DataWord, z: DataWord): DataWord } case object ADDMOD extends TernaryOp(0x08) with ConstGas[(DataWord, DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_mid protected def f(x: DataWord, y: DataWord, z: DataWord) = x.addmod(y, z) } case object MULMOD extends TernaryOp(0x09) with ConstGas[(DataWord, DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_mid protected def f(x: DataWord, y: DataWord, z: DataWord) = x.mulmod(y, z) } case object SHA3 extends OpCode[(DataWord, DataWord)](0x20, 2, 1) { protected def constGas(s: FeeSchedule) = s.G_sha3 protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { // do not need to check params bounds, just use safe int value val List(offset, size) = state.stack.pop(2) (DataWord.safe(offset.intValueSafe), DataWord.safe(size.intValueSafe)) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): ProgramState[W, S] = { val (offset, size) = params val input = state.memory.load(offset.intValueSafe, size.intValueSafe) val hash = crypto.kec256(input.toArray) state.stack.push(DataWord(hash)) state.step() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): Long = { val (offset, size) = params val memCost = state.config.calcMemCost(state.memory.size, offset.longValueSafe, size.longValueSafe) val shaCost = state.config.feeSchedule.G_sha3word * DataWord.wordsForBytes(size.longValueSafe) memCost + shaCost } } sealed abstract class ConstOp(code: Int) extends OpCode[Unit](code, 0, 1) with ConstGas[Unit] { final protected def constGas(s: FeeSchedule) = s.G_base final protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = Nil final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { state.stack.push(f(state)) state.step() } protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]): DataWord } case object ADDRESS extends ConstOp(0x30) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = s.env.ownerAddr.toDataWord } case object ORIGIN extends ConstOp(0x32) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = s.env.originAddr.toDataWord } case object CALLER extends ConstOp(0x33) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = s.env.callerAddr.toDataWord } case object CALLVALUE extends ConstOp(0x34) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = s.env.value } case object CALLDATASIZE extends ConstOp(0x36) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord.safe(s.input.size) } case object GASPRICE extends ConstOp(0x3a) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = s.env.gasPrice } case object CODESIZE extends ConstOp(0x38) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord.safe(s.env.program.length) } case object COINBASE extends ConstOp(0x41) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord(s.env.blockHeader.beneficiary) } case object TIMESTAMP extends ConstOp(0x42) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord(s.env.blockHeader.unixTimestamp) } case object NUMBER extends ConstOp(0x43) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord(s.env.blockHeader.number) } case object DIFFICULTY extends ConstOp(0x44) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = s.env.blockHeader.difficulty } case object GASLIMIT extends ConstOp(0x45) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord(s.env.blockHeader.gasLimit) } case object PC extends ConstOp(0x58) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord.safe(s.pc) } case object MSIZE extends ConstOp(0x59) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord(DataWord.SIZE * DataWord.wordsForBytes(s.memory.size)) } case object GAS extends ConstOp(0x5a) { protected def f(s: ProgramState[_ <: WorldState[_, _ <: Storage[_]], _ <: Storage[_]]) = DataWord(s.gas - s.config.feeSchedule.G_base) } case object BALANCE extends OpCode[DataWord](0x31, 1, 1) with ConstGas[DataWord] { protected def constGas(s: FeeSchedule) = s.G_balance protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(accountAddress) = state.stack.pop() accountAddress } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): ProgramState[W, S] = { val accountAddress = params val accountBalance = state.world.getBalance(Address(accountAddress)) state.stack.push(accountBalance) state.withParallelRaceCondition(ProgramState.OnAccount).step() } } case object CALLDATALOAD extends OpCode[Int](0x35, 1, 1) with ConstGas[Int] { protected def constGas(s: FeeSchedule) = s.G_verylow protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { // do not need to check params bound, just use int value, possible overflow is processed in sliceBytes val List(offset) = state.stack.pop() offset.intValueSafe // Note: ethereumj seems use offset.n.intValue here, it won't work on Tx 0x3d956f1ae474bb1d2d5147332e052912a4b94a956fee945e7a5074e5657459f9 } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Int): ProgramState[W, S] = { val offset = params val data = OpCode.sliceBytes(state.input, offset, 32) state.stack.push(DataWord(data)) state.step() } } case object CALLDATACOPY extends OpCode[(DataWord, DataWord, DataWord)](0x37, 3, 0) { protected def constGas(s: FeeSchedule) = s.G_verylow protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { // do not need to check params bound, just use save int value val List(memOffset, dataOffset, size) = state.stack.pop(3) (memOffset, dataOffset, size) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): ProgramState[W, S] = { val (memOffset, dataOffset, size) = params val data = OpCode.sliceBytes(state.input, dataOffset.intValueSafe, size.intValueSafe) state.memory.store(memOffset.intValueSafe, data) state.step() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): Long = { val (memOffset, _, size) = params val memCost = state.config.calcMemCost(state.memory.size, memOffset.longValueSafe, size.longValueSafe) val copyCost = state.config.feeSchedule.G_copy * DataWord.wordsForBytes(size.longValueSafe) memCost + copyCost } } case object CODECOPY extends OpCode[(DataWord, DataWord, DataWord)](0x39, 3, 0) { protected def constGas(s: FeeSchedule) = s.G_verylow protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { // do not need to check params bound, just use safe int value val List(memOffset, codeOffset, size) = state.stack.pop(3) (memOffset, codeOffset, size) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): ProgramState[W, S] = { val (memOffset, codeOffset, size) = params val bytes = OpCode.sliceBytes(state.program.code, codeOffset.intValueSafe, size.intValueSafe) state.memory.store(memOffset.intValueSafe, bytes) state.step() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): Long = { val (memOffset, _, size) = params val memCost = state.config.calcMemCost(state.memory.size, memOffset.longValueSafe, size.longValueSafe) val copyCost = state.config.feeSchedule.G_copy * DataWord.wordsForBytes(size.longValueSafe) memCost + copyCost } } case object EXTCODESIZE extends OpCode[DataWord](0x3b, 1, 1) with ConstGas[DataWord] { protected def constGas(s: FeeSchedule) = s.G_extcodesize protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(addr) = state.stack.pop() addr } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): ProgramState[W, S] = { val addr = params val codeSize = state.world.getCode(Address(addr)).size state.stack.push(DataWord(codeSize)) state.step() } } case object EXTCODECOPY extends OpCode[(DataWord, DataWord, DataWord, DataWord)](0x3c, 4, 0) { protected def constGas(s: FeeSchedule) = s.G_extcodecopy protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { // do not need to check params bound, just use safe int value val List(address, memOffset, codeOffset, size) = state.stack.pop(4) (address, DataWord.safe(memOffset.intValueSafe), DataWord.safe(codeOffset.intValueSafe), DataWord.safe(size.intValueSafe)) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord, DataWord)): ProgramState[W, S] = { val (address, memOffset, codeOffset, size) = params val codeCopy = OpCode.sliceBytes(state.world.getCode(Address(address)), codeOffset.intValueSafe, size.intValueSafe) state.memory.store(memOffset.intValueSafe, codeCopy) state.step() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord, DataWord)): Long = { val (_, memOffset, _, size) = params val memCost = state.config.calcMemCost(state.memory.size, memOffset.longValueSafe, size.longValueSafe) val copyCost = state.config.feeSchedule.G_copy * DataWord.wordsForBytes(size.longValueSafe) memCost + copyCost } } case object EXTCODEHASH extends OpCode[DataWord](0x3f, 1, 1) with ConstGas[DataWord] { protected def constGas(s: FeeSchedule) = s.G_extcodehash protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(addr) = state.stack.pop() addr } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): ProgramState[W, S] = { val addr = params val codeHash = state.world.getCodeHash(Address(addr)).getOrElse(DataWord.Zero) state.stack.push(codeHash) state.step() } } case object RETURNDATASIZE extends OpCode[Unit](0x3d, 0, 1) with ConstGas[Unit] { protected def constGas(s: FeeSchedule) = s.G_base protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { val dataSize = state.returnDataBuffer.length state.stack.push(DataWord(dataSize)) state.step() } } case object RETURNDATACOPY extends OpCode[(DataWord, DataWord, DataWord)](0x3e, 3, 0) { protected def constGas(s: FeeSchedule) = s.G_verylow protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { // do not need to check params bound, just use safe int value val List(memOffset, dataOffset, size) = state.stack.pop(3) (memOffset, dataOffset, size) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): ProgramState[W, S] = { val (memOffset, dataOffset, size) = params val data = OpCode.sliceBytes(state.returnDataBuffer, dataOffset.intValueSafe, size.intValueSafe) state.memory.store(memOffset.intValueSafe, data) state.step() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): Long = { val (memOffset, _, size) = params val memCost = state.config.calcMemCost(state.memory.size, memOffset.longValueSafe, size.longValueSafe) val copyCost = state.config.feeSchedule.G_copy * DataWord.wordsForBytes(size.longValueSafe) memCost + copyCost } } case object BLOCKHASH extends OpCode[Int](0x40, 1, 1) with ConstGas[Int] { protected def constGas(s: FeeSchedule) = s.G_blockhash protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(blockNumber) = state.stack.pop() blockNumber.intValueSafe } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Int): ProgramState[W, S] = { val blockNumber = params val outOfLimits = state.env.blockHeader.number - blockNumber > 256 || blockNumber >= state.env.blockHeader.number val hash = if (outOfLimits) DataWord.Zero else state.world.getBlockHash(blockNumber).getOrElse(DataWord.Zero) state.stack.push(hash) state.step() } } case object CHAINID extends OpCode[Unit](0x46, 0, 1) with ConstGas[Unit] { protected def constGas(s: FeeSchedule) = s.G_base protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { val chainId = state.config.chainId state.stack.push(chainId) state.step() } } case object SELFBALANCE extends OpCode[Unit](0x47, 0, 1) with ConstGas[Unit] { protected def constGas(s: FeeSchedule) = s.G_low protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { val balance = state.ownBalance state.stack.push(balance) state.step() } } case object POP extends OpCode[Unit](0x50, 1, 0) with ConstGas[Unit] { protected def constGas(s: FeeSchedule) = s.G_base protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { state.stack.pop() state.step() } } case object MLOAD extends OpCode[DataWord](0x51, 1, 1) { protected def constGas(s: FeeSchedule) = s.G_verylow protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(offset) = state.stack.pop() if (offset.compareTo(DataWord.MaxInt) > 0) { state.withError(ArithmeticException) // why MLOAD/MSTORE requires bounded offset } offset } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): ProgramState[W, S] = { val offset = params val word = state.memory.load(offset.intValueSafe) state.stack.push(word) state.step() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): Long = { val offset = params state.config.calcMemCost(state.memory.size, offset.longValueSafe, DataWord.SIZE) } } case object MSTORE extends OpCode[(DataWord, DataWord)](0x52, 2, 0) { protected def constGas(s: FeeSchedule) = s.G_verylow protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(offset, value) = state.stack.pop(2) if (offset.compareTo(DataWord.MaxInt) > 0) { state.withError(ArithmeticException) } (offset, value) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): ProgramState[W, S] = { val (offset, value) = params state.memory.store(offset.intValueSafe, value) state.step() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): Long = { val (offset, _) = params state.config.calcMemCost(state.memory.size, offset.longValueSafe, DataWord.SIZE) } } case object MSTORE8 extends OpCode[(DataWord, DataWord)](0x53, 2, 0) { protected def constGas(s: FeeSchedule) = s.G_verylow protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { // do not need to check params bound, just use safe int value val List(offset, value) = state.stack.pop(2) (offset, value) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): ProgramState[W, S] = { val (offset, value) = params val valueToByte = (value mod DataWord.TwoFiveSix).n.byteValue state.memory.store(offset.intValueSafe, valueToByte) state.step() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): Long = { val (offset, _) = params state.config.calcMemCost(state.memory.size, offset.longValueSafe, 1) } } case object SLOAD extends OpCode[DataWord](0x54, 1, 1) with ConstGas[DataWord] { protected def constGas(s: FeeSchedule) = s.G_sload protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(offset) = state.stack.pop() offset } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): ProgramState[W, S] = { val offset = params val value = state.storage.load(offset) state.stack.push(value) state.step() } } case object SSTORE extends OpCode[(DataWord, DataWord)](0x55, 2, 0) { protected def constGas(s: FeeSchedule) = s.G_zero protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(offset, value) = state.stack.pop(2) (offset, value) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): ProgramState[W, S] = { if (state.context.isStaticCall) { state.withError(StaticCallModification) } else { val (offset, newValue) = params val refund = refundGas(state, params) // must calc before storage.store(key, newValue) to keep currValue val updatedStorage = state.storage.store(offset, newValue) val world = state.world.saveStorage(state.ownAddress, updatedStorage) state .withWorld(world) .refundGas(refund) .step() } } private def getOriginalValue[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], offset: DataWord) = { state.context.originalStorageValues.get(state.ownAddress) match { case Some(map) => map.get(offset) match { case Some(ori) => ori case None => val ori = state.storage.load(offset) map += (offset -> ori) ori } case None => val map = new mutable.HashMap[DataWord, DataWord]() state.context.originalStorageValues += (state.ownAddress -> map) val ori = state.storage.load(offset) map += (offset -> ori) ori } } private def refundGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): Long = { val (offset, newValue) = params val currValue = state.storage.load(offset) if (state.config.eip2200) { // https://eips.ethereum.org/EIPS/eip-2200 if (currValue == newValue) { 0L } else { // currValue != newValue val origValue = getOriginalValue(state, offset) if (currValue == origValue) { if (origValue.isZero) { 0L } else if (newValue.isZero) { state.config.feeSchedule.R_sclear } else { 0L } } else { // currValue != origValue and currValue != newValue var _refund = 0L if (origValue.nonZero) { if (currValue.isZero) { _refund -= state.config.feeSchedule.R_sclear } else if (newValue.isZero) { _refund += state.config.feeSchedule.R_sclear } } if (origValue == newValue) { // this storage slot is reset if (origValue.isZero) { _refund += (state.config.feeSchedule.G_sset - state.config.feeSchedule.G_sload) } else { _refund += (state.config.feeSchedule.G_sreset - state.config.feeSchedule.G_sload) } } _refund } } } else { if (currValue.nonZero && newValue.isZero) { state.config.feeSchedule.R_sclear } else { 0L } } } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): Long = { if (state.config.eip2200 && state.gas <= state.config.feeSchedule.G_ssentry) { -1 // OutOfGas } else { val (offset, newValue) = params val currValue = state.storage.load(offset) if (state.config.eip2200) { // https://eips.ethereum.org/EIPS/eip-2200 if (currValue == newValue) { state.config.feeSchedule.G_sload } else { // currValue != newValue val origValue = getOriginalValue(state, offset) if (currValue == origValue) { // this storage slot has not been changed by the current execution context if (origValue.isZero) { state.config.feeSchedule.G_sset } else { state.config.feeSchedule.G_sreset } } else { // currValue != origValue and currValue != newValue, this storage slot is dirty state.config.feeSchedule.G_sload } } } else { if (currValue.isZero && newValue.nonZero) { state.config.feeSchedule.G_sset } else { state.config.feeSchedule.G_sreset } } } } } case object JUMP extends OpCode[DataWord](0x56, 1, 0) with ConstGas[DataWord] { protected def constGas(s: FeeSchedule) = s.G_mid protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(pos) = state.stack.pop() pos } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): ProgramState[W, S] = { val pos = params val dest = pos.toInt // fail with InvalidJump if convertion to Int is lossy if (pos == dest && state.program.isValidJumpDestination(dest)) { state.goto(dest) } else { state.withError(InvalidJump(pos)) } } } case object JUMPI extends OpCode[(DataWord, DataWord)](0x57, 2, 0) with ConstGas[(DataWord, DataWord)] { protected def constGas(s: FeeSchedule) = s.G_high protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(pos, cond) = state.stack.pop(2) (pos, cond) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): ProgramState[W, S] = { val (pos, cond) = params val dest = pos.toInt // fail with InvalidJump if convertion to Int is lossy if (cond.isZero) { state.step() } else if (pos == dest && state.program.isValidJumpDestination(dest)) { state.goto(dest) } else { state.withError(InvalidJump(pos)) } } } case object JUMPDEST extends OpCode[Unit](0x5b, 0, 0) with ConstGas[Unit] { protected def constGas(s: FeeSchedule) = s.G_jumpdest protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { state.step() } } sealed abstract class PushOp private (code: Int, val i: Int) extends OpCode[Unit](code, 0, 1) with ConstGas[Unit] { def this(code: Int) = this(code, code - 0x60) final protected def constGas(s: FeeSchedule) = s.G_verylow final protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { val n = i + 1 val bytes = state.program.getBytes(state.pc + 1, n) state.stack.push(DataWord(bytes)) state.step(n + 1) } } case object PUSH1 extends PushOp(0x60) case object PUSH2 extends PushOp(0x61) case object PUSH3 extends PushOp(0x62) case object PUSH4 extends PushOp(0x63) case object PUSH5 extends PushOp(0x64) case object PUSH6 extends PushOp(0x65) case object PUSH7 extends PushOp(0x66) case object PUSH8 extends PushOp(0x67) case object PUSH9 extends PushOp(0x68) case object PUSH10 extends PushOp(0x69) case object PUSH11 extends PushOp(0x6a) case object PUSH12 extends PushOp(0x6b) case object PUSH13 extends PushOp(0x6c) case object PUSH14 extends PushOp(0x6d) case object PUSH15 extends PushOp(0x6e) case object PUSH16 extends PushOp(0x6f) case object PUSH17 extends PushOp(0x70) case object PUSH18 extends PushOp(0x71) case object PUSH19 extends PushOp(0x72) case object PUSH20 extends PushOp(0x73) case object PUSH21 extends PushOp(0x74) case object PUSH22 extends PushOp(0x75) case object PUSH23 extends PushOp(0x76) case object PUSH24 extends PushOp(0x77) case object PUSH25 extends PushOp(0x78) case object PUSH26 extends PushOp(0x79) case object PUSH27 extends PushOp(0x7a) case object PUSH28 extends PushOp(0x7b) case object PUSH29 extends PushOp(0x7c) case object PUSH30 extends PushOp(0x7d) case object PUSH31 extends PushOp(0x7e) case object PUSH32 extends PushOp(0x7f) sealed abstract class DupOp private (code: Int, val i: Int) extends OpCode[Unit](code, i + 1, i + 2) with ConstGas[Unit] { def this(code: Int) = this(code, code - 0x80) final protected def constGas(s: FeeSchedule) = s.G_verylow final protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { state.stack.dup(i) state.step() } } case object DUP1 extends DupOp(0x80) case object DUP2 extends DupOp(0x81) case object DUP3 extends DupOp(0x82) case object DUP4 extends DupOp(0x83) case object DUP5 extends DupOp(0x84) case object DUP6 extends DupOp(0x85) case object DUP7 extends DupOp(0x86) case object DUP8 extends DupOp(0x87) case object DUP9 extends DupOp(0x88) case object DUP10 extends DupOp(0x89) case object DUP11 extends DupOp(0x8a) case object DUP12 extends DupOp(0x8b) case object DUP13 extends DupOp(0x8c) case object DUP14 extends DupOp(0x8d) case object DUP15 extends DupOp(0x8e) case object DUP16 extends DupOp(0x8f) sealed abstract class SwapOp private (code: Int, val i: Int) extends OpCode[Unit](code, i + 2, i + 2) with ConstGas[Unit] { def this(code: Int) = this(code, code - 0x90) final protected def constGas(s: FeeSchedule) = s.G_verylow final protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = { state.stack.swap(i + 1) state.step() } } case object SWAP1 extends SwapOp(0x90) case object SWAP2 extends SwapOp(0x91) case object SWAP3 extends SwapOp(0x92) case object SWAP4 extends SwapOp(0x93) case object SWAP5 extends SwapOp(0x94) case object SWAP6 extends SwapOp(0x95) case object SWAP7 extends SwapOp(0x96) case object SWAP8 extends SwapOp(0x97) case object SWAP9 extends SwapOp(0x98) case object SWAP10 extends SwapOp(0x99) case object SWAP11 extends SwapOp(0x9a) case object SWAP12 extends SwapOp(0x9b) case object SWAP13 extends SwapOp(0x9c) case object SWAP14 extends SwapOp(0x9d) case object SWAP15 extends SwapOp(0x9e) case object SWAP16 extends SwapOp(0x9f) sealed abstract class LogOp private (code: Int, val i: Int) extends OpCode[(DataWord, DataWord, List[DataWord])](code, i + 2, 0) { def this(code: Int) = this(code, code - 0xa0) final protected def constGas(s: FeeSchedule) = s.G_log final protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { // do not need to check params bound, just use save int value val offset :: size :: topics = state.stack.pop(delta) (offset, size, topics) } final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, List[DataWord])): ProgramState[W, S] = { if (state.context.isStaticCall) { state.withError(StaticCallModification) } else { val (offset, size, topics) = params val data = state.memory.load(offset.intValueSafe, size.intValueSafe) val logEntry = TxLogEntry(state.env.ownerAddr, topics.map(x => ByteString(x.bytes)), data) state.withTxLog(logEntry).step() } } final protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, List[DataWord])): Long = { val (offset, size, _) = params val memCost = state.config.calcMemCost(state.memory.size, offset.longValueSafe, size.longValueSafe) val logCost = state.config.feeSchedule.G_logdata * size.toMaxLong + i * state.config.feeSchedule.G_logtopic memCost + logCost } } case object LOG0 extends LogOp(0xa0) case object LOG1 extends LogOp(0xa1) case object LOG2 extends LogOp(0xa2) case object LOG3 extends LogOp(0xa3) case object LOG4 extends LogOp(0xa4) sealed abstract class CreatOp[P](code: Int, delta: Int, alpha: Int) extends OpCode[P](code.toByte, delta, alpha) { final protected def doExec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], endowment: DataWord, inOffset: DataWord, inSize: DataWord, salt: Array[Byte], params: P): ProgramState[W, S] = { if (state.context.isStaticCall) { state.withError(StaticCallModification) } else { state.resetReturnDataBuffer() // reset before call val isValidCall = state.env.callDepth < EvmConfig.MaxCallDepth && endowment <= state.ownBalance if (isValidCall) { //FIXME: to avoid calculating this twice, we could adjust state.gas prior to execution in OpCode#execute //not sure how this would affect other opcodes [EC-243] val availableGas = state.gas - (constGas(state.config.feeSchedule) + variableGas(state, params)) val startGas = state.config.gasCap(availableGas) val initCode = state.memory.load(inOffset.intValueSafe, inSize.intValueSafe).toArray // if creation fails at this point we still leave the creators nonce incremented createContactAddress[W, S](state, initCode, salt) match { case Right((address, world)) => val (newAddress, checkpoint, worldAtCheckpoint) = (address, world.copy, world) //println(s"newAddress: $newAddress via ${state.env.ownerAddr} in CREATE") val worldBeforeTransfer = if (state.config.eip161) { worldAtCheckpoint.increaseNonce(newAddress) } else { worldAtCheckpoint } val worldAfterTransfer = worldBeforeTransfer.transfer(state.env.ownerAddr, newAddress, endowment) val env = state.env.copy( callerAddr = state.env.ownerAddr, ownerAddr = newAddress, value = endowment, program = Program(initCode, state.config), input = ByteString(), callDepth = state.env.callDepth + 1 ) val context = ProgramContext[W, S]( env, newAddress, startGas, worldAfterTransfer, state.config, state.addressesToDelete, state.addressesTouched + newAddress, state.context.isStaticCall, state.context.originalStorageValues ) val result = VM.run(context, state.isDebugTraceEnabled) state.mergeParallelRaceConditions(result.parallelRaceConditions) if (result.isRevert) { state.withReturnDataBuffer(result.returnData) } val gasUsedInCreating = startGas - result.gasRemaining val code = result.returnData val codeDepositGas = state.config.calcCodeDepositCost(code) val isRequireGasForCodeDeposit = state.config.exceptionalFailedCodeDeposit && !result.isRevert val notEnoughGasForCodeDeposit = gasUsedInCreating + codeDepositGas > startGas val isCreationFailed = result.error.isDefined || (isRequireGasForCodeDeposit && notEnoughGasForCodeDeposit) if (isCreationFailed || result.isRevert) { state.stack.push(DataWord.Zero) if (result.error.isEmpty && result.isRevert) { state.spendGas(gasUsedInCreating) } else { state.spendGas(startGas) } // the error result may be caused by parallel race condition, so merge all possible modifies state .withParallelRaceCondition(ProgramState.OnError) .withWorld(checkpoint.mergeRaceConditions(result.world)) .step() } else { state.stack.push(newAddress.toDataWord) state.spendGas(gasUsedInCreating) if (notEnoughGasForCodeDeposit) { state.withWorld(result.world) } else { if (code.length > state.config.maxContractSize) { //println(s"Contract size too large: ${code.length}") state.withWorld(result.world).withError(OutOfGas) } else { if (!result.isRevert) { val world3 = result.world.saveCode(newAddress, code) state.withWorld(world3).spendGas(codeDepositGas) } } } state .refundGas(result.gasRefund) .withAddAddressesToDelete(result.addressesToDelete) .withAddAddressesTouched(result.addressesTouched) .withTxLogs(result.txLogs) .step() } case Left(WorldState.AddressCollisions(address)) => // throws immediately, with exactly the same behavior as would arise // if the first byte in the init code were an invalid opcode. state.stack.push(DataWord.Zero) state .spendGas(startGas) .withInfo(s"Address collision at $address") .withParallelRaceCondition(ProgramState.OnAccount) .step() } } else { // invalid call state.stack.push(DataWord.Zero) if (endowment <= state.ownBalance) { state.withParallelRaceCondition(ProgramState.OnAccount) } state .step() } } } protected def createContactAddress[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], initCode: Array[Byte], salt: Array[Byte]): Either[WorldState.AddressCollisions, (Address, W)] } case object CREATE extends CreatOp[(DataWord, DataWord, DataWord)](0xf0, 3, 1) { protected def constGas(s: FeeSchedule) = s.G_create protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(endowment, inOffset, inSize) = state.stack.pop(3) if (inOffset.compareTo(DataWord.MaxInt) > 0 || inSize.compareTo(DataWord.MaxInt) > 0) { state.withError(ArithmeticException) } (endowment, inOffset, inSize) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): ProgramState[W, S] = { val (endowment, inOffset, inSize) = params doExec(state, endowment, inOffset, inSize, null, params) } protected def createContactAddress[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], initCode: Array[Byte], salt: Array[Byte]): Either[WorldState.AddressCollisions, (Address, W)] = { state.world.createContractAddress(state.env.ownerAddr) } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord)): Long = { val (_, inOffset, inSize) = params val memCost = state.config.calcMemCost(state.memory.size, inOffset.longValueSafe, inSize.longValueSafe) memCost } } case object CREATE2 extends CreatOp[(DataWord, DataWord, DataWord, DataWord)](0xf5, 4, 1) { protected def constGas(s: FeeSchedule) = s.G_create protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(endowment, inOffset, inSize, salt) = state.stack.pop(4) if (inOffset.compareTo(DataWord.MaxInt) > 0 || inSize.compareTo(DataWord.MaxInt) > 0) { state.withError(ArithmeticException) } (endowment, inOffset, inSize, salt) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord, DataWord)): ProgramState[W, S] = { val (endowment, inOffset, inSize, salt) = params doExec(state, endowment, inOffset, inSize, salt.bytes, params) } protected def createContactAddress[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], initCode: Array[Byte], salt: Array[Byte]): Either[WorldState.AddressCollisions, (Address, W)] = { state.world.createContractAddress(state.env.ownerAddr, initCode, salt) } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord, DataWord)): Long = { val (_, inOffset, inSize, _) = params val memCost = state.config.calcMemCost(state.memory.size, inOffset.longValueSafe, inSize.longValueSafe) val shaCost = state.config.feeSchedule.G_sha3word * DataWord.wordsForBytes(inSize.longValueSafe) memCost + shaCost } } sealed abstract class CallOp(code: Int, delta: Int, alpha: Int, hasValue: Boolean, isStateless: Boolean, isStatic: Boolean) extends OpCode[(DataWord, DataWord, DataWord, DataWord, DataWord, DataWord, DataWord)](code.toByte, delta, alpha) { final protected def constGas(s: FeeSchedule) = s.G_zero final protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(gas, target, callValue, inOffset, inSize, outOffset, outSize) = if (hasValue) { state.stack.pop(7) } else { val List(gas, target, inOffset, inSize, outOffset, outSize) = state.stack.pop(6) List(gas, target, DataWord.Zero, inOffset, inSize, outOffset, outSize) } if (inOffset.compareTo(DataWord.MaxInt) > 0 || inSize.compareTo(DataWord.MaxInt) > 0 || outOffset.compareTo(DataWord.MaxInt) > 0 || outOffset.compareTo(DataWord.MaxInt) > 0) { state.withError(ArithmeticException) } (gas, target, callValue, inOffset, inSize, outOffset, outSize) } /** * At block 2675119, shortly after the planned “Spurious Dragon” hard fork, see: * https://github.com/ethereum/EIPs/issues/716 "Clarification about when touchedness is reverted during state clearance" * https://github.com/ethereum/go-ethereum/pull/3341/files#r89547994 */ final protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord, DataWord, DataWord, DataWord, DataWord)): ProgramState[W, S] = { val (gas, target, callValue, inOffset, inSize, outOffset, outSize) = params if (state.context.isStaticCall && (this == CALL || this == CALLCODE) && callValue.nonZero) { // alreay in staticCall and call with noZero value state.withError(StaticCallModification) } else { state.resetReturnDataBuffer() // reset before call val codeAddress = Address(target) val endowment = callValue //println(s"ownAddress: ${state.ownAddress} -> codeAddress: $codeAddress with value $callValue in $this") val startGas = { val gMemIn = state.config.calcMemCost(state.memory.size, inOffset.longValueSafe, inSize.longValueSafe) val gMemOut = state.config.calcMemCost(state.memory.size, outOffset.longValueSafe, outSize.longValueSafe) val gMem = math.max(gMemIn, gMemOut) val gExtra = gasExtra(state, endowment, codeAddress) val gAdjust = gasAdjust(state, gas.longValueSafe, gExtra + gMem) //if (state.isTraceEnabled) state.addTrace(s"CallOp state.gas: ${state.gas}, gasRequest: ${gas.longValueSafe}, gExtra: $gExtra, gMemIn: $gMemIn, gMemOut: $gMemOut, gMem: $gMem, gAdjust: $gAdjust, endowment: $endowment, ownBalance: ${state.ownBalance}") // startGas is calculated as gAdjust and the following G_callstipend if applicable // varGas is calculated as gas that will be consumered if (endowment.isZero) gAdjust else gAdjust + state.config.feeSchedule.G_callstipend } // expand memory according to max in/out offset + in/out size, you know, we've paid gas for it // e.g, tx 0xd31250c86050cb571c548315c0018626989f2fb2385455ec301bd4cdd21ee1c7 should use inOffset + inSize if (inOffset.longValueSafe + inSize.longValueSafe > outOffset.longValueSafe + outSize.longValueSafe) { state.memory.expand(inOffset.intValueSafe, inSize.intValueSafe) } else { state.memory.expand(outOffset.intValueSafe, outSize.intValueSafe) } val isValidCall = state.env.callDepth < EvmConfig.MaxCallDepth && endowment <= state.ownBalance if (isValidCall) { val (checkpoint, worldAtCheckpoint) = (state.world.copy, state.world) def prepareProgramContext(code: ByteString): ProgramContext[W, S] = { val input = state.memory.load(inOffset.intValueSafe, inSize.intValueSafe) val (owner, caller, value) = this match { case CALL => (codeAddress, state.ownAddress, callValue) case STATICCALL => (codeAddress, state.ownAddress, callValue) case CALLCODE => (state.ownAddress, state.ownAddress, callValue) case DELEGATECALL => (state.ownAddress, state.env.callerAddr, state.env.value) } val env = state.env.copy( ownerAddr = owner, callerAddr = caller, value = value, program = Program(code.toArray, state.config), input = input, callDepth = state.env.callDepth + 1 ) val worldAfterTransfer = this match { case CALL => worldAtCheckpoint.transfer(state.ownAddress, codeAddress, endowment) case _ => worldAtCheckpoint } state.context.copy( env = env, targetAddress = codeAddress, startGas = startGas, world = worldAfterTransfer, initialAddressesToDelete = state.addressesToDelete, initialAddressesTouched = if (isStateless) state.addressesTouched else state.addressesTouched + codeAddress, isStaticCall = state.context.isStaticCall || this.isStatic, originalStorageValues = state.context.originalStorageValues ) } val result = PrecompiledContracts.getContractForAddress(codeAddress, state.config) match { case Some(contract) => val context = prepareProgramContext(ByteString()) contract.run(context) case None => val code = state.world.getCode(codeAddress) val context = prepareProgramContext(code) VM.run(context, state.isDebugTraceEnabled) } //println(s"result: $result") state.mergeParallelRaceConditions(result.parallelRaceConditions) state.withReturnDataBuffer(result.returnData) // NOTE even if result.isRevert, we'll still put returnData to memory, // which could be reason message etc that could be used by caller. if (result.error.isEmpty) { val sizeCap = math.min(outSize.intValueSafe, result.returnData.size) if (sizeCap >= 0) { val output = result.returnData.take(sizeCap) state.memory.store(outOffset.intValueSafe, output) } } if (result.error.isEmpty && !result.isRevert) { // everything ok state.stack.push(DataWord.One) state .spendGas(-result.gasRemaining) .refundGas(result.gasRefund) .withWorld(result.world) .withAddAddressesToDelete(result.addressesToDelete) .withAddAddressesTouched(result.addressesTouched) .withTxLogs(result.txLogs) .step() } else { state.stack.push(DataWord.Zero) //println(s"error in $this: ${error} with result: ${result}") // Speical case for #2675119 // https://github.com/ethereum/go-ethereum/pull/3341/files#r89547994 // Parity has a bad implementation of EIP 161. That caused account // 0000000000000000000000000000000000000003 to be deleted in block 2675119, // even though the deletion should have been reverted due to an out of gas error. // Geth didn't handle revertals at all (hence today's bug), but because of this, // there wasn't a consensus failure 2 days ago. To avoid rewinding the chain, // we added this special case for the Parity bug. if (state.config.eip161Patch && codeAddress == PrecompiledContracts.Rip160Addr) { state.withAddAddressTouched(codeAddress) } if (result.isRevert && result.error.isEmpty) { state.spendGas(-result.gasRemaining) } // do not relay error to parent state, since it's only of the sub-routine // the error result may be caused by parallel condition, so merge all possible modifies state .withParallelRaceCondition(ProgramState.OnError) .withWorld(checkpoint.mergeRaceConditions(result.world)) .step() } } else { // invalid call state.stack.push(DataWord.Zero) if (endowment <= state.ownBalance) { state.withParallelRaceCondition(ProgramState.OnAccount) } state .spendGas(-startGas) .step() } } } final protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord, DataWord, DataWord, DataWord, DataWord, DataWord)): Long = { val (gas, target, callValue, inOffset, inSize, outOffset, outSize) = params // TODO how about gas < 0? return a Long.MaxValue? val endowment = callValue val gMemIn = state.config.calcMemCost(state.memory.size, inOffset.longValueSafe, inSize.longValueSafe) val gMemOut = state.config.calcMemCost(state.memory.size, outOffset.longValueSafe, outSize.longValueSafe) val gMem = math.max(gMemIn, gMemOut) // FIXME: these are calculated twice (for gas and exec), especially account existence. Can we do better? [EC-243] val gExtra = gasExtra(state, endowment, Address(target)) val gAdjust = gasAdjust(state, gas.longValueSafe, gExtra + gMem) gExtra + gMem + gAdjust } private def gasAdjust[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], gRequest: Long, gConsumed: Long): Long = { val gLeft = state.gas - gConsumed if (state.config.subGasCapDivisor.isDefined && gLeft >= 0) { math.min(gRequest, state.config.gasCap(gLeft)) } else { gRequest } } private def gasExtra[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], endowment: DataWord, target: Address): Long = { val c_new = this match { case CALL => if (state.config.eip161) { if (state.world.isAccountDead(target) && endowment.compare(DataWord.Zero) != 0) { state.config.feeSchedule.G_newaccount } else { 0 } } else { if (!state.world.isAccountExist(target)) { state.config.feeSchedule.G_newaccount } else { 0 } } case _ => 0 } val c_xfer = if (endowment.isZero) 0 else state.config.feeSchedule.G_callvalue state.config.feeSchedule.G_call + c_xfer + c_new } } /** * (cxf1) Message-call into an account */ case object CALL extends CallOp(0xf1, 7, 1, hasValue = true, isStateless = false, isStatic = false) /** * (0xf2) Calls self, but grabbing the code from the * TO argument instead of from one's own address */ case object CALLCODE extends CallOp(0xf2, 7, 1, hasValue = true, isStateless = true, isStatic = false) /** * (0xf4) similar in idea to CALLCODE, except that it propagates the sender and value * from the parent scope to the child scope, ie. the call created has the same sender * and value as the original call. * also the Value parameter is omitted for this opCode */ case object DELEGATECALL extends CallOp(0xf4, 6, 1, hasValue = false, isStateless = true, isStatic = false) /** * (0xfa) opcode that can be used to call another contract (or itself) while disallowing any * modifications to the state during the call (and its subcalls, if present). * Any opcode that attempts to perform such a modification (see below for details) * will result in an exception instead of performing the modification. */ case object STATICCALL extends CallOp(0xfa, 6, 1, hasValue = false, isStateless = false, isStatic = true) case object RETURN extends OpCode[(DataWord, DataWord)](0xf3, 2, 0) { protected def constGas(s: FeeSchedule) = s.G_zero protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(offset, size) = state.stack.pop(2) if (offset.compareTo(DataWord.MaxInt) > 0 || size.compareTo(DataWord.MaxInt) > 0) { state.withError(ArithmeticException) } (offset, size) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): ProgramState[W, S] = { val (offset, size) = params val data = state.memory.load(offset.intValueSafe, size.intValueSafe) state.withReturnData(data).halt() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): Long = { val (offset, size) = params state.config.calcMemCost(state.memory.size, offset.longValueSafe, size.longValueSafe) } } case object REVERT extends OpCode[(DataWord, DataWord)](0xfd, 2, 0) { protected def constGas(s: FeeSchedule) = s.G_zero protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(offset, size) = state.stack.pop(2) if (offset.compareTo(DataWord.MaxInt) > 0 || size.compareTo(DataWord.MaxInt) > 0) { state.withError(ArithmeticException) } (offset, size) } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): ProgramState[W, S] = { val (offset, size) = params val ret = state.memory.load(offset.intValueSafe, size.intValueSafe) state.withReturnData(ret).halt().revert() } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: (DataWord, DataWord)): Long = { val (offset, size) = params state.config.calcMemCost(state.memory.size, offset.longValueSafe, size.longValueSafe) } } case object INVALID extends OpCode[Unit](0xfe, 0, 0) with ConstGas[Unit] { protected def constGas(s: FeeSchedule) = s.G_zero protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = () protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: Unit): ProgramState[W, S] = state.withError(InvalidOpCode(code)) } /** * Also as SUICIDE, Renaming SUICIDE opcode to SELFDESTRUCT as in eip-6 * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-6.md */ case object SELFDESTRUCT extends OpCode[DataWord](0xff, 1, 0) { protected def constGas(s: FeeSchedule) = s.G_selfdestruct protected def getParams[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S]) = { val List(refundAddr) = state.stack.pop() refundAddr } protected def exec[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): ProgramState[W, S] = { if (state.context.isStaticCall) { state.withError(StaticCallModification) } else { val refundAddr = params val refundAddress = Address(refundAddr) //println(s"refundAddress: $refundAddress in SELFDESTRUCT") val gasRefund = if (state.addressesToDelete contains state.ownAddress) { 0 } else { state.config.feeSchedule.R_selfdestruct } val world = state.world.transfer(state.ownAddress, refundAddress, state.ownBalance) state .withWorld(world) .refundGas(gasRefund) .withAddAddressToDelete(state.ownAddress) .withAddAddressTouched(refundAddress) .halt } } protected def variableGas[W <: WorldState[W, S], S <: Storage[S]](state: ProgramState[W, S], params: DataWord): Long = { val refundAddr = params val refundAddress = Address(refundAddr) if (state.config.eip161) { if (state.world.isAccountDead(refundAddress) && state.world.getBalance(state.ownAddress).nonZero) { state.config.feeSchedule.G_newaccount } else { 0 } } else { if (state.config.chargeSelfDestructForNewAccount && !state.world.isAccountExist(refundAddress)) { state.config.feeSchedule.G_newaccount } else { 0 } } } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Tione.V20191022.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateNotebookInstanceResponse : AbstractModel { /// <summary> /// Notebook实例名字 /// </summary> [JsonProperty("NotebookInstanceName")] public string NotebookInstanceName{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "NotebookInstanceName", this.NotebookInstanceName); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/chime/Chime_EXPORTS.h> #include <aws/chime/model/Origination.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Chime { namespace Model { class AWS_CHIME_API GetVoiceConnectorOriginationResult { public: GetVoiceConnectorOriginationResult(); GetVoiceConnectorOriginationResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); GetVoiceConnectorOriginationResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The origination setting details.</p> */ inline const Origination& GetOrigination() const{ return m_origination; } /** * <p>The origination setting details.</p> */ inline void SetOrigination(const Origination& value) { m_origination = value; } /** * <p>The origination setting details.</p> */ inline void SetOrigination(Origination&& value) { m_origination = std::move(value); } /** * <p>The origination setting details.</p> */ inline GetVoiceConnectorOriginationResult& WithOrigination(const Origination& value) { SetOrigination(value); return *this;} /** * <p>The origination setting details.</p> */ inline GetVoiceConnectorOriginationResult& WithOrigination(Origination&& value) { SetOrigination(std::move(value)); return *this;} private: Origination m_origination; }; } // namespace Model } // namespace Chime } // namespace Aws
{ "pile_set_name": "Github" }
import yt import matplotlib.cm as cm # Load the dataset. ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") # Create projections using each colormap available. p = yt.ProjectionPlot(ds, "z", "density", weight_field="density", width=0.4) for cmap in cm.datad: if cmap.startswith("idl"): continue p.set_cmap(field="density", cmap=cmap) p.annotate_title(cmap) p.save("Projection_%s.png" % cmap.replace(" ", "_"))
{ "pile_set_name": "Github" }
// Copyright 2017 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 go1.9 // +build darwin dragonfly freebsd linux netbsd openbsd solaris package ipv6 import ( "net" "golang.org/x/net/internal/socket" ) func (c *payloadHandler) readFrom(b []byte) (int, *ControlMessage, net.Addr, error) { c.rawOpt.RLock() m := socket.Message{ Buffers: [][]byte{b}, OOB: NewControlMessage(c.rawOpt.cflags), } c.rawOpt.RUnlock() switch c.PacketConn.(type) { case *net.UDPConn: if err := c.RecvMsg(&m, 0); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } case *net.IPConn: if err := c.RecvMsg(&m, 0); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } default: return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errInvalidConnType} } var cm *ControlMessage if m.NN > 0 { cm = new(ControlMessage) if err := cm.Parse(m.OOB[:m.NN]); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } cm.Src = netAddrToIP16(m.Addr) } return m.N, cm, m.Addr, nil } func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (int, error) { m := socket.Message{ Buffers: [][]byte{b}, OOB: cm.Marshal(), Addr: dst, } err := c.SendMsg(&m, 0) if err != nil { err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Addr: opAddr(dst), Err: err} } return m.N, err }
{ "pile_set_name": "Github" }
-Xlog-implicits
{ "pile_set_name": "Github" }
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.windows; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.SPDSettings; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene; import com.shatteredpixel.shatteredpixeldungeon.ui.ItemSlot; import com.shatteredpixel.shatteredpixeldungeon.ui.RedButton; import com.shatteredpixel.shatteredpixeldungeon.ui.RenderedTextBlock; import com.shatteredpixel.shatteredpixeldungeon.ui.Window; import java.util.ArrayList; import java.util.Comparator; public class WndItem extends Window { //only one wnditem can appear at a time private static WndItem INSTANCE; private static final float BUTTON_HEIGHT = 16; private static final float GAP = 2; private static final int WIDTH_MIN = 120; private static final int WIDTH_MAX = 220; public WndItem( final WndBag owner, final Item item ){ this( owner, item, owner != null ); } public WndItem( final WndBag owner, final Item item , final boolean options ) { super(); if( INSTANCE != null ){ INSTANCE.hide(); } INSTANCE = this; int width = WIDTH_MIN; RenderedTextBlock info = PixelScene.renderTextBlock( item.info(), 6 ); info.maxWidth(width); //info box can go out of the screen on landscape, so widen it while (SPDSettings.landscape() && info.height() > 100 && width < WIDTH_MAX){ width += 20; info.maxWidth(width); } IconTitle titlebar = new IconTitle( item ); titlebar.setRect( 0, 0, width, 0 ); add( titlebar ); if (item.levelKnown && item.level() > 0) { titlebar.color( ItemSlot.UPGRADED ); } else if (item.levelKnown && item.level() < 0) { titlebar.color( ItemSlot.DEGRADED ); } info.setPos(titlebar.left(), titlebar.bottom() + GAP); add( info ); float y = info.top() + info.height() + GAP; if (Dungeon.hero.isAlive() && options) { ArrayList<RedButton> buttons = new ArrayList<>(); for (final String action:item.actions( Dungeon.hero )) { RedButton btn = new RedButton( Messages.get(item, "ac_" + action), 8 ) { @Override protected void onClick() { hide(); if (owner != null && owner.parent != null) owner.hide(); if (Dungeon.hero.isAlive()) item.execute( Dungeon.hero, action ); } }; btn.setSize( btn.reqWidth(), BUTTON_HEIGHT ); buttons.add(btn); add( btn ); if (action.equals(item.defaultAction)) { btn.textColor( TITLE_COLOR ); } } y = layoutButtons(buttons, width, y); } resize( width, (int)(y) ); } private static float layoutButtons(ArrayList<RedButton> buttons, float width, float y){ ArrayList<RedButton> curRow = new ArrayList<>(); float widthLeftThisRow = width; while( !buttons.isEmpty() ){ RedButton btn = buttons.get(0); widthLeftThisRow -= btn.width(); if (curRow.isEmpty()) { curRow.add(btn); buttons.remove(btn); } else { widthLeftThisRow -= 1; if (widthLeftThisRow >= 0) { curRow.add(btn); buttons.remove(btn); } } //layout current row. Currently forces a max of 3 buttons but can work with more if (buttons.isEmpty() || widthLeftThisRow <= 0 || curRow.size() >= 3){ //re-use this variable for laying out the buttons widthLeftThisRow = width - (curRow.size()-1); for (RedButton b : curRow){ widthLeftThisRow -= b.width(); } //while we still have space in this row, find the shortest button(s) and extend them while (widthLeftThisRow > 0){ ArrayList<RedButton> shortest = new ArrayList<>(); RedButton secondShortest = null; for (RedButton b : curRow) { if (shortest.isEmpty()) { shortest.add(b); } else { if (b.width() < shortest.get(0).width()) { secondShortest = shortest.get(0); shortest.clear(); shortest.add(b); } else if (b.width() == shortest.get(0).width()) { shortest.add(b); } else if (secondShortest == null || secondShortest.width() > b.width()){ secondShortest = b; } } } float widthToGrow; if (secondShortest == null){ widthToGrow = widthLeftThisRow / shortest.size(); widthLeftThisRow = 0; } else { widthToGrow = secondShortest.width() - shortest.get(0).width(); if ((widthToGrow * shortest.size()) >= widthLeftThisRow){ widthToGrow = widthLeftThisRow / shortest.size(); widthLeftThisRow = 0; } else { widthLeftThisRow -= widthToGrow * shortest.size(); } } for (RedButton toGrow : shortest){ toGrow.setRect(0, 0, toGrow.width()+widthToGrow, toGrow.height()); } } //finally set positions float x = 0; for (RedButton b : curRow){ b.setRect(x, y, b.width(), b.height()); x += b.width() + 1; } //move to next line and reset variables y += BUTTON_HEIGHT+1; widthLeftThisRow = width; curRow.clear(); } } return y - 1; } @Override public void hide() { super.hide(); if (INSTANCE == this){ INSTANCE = null; } } private static Comparator<RedButton> widthComparator = new Comparator<RedButton>() { @Override public int compare(RedButton lhs, RedButton rhs) { if (lhs.width() < rhs.width()){ return -1; } else if (lhs.width() == rhs.width()){ return 0; } else { return 1; } } }; }
{ "pile_set_name": "Github" }
file (GLOB SOURCE_FILES parser.cpp) init_target (test_http) build_test (${TARGET_NAME} ${SOURCE_FILES}) link_boost () final_target () set_target_properties(${TARGET_NAME} PROPERTIES FOLDER "test")
{ "pile_set_name": "Github" }
# [20170202 码农日报](02.md) [前端日报](http://caibaojian.com/c/news)栏目数据来自[码农头条](http://hao.caibaojian.com/)(我开发的爬虫),每日分享前端、移动开发、设计、资源和资讯等,为开发者提供动力,点击Star按钮来关注这个项目,点击Watch来收听每日的更新[Github主页](https://github.com/kujian/frontendDaily) * [Java Mybatis 框架入门教程](http://hao.caibaojian.com/24497.html) (程序员俱乐部) * [优秀设计的 10 个标准](http://hao.caibaojian.com/24515.html) (程序师视野) * [如何通过提前Bake Docker镜像加快基础设施的启动速度](http://hao.caibaojian.com/24465.html) (Docker精选) * [教你绘制深夜加班的场景插画](http://hao.caibaojian.com/24532.html) (优秀网页设计) * [如何管理 Vim 插件](http://hao.caibaojian.com/24498.html) (程序员俱乐部) *** * [浅谈 Java 中 MongoDB NoSQL数据库使用指南](http://hao.caibaojian.com/24516.html) (程序师视野) * [iPhone这个铃声,多少人只听过开头却没听过完整版](http://hao.caibaojian.com/24467.html) (全栈开发者) * [route 命令](http://hao.caibaojian.com/24538.html) (伯乐在线官方微博) * [一名软件工程师实习生的创业公司体验](http://hao.caibaojian.com/24499.html) (程序员俱乐部) * [C语言实现LRU缓存](http://hao.caibaojian.com/24518.html) (实验楼官方微博) *** * [OpenSSL 在 Apache 和 Dovecot 下的使用(一)](http://hao.caibaojian.com/24478.html) (Linux中国) * [An Intro to Templates in Go &#8211; Contextual Encoding](http://hao.caibaojian.com/24539.html) (开发者头条) * [PHP Socket 编程过程详解](http://hao.caibaojian.com/24500.html) (程序员俱乐部) * [每个 Java 开发者应该知道并爱上的 8 个工具](http://hao.caibaojian.com/24519.html) (实验楼官方微博) * [小程序之API管理](http://hao.caibaojian.com/24485.html) (阿里云云栖社区) *** * [Chrome 扩展 “智慧驾培助手” 开发心得](http://hao.caibaojian.com/24540.html) (开发者头条) * [LinkedIn架构演化历史解析](http://hao.caibaojian.com/24501.html) (程序员俱乐部) * [在 Java 中运用动态挂载实现 Bug 的热修复](http://hao.caibaojian.com/24520.html) (酷勤网-程序员的那点事) * [史上最全的物联网资料](http://hao.caibaojian.com/24486.html) (阿里云云栖社区) * [优雅地关闭 Kubernetes 中的 Nginx](http://hao.caibaojian.com/24541.html) (开发者头条) *** * [JavaScript 模块化编程(一):模块的写法](http://hao.caibaojian.com/24502.html) (程序员俱乐部) * [给所有开发者的 React Native 详细入门指南(第一阶段)](http://hao.caibaojian.com/24523.html) (IT程序狮) * [Stack Overflow 2016最新架构探秘](http://hao.caibaojian.com/24489.html) (JAVA大本营) * [热闹驱动开发](http://hao.caibaojian.com/24542.html) (开发者头条) * [JavaScript 很少为人所知的玩法](http://hao.caibaojian.com/24507.html) (开发者头条) *** * [Mac 上快速预览插件合辑](http://hao.caibaojian.com/24524.html) (IT程序狮) * [为什么你招聘不到程序员](http://hao.caibaojian.com/24490.html) (JAVA大本营) * [真正的 IT 男到底是什么样的](http://hao.caibaojian.com/24543.html) (开发者头条) * [免越狱 tweak 应用逆向开发](http://hao.caibaojian.com/24508.html) (开发者头条) * [使用 Vue 完成知乎日报 Web 版](http://hao.caibaojian.com/24525.html) (IT程序狮) 日报维护作者:[前端开发博客](http://caibaojian.com/)
{ "pile_set_name": "Github" }
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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. * */ using System.Collections.Generic; using Newtonsoft.Json; namespace IBM.Watson.Discovery.v2.Model { /// <summary> /// Returns the top values for the field specified. /// </summary> public class QueryTermAggregation : QueryAggregation { /// <summary> /// The field in the document used to generate top values from. /// </summary> [JsonProperty("field", NullValueHandling = NullValueHandling.Ignore)] public string Field { get; set; } /// <summary> /// The number of top values returned. /// </summary> [JsonProperty("count", NullValueHandling = NullValueHandling.Ignore)] public long? Count { get; set; } /// <summary> /// Identifier specified in the query request of this aggregation. /// </summary> [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } /// <summary> /// Array of top values for the field. /// </summary> [JsonProperty("results", NullValueHandling = NullValueHandling.Ignore)] public List<QueryTermAggregationResult> Results { get; set; } } }
{ "pile_set_name": "Github" }
public class HelloWorld { void testMethod() {} private int testVariable; }
{ "pile_set_name": "Github" }
### 欧美20余高级将领会议 2人确诊感染武汉肺炎 ------------------------ #### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) &nbsp;&nbsp;|&nbsp;&nbsp; [手把手翻墙教程](https://github.com/gfw-breaker/guides/wiki) &nbsp;&nbsp;|&nbsp;&nbsp; [禁闻聚合安卓版](https://github.com/gfw-breaker/bn-android) &nbsp;&nbsp;|&nbsp;&nbsp; [网门安卓版](https://github.com/oGate2/oGate) &nbsp;&nbsp;|&nbsp;&nbsp; [神州正道安卓版](https://github.com/SzzdOgate/update) <div><div class="featured_image"> <a href="https://i.ntdtv.com/assets/uploads/2020/03/GettyImages-696563190.jpg" target="_blank"> <figure> <img alt="欧美20余高级将领会议 2人确诊感染武汉肺炎" src="https://i.ntdtv.com/assets/uploads/2020/03/GettyImages-696563190-800x450.jpg"/> </figure><br/> </a> <span class="caption"> 8日,意大利陆军参谋长法里纳被验出确诊感染武汉肺炎。(WOJTEK RADWANSKI/AFP via Getty Images) </span> </div> </div><hr/> #### [翻墙必看视频(文昭、江峰、法轮功、八九六四、香港反送中...)](https://github.com/gfw-breaker/banned-news/blob/master/pages/link3.md) <div><div class="post_content" itemprop="articleBody"> <p> 【新唐人北京时间2020年03月13日讯】武汉病毒肆虐全球,本月6日美国驻欧陆军在 <ok href="https://www.ntdtv.com/gb/威斯巴登.htm"> 威斯巴登 </ok> 举行的一场陆军指挥官会议后,至少有两名欧洲高级军事指挥官感染 <ok href="https://www.ntdtv.com/gb/武汉肺炎.htm"> 武汉肺炎 </ok> ,驻欧美国陆军司令卡沃里已自我隔离,以防自己也有感染风险。 </p> <p> 美国驻欧陆军在 <ok href="https://www.ntdtv.com/gb/威斯巴登.htm"> 威斯巴登 </ok> (Wiesbaden)举行的会议上,共有来自 <ok href="https://www.ntdtv.com/gb/北大西洋公约组织.htm"> 北大西洋公约组织 </ok> (NATO)、欧洲联盟(EU)及欧美多国的24名高级军事代表齐聚一堂。 </p> <p> 美国陆军部长麦卡锡(Ryan McCarthy)表示,“基于充分考虑,并且遵循建议的规范”,卡沃里(Christopher Cavoli)以及多名德国威斯巴登美军要塞工作人员已自我隔离。 </p> <p> 美国驻欧陆军发言人陶玛希(John Tomassi)证实,这场感染可能发生于6日的美国驻欧陆军在威斯巴登举行的一场陆军指挥官会议上。但他未说明谁被视为在会议上的带原者。 </p> <p> 目前已有两名与会人士表明,他们的 <ok href="https://www.ntdtv.com/gb/武汉肺炎.htm"> 武汉肺炎 </ok> 检测结果呈阳性。包括57岁的武装部队总司令部指挥官米卡(Jaroslaw Mika)与 <ok href="https://www.ntdtv.com/gb/意大利.htm"> 意大利 </ok> 陆军参谋长法里纳(Salvatore Farina)。 </p> <figure class="wp-caption alignnone" id="attachment_102796563" style="width: 600px"> <img alt="" class="size-medium wp-image-102796563" src="https://i.ntdtv.com/assets/uploads/2020/03/GettyImages-631535326-600x376.jpg"> <br/><figcaption class="wp-caption-text"> <ok href="https://www.ntdtv.com/gb/波兰.htm"> 波兰 </ok> 武装部队总司令部指挥官米卡将军自德国返回后,确诊感染武汉肺炎。(NATALIA DOBRYSZYCKA/AFP via Getty Images) </figcaption><br/> </img> </figure><br/> <p> 米卡确诊感染武汉肺炎后,目前感觉状况良好,而与他同赴威斯巴登的人士已受隔离。法里纳返国后,也遵从政府当局发布的指示和卫生规范,“在自家公寓隔离”,当局也正在找出过去几天与法里纳接触的人士。 </p> <p> (责任编辑:卢勇信) </p> <div class="single_ad"> </div> </div> </div> <hr/> 手机上长按并复制下列链接或二维码分享本文章:<br/> https://github.com/gfw-breaker/banned-news/blob/master/pages/prog202/a102798930.md <br/> <a href='https://github.com/gfw-breaker/banned-news/blob/master/pages/prog202/a102798930.md'><img src='https://github.com/gfw-breaker/banned-news/blob/master/pages/prog202/a102798930.md.png'/></a> <br/> 原文地址(需翻墙访问):https://www.ntdtv.com/gb/2020/03/13/a102798930.html ------------------------ #### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) &nbsp;|&nbsp; [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md) &nbsp;| [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) | [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md) | [《共产主义的终极目的》](https://github.com/gfw-breaker/gczydzjmd.md/blob/master/README.md) <img src='http://gfw-breaker.win/banned-news/pages/prog202/a102798930.md' width='0px' height='0px'/>
{ "pile_set_name": "Github" }
@mixin button ($style: simple, $base-color: #4294f0) { @if type-of($style) == color { $base-color: $style; $style: simple; } // Grayscale button @if $base-color == grayscale($base-color) { @if $style == simple { @include simple($base-color, $grayscale: true); } @else if $style == shiny { @include shiny($base-color, $grayscale: true); } @else if $style == pill { @include pill($base-color, $grayscale: true); } } // Colored button @else { @if $style == simple { @include simple($base-color); } @else if $style == shiny { @include shiny($base-color); } @else if $style == pill { @include pill($base-color); } } &:disabled { opacity: 0.5; cursor: not-allowed; } } // Simple Button //************************************************************************// @mixin simple($base-color, $grayscale: false) { $color: hsl(0, 0, 100%); $border: adjust-color($base-color, $saturation: 9%, $lightness: -14%); $inset-shadow: adjust-color($base-color, $saturation: -8%, $lightness: 15%); $stop-gradient: adjust-color($base-color, $saturation: 9%, $lightness: -11%); $text-shadow: adjust-color($base-color, $saturation: 15%, $lightness: -18%); @if lightness($base-color) > 70% { $color: hsl(0, 0, 20%); $text-shadow: adjust-color($base-color, $saturation: 10%, $lightness: 4%); } @if $grayscale == true { $border: grayscale($border); $inset-shadow: grayscale($inset-shadow); $stop-gradient: grayscale($stop-gradient); $text-shadow: grayscale($text-shadow); } border: 1px solid $border; border-radius: 3px; box-shadow: inset 0 1px 0 0 $inset-shadow; color: $color; display: inline-block; font-size: 11px; font-weight: bold; @include linear-gradient ($base-color, $stop-gradient); padding: 7px 18px; text-decoration: none; text-shadow: 0 1px 0 $text-shadow; background-clip: padding-box; &:hover:not(:disabled) { $base-color-hover: adjust-color($base-color, $saturation: -4%, $lightness: -5%); $inset-shadow-hover: adjust-color($base-color, $saturation: -7%, $lightness: 5%); $stop-gradient-hover: adjust-color($base-color, $saturation: 8%, $lightness: -14%); @if $grayscale == true { $base-color-hover: grayscale($base-color-hover); $inset-shadow-hover: grayscale($inset-shadow-hover); $stop-gradient-hover: grayscale($stop-gradient-hover); } box-shadow: inset 0 1px 0 0 $inset-shadow-hover; cursor: pointer; @include linear-gradient ($base-color-hover, $stop-gradient-hover); } &:active:not(:disabled) { $border-active: adjust-color($base-color, $saturation: 9%, $lightness: -14%); $inset-shadow-active: adjust-color($base-color, $saturation: 7%, $lightness: -17%); @if $grayscale == true { $border-active: grayscale($border-active); $inset-shadow-active: grayscale($inset-shadow-active); } border: 1px solid $border-active; box-shadow: inset 0 0 8px 4px $inset-shadow-active, inset 0 0 8px 4px $inset-shadow-active, 0 1px 1px 0 #eee; } } // Shiny Button //************************************************************************// @mixin shiny($base-color, $grayscale: false) { $color: hsl(0, 0, 100%); $border: adjust-color($base-color, $red: -117, $green: -111, $blue: -81); $border-bottom: adjust-color($base-color, $red: -126, $green: -127, $blue: -122); $fourth-stop: adjust-color($base-color, $red: -79, $green: -70, $blue: -46); $inset-shadow: adjust-color($base-color, $red: 37, $green: 29, $blue: 12); $second-stop: adjust-color($base-color, $red: -56, $green: -50, $blue: -33); $text-shadow: adjust-color($base-color, $red: -140, $green: -141, $blue: -114); $third-stop: adjust-color($base-color, $red: -86, $green: -75, $blue: -48); @if lightness($base-color) > 70% { $color: hsl(0, 0, 20%); $text-shadow: adjust-color($base-color, $saturation: 10%, $lightness: 4%); } @if $grayscale == true { $border: grayscale($border); $border-bottom: grayscale($border-bottom); $fourth-stop: grayscale($fourth-stop); $inset-shadow: grayscale($inset-shadow); $second-stop: grayscale($second-stop); $text-shadow: grayscale($text-shadow); $third-stop: grayscale($third-stop); } border: 1px solid $border; border-bottom: 1px solid $border-bottom; border-radius: 5px; box-shadow: inset 0 1px 0 0 $inset-shadow; color: $color; display: inline-block; font-size: 14px; font-weight: bold; @include linear-gradient(top, $base-color 0%, $second-stop 50%, $third-stop 50%, $fourth-stop 100%); padding: 8px 20px; text-align: center; text-decoration: none; text-shadow: 0 -1px 1px $text-shadow; &:hover:not(:disabled) { $first-stop-hover: adjust-color($base-color, $red: -13, $green: -15, $blue: -18); $second-stop-hover: adjust-color($base-color, $red: -66, $green: -62, $blue: -51); $third-stop-hover: adjust-color($base-color, $red: -93, $green: -85, $blue: -66); $fourth-stop-hover: adjust-color($base-color, $red: -86, $green: -80, $blue: -63); @if $grayscale == true { $first-stop-hover: grayscale($first-stop-hover); $second-stop-hover: grayscale($second-stop-hover); $third-stop-hover: grayscale($third-stop-hover); $fourth-stop-hover: grayscale($fourth-stop-hover); } cursor: pointer; @include linear-gradient(top, $first-stop-hover 0%, $second-stop-hover 50%, $third-stop-hover 50%, $fourth-stop-hover 100%); } &:active:not(:disabled) { $inset-shadow-active: adjust-color($base-color, $red: -111, $green: -116, $blue: -122); @if $grayscale == true { $inset-shadow-active: grayscale($inset-shadow-active); } box-shadow: inset 0 0 20px 0 $inset-shadow-active, 0 1px 0 #fff; } } // Pill Button //************************************************************************// @mixin pill($base-color, $grayscale: false) { $color: hsl(0, 0, 100%); $border-bottom: adjust-color($base-color, $hue: 8, $saturation: -11%, $lightness: -26%); $border-sides: adjust-color($base-color, $hue: 4, $saturation: -21%, $lightness: -21%); $border-top: adjust-color($base-color, $hue: -1, $saturation: -30%, $lightness: -15%); $inset-shadow: adjust-color($base-color, $hue: -1, $saturation: -1%, $lightness: 7%); $stop-gradient: adjust-color($base-color, $hue: 8, $saturation: 14%, $lightness: -10%); $text-shadow: adjust-color($base-color, $hue: 5, $saturation: -19%, $lightness: -15%); @if lightness($base-color) > 70% { $color: hsl(0, 0, 20%); $text-shadow: adjust-color($base-color, $saturation: 10%, $lightness: 4%); } @if $grayscale == true { $border-bottom: grayscale($border-bottom); $border-sides: grayscale($border-sides); $border-top: grayscale($border-top); $inset-shadow: grayscale($inset-shadow); $stop-gradient: grayscale($stop-gradient); $text-shadow: grayscale($text-shadow); } border: 1px solid $border-top; border-color: $border-top $border-sides $border-bottom; border-radius: 16px; box-shadow: inset 0 1px 0 0 $inset-shadow, 0 1px 2px 0 #b3b3b3; color: $color; display: inline-block; font-size: 11px; font-weight: normal; line-height: 1; @include linear-gradient ($base-color, $stop-gradient); padding: 5px 16px; text-align: center; text-decoration: none; text-shadow: 0 -1px 1px $text-shadow; background-clip: padding-box; &:hover:not(:disabled) { $base-color-hover: adjust-color($base-color, $lightness: -4.5%); $border-bottom: adjust-color($base-color, $hue: 8, $saturation: 13.5%, $lightness: -32%); $border-sides: adjust-color($base-color, $hue: 4, $saturation: -2%, $lightness: -27%); $border-top: adjust-color($base-color, $hue: -1, $saturation: -17%, $lightness: -21%); $inset-shadow-hover: adjust-color($base-color, $saturation: -1%, $lightness: 3%); $stop-gradient-hover: adjust-color($base-color, $hue: 8, $saturation: -4%, $lightness: -15.5%); $text-shadow-hover: adjust-color($base-color, $hue: 5, $saturation: -5%, $lightness: -22%); @if $grayscale == true { $base-color-hover: grayscale($base-color-hover); $border-bottom: grayscale($border-bottom); $border-sides: grayscale($border-sides); $border-top: grayscale($border-top); $inset-shadow-hover: grayscale($inset-shadow-hover); $stop-gradient-hover: grayscale($stop-gradient-hover); $text-shadow-hover: grayscale($text-shadow-hover); } border: 1px solid $border-top; border-color: $border-top $border-sides $border-bottom; box-shadow: inset 0 1px 0 0 $inset-shadow-hover; cursor: pointer; @include linear-gradient ($base-color-hover, $stop-gradient-hover); text-shadow: 0 -1px 1px $text-shadow-hover; background-clip: padding-box; } &:active:not(:disabled) { $active-color: adjust-color($base-color, $hue: 4, $saturation: -12%, $lightness: -10%); $border-active: adjust-color($base-color, $hue: 6, $saturation: -2.5%, $lightness: -30%); $border-bottom-active: adjust-color($base-color, $hue: 11, $saturation: 6%, $lightness: -31%); $inset-shadow-active: adjust-color($base-color, $hue: 9, $saturation: 2%, $lightness: -21.5%); $text-shadow-active: adjust-color($base-color, $hue: 5, $saturation: -12%, $lightness: -21.5%); @if $grayscale == true { $active-color: grayscale($active-color); $border-active: grayscale($border-active); $border-bottom-active: grayscale($border-bottom-active); $inset-shadow-active: grayscale($inset-shadow-active); $text-shadow-active: grayscale($text-shadow-active); } background: $active-color; border: 1px solid $border-active; border-bottom: 1px solid $border-bottom-active; box-shadow: inset 0 0 6px 3px $inset-shadow-active, 0 1px 0 0 #fff; text-shadow: 0 -1px 1px $text-shadow-active; } }
{ "pile_set_name": "Github" }
# frozen_string_literal: true require 'spec_helper' RSpec.describe Gitlab::HookData::BaseBuilder do describe '#absolute_image_urls' do let(:subclass) do Class.new(described_class) do public :absolute_image_urls end end using RSpec::Parameterized::TableSyntax context 'with an upload prefix specified' do let(:project_with_path) { double(full_path: 'baz/bar') } let(:object_with_project) { double(project: project_with_path) } subject { subclass.new(object_with_project) } where do { 'relative image URL' => { input: '![an image](foo.png)', output: "![an image](#{Gitlab.config.gitlab.url}/foo.png)" }, 'absolute upload URL' => { input: '![an image](/uploads/foo.png)', output: "![an image](#{Gitlab.config.gitlab.url}/baz/bar/uploads/foo.png)" }, 'absolute non-upload URL' => { input: '![an image](/downloads/foo.png)', output: "![an image](#{Gitlab.config.gitlab.url}/downloads/foo.png)" } } end with_them do it { expect(subject.absolute_image_urls(input)).to eq(output) } end end context 'without an upload prefix specified' do subject { subclass.new(nil) } where do { 'relative image URL' => { input: '![an image](foo.png)', output: "![an image](#{Gitlab.config.gitlab.url}/foo.png)" }, 'absolute upload URL' => { input: '![an image](/uploads/foo.png)', output: "![an image](#{Gitlab.config.gitlab.url}/uploads/foo.png)" }, 'absolute non-upload URL' => { input: '![an image](/downloads/foo.png)', output: "![an image](#{Gitlab.config.gitlab.url}/downloads/foo.png)" }, 'HTTP URL' => { input: '![an image](http://example.com/foo.png)', output: '![an image](http://example.com/foo.png)' }, 'HTTPS URL' => { input: '![an image](https://example.com/foo.png)', output: '![an image](https://example.com/foo.png)' }, 'protocol-relative URL' => { input: '![an image](//example.com/foo.png)', output: '![an image](//example.com/foo.png)' }, 'URL reference by title' => { input: "![foo]\n\n[foo]: foo.png", output: "![foo]\n\n[foo]: foo.png" }, 'URL reference by label' => { input: "![][foo]\n\n[foo]: foo.png", output: "![][foo]\n\n[foo]: foo.png" }, 'in Markdown inline code block' => { input: '`![an image](foo.png)`', output: "`![an image](#{Gitlab.config.gitlab.url}/foo.png)`" }, 'in HTML tag on the same line' => { input: '<p>![an image](foo.png)</p>', output: "<p>![an image](#{Gitlab.config.gitlab.url}/foo.png)</p>" }, 'in Markdown multi-line code block' => { input: "```\n![an image](foo.png)\n```", output: "```\n![an image](foo.png)\n```" }, 'in HTML tag on different lines' => { input: "<p>\n![an image](foo.png)\n</p>", output: "<p>\n![an image](foo.png)\n</p>" } } end with_them do it { expect(subject.absolute_image_urls(input)).to eq(output) } end end end end
{ "pile_set_name": "Github" }
{ "frameGrid" : { "size" : [16, 16], "dimensions" : [2, 1], "names" : [ [ "front", "back" ] ] } }
{ "pile_set_name": "Github" }
(* Coq JavaScript API. Based in the coq source code and js_of_ocaml. * * By Emilio J. Gallego Arias, Mines ParisTech, Paris. * LICENSE: GPLv3+ * * This file contains the basic coq library definitions used in jscoq. *) (* Information about a Coq library. * * We could have accessed Loadpath.t, etc..., but we've opted to keep * this module separated from Coq *) type coq_pkg = { pkg_id : string list; vo_files : (string * Digest.t) list; cma_files : (string * Digest.t) list; } type coq_bundle = { desc : string; deps : string list; pkgs : coq_pkg list; } val to_dir : coq_pkg -> string val to_desc : coq_pkg -> string val no_files : coq_pkg -> int (* JSON handling *) open Yojson.Safe (* XXX Use PPX *) val coq_pkg_to_yojson : coq_pkg -> json val coq_pkg_of_yojson : json -> (coq_pkg, string) Result.result val coq_bundle_to_yojson : coq_bundle -> json val coq_bundle_of_yojson : json -> (coq_bundle, string) Result.result
{ "pile_set_name": "Github" }
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1beta1 import ( v1beta1 "k8s.io/api/events/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) // EventsGetter has a method to return a EventInterface. // A group's client should implement this interface. type EventsGetter interface { Events(namespace string) EventInterface } // EventInterface has methods to work with Event resources. type EventInterface interface { Create(*v1beta1.Event) (*v1beta1.Event, error) Update(*v1beta1.Event) (*v1beta1.Event, error) Delete(name string, options *v1.DeleteOptions) error DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error Get(name string, options v1.GetOptions) (*v1beta1.Event, error) List(opts v1.ListOptions) (*v1beta1.EventList, error) Watch(opts v1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Event, err error) EventExpansion } // events implements EventInterface type events struct { client rest.Interface ns string } // newEvents returns a Events func newEvents(c *EventsV1beta1Client, namespace string) *events { return &events{ client: c.RESTClient(), ns: namespace, } } // Get takes name of the event, and returns the corresponding event object, and an error if there is any. func (c *events) Get(name string, options v1.GetOptions) (result *v1beta1.Event, err error) { result = &v1beta1.Event{} err = c.client.Get(). Namespace(c.ns). Resource("events"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(). Into(result) return } // List takes label and field selectors, and returns the list of Events that match those selectors. func (c *events) List(opts v1.ListOptions) (result *v1beta1.EventList, err error) { result = &v1beta1.EventList{} err = c.client.Get(). Namespace(c.ns). Resource("events"). VersionedParams(&opts, scheme.ParameterCodec). Do(). Into(result) return } // Watch returns a watch.Interface that watches the requested events. func (c *events) Watch(opts v1.ListOptions) (watch.Interface, error) { opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("events"). VersionedParams(&opts, scheme.ParameterCodec). Watch() } // Create takes the representation of a event and creates it. Returns the server's representation of the event, and an error, if there is any. func (c *events) Create(event *v1beta1.Event) (result *v1beta1.Event, err error) { result = &v1beta1.Event{} err = c.client.Post(). Namespace(c.ns). Resource("events"). Body(event). Do(). Into(result) return } // Update takes the representation of a event and updates it. Returns the server's representation of the event, and an error, if there is any. func (c *events) Update(event *v1beta1.Event) (result *v1beta1.Event, err error) { result = &v1beta1.Event{} err = c.client.Put(). Namespace(c.ns). Resource("events"). Name(event.Name). Body(event). Do(). Into(result) return } // Delete takes name of the event and deletes it. Returns an error if one occurs. func (c *events) Delete(name string, options *v1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("events"). Name(name). Body(options). Do(). Error() } // DeleteCollection deletes a collection of objects. func (c *events) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("events"). VersionedParams(&listOptions, scheme.ParameterCodec). Body(options). Do(). Error() } // Patch applies the patch and returns the patched event. func (c *events) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Event, err error) { result = &v1beta1.Event{} err = c.client.Patch(pt). Namespace(c.ns). Resource("events"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">{ "Info": [ { "IsSuccess": "True", "InAddress": "基隆市中山區復興路181號", "InSRS": "EPSG:4326", "InFuzzyType": "[單雙號機制]+[最近門牌號機制]", "InFuzzyBuffer": "0", "InIsOnlyFullMatch": "False", "InIsLockCounty": "True", "InIsLockTown": "False", "InIsLockVillage": "False", "InIsLockRoadSection": "False", "InIsLockLane": "False", "InIsLockAlley": "False", "InIsLockArea": "False", "InIsSameNumber_SubNumber": "True", "InCanIgnoreVillage": "True", "InCanIgnoreNeighborhood": "True", "InReturnMaxCount": "0", "OutTotal": "1", "OutMatchType": "完全比對", "OutMatchCode": "[基隆市]\tFULL:1", "OutTraceInfo": "[基隆市]\t { 完全比對 } 找到符合的門牌地址" } ], "AddressList": [ { "FULL_ADDR": "基隆市中山區德和里32鄰復興路181號", "COUNTY": "基隆市", "TOWN": "中山區", "VILLAGE": "德和里", "NEIGHBORHOOD": "32鄰", "ROAD": "復興路", "SECTION": "", "LANE": "", "ALLEY": "", "SUB_ALLEY": "", "TONG": "", "NUMBER": "181號", "X": 121.726438, "Y": 25.145870 } ] }</string>
{ "pile_set_name": "Github" }
## Security Please report any security issue to [[email protected]](mailto:[email protected]) as soon as it is discovered. This library limits its runtime dependencies in order to reduce the total cost of ownership as much as can be, but all consumers should remain vigilant and have their security stakeholders review all third-party products (3PP) like this one and their dependencies.
{ "pile_set_name": "Github" }
The Czech Republic and Spain played out a scoreless draw in their World Cup group six qualifier on Wednesday, in a match that never lived up to expectations. The Czechs were facing their first big test since they reached the Euro 96 final, while Real Madrid's teenage striker Raul was looking to spark a depleted Spanish attack in his first full international. Both sides opened their World Cup campaigns last month with high-scoring victories over the two weakest teams in the group, Spain winning 6-2 in the Faroe Islands and the Czechs thrashing Malta 6-0. But Yugoslavia have already collected three wins and Slovakia two against the same two hapless victims and neither team could afford to give ground in Prague. Like two heavyweights feeling each other out in the early rounds, both teams started tentatively, waiting to pounce on the other's mistakes. The Spaniard's were the first to flinch when Kaiserslautern striker Pavel Kuka's cross found an unmarked Karel Poborsky just outside the crease. But the Manchester United midfielder failed to control the ball, wasting what would turn out be one of the game's few good scoring chances. Next it was the Czechs turn to falter. Newcastle United goalkeeper Pavel Srnicek, winning his first cap in over a year, tried to clear the ball, but hit attacker Alfonso Perez and watched helplessly as it rolled just wide of the net. The Czechs picked up their play in the second half, putting Spain on their heels for the rest of the game. "I don't think we lost points tonight because they are such an excellent team. They played strongly in the defence and its too bad we missed out on the two great chances we had," said Czech striker Patrik Berger. Teams: Czech Republic: 1-Pavel Srnicek, 2-Radoslav Latal, 3-Jan Suchoparek, 4-Pavel Nedved (15-Martin Frydek, 86th), 5-Miroslav Kadlec, 6-Michal Hornak, 7-Jiri Nemec, 8-Karel Poborsky (17-Vladimir Smicer, 58th), 9-Pavel Kuka, 10-Patrik Berger, 11-Radek Bejbl Spain: 1-Andoni Zubizarreta, 2-Abelardo Fernandez, 3-Sergi Barjuan, 4-Rafael Alkorta, 5-Miguel Angel Nadal, 6-Fernando Hierro, 7-Raul Gonzalez, 8-Luis Enrique Martinez, 9-Guillermo Amor (18-Ismael Urzaiz, 76th), 10-Julen Guerrero (14-Josep Guardiola, 52nd), 11-Alfonso Perez (15-Roberto Rios, 73rd)
{ "pile_set_name": "Github" }
"use strict"; module.exports = function (t, a) { var x = {}; a(t.call([3, "raz", {}, x, {}], x), 3, "Regular"); a(t.call([3, "raz", NaN, {}, NaN], NaN), 2, "NaN"); a(t.call([3, "raz", 0, {}, -0], -0), 2, "-0"); a(t.call([3, "raz", -0, {}, 0], +0), 2, "+0"); a(t.call([3, "raz", NaN, {}, NaN], NaN, 3), 4, "fromIndex"); a(t.call([3, "raz", NaN, {}, NaN], NaN, -1), 4, "fromIndex negative #1"); a(t.call([3, "raz", NaN, {}, NaN], NaN, -2), 4, "fromIndex negative #2"); a(t.call([3, "raz", NaN, {}, NaN], NaN, -3), 2, "fromIndex negative #3"); };
{ "pile_set_name": "Github" }
a524a76c85f55b7d63914fc1543a5268
{ "pile_set_name": "Github" }
/** * Estonian translation for bootstrap-datepicker * Ando Roots <https://github.com/anroots> * Fixes by Illimar Tambek <<https://github.com/ragulka> */ ;(function($){ $.fn.datepicker.dates['et'] = { days: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev", "Pühapäev"], daysShort: ["Pühap", "Esmasp", "Teisip", "Kolmap", "Neljap", "Reede", "Laup", "Pühap"], daysMin: ["P", "E", "T", "K", "N", "R", "L", "P"], months: ["Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"], monthsShort: ["Jaan", "Veebr", "Märts", "Apr", "Mai", "Juuni", "Juuli", "Aug", "Sept", "Okt", "Nov", "Dets"], today: "Täna", clear: "Tühjenda", weekStart: 1, format: "dd.mm.yyyy" }; }(jQuery));
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); /** * This file is part of the Vökuró. * * (c) Phalcon Team <[email protected]> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Vokuro\Models; use Phalcon\Mvc\Model; /** * PasswordChanges * Register when a user changes his/her password */ class PasswordChanges extends Model { /** * * @var integer */ public $id; /** * * @var integer */ public $usersId; /** * * @var string */ public $ipAddress; /** * * @var string */ public $userAgent; /** * * @var integer */ public $createdAt; public function initialize() { $this->belongsTo('usersId', Users::class, 'id', [ 'alias' => 'user', ]); } /** * Before create the user assign a password */ public function beforeValidationOnCreate() { // Timestamp the confirmation $this->createdAt = time(); } }
{ "pile_set_name": "Github" }
[ { "class" : "org.batfish.question.OspfStatusQuestionPlugin$OspfStatusAnswerElement", "ospfStatuses" : [ { "interface" : { "hostname" : "as1border1", "interface" : "Loopback0" }, "ospfStatus" : "ENABLED_PASSIVE" } ] } ]
{ "pile_set_name": "Github" }
package com.twitter.finatra.thrift.exceptions import com.twitter.finagle.stats.StatsReceiver import com.twitter.inject.Injector import com.twitter.inject.TypeUtils.singleTypeParam import com.twitter.util.Future import java.lang.reflect.Type import java.util.concurrent.ConcurrentHashMap import javax.inject.Singleton import net.codingwell.scalaguice.typeLiteral import scala.annotation.tailrec import scala.collection.JavaConverters._ /** * A class to register [[com.twitter.finatra.thrift.exceptions.ExceptionMapper]]s and * handle exceptions * * Given an exception, the ExceptionManager will find an * [[com.twitter.finatra.thrift.exceptions.ExceptionMapper]] to handle that particular * class of exceptions. If the mapper for that exception isn't registered, the ExceptionManager * will try the exception's parent class, until it reaches a Throwable class. If no Throwable class * exception mapper is found, it won't handle the exception. Users are free to register their own * ExceptionMapper[Throwable] which will be the root exception mapper. */ @Singleton class ExceptionManager(injector: Injector, statsReceiver: StatsReceiver) { private val mappers = new ConcurrentHashMap[Type, ExceptionMapper[_, _]]().asScala /* Public */ /** * Add a [[com.twitter.finatra.thrift.exceptions.ExceptionMapper]] by type [[T]] * * @tparam T - ExceptionMapper type T, which should be a subclass of * [[com.twitter.finatra.thrift.exceptions.ExceptionMapper]] */ def add[T <: ExceptionMapper[_, _]: Manifest]: Unit = { val mapperType = typeLiteral[T].getSupertype(classOf[ExceptionMapper[_, _]]).getType val throwableType = singleTypeParam(mapperType) register(throwableType, injector.instance[T]) } /** * Add a [[com.twitter.finatra.thrift.exceptions.ExceptionMapper]] over type [[T]] to the manager. * If a mapper has already been added for the given [[T]], it will be replaced. * * @param mapper - [[com.twitter.finatra.thrift.exceptions.ExceptionMapper]] to add * @tparam T - exception class type which should be a subclass of [[java.lang.Throwable]] */ def add[T <: Throwable: Manifest](mapper: ExceptionMapper[T, _]): Unit = { register(manifest[T].runtimeClass, mapper) } /** * Returns a Future[Rep] as computed by the matching * [[com.twitter.finatra.thrift.exceptions.ExceptionMapper]] to the given throwable. * * @param throwable - [[java.lang.Throwable]] to match against registered ExceptionMappers. * @return a response wrapped in Future */ def handleException[Rep](throwable: Throwable): Future[Rep] = { val mapper = getMapper(throwable.getClass) mapper.asInstanceOf[ExceptionMapper[Throwable, Rep]].handleException(throwable) } /* Private */ // Last entry by type overrides any previous entry. private def register(throwableType: Type, mapper: ExceptionMapper[_, _]): Unit = { mappers.update(throwableType, mapper) } // Get mapper for this throwable class if it exists, otherwise // search for parent Throwable class. If we reach the Throwable // class then return the default mapper. // // Note: we avoid getOrElse so we have tail recursion @tailrec private def getMapper(cls: Class[_]): ExceptionMapper[_, _] = { mappers.get(cls) match { case Some(mapper) => mapper case None => getMapper(cls.getSuperclass) } } }
{ "pile_set_name": "Github" }
// Check string .String = 'Hello' .OtherStringA = 'Hello' .OtherStringB = 'Goodbye' // Strings match If (.String == .OtherStringA) { Print( "Success" ) } If (.String != .OtherStringA) { Print( "Failure" ) } // Strings don't match If (.String == .OtherStringB) { Print( "Failure" ) } If (.String != .OtherStringB) { Print( "Success" ) } // String compare .StringA = 'AAA' .StringB = 'BBB' If (.StringA > .StringB) { Print( "Failure" ) } If (.StringA >= .StringB) { Print( "Failure" ) } If (.StringB < .StringA) { Print( "Failure" ) } If (.StringB <= .StringA) { Print( "Failure" ) }
{ "pile_set_name": "Github" }
# encoding: utf-8 task default: :test desc 'Use UglifyJS to compress Underscore.string' task :build do require 'uglifier' source = File.read('lib/underscore.string.js') compressed = Uglifier.compile(source, copyright: false) File.open('dist/underscore.string.min.js', 'w'){ |f| f.write compressed } compression_rate = compressed.length.to_f/source.length puts "compressed dist/underscore.string.min.js: #{compressed.length}/#{source.length} #{(compression_rate * 100).round}%" end desc 'Run tests' task :test do pid = spawn('bundle exec serve', err: '/dev/null') sleep 2 puts "Running underscore.string test suite." result1 = system %{phantomjs ./test/run-qunit.js "http://localhost:4000/test/test.html"} puts "Running Underscore test suite." result2 = system %{phantomjs ./test/run-qunit.js "http://localhost:4000/test/test_underscore/test.html"} Process.kill 'INT', pid exit(result1 && result2 ? 0 : 1) end
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Player sources</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript" src="../../../mwEmbedStartup.php"></script> <script type="text/javascript"> $(document).ready(function(){ $('#test').text('jQuery $ supported' ); }); </script> </head> <body> <div id="test"></div> <video poster="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/elephants-dream.jpg" duration="10:53" preload="auto"> <source type="video/webm" src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/elephants-dream_400p.webm" /> <source type="video/h264" src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/elephants-dream_iphone.m4v" /> <source type="video/ogg" src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/elephants-dream_400p.ogv" /> </video> </body> </html>
{ "pile_set_name": "Github" }
<?php /** * This is the central file for maintenance scripts. * It is not the entry point however. * * @author Timo Tijhof * @since 1.0.0 * @package TestSwarm */ abstract class MaintenanceScript { private $context, $name, $description; private $flags = array(); private $options = array(); private $generalArgKeys = array(); private $parsed = array(); abstract protected function init(); abstract protected function execute(); final protected function setDescription( $description ) { $this->description = $description; } /** * Register a flag, usage any of these 4: * - php script.php -a -b value -c "value" -d="value" * @param string $key: one single character. * @param string $type: one of "boolean", "value" * @param string $description */ protected function registerFlag( $key, $type, $description ) { static $types = array( 'boolean', 'value' ); if ( !is_string( $key ) || strlen( $key ) !== 1 || !in_array( $type, $types ) ) { $this->error( 'Illegal flag registration' ); } $this->flags[$key] = array( 'type' => $type, 'description' => $description, ); } /** * Register an option, usage any of these 4: * - php script.php --foo --bar=value --quux="value" * @param string $name: at least 2 characters * @param string $type: one of "boolean", "value" * @param string $description */ protected function registerOption( $name, $type, $description ) { static $types = array( 'boolean', 'value' ); if ( !is_string( $name ) || strlen( $name ) < 2 || !in_array( $type, $types ) ) { $this->error( 'Illegal option registration' ); } $this->options[$name] = array( 'type' => $type, 'description' => $description, ); } protected function parseCliArguments() { // Prepare for getopt(). Note that it supports "require value" for cli args, // but we use our own format instead (see also php.net/getopt). $getoptShort = ''; $getoptLong = array(); foreach ( $this->flags as $flagKey => $flagInfo ) { switch ( $flagInfo['type'] ) { case 'value': $getoptShort .= $flagKey . '::'; break; case 'boolean': $getoptShort .= $flagKey; break; } } foreach ( $this->options as $optionName => $optionInfo ) { switch ( $optionInfo['type'] ) { case 'value': $getoptLong[] = $optionName . '::'; break; case 'boolean': $getoptLong[] = $optionName; break; } } $parsed = getopt( $getoptShort, $getoptLong ); if ( !is_array( $parsed ) ) { $this->error( 'Parsing command line arguments failed.' ); } $this->parsed = $parsed; } protected function getFlag( $key ) { if ( !isset( $this->flags[$key] ) || !isset( $this->parsed[$key] ) ) { return false; } return $this->flags[$key]['type'] === 'boolean' ? true : $this->parsed[$key]; } protected function getOption( $name ) { if ( !isset( $this->options[$name] ) || !isset( $this->parsed[$name] ) ) { return false; } return $this->options[$name]['type'] === 'boolean' ? true :$this->parsed[$name]; } public function run() { if ( !defined( 'SWARM_ENTRY' ) || SWARM_ENTRY !== 'SCRIPT' ) { $this->error( 'MaintenanceScript instances may only be run as part of a maintenace script.' ); } if ( php_sapi_name() !== 'cli' ) { $this->error( 'Maintenance scripts may only be run from the command-line interface.' ); } if ( !ini_get( 'register_argc_argv' ) || ini_get( 'register_argc_argv' ) == '0' ) { $this->error( 'Maintenance scripts require `register_argc_argv` to be enabled in php.ini.' ); } // General options for all scripts $this->registerOption( 'help', 'boolean', 'Display this message' ); // E.g. to allow puppet to run a script without it facing "(Y/N)" or something. $this->registerOption( 'quiet', 'boolean', 'Surpress standard output and requests for cli input' ); $this->generalArgKeys = array_merge( array_keys( $this->options ), array_keys( $this->flags ) ); $this->init(); $name = get_class( $this ); // "class FooBarScript extends .." if ( substr( $name, -6 ) === 'Script' ) { $name = substr( $name, 0, -6 ); } $this->name = $name; if ( !isset( $this->description ) ) { $this->error( "{$this->name} is missing a description." ); } $this->parseCliArguments(); // Generate header $version = $this->getContext()->getVersionInfo( 'bypass-cache' ); $versionText = $version['TestSwarm']; if ( $version['devInfo'] ) { $versionText .= ' (' . $version['devInfo']['branch'] . ' ' . substr( $version['devInfo']['SHA1'], 0, 7 ) . ')'; } $description = wordwrap( $this->description, 72, "\n", true ); $description = explode( "\n", $description ); $description[] = str_repeat( '-', 72 ); $label = "{$this->name}: "; $prefix = str_repeat( ' ', strlen( $label ) ); $description = $label . implode( "\n" . $prefix, $description ); $this->out("[TestSwarm $versionText] Maintenance script $description "); // Help or continue if ( $this->getOption( 'help' ) ) { $this->displayHelp(); } else { try { $this->execute(); } catch ( Exception $e ) { $this->error( $e ); } } $this->out( '' ); exit; } protected function displayHelp() { $helpScript = ''; $helpGeneral = ''; $placeholder = array( 'boolean' => '', 'value' => ' <value>', ); foreach ( $this->flags as $flagKey => $flagInfo ) { $help = "\n -{$flagKey}" . $placeholder[$flagInfo['type']] . ": {$flagInfo['description']}"; if ( in_array( $flagKey, $this->generalArgKeys ) ) { $helpGeneral .= $help; } else { $helpScript .= $help; } } foreach ( $this->options as $optionName => $optionInfo ) { $help = "\n --{$optionName}" . $placeholder[$optionInfo['type']] . ": {$optionInfo['description']}"; if ( in_array( $optionName, $this->generalArgKeys ) ) { $helpGeneral .= $help; } else { $helpScript .= $help; } } print ($helpScript ? "Parameters to this script:$helpScript" : '') . ($helpScript && $helpGeneral ? "\n\n" : '') . ($helpGeneral ? "General parameters:$helpGeneral" : ''); } /** @param $seconds int */ protected function wait( $seconds, $message = '' ) { print $message; $backspace = chr(8); for ( $i = $seconds; $i >= 0; $i-- ) { if ( $i != $seconds ) { $prevNrLen = strlen( $i + 1 ); // We have to both print backspaces, spaces and then backspaces again. On // MacOSX, backspaces only move the cursor, it doesn't hide the characters. // So we overwrite with spaces and then back up (10|->9| instead of 10|->9|0) print str_repeat( $backspace, $prevNrLen ) . str_repeat( ' ', $prevNrLen ) . str_repeat( $backspace, $prevNrLen ); } print $i; flush(); if ( $i > 0 ) { sleep( 1 ); } } print "\n"; } /** * @param string $action: Correct grammar "This script will $action!" */ protected function timeWarningForScriptWill( $action, $seconds = 10 ) { $this->wait( 10, "WARNING: This script will $action!\nYou can abort now with Control-C. Starting in " ); } /** * @param string $message: [optional] Output text before the input cursor. * @return string */ protected function cliInput( $prefix = '> ' ) { if ( $this->getOption( 'quiet' ) ) { return ''; } $this->checkAtty(); if ( function_exists( 'readline' ) ) { // Use readline if available, it's much nicer to work with for the user // (autocompletion of filenames and no weird characters when using arrow keys) return readline( $prefix ); } else { // Readline is not available on Windows platforms (php.net/intro.readline) $this->outRaw( $prefix ); return rtrim( fgets( STDIN ), "\n" ); } } /** * Retrieve a secret value from the cli. * Based on http://www.dasprids.de/blog/2008/08/22/getting-a-password-hidden-from-stdin-with-php-cli. * * @param string $message: [optional] text before the input cursor. * @param string $type: [optional] hidden or stars. * @return string */ protected function cliInputSecret( $prefix = '> ', $type = 'stars' ) { if ( $this->getOption( 'quiet' ) ) { return ''; } $this->checkAtty(); // Can't use readline, it always echoes to the screen. $this->outRaw( $prefix ); $sttyStyle = shell_exec( 'stty -g' ); if ( $type !== 'stars' ) { shell_exec( 'stty -echo' ); $input = rtrim( fgets( STDIN ), "\n" ); $this->outRaw( "\n" ); } else { shell_exec( 'stty -icanon -echo min 1 time 0' ); $input = ''; while ( true ) { $char = fgetc( STDIN ); // Ready if ( $char === "\n" ) { $this->outRaw( "\n" ); break; // Backspace } else if ( ord( $char) === 127 ) { if ( strlen( $input) > 0 ) { // Replace last character with blank and return to previous position // (back, space, back). fwrite( STDOUT, "\x08 \x08" ); $input = substr( $input, 0, -1 ); } // More input } else { fwrite( STDOUT, '*' ); $input .= $char; } } } // Restore stty style shell_exec( 'stty ' . $sttyStyle ); return $input; } /** @return bool */ final protected function checkAtty() { static $isatty = null; if ( $isatty === null ) { // Both `echo "foo" | php script.php` and `php script.php > foo.txt` // are being prevented. $isatty = posix_isatty( STDIN ) && posix_isatty( STDOUT ); // No need to re-run this check each time, we abort within the if-null check if ( !$isatty ) { $this->error( 'This script requires an interactive terminal for output and input. Use --quiet to skip input requests.' ); } } return $isatty; } protected function out( $text ) { $this->outRaw( "$text\n" ); } protected function outRaw( $text ) { if ( !$this->getOption( 'quiet' ) ) { print $text; } } protected function error( $msg ) { $msg = "Error: $msg\n"; fwrite( STDERR, $msg ); exit( E_ERROR ); } public static function newFromContext( TestSwarmContext $context ) { $script = new static(); $script->context = $context; return $script; } final protected function getContext() { return $this->context; } final private function __construct() {} }
{ "pile_set_name": "Github" }
/* cobyla : contrained optimization by linear approximation */ /* * Copyright (c) 1992, Michael J. D. Powell ([email protected]) * Copyright (c) 2004, Jean-Sebastien Roy ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * This software is a C version of COBYLA2, a contrained optimization by linear * approximation package developed by Michael J. D. Powell in Fortran. * * The original source code can be found at : * http://plato.la.asu.edu/topics/problems/nlores.html */ static char const rcsid[] = "@(#) $Jeannot: cobyla.c,v 1.11 2004/04/18 09:51:36 js Exp $"; #include <stdlib.h> #include <stdio.h> #include <math.h> #include "cobyla.h" /* SGJ, 2008: modified COBYLA code to take explicit account of bound constraints. Since bound constraints are linear, these should already be handled exactly when COBYLA optimizes it linear model. However, they were not handled properly when COBYLA created its initial simplex, or when COBYLA updated unacceptable simplices. Since NLopt guarantees that the objective will not be evaluated outside the bound constraints, this required us to handle such points by putting a slope discontinuity into the objective & constraints (below), which slows convergence considerably for smooth functions. Instead, handling them explicitly prevents this problem */ #define ENFORCE_BOUNDS 1 #define MIN2(a,b) ((a) <= (b) ? (a) : (b)) #define MAX2(a,b) ((a) >= (b) ? (a) : (b)) #define U(n) ((unsigned) (n)) /**************************************************************************/ /* SGJ, 2008: NLopt-style interface function: */ typedef struct { nlopt_func f; void *f_data; unsigned m_orig; nlopt_constraint *fc; unsigned p; nlopt_constraint *h; double *xtmp; double *lb, *ub; double *con_tol, *scale; nlopt_stopping *stop; } func_wrap_state; static int func_wrap(int ni, int mi, double *x, double *f, double *con, func_wrap_state *s) { unsigned n = U(ni); unsigned i, j, k; double *xtmp = s->xtmp; const double *lb = s->lb, *ub = s->ub; (void) mi; /* unused */ /* in nlopt, we guarante that the function is never evaluated outside the lb and ub bounds, so we need force this with xtmp ... note that this leads to discontinuity in the first derivative, which slows convergence if we don't enable the ENFORCE_BOUNDS feature above. */ for (j = 0; j < n; ++j) { if (x[j] < lb[j]) xtmp[j] = lb[j]; else if (x[j] > ub[j]) xtmp[j] = ub[j]; else xtmp[j] = x[j]; } nlopt_unscale(n, s->scale, xtmp, xtmp); *f = s->f(n, xtmp, NULL, s->f_data); if (nlopt_stop_forced(s->stop)) return 1; i = 0; for (j = 0; j < s->m_orig; ++j) { nlopt_eval_constraint(con + i, NULL, s->fc+j, n, xtmp); if (nlopt_stop_forced(s->stop)) return 1; for (k = 0; k < s->fc[j].m; ++k) con[i + k] = -con[i + k]; i += s->fc[j].m; } for (j = 0; j < s->p; ++j) { nlopt_eval_constraint(con + i, NULL, s->h+j, n, xtmp); if (nlopt_stop_forced(s->stop)) return 1; for (k = 0; k < s->h[j].m; ++k) con[(i + s->h[j].m) + k] = -con[i + k]; i += 2 * s->h[j].m; } for (j = 0; j < n; ++j) { if (!nlopt_isinf(lb[j])) con[i++] = x[j] - lb[j]; if (!nlopt_isinf(ub[j])) con[i++] = ub[j] - x[j]; } return 0; } /* * Verbosity level */ typedef enum { COBYLA_MSG_NONE = 0, /* No messages */ COBYLA_MSG_EXIT = 1, /* Exit reasons */ COBYLA_MSG_ITER = 2, /* Rho and Sigma changes */ COBYLA_MSG_INFO = 3 /* Informational messages */ } cobyla_message; /* * A function as required by cobyla * state is a void pointer provided to the function at each call * * n : the number of variables * m : the number of constraints * x : on input, then vector of variables (should not be modified) * f : on output, the value of the function * con : on output, the value of the constraints (vector of size m) * state : on input, the value of the state variable as provided to cobyla * * COBYLA will try to make all the values of the constraints positive. * So if you want to input a constraint j such as x[i] <= MAX, set: * con[j] = MAX - x[i] * The function must returns 0 if no error occurs or 1 to immediately end the * minimization. * */ typedef int cobyla_function(int n, int m, double *x, double *f, double *con, func_wrap_state *state); /* * cobyla : minimize a function subject to constraints * * n : number of variables (>=0) * m : number of constraints (>=0) * x : on input, initial estimate ; on output, the solution * minf : on output, minimum objective function * rhobeg : a reasonable initial change to the variables * stop : the NLopt stopping criteria * lb, ub : lower and upper bounds on x * message : see the cobyla_message enum * calcfc : the function to minimize (see cobyla_function) * state : used by function (see cobyla_function) * * The cobyla function returns the usual nlopt_result codes. * */ extern nlopt_result cobyla(int n, int m, double *x, double *minf, double rhobeg, double rhoend, nlopt_stopping *stop, const double *lb, const double *ub, int message, cobyla_function *calcfc, func_wrap_state *state); nlopt_result cobyla_minimize(unsigned n, nlopt_func f, void *f_data, unsigned m, nlopt_constraint *fc, unsigned p, nlopt_constraint *h, const double *lb, const double *ub, /* bounds */ double *x, /* in: initial guess, out: minimizer */ double *minf, nlopt_stopping *stop, const double *dx) { unsigned i, j; func_wrap_state s; nlopt_result ret; double rhobeg, rhoend; s.f = f; s.f_data = f_data; s.m_orig = m; s.fc = fc; s.p = p; s.h = h; s.stop = stop; s.lb = s.ub = s.xtmp = s.con_tol = s.scale = NULL; s.scale = nlopt_compute_rescaling(n, dx); if (!s.scale) { ret = NLOPT_OUT_OF_MEMORY; goto done; } s.lb = nlopt_new_rescaled(n, s.scale, lb); if (!s.lb) { ret = NLOPT_OUT_OF_MEMORY; goto done; } s.ub = nlopt_new_rescaled(n, s.scale, ub); if (!s.ub) { ret = NLOPT_OUT_OF_MEMORY; goto done; } nlopt_reorder_bounds(n, s.lb, s.ub); s.xtmp = (double *) malloc(sizeof(double) * n); if (!s.xtmp) { ret = NLOPT_OUT_OF_MEMORY; goto done; } /* SGJ, 2008: compute rhoend from NLopt stop info */ rhobeg = fabs(dx[0] / s.scale[0]); rhoend = stop->xtol_rel * (rhobeg); for (j = 0; j < n; ++j) if (rhoend < stop->xtol_abs[j] / fabs(s.scale[j])) rhoend = stop->xtol_abs[j] / fabs(s.scale[j]); /* each equality constraint gives two inequality constraints */ m = nlopt_count_constraints(m, fc) + 2 * nlopt_count_constraints(p, h); /* add constraints for lower/upper bounds (if any) */ for (j = 0; j < n; ++j) { if (!nlopt_isinf(lb[j])) ++m; if (!nlopt_isinf(ub[j])) ++m; } s.con_tol = (double *) malloc(sizeof(double) * m); if (m && !s.con_tol) { ret = NLOPT_OUT_OF_MEMORY; goto done; } for (j = 0; j < m; ++j) s.con_tol[j] = 0; for (j = i = 0; i < s.m_orig; ++i) { unsigned ji = j, jnext = j + fc[i].m; for (; j < jnext; ++j) s.con_tol[j] = fc[i].tol[j - ji]; } for (i = 0; i < s.p; ++i) { unsigned ji = j, jnext = j + h[i].m; for (; j < jnext; ++j) s.con_tol[j] = h[i].tol[j - ji]; ji = j; jnext = j + h[i].m; for (; j < jnext; ++j) s.con_tol[j] = h[i].tol[j - ji]; } nlopt_rescale(n, s.scale, x, x); ret = cobyla((int) n, (int) m, x, minf, rhobeg, rhoend, stop, s.lb, s.ub, COBYLA_MSG_NONE, func_wrap, &s); nlopt_unscale(n, s.scale, x, x); /* make sure e.g. rounding errors didn't push us slightly out of bounds */ for (j = 0; j < n; ++j) { if (x[j] < lb[j]) x[j] = lb[j]; if (x[j] > ub[j]) x[j] = ub[j]; } done: free(s.con_tol); free(s.xtmp); free(s.ub); free(s.lb); free(s.scale); return ret; } /**************************************************************************/ /* SGJ, 2010: I find that it seems to increase robustness of the algorithm if, on "simplex" steps (which are intended to improve the linear independence of the simplex, not improve the objective), we multiply the steps by pseudorandom numbers in [0,1). Intuitively, pseudorandom steps are likely to avoid any accidental dependency in the simplex vertices. However, since I still want COBYLA to be a deterministic algorithm, and I don't care all that much about the quality of the randomness here, I implement a simple linear congruential generator rather than use nlopt_urand, and set the initial seed deterministically. */ #if defined(HAVE_STDINT_H) # include <stdint.h> #endif #ifndef HAVE_UINT32_T # if SIZEOF_UNSIGNED_LONG == 4 typedef unsigned long uint32_t; # elif SIZEOF_UNSIGNED_INT == 4 typedef unsigned int uint32_t; # else # error No 32-bit unsigned integer type # endif #endif /* a simple linear congruential generator */ static uint32_t lcg_rand(uint32_t *seed) { return (*seed = *seed * 1103515245 + 12345); } static double lcg_urand(uint32_t *seed, double a, double b) { return a + lcg_rand(seed) * (b - a) / ((uint32_t) -1); } /**************************************************************************/ static nlopt_result cobylb(int *n, int *m, int *mpp, double *x, double *minf, double *rhobeg, double rhoend, nlopt_stopping *stop, const double *lb, const double *ub, int *iprint, double *con, double *sim, double *simi, double *datmat, double *a, double *vsig, double *veta, double *sigbar, double *dx, double *w, int *iact, cobyla_function *calcfc, func_wrap_state *state); static nlopt_result trstlp(int *n, int *m, double *a, double *b, double *rho, double *dx, int *ifull, int *iact, double *z__, double *zdota, double *vmultc, double *sdirn, double *dxnew, double *vmultd); /* ------------------------------------------------------------------------ */ nlopt_result cobyla(int n, int m, double *x, double *minf, double rhobeg, double rhoend, nlopt_stopping *stop, const double *lb, const double *ub, int iprint, cobyla_function *calcfc, func_wrap_state *state) { int icon, isim, isigb, idatm, iveta, isimi, ivsig, iwork, ia, idx, mpp; int *iact; double *w; nlopt_result rc; /* * This subroutine minimizes an objective function F(X) subject to M * inequality constraints on X, where X is a vector of variables that has * N components. The algorithm employs linear approximations to the * objective and constraint functions, the approximations being formed by * linear interpolation at N+1 points in the space of the variables. * We regard these interpolation points as vertices of a simplex. The * parameter RHO controls the size of the simplex and it is reduced * automatically from RHOBEG to RHOEND. For each RHO the subroutine tries * to achieve a good vector of variables for the current size, and then * RHO is reduced until the value RHOEND is reached. Therefore RHOBEG and * RHOEND should be set to reasonable initial changes to and the required * accuracy in the variables respectively, but this accuracy should be * viewed as a subject for experimentation because it is not guaranteed. * The subroutine has an advantage over many of its competitors, however, * which is that it treats each constraint individually when calculating * a change to the variables, instead of lumping the constraints together * into a single penalty function. The name of the subroutine is derived * from the phrase Constrained Optimization BY Linear Approximations. * * The user must set the values of N, M, RHOBEG and RHOEND, and must * provide an initial vector of variables in X. Further, the value of * IPRINT should be set to 0, 1, 2 or 3, which controls the amount of * printing during the calculation. Specifically, there is no output if * IPRINT=0 and there is output only at the end of the calculation if * IPRINT=1. Otherwise each new value of RHO and SIGMA is printed. * Further, the vector of variables and some function information are * given either when RHO is reduced or when each new value of F(X) is * computed in the cases IPRINT=2 or IPRINT=3 respectively. Here SIGMA * is a penalty parameter, it being assumed that a change to X is an * improvement if it reduces the merit function * F(X)+SIGMA*MAX(0.0,-C1(X),-C2(X),...,-CM(X)), * where C1,C2,...,CM denote the constraint functions that should become * nonnegative eventually, at least to the precision of RHOEND. In the * printed output the displayed term that is multiplied by SIGMA is * called MAXCV, which stands for 'MAXimum Constraint Violation'. The * argument MAXFUN is an int variable that must be set by the user to a * limit on the number of calls of CALCFC, the purpose of this routine being * given below. The value of MAXFUN will be altered to the number of calls * of CALCFC that are made. The arguments W and IACT provide real and * int arrays that are used as working space. Their lengths must be at * least N*(3*N+2*M+11)+4*M+6 and M+1 respectively. * * In order to define the objective and constraint functions, we require * a subroutine that has the name and arguments * SUBROUTINE CALCFC (N,M,X,F,CON) * DIMENSION X(*),CON(*) . * The values of N and M are fixed and have been defined already, while * X is now the current vector of variables. The subroutine should return * the objective and constraint functions at X in F and CON(1),CON(2), * ...,CON(M). Note that we are trying to adjust X so that F(X) is as * small as possible subject to the constraint functions being nonnegative. * * Partition the working space array W to provide the storage that is needed * for the main calculation. */ stop->nevals = 0; if (n == 0) { if (iprint>=1) fprintf(stderr, "cobyla: N==0.\n"); return NLOPT_SUCCESS; } if (n < 0 || m < 0) { if (iprint>=1) fprintf(stderr, "cobyla: N<0 or M<0.\n"); return NLOPT_INVALID_ARGS; } /* workspace allocation */ w = (double*) malloc(U(n*(3*n+2*m+11)+4*m+6)*sizeof(*w)); if (w == NULL) { if (iprint>=1) fprintf(stderr, "cobyla: memory allocation error.\n"); return NLOPT_OUT_OF_MEMORY; } iact = (int*)malloc(U(m+1)*sizeof(*iact)); if (iact == NULL) { if (iprint>=1) fprintf(stderr, "cobyla: memory allocation error.\n"); free(w); return NLOPT_OUT_OF_MEMORY; } /* Parameter adjustments */ --iact; --w; --x; --lb; --ub; /* Function Body */ mpp = m + 2; icon = 1; isim = icon + mpp; isimi = isim + n * n + n; idatm = isimi + n * n; ia = idatm + n * mpp + mpp; ivsig = ia + m * n + n; iveta = ivsig + n; isigb = iveta + n; idx = isigb + n; iwork = idx + n; rc = cobylb(&n, &m, &mpp, &x[1], minf, &rhobeg, rhoend, stop, &lb[1], &ub[1], &iprint, &w[icon], &w[isim], &w[isimi], &w[idatm], &w[ia], &w[ivsig], &w[iveta], &w[isigb], &w[idx], &w[iwork], &iact[1], calcfc, state); /* Parameter adjustments (reverse) */ ++iact; ++w; free(w); free(iact); return rc; } /* cobyla */ /* ------------------------------------------------------------------------- */ static nlopt_result cobylb(int *n, int *m, int *mpp, double *x, double *minf, double *rhobeg, double rhoend, nlopt_stopping *stop, const double *lb, const double *ub, int *iprint, double *con, double *sim, double *simi, double *datmat, double *a, double *vsig, double *veta, double *sigbar, double *dx, double *w, int *iact, cobyla_function *calcfc, func_wrap_state *state) { /* System generated locals */ int sim_dim1, sim_offset, simi_dim1, simi_offset, datmat_dim1, datmat_offset, a_dim1, a_offset, i__1, i__2, i__3; double d__1, d__2; /* Local variables */ double alpha, delta, denom, tempa, barmu; double beta, cmin = 0.0, cmax = 0.0; double cvmaxm, dxsign, prerem = 0.0; double edgmax, pareta, prerec = 0.0, phimin, parsig = 0.0; double gamma_; double phi, rho, sum = 0.0; double ratio, vmold, parmu, error, vmnew; double resmax, cvmaxp; double resnew, trured; double temp, wsig, f; double weta; int i__, j, k, l; int idxnew; int iflag = 0; int iptemp; int isdirn, izdota; int ivmc; int ivmd; int mp, np, iz, ibrnch; int nbest, ifull, iptem, jdrop; nlopt_result rc = NLOPT_SUCCESS; uint32_t seed = (uint32_t) (*n + *m); /* arbitrary deterministic LCG seed */ int feasible; /* SGJ, 2008: added code to keep track of minimum feasible function val */ *minf = HUGE_VAL; /* Set the initial values of some parameters. The last column of SIM holds */ /* the optimal vertex of the current simplex, and the preceding N columns */ /* hold the displacements from the optimal vertex to the other vertices. */ /* Further, SIMI holds the inverse of the matrix that is contained in the */ /* first N columns of SIM. */ /* Parameter adjustments */ a_dim1 = *n; a_offset = 1 + a_dim1 * 1; a -= a_offset; simi_dim1 = *n; simi_offset = 1 + simi_dim1 * 1; simi -= simi_offset; sim_dim1 = *n; sim_offset = 1 + sim_dim1 * 1; sim -= sim_offset; datmat_dim1 = *mpp; datmat_offset = 1 + datmat_dim1 * 1; datmat -= datmat_offset; --x; --con; --vsig; --veta; --sigbar; --dx; --w; --iact; --lb; --ub; /* Function Body */ iptem = MIN2(*n,4); iptemp = iptem + 1; np = *n + 1; mp = *m + 1; alpha = .25; beta = 2.1; gamma_ = .5; delta = 1.1; rho = *rhobeg; parmu = 0.; if (*iprint >= 2) { fprintf(stderr, "cobyla: the initial value of RHO is %12.6E and PARMU is set to zero.\n", rho); } temp = 1. / rho; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { double rhocur; sim[i__ + np * sim_dim1] = x[i__]; i__2 = *n; for (j = 1; j <= i__2; ++j) { sim[i__ + j * sim_dim1] = 0.; simi[i__ + j * simi_dim1] = 0.; } rhocur = rho; #if ENFORCE_BOUNDS /* SGJ: make sure step rhocur stays inside [lb,ub] */ if (x[i__] + rhocur > ub[i__]) { if (x[i__] - rhocur >= lb[i__]) rhocur = -rhocur; else if (ub[i__] - x[i__] > x[i__] - lb[i__]) rhocur = 0.5 * (ub[i__] - x[i__]); else rhocur = 0.5 * (x[i__] - lb[i__]); } #endif sim[i__ + i__ * sim_dim1] = rhocur; simi[i__ + i__ * simi_dim1] = 1.0 / rhocur; } jdrop = np; ibrnch = 0; /* Make the next call of the user-supplied subroutine CALCFC. These */ /* instructions are also used for calling CALCFC during the iterations of */ /* the algorithm. */ /* SGJ comment: why the hell couldn't he just use a damn subroutine? #*&!%*@ Fortran-66 spaghetti code */ L40: if (nlopt_stop_forced(stop)) rc = NLOPT_FORCED_STOP; else if (stop->nevals > 0) { if (nlopt_stop_evals(stop)) rc = NLOPT_MAXEVAL_REACHED; else if (nlopt_stop_time(stop)) rc = NLOPT_MAXTIME_REACHED; } if (rc != NLOPT_SUCCESS) goto L600; stop->nevals++; if (calcfc(*n, *m, &x[1], &f, &con[1], state)) { if (*iprint >= 1) { fprintf(stderr, "cobyla: user requested end of minimization.\n"); } rc = NLOPT_FORCED_STOP; goto L600; } resmax = 0.; feasible = 1; /* SGJ, 2010 */ if (*m > 0) { i__1 = *m; for (k = 1; k <= i__1; ++k) { d__1 = resmax, d__2 = -con[k]; resmax = MAX2(d__1,d__2); if (d__2 > state->con_tol[k-1]) feasible = 0; /* SGJ, 2010 */ } } /* SGJ, 2008: check for minf_max reached by feasible point */ if (f < stop->minf_max && feasible) { rc = NLOPT_MINF_MAX_REACHED; goto L620; /* not L600 because we want to use current x, f, resmax */ } if (stop->nevals == *iprint - 1 || *iprint == 3) { fprintf(stderr, "cobyla: NFVALS = %4d, F =%13.6E, MAXCV =%13.6E\n", stop->nevals, f, resmax); i__1 = iptem; fprintf(stderr, "cobyla: X ="); for (i__ = 1; i__ <= i__1; ++i__) { if (i__>1) fprintf(stderr, " "); fprintf(stderr, "%13.6E", x[i__]); } if (iptem < *n) { i__1 = *n; for (i__ = iptemp; i__ <= i__1; ++i__) { if (!((i__-1) % 4)) fprintf(stderr, "\ncobyla: "); fprintf(stderr, "%15.6E", x[i__]); } } fprintf(stderr, "\n"); } con[mp] = f; con[*mpp] = resmax; if (ibrnch == 1) { goto L440; } /* Set the recently calculated function values in a column of DATMAT. This */ /* array has a column for each vertex of the current simplex, the entries of */ /* each column being the values of the constraint functions (if any) */ /* followed by the objective function and the greatest constraint violation */ /* at the vertex. */ i__1 = *mpp; for (k = 1; k <= i__1; ++k) { datmat[k + jdrop * datmat_dim1] = con[k]; } if (stop->nevals > np) { goto L130; } /* Exchange the new vertex of the initial simplex with the optimal vertex if */ /* necessary. Then, if the initial simplex is not complete, pick its next */ /* vertex and calculate the function values there. */ if (jdrop <= *n) { if (datmat[mp + np * datmat_dim1] <= f) { x[jdrop] = sim[jdrop + np * sim_dim1]; } else { /* improvement in function val */ double rhocur = x[jdrop] - sim[jdrop + np * sim_dim1]; /* SGJ: use rhocur instead of rho. In original code, rhocur == rho always, but I want to change this to ensure that simplex points fall within [lb,ub]. */ sim[jdrop + np * sim_dim1] = x[jdrop]; i__1 = *mpp; for (k = 1; k <= i__1; ++k) { datmat[k + jdrop * datmat_dim1] = datmat[k + np * datmat_dim1] ; datmat[k + np * datmat_dim1] = con[k]; } i__1 = jdrop; for (k = 1; k <= i__1; ++k) { sim[jdrop + k * sim_dim1] = -rhocur; temp = 0.f; i__2 = jdrop; for (i__ = k; i__ <= i__2; ++i__) { temp -= simi[i__ + k * simi_dim1]; } simi[jdrop + k * simi_dim1] = temp; } } } if (stop->nevals <= *n) { /* evaluating initial simplex */ jdrop = stop->nevals; /* SGJ: was += rho, but using sim[jdrop,jdrop] enforces consistency if we change the stepsize above to stay in [lb,ub]. */ x[jdrop] += sim[jdrop + jdrop * sim_dim1]; goto L40; } L130: ibrnch = 1; /* Identify the optimal vertex of the current simplex. */ L140: phimin = datmat[mp + np * datmat_dim1] + parmu * datmat[*mpp + np * datmat_dim1]; nbest = np; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = datmat[mp + j * datmat_dim1] + parmu * datmat[*mpp + j * datmat_dim1]; if (temp < phimin) { nbest = j; phimin = temp; } else if (temp == phimin && parmu == 0.) { if (datmat[*mpp + j * datmat_dim1] < datmat[*mpp + nbest * datmat_dim1]) { nbest = j; } } } /* Switch the best vertex into pole position if it is not there already, */ /* and also update SIM, SIMI and DATMAT. */ if (nbest <= *n) { i__1 = *mpp; for (i__ = 1; i__ <= i__1; ++i__) { temp = datmat[i__ + np * datmat_dim1]; datmat[i__ + np * datmat_dim1] = datmat[i__ + nbest * datmat_dim1] ; datmat[i__ + nbest * datmat_dim1] = temp; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = sim[i__ + nbest * sim_dim1]; sim[i__ + nbest * sim_dim1] = 0.; sim[i__ + np * sim_dim1] += temp; tempa = 0.; i__2 = *n; for (k = 1; k <= i__2; ++k) { sim[i__ + k * sim_dim1] -= temp; tempa -= simi[k + i__ * simi_dim1]; } simi[nbest + i__ * simi_dim1] = tempa; } } /* Make an error return if SIGI is a poor approximation to the inverse of */ /* the leading N by N submatrix of SIG. */ error = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *n; for (j = 1; j <= i__2; ++j) { temp = 0.; if (i__ == j) { temp += -1.; } i__3 = *n; for (k = 1; k <= i__3; ++k) if (sim[k + j * sim_dim1] != 0) { temp += simi[i__ + k * simi_dim1] * sim[k + j * sim_dim1]; } d__1 = error, d__2 = fabs(temp); error = MAX2(d__1,d__2); } } if (error > .1) { if (*iprint >= 1) { fprintf(stderr, "cobyla: rounding errors are becoming damaging.\n"); } rc = NLOPT_ROUNDOFF_LIMITED; goto L600; } /* Calculate the coefficients of the linear approximations to the objective */ /* and constraint functions, placing minus the objective function gradient */ /* after the constraint gradients in the array A. The vector W is used for */ /* working space. */ i__2 = mp; for (k = 1; k <= i__2; ++k) { con[k] = -datmat[k + np * datmat_dim1]; i__1 = *n; for (j = 1; j <= i__1; ++j) { w[j] = datmat[k + j * datmat_dim1] + con[k]; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = 0.; i__3 = *n; for (j = 1; j <= i__3; ++j) { temp += w[j] * simi[j + i__ * simi_dim1]; } if (k == mp) { temp = -temp; } a[i__ + k * a_dim1] = temp; } } /* Calculate the values of sigma and eta, and set IFLAG=0 if the current */ /* simplex is not acceptable. */ iflag = 1; parsig = alpha * rho; pareta = beta * rho; i__1 = *n; for (j = 1; j <= i__1; ++j) { wsig = 0.; weta = 0.; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { d__1 = simi[j + i__ * simi_dim1]; wsig += d__1 * d__1; d__1 = sim[i__ + j * sim_dim1]; weta += d__1 * d__1; } vsig[j] = 1. / sqrt(wsig); veta[j] = sqrt(weta); if (vsig[j] < parsig || veta[j] > pareta) { iflag = 0; } } /* If a new vertex is needed to improve acceptability, then decide which */ /* vertex to drop from the simplex. */ if (ibrnch == 1 || iflag == 1) { goto L370; } jdrop = 0; temp = pareta; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (veta[j] > temp) { jdrop = j; temp = veta[j]; } } if (jdrop == 0) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (vsig[j] < temp) { jdrop = j; temp = vsig[j]; } } } /* Calculate the step to the new vertex and its sign. */ temp = gamma_ * rho * vsig[jdrop]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dx[i__] = temp * simi[jdrop + i__ * simi_dim1]; } cvmaxp = 0.; cvmaxm = 0.; i__1 = mp; for (k = 1; k <= i__1; ++k) { sum = 0.; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { sum += a[i__ + k * a_dim1] * dx[i__]; } if (k < mp) { temp = datmat[k + np * datmat_dim1]; d__1 = cvmaxp, d__2 = -sum - temp; cvmaxp = MAX2(d__1,d__2); d__1 = cvmaxm, d__2 = sum - temp; cvmaxm = MAX2(d__1,d__2); } } dxsign = 1.; if (parmu * (cvmaxp - cvmaxm) > sum + sum) { dxsign = -1.; } /* Update the elements of SIM and SIMI, and set the next X. */ temp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* SGJ, 2010: pseudo-randomize simplex steps (see LCG comments above) */ dx[i__] = dxsign * dx[i__] * lcg_urand(&seed, 0.01, 1); /* SGJ: make sure dx step says in [lb,ub] */ #if ENFORCE_BOUNDS { double xi = sim[i__ + np * sim_dim1]; fixdx: if (xi + dx[i__] > ub[i__]) dx[i__] = -dx[i__]; if (xi + dx[i__] < lb[i__]) { if (xi - dx[i__] <= ub[i__]) dx[i__] = -dx[i__]; else { /* try again with halved step */ dx[i__] *= 0.5; goto fixdx; } } } #endif sim[i__ + jdrop * sim_dim1] = dx[i__]; temp += simi[jdrop + i__ * simi_dim1] * dx[i__]; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { simi[jdrop + i__ * simi_dim1] /= temp; } i__1 = *n; for (j = 1; j <= i__1; ++j) { if (j != jdrop) { temp = 0.; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp += simi[j + i__ * simi_dim1] * dx[i__]; } i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { simi[j + i__ * simi_dim1] -= temp * simi[jdrop + i__ * simi_dim1]; } } x[j] = sim[j + np * sim_dim1] + dx[j]; } goto L40; /* Calculate DX=x(*)-x(0). Branch if the length of DX is less than 0.5*RHO. */ L370: iz = 1; izdota = iz + *n * *n; ivmc = izdota + *n; isdirn = ivmc + mp; idxnew = isdirn + *n; ivmd = idxnew + *n; rc = trstlp(n, m, &a[a_offset], &con[1], &rho, &dx[1], &ifull, &iact[1], &w[ iz], &w[izdota], &w[ivmc], &w[isdirn], &w[idxnew], &w[ivmd]); if (rc != NLOPT_SUCCESS) goto L600; #if ENFORCE_BOUNDS /* SGJ: since the bound constraints are linear, we should never get a dx that lies outside the [lb,ub] constraints here, but we'll enforce this anyway just to be paranoid */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { double xi = sim[i__ + np * sim_dim1]; if (xi + dx[i__] > ub[i__]) dx[i__] = ub[i__] - xi; if (xi + dx[i__] < lb[i__]) dx[i__] = xi - lb[i__]; } #endif if (ifull == 0) { temp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__1 = dx[i__]; temp += d__1 * d__1; } if (temp < rho * .25 * rho) { ibrnch = 1; goto L550; } } /* Predict the change to F and the new maximum constraint violation if the */ /* variables are altered from x(0) to x(0)+DX. */ resnew = 0.; con[mp] = 0.; i__1 = mp; for (k = 1; k <= i__1; ++k) { sum = con[k]; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { sum -= a[i__ + k * a_dim1] * dx[i__]; } if (k < mp) { resnew = MAX2(resnew,sum); } } /* Increase PARMU if necessary and branch back if this change alters the */ /* optimal vertex. Otherwise PREREM and PREREC will be set to the predicted */ /* reductions in the merit function and the maximum constraint violation */ /* respectively. */ barmu = 0.; prerec = datmat[*mpp + np * datmat_dim1] - resnew; if (prerec > 0.) { barmu = sum / prerec; } if (parmu < barmu * 1.5) { parmu = barmu * 2.; if (*iprint >= 2) { fprintf(stderr, "cobyla: increase in PARMU to %12.6E\n", parmu); } phi = datmat[mp + np * datmat_dim1] + parmu * datmat[*mpp + np * datmat_dim1]; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = datmat[mp + j * datmat_dim1] + parmu * datmat[*mpp + j * datmat_dim1]; if (temp < phi) { goto L140; } if (temp == phi && parmu == 0.f) { if (datmat[*mpp + j * datmat_dim1] < datmat[*mpp + np * datmat_dim1]) { goto L140; } } } } prerem = parmu * prerec - sum; /* Calculate the constraint and objective functions at x(*). Then find the */ /* actual reduction in the merit function. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { x[i__] = sim[i__ + np * sim_dim1] + dx[i__]; } ibrnch = 1; goto L40; L440: vmold = datmat[mp + np * datmat_dim1] + parmu * datmat[*mpp + np * datmat_dim1]; vmnew = f + parmu * resmax; trured = vmold - vmnew; if (parmu == 0. && f == datmat[mp + np * datmat_dim1]) { prerem = prerec; trured = datmat[*mpp + np * datmat_dim1] - resmax; } /* Begin the operations that decide whether x(*) should replace one of the */ /* vertices of the current simplex, the change being mandatory if TRURED is */ /* positive. Firstly, JDROP is set to the index of the vertex that is to be */ /* replaced. */ ratio = 0.; if (trured <= 0.f) { ratio = 1.f; } jdrop = 0; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = 0.; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp += simi[j + i__ * simi_dim1] * dx[i__]; } temp = fabs(temp); if (temp > ratio) { jdrop = j; ratio = temp; } sigbar[j] = temp * vsig[j]; } /* Calculate the value of ell. */ edgmax = delta * rho; l = 0; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (sigbar[j] >= parsig || sigbar[j] >= vsig[j]) { temp = veta[j]; if (trured > 0.) { temp = 0.; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { d__1 = dx[i__] - sim[i__ + j * sim_dim1]; temp += d__1 * d__1; } temp = sqrt(temp); } if (temp > edgmax) { l = j; edgmax = temp; } } } if (l > 0) { jdrop = l; } if (jdrop == 0) { goto L550; } /* Revise the simplex by updating the elements of SIM, SIMI and DATMAT. */ temp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sim[i__ + jdrop * sim_dim1] = dx[i__]; temp += simi[jdrop + i__ * simi_dim1] * dx[i__]; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { simi[jdrop + i__ * simi_dim1] /= temp; } i__1 = *n; for (j = 1; j <= i__1; ++j) { if (j != jdrop) { temp = 0.; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp += simi[j + i__ * simi_dim1] * dx[i__]; } i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { simi[j + i__ * simi_dim1] -= temp * simi[jdrop + i__ * simi_dim1]; } } } i__1 = *mpp; for (k = 1; k <= i__1; ++k) { datmat[k + jdrop * datmat_dim1] = con[k]; } /* Branch back for further iterations with the current RHO. */ if (trured > 0. && trured >= prerem * .1) { /* SGJ, 2010: following a suggestion in the SAS manual (which mentions a similar modification to COBYLA, although they didn't publish their source code), increase rho if predicted reduction is sufficiently close to the actual reduction. Otherwise, COBLYA seems to easily get stuck making very small steps. Also require iflag != 0 (i.e., acceptable simplex), again following SAS suggestion (otherwise I get convergence failure in some cases.) */ if (trured >= prerem * 0.9 && trured <= prerem * 1.1 && iflag) { rho *= 2.0; } goto L140; } L550: if (iflag == 0) { ibrnch = 0; goto L140; } /* SGJ, 2008: convergence tests for function vals; note that current best val is stored in datmat[mp + np * datmat_dim1], or in f if ifull == 1, and previous best is in *minf. This seems like a sensible place to put the convergence test, as it is the same place that Powell checks the x tolerance (rho > rhoend). */ { double fbest = ifull == 1 ? f : datmat[mp + np * datmat_dim1]; if (fbest < *minf && nlopt_stop_ftol(stop, fbest, *minf)) { rc = NLOPT_FTOL_REACHED; goto L600; } *minf = fbest; } /* Otherwise reduce RHO if it is not at its least value and reset PARMU. */ if (rho > rhoend) { rho *= .5; if (rho <= rhoend * 1.5) { rho = rhoend; } if (parmu > 0.) { denom = 0.; i__1 = mp; for (k = 1; k <= i__1; ++k) { cmin = datmat[k + np * datmat_dim1]; cmax = cmin; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { d__1 = cmin, d__2 = datmat[k + i__ * datmat_dim1]; cmin = MIN2(d__1,d__2); d__1 = cmax, d__2 = datmat[k + i__ * datmat_dim1]; cmax = MAX2(d__1,d__2); } if (k <= *m && cmin < cmax * .5) { temp = MAX2(cmax,0.) - cmin; if (denom <= 0.) { denom = temp; } else { denom = MIN2(denom,temp); } } } if (denom == 0.) { parmu = 0.; } else if (cmax - cmin < parmu * denom) { parmu = (cmax - cmin) / denom; } } if (*iprint >= 2) { fprintf(stderr, "cobyla: reduction in RHO to %12.6E and PARMU =%13.6E\n", rho, parmu); } if (*iprint == 2) { fprintf(stderr, "cobyla: NFVALS = %4d, F =%13.6E, MAXCV =%13.6E\n", stop->nevals, datmat[mp + np * datmat_dim1], datmat[*mpp + np * datmat_dim1]); fprintf(stderr, "cobyla: X ="); i__1 = iptem; for (i__ = 1; i__ <= i__1; ++i__) { if (i__>1) fprintf(stderr, " "); fprintf(stderr, "%13.6E", sim[i__ + np * sim_dim1]); } if (iptem < *n) { i__1 = *n; for (i__ = iptemp; i__ <= i__1; ++i__) { if (!((i__-1) % 4)) fprintf(stderr, "\ncobyla: "); fprintf(stderr, "%15.6E", x[i__]); } } fprintf(stderr, "\n"); } goto L140; } else /* rho <= rhoend */ rc = rhoend > 0 ? NLOPT_XTOL_REACHED : NLOPT_ROUNDOFF_LIMITED; /* Return the best calculated values of the variables. */ if (*iprint >= 1) { fprintf(stderr, "cobyla: normal return.\n"); } if (ifull == 1) { goto L620; } L600: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { x[i__] = sim[i__ + np * sim_dim1]; } f = datmat[mp + np * datmat_dim1]; resmax = datmat[*mpp + np * datmat_dim1]; L620: *minf = f; if (*iprint >= 1) { fprintf(stderr, "cobyla: NFVALS = %4d, F =%13.6E, MAXCV =%13.6E\n", stop->nevals, f, resmax); i__1 = iptem; fprintf(stderr, "cobyla: X ="); for (i__ = 1; i__ <= i__1; ++i__) { if (i__>1) fprintf(stderr, " "); fprintf(stderr, "%13.6E", x[i__]); } if (iptem < *n) { i__1 = *n; for (i__ = iptemp; i__ <= i__1; ++i__) { if (!((i__-1) % 4)) fprintf(stderr, "\ncobyla: "); fprintf(stderr, "%15.6E", x[i__]); } } fprintf(stderr, "\n"); } return rc; } /* cobylb */ /* ------------------------------------------------------------------------- */ static nlopt_result trstlp(int *n, int *m, double *a, double *b, double *rho, double *dx, int *ifull, int *iact, double *z__, double *zdota, double *vmultc, double *sdirn, double *dxnew, double *vmultd) { /* System generated locals */ int a_dim1, a_offset, z_dim1, z_offset, i__1, i__2; double d__1, d__2; /* Local variables */ double alpha, tempa; double beta; double optnew, stpful, sum, tot, acca, accb; double ratio, vsave, zdotv, zdotw, dd; double sd; double sp, ss, resold = 0.0, zdvabs, zdwabs, sumabs, resmax, optold; double spabs; double temp, step; int icount; int iout, i__, j, k; int isave; int kk; int kl, kp, kw; int nact, icon = 0, mcon; int nactx = 0; /* This subroutine calculates an N-component vector DX by applying the */ /* following two stages. In the first stage, DX is set to the shortest */ /* vector that minimizes the greatest violation of the constraints */ /* A(1,K)*DX(1)+A(2,K)*DX(2)+...+A(N,K)*DX(N) .GE. B(K), K=2,3,...,M, */ /* subject to the Euclidean length of DX being at most RHO. If its length is */ /* strictly less than RHO, then we use the resultant freedom in DX to */ /* minimize the objective function */ /* -A(1,M+1)*DX(1)-A(2,M+1)*DX(2)-...-A(N,M+1)*DX(N) */ /* subject to no increase in any greatest constraint violation. This */ /* notation allows the gradient of the objective function to be regarded as */ /* the gradient of a constraint. Therefore the two stages are distinguished */ /* by MCON .EQ. M and MCON .GT. M respectively. It is possible that a */ /* degeneracy may prevent DX from attaining the target length RHO. Then the */ /* value IFULL=0 would be set, but usually IFULL=1 on return. */ /* In general NACT is the number of constraints in the active set and */ /* IACT(1),...,IACT(NACT) are their indices, while the remainder of IACT */ /* contains a permutation of the remaining constraint indices. Further, Z is */ /* an orthogonal matrix whose first NACT columns can be regarded as the */ /* result of Gram-Schmidt applied to the active constraint gradients. For */ /* J=1,2,...,NACT, the number ZDOTA(J) is the scalar product of the J-th */ /* column of Z with the gradient of the J-th active constraint. DX is the */ /* current vector of variables and here the residuals of the active */ /* constraints should be zero. Further, the active constraints have */ /* nonnegative Lagrange multipliers that are held at the beginning of */ /* VMULTC. The remainder of this vector holds the residuals of the inactive */ /* constraints at DX, the ordering of the components of VMULTC being in */ /* agreement with the permutation of the indices of the constraints that is */ /* in IACT. All these residuals are nonnegative, which is achieved by the */ /* shift RESMAX that makes the least residual zero. */ /* Initialize Z and some other variables. The value of RESMAX will be */ /* appropriate to DX=0, while ICON will be the index of a most violated */ /* constraint if RESMAX is positive. Usually during the first stage the */ /* vector SDIRN gives a search direction that reduces all the active */ /* constraint violations by one simultaneously. */ /* Parameter adjustments */ z_dim1 = *n; z_offset = 1 + z_dim1 * 1; z__ -= z_offset; a_dim1 = *n; a_offset = 1 + a_dim1 * 1; a -= a_offset; --b; --dx; --iact; --zdota; --vmultc; --sdirn; --dxnew; --vmultd; /* Function Body */ *ifull = 1; mcon = *m; nact = 0; resmax = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *n; for (j = 1; j <= i__2; ++j) { z__[i__ + j * z_dim1] = 0.; } z__[i__ + i__ * z_dim1] = 1.; dx[i__] = 0.; } if (*m >= 1) { i__1 = *m; for (k = 1; k <= i__1; ++k) { if (b[k] > resmax) { resmax = b[k]; icon = k; } } i__1 = *m; for (k = 1; k <= i__1; ++k) { iact[k] = k; vmultc[k] = resmax - b[k]; } } if (resmax == 0.) { goto L480; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sdirn[i__] = 0.; } /* End the current stage of the calculation if 3 consecutive iterations */ /* have either failed to reduce the best calculated value of the objective */ /* function or to increase the number of active constraints since the best */ /* value was calculated. This strategy prevents cycling, but there is a */ /* remote possibility that it will cause premature termination. */ L60: optold = 0.; icount = 0; L70: if (mcon == *m) { optnew = resmax; } else { optnew = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { optnew -= dx[i__] * a[i__ + mcon * a_dim1]; } } if (icount == 0 || optnew < optold) { optold = optnew; nactx = nact; icount = 3; } else if (nact > nactx) { nactx = nact; icount = 3; } else { --icount; if (icount == 0) { goto L490; } } /* If ICON exceeds NACT, then we add the constraint with index IACT(ICON) to */ /* the active set. Apply Givens rotations so that the last N-NACT-1 columns */ /* of Z are orthogonal to the gradient of the new constraint, a scalar */ /* product being set to zero if its nonzero value could be due to computer */ /* rounding errors. The array DXNEW is used for working space. */ if (icon <= nact) { goto L260; } kk = iact[icon]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dxnew[i__] = a[i__ + kk * a_dim1]; } tot = 0.; k = *n; L100: if (k > nact) { sp = 0.; spabs = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = z__[i__ + k * z_dim1] * dxnew[i__]; sp += temp; spabs += fabs(temp); } acca = spabs + fabs(sp) * .1; accb = spabs + fabs(sp) * .2; if (spabs >= acca || acca >= accb) { sp = 0.; } if (tot == 0.) { tot = sp; } else { kp = k + 1; temp = sqrt(sp * sp + tot * tot); alpha = sp / temp; beta = tot / temp; tot = temp; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = alpha * z__[i__ + k * z_dim1] + beta * z__[i__ + kp * z_dim1]; z__[i__ + kp * z_dim1] = alpha * z__[i__ + kp * z_dim1] - beta * z__[i__ + k * z_dim1]; z__[i__ + k * z_dim1] = temp; } } --k; goto L100; } /* Add the new constraint if this can be done without a deletion from the */ /* active set. */ if (tot != 0.) { ++nact; zdota[nact] = tot; vmultc[icon] = vmultc[nact]; vmultc[nact] = 0.; goto L210; } /* The next instruction is reached if a deletion has to be made from the */ /* active set in order to make room for the new active constraint, because */ /* the new constraint gradient is a linear combination of the gradients of */ /* the old active constraints. Set the elements of VMULTD to the multipliers */ /* of the linear combination. Further, set IOUT to the index of the */ /* constraint to be deleted, but branch if no suitable index can be found. */ ratio = -1.; k = nact; L130: zdotv = 0.; zdvabs = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = z__[i__ + k * z_dim1] * dxnew[i__]; zdotv += temp; zdvabs += fabs(temp); } acca = zdvabs + fabs(zdotv) * .1; accb = zdvabs + fabs(zdotv) * .2; if (zdvabs < acca && acca < accb) { temp = zdotv / zdota[k]; if (temp > 0. && iact[k] <= *m) { tempa = vmultc[k] / temp; if (ratio < 0. || tempa < ratio) { ratio = tempa; iout = k; } } if (k >= 2) { kw = iact[k]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dxnew[i__] -= temp * a[i__ + kw * a_dim1]; } } vmultd[k] = temp; } else { vmultd[k] = 0.; } --k; if (k > 0) { goto L130; } if (ratio < 0.) { goto L490; } /* Revise the Lagrange multipliers and reorder the active constraints so */ /* that the one to be replaced is at the end of the list. Also calculate the */ /* new value of ZDOTA(NACT) and branch if it is not acceptable. */ i__1 = nact; for (k = 1; k <= i__1; ++k) { d__1 = 0., d__2 = vmultc[k] - ratio * vmultd[k]; vmultc[k] = MAX2(d__1,d__2); } if (icon < nact) { isave = iact[icon]; vsave = vmultc[icon]; k = icon; L170: kp = k + 1; kw = iact[kp]; sp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sp += z__[i__ + k * z_dim1] * a[i__ + kw * a_dim1]; } d__1 = zdota[kp]; temp = sqrt(sp * sp + d__1 * d__1); alpha = zdota[kp] / temp; beta = sp / temp; zdota[kp] = alpha * zdota[k]; zdota[k] = temp; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = alpha * z__[i__ + kp * z_dim1] + beta * z__[i__ + k * z_dim1]; z__[i__ + kp * z_dim1] = alpha * z__[i__ + k * z_dim1] - beta * z__[i__ + kp * z_dim1]; z__[i__ + k * z_dim1] = temp; } iact[k] = kw; vmultc[k] = vmultc[kp]; k = kp; if (k < nact) { goto L170; } iact[k] = isave; vmultc[k] = vsave; } temp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp += z__[i__ + nact * z_dim1] * a[i__ + kk * a_dim1]; } if (temp == 0.) { goto L490; } zdota[nact] = temp; vmultc[icon] = 0.; vmultc[nact] = ratio; /* Update IACT and ensure that the objective function continues to be */ /* treated as the last active constraint when MCON>M. */ L210: iact[icon] = iact[nact]; iact[nact] = kk; if (mcon > *m && kk != mcon) { k = nact - 1; sp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sp += z__[i__ + k * z_dim1] * a[i__ + kk * a_dim1]; } d__1 = zdota[nact]; temp = sqrt(sp * sp + d__1 * d__1); alpha = zdota[nact] / temp; beta = sp / temp; zdota[nact] = alpha * zdota[k]; zdota[k] = temp; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = alpha * z__[i__ + nact * z_dim1] + beta * z__[i__ + k * z_dim1]; z__[i__ + nact * z_dim1] = alpha * z__[i__ + k * z_dim1] - beta * z__[i__ + nact * z_dim1]; z__[i__ + k * z_dim1] = temp; } iact[nact] = iact[k]; iact[k] = kk; temp = vmultc[k]; vmultc[k] = vmultc[nact]; vmultc[nact] = temp; } /* If stage one is in progress, then set SDIRN to the direction of the next */ /* change to the current vector of variables. */ if (mcon > *m) { goto L320; } kk = iact[nact]; temp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp += sdirn[i__] * a[i__ + kk * a_dim1]; } temp += -1.; temp /= zdota[nact]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sdirn[i__] -= temp * z__[i__ + nact * z_dim1]; } goto L340; /* Delete the constraint that has the index IACT(ICON) from the active set. */ L260: if (icon < nact) { isave = iact[icon]; vsave = vmultc[icon]; k = icon; L270: kp = k + 1; kk = iact[kp]; sp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sp += z__[i__ + k * z_dim1] * a[i__ + kk * a_dim1]; } d__1 = zdota[kp]; temp = sqrt(sp * sp + d__1 * d__1); alpha = zdota[kp] / temp; beta = sp / temp; zdota[kp] = alpha * zdota[k]; zdota[k] = temp; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = alpha * z__[i__ + kp * z_dim1] + beta * z__[i__ + k * z_dim1]; z__[i__ + kp * z_dim1] = alpha * z__[i__ + k * z_dim1] - beta * z__[i__ + kp * z_dim1]; z__[i__ + k * z_dim1] = temp; } iact[k] = kk; vmultc[k] = vmultc[kp]; k = kp; if (k < nact) { goto L270; } iact[k] = isave; vmultc[k] = vsave; } --nact; /* If stage one is in progress, then set SDIRN to the direction of the next */ /* change to the current vector of variables. */ if (mcon > *m) { goto L320; } temp = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp += sdirn[i__] * z__[i__ + (nact + 1) * z_dim1]; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sdirn[i__] -= temp * z__[i__ + (nact + 1) * z_dim1]; } goto L340; /* Pick the next search direction of stage two. */ L320: temp = 1. / zdota[nact]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sdirn[i__] = temp * z__[i__ + nact * z_dim1]; } /* Calculate the step to the boundary of the trust region or take the step */ /* that reduces RESMAX to zero. The two statements below that include the */ /* factor 1.0E-6 prevent some harmless underflows that occurred in a test */ /* calculation. Further, we skip the step if it could be zero within a */ /* reasonable tolerance for computer rounding errors. */ L340: dd = *rho * *rho; sd = 0.; ss = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if ((d__1 = dx[i__], fabs(d__1)) >= *rho * 1e-6f) { d__2 = dx[i__]; dd -= d__2 * d__2; } sd += dx[i__] * sdirn[i__]; d__1 = sdirn[i__]; ss += d__1 * d__1; } if (dd <= 0.) { goto L490; } temp = sqrt(ss * dd); if (fabs(sd) >= temp * 1e-6f) { temp = sqrt(ss * dd + sd * sd); } stpful = dd / (temp + sd); step = stpful; if (mcon == *m) { acca = step + resmax * .1; accb = step + resmax * .2; if (step >= acca || acca >= accb) { goto L480; } step = MIN2(step,resmax); } /* SGJ, 2010: check for error here */ if (nlopt_isinf(step)) return NLOPT_ROUNDOFF_LIMITED; /* Set DXNEW to the new variables if STEP is the steplength, and reduce */ /* RESMAX to the corresponding maximum residual if stage one is being done. */ /* Because DXNEW will be changed during the calculation of some Lagrange */ /* multipliers, it will be restored to the following value later. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dxnew[i__] = dx[i__] + step * sdirn[i__]; } if (mcon == *m) { resold = resmax; resmax = 0.; i__1 = nact; for (k = 1; k <= i__1; ++k) { kk = iact[k]; temp = b[kk]; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp -= a[i__ + kk * a_dim1] * dxnew[i__]; } resmax = MAX2(resmax,temp); } } /* Set VMULTD to the VMULTC vector that would occur if DX became DXNEW. A */ /* device is included to force VMULTD(K)=0.0 if deviations from this value */ /* can be attributed to computer rounding errors. First calculate the new */ /* Lagrange multipliers. */ k = nact; L390: zdotw = 0.; zdwabs = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = z__[i__ + k * z_dim1] * dxnew[i__]; zdotw += temp; zdwabs += fabs(temp); } acca = zdwabs + fabs(zdotw) * .1; accb = zdwabs + fabs(zdotw) * .2; if (zdwabs >= acca || acca >= accb) { zdotw = 0.; } vmultd[k] = zdotw / zdota[k]; if (k >= 2) { kk = iact[k]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dxnew[i__] -= vmultd[k] * a[i__ + kk * a_dim1]; } --k; goto L390; } if (mcon > *m) { d__1 = 0., d__2 = vmultd[nact]; vmultd[nact] = MAX2(d__1,d__2); } /* Complete VMULTC by finding the new constraint residuals. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dxnew[i__] = dx[i__] + step * sdirn[i__]; } if (mcon > nact) { kl = nact + 1; i__1 = mcon; for (k = kl; k <= i__1; ++k) { kk = iact[k]; sum = resmax - b[kk]; sumabs = resmax + (d__1 = b[kk], fabs(d__1)); i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[i__ + kk * a_dim1] * dxnew[i__]; sum += temp; sumabs += fabs(temp); } acca = sumabs + fabs(sum) * .1f; accb = sumabs + fabs(sum) * .2f; if (sumabs >= acca || acca >= accb) { sum = 0.f; } vmultd[k] = sum; } } /* Calculate the fraction of the step from DX to DXNEW that will be taken. */ ratio = 1.; icon = 0; i__1 = mcon; for (k = 1; k <= i__1; ++k) { if (vmultd[k] < 0.) { temp = vmultc[k] / (vmultc[k] - vmultd[k]); if (temp < ratio) { ratio = temp; icon = k; } } } /* Update DX, VMULTC and RESMAX. */ temp = 1. - ratio; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dx[i__] = temp * dx[i__] + ratio * dxnew[i__]; } i__1 = mcon; for (k = 1; k <= i__1; ++k) { d__1 = 0., d__2 = temp * vmultc[k] + ratio * vmultd[k]; vmultc[k] = MAX2(d__1,d__2); } if (mcon == *m) { resmax = resold + ratio * (resmax - resold); } /* If the full step is not acceptable then begin another iteration. */ /* Otherwise switch to stage two or end the calculation. */ if (icon > 0) { goto L70; } if (step == stpful) { goto L500; } L480: mcon = *m + 1; icon = mcon; iact[mcon] = mcon; vmultc[mcon] = 0.; goto L60; /* We employ any freedom that may be available to reduce the objective */ /* function before returning a DX whose length is less than RHO. */ L490: if (mcon == *m) { goto L480; } *ifull = 0; L500: return NLOPT_SUCCESS; } /* trstlp */
{ "pile_set_name": "Github" }
/* ----------------------------------------------------------------------------------------------------------- Software License for The Fraunhofer FDK AAC Codec Library for Android � Copyright 1995 - 2013 Fraunhofer-Gesellschaft zur F�rderung der angewandten Forschung e.V. All rights reserved. 1. INTRODUCTION The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio. This FDK AAC Codec software is intended to be used on a wide variety of Android devices. AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part of the MPEG specifications. Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer) may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners individually for the purpose of encoding or decoding bit streams in products that are compliant with the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec software may already be covered under those patent licenses when it is used for those licensed purposes only. Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality, are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional applications information and documentation. 2. COPYRIGHT LICENSE Redistribution and use in source and binary forms, with or without modification, are permitted without payment of copyright license fees provided that you satisfy the following conditions: You must retain the complete text of this software license in redistributions of the FDK AAC Codec or your modifications thereto in source code form. You must retain the complete text of this software license in the documentation and/or other materials provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form. You must make available free of charge copies of the complete source code of the FDK AAC Codec and your modifications thereto to recipients of copies in binary form. The name of Fraunhofer may not be used to endorse or promote products derived from this library without prior written permission. You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec software or your modifications thereto. Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software and the date of any change. For modified versions of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android." 3. NO PATENT LICENSE NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with respect to this software. You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized by appropriate patent licenses. 4. DISCLAIMER This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages, including but not limited to procurement of substitute goods or services; loss of use, data, or profits, or business interruption, however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence), arising in any way out of the use of this software, even if advised of the possibility of such damage. 5. CONTACT INFORMATION Fraunhofer Institute for Integrated Circuits IIS Attention: Audio and Multimedia Departments - FDK AAC LL Am Wolfsmantel 33 91058 Erlangen, Germany www.iis.fraunhofer.de/amm [email protected] ----------------------------------------------------------------------------------------------------------- */ /******************************** MPEG Audio Encoder ************************** Initial author: M.Werner contents/description: Spreading of energy and weighted tonality ******************************************************************************/ #ifndef _SPREADING_H #define _SPREADING_H #include "common_fix.h" void FDKaacEnc_SpreadingMax(const INT pbCnt, const FIXP_DBL *RESTRICT maskLowFactor, const FIXP_DBL *RESTRICT maskHighFactor, FIXP_DBL *RESTRICT pbSpreadEnergy); #endif /* #ifndef _SPREADING_H */
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE 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 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" #if ENABLE(WEB_AUDIO) #include "FFTFrame.h" #include "Logging.h" #include "VectorMath.h" #include <complex> #include <wtf/MathExtras.h> #ifndef NDEBUG #include <stdio.h> #endif namespace WebCore { void FFTFrame::doPaddedFFT(const float* data, size_t dataSize) { // Zero-pad the impulse response AudioFloatArray paddedResponse(fftSize()); // zero-initialized paddedResponse.copyToRange(data, 0, dataSize); // Get the frequency-domain version of padded response doFFT(paddedResponse.data()); } std::unique_ptr<FFTFrame> FFTFrame::createInterpolatedFrame(const FFTFrame& frame1, const FFTFrame& frame2, double x) { auto newFrame = makeUnique<FFTFrame>(frame1.fftSize()); newFrame->interpolateFrequencyComponents(frame1, frame2, x); // In the time-domain, the 2nd half of the response must be zero, to avoid circular convolution aliasing... int fftSize = newFrame->fftSize(); AudioFloatArray buffer(fftSize); newFrame->doInverseFFT(buffer.data()); buffer.zeroRange(fftSize / 2, fftSize); // Put back into frequency domain. newFrame->doFFT(buffer.data()); return newFrame; } void FFTFrame::interpolateFrequencyComponents(const FFTFrame& frame1, const FFTFrame& frame2, double interp) { // FIXME : with some work, this method could be optimized float* realP = realData(); float* imagP = imagData(); const float* realP1 = frame1.realData(); const float* imagP1 = frame1.imagData(); const float* realP2 = frame2.realData(); const float* imagP2 = frame2.imagData(); m_FFTSize = frame1.fftSize(); m_log2FFTSize = frame1.log2FFTSize(); double s1base = (1.0 - interp); double s2base = interp; double phaseAccum = 0.0; double lastPhase1 = 0.0; double lastPhase2 = 0.0; realP[0] = static_cast<float>(s1base * realP1[0] + s2base * realP2[0]); imagP[0] = static_cast<float>(s1base * imagP1[0] + s2base * imagP2[0]); int n = m_FFTSize / 2; for (int i = 1; i < n; ++i) { std::complex<double> c1(realP1[i], imagP1[i]); std::complex<double> c2(realP2[i], imagP2[i]); double mag1 = abs(c1); double mag2 = abs(c2); // Interpolate magnitudes in decibels double mag1db = 20.0 * log10(mag1); double mag2db = 20.0 * log10(mag2); double s1 = s1base; double s2 = s2base; double magdbdiff = mag1db - mag2db; // Empirical tweak to retain higher-frequency zeroes double threshold = (i > 16) ? 5.0 : 2.0; if (magdbdiff < -threshold && mag1db < 0.0) { s1 = pow(s1, 0.75); s2 = 1.0 - s1; } else if (magdbdiff > threshold && mag2db < 0.0) { s2 = pow(s2, 0.75); s1 = 1.0 - s2; } // Average magnitude by decibels instead of linearly double magdb = s1 * mag1db + s2 * mag2db; double mag = pow(10.0, 0.05 * magdb); // Now, deal with phase double phase1 = arg(c1); double phase2 = arg(c2); double deltaPhase1 = phase1 - lastPhase1; double deltaPhase2 = phase2 - lastPhase2; lastPhase1 = phase1; lastPhase2 = phase2; // Unwrap phase deltas if (deltaPhase1 > piDouble) deltaPhase1 -= 2.0 * piDouble; if (deltaPhase1 < -piDouble) deltaPhase1 += 2.0 * piDouble; if (deltaPhase2 > piDouble) deltaPhase2 -= 2.0 * piDouble; if (deltaPhase2 < -piDouble) deltaPhase2 += 2.0 * piDouble; // Blend group-delays double deltaPhaseBlend; if (deltaPhase1 - deltaPhase2 > piDouble) deltaPhaseBlend = s1 * deltaPhase1 + s2 * (2.0 * piDouble + deltaPhase2); else if (deltaPhase2 - deltaPhase1 > piDouble) deltaPhaseBlend = s1 * (2.0 * piDouble + deltaPhase1) + s2 * deltaPhase2; else deltaPhaseBlend = s1 * deltaPhase1 + s2 * deltaPhase2; phaseAccum += deltaPhaseBlend; // Unwrap if (phaseAccum > piDouble) phaseAccum -= 2.0 * piDouble; if (phaseAccum < -piDouble) phaseAccum += 2.0 * piDouble; std::complex<double> c = std::polar(mag, phaseAccum); realP[i] = static_cast<float>(c.real()); imagP[i] = static_cast<float>(c.imag()); } } void FFTFrame::scaleFFT(float factor) { VectorMath::vsmul(realData(), 1, &factor, realData(), 1, fftSize()); VectorMath::vsmul(imagData(), 1, &factor, imagData(), 1, fftSize()); } void FFTFrame::multiply(const FFTFrame& frame) { FFTFrame& frame1 = *this; const FFTFrame& frame2 = frame; float* realP1 = frame1.realData(); float* imagP1 = frame1.imagData(); const float* realP2 = frame2.realData(); const float* imagP2 = frame2.imagData(); unsigned halfSize = m_FFTSize / 2; float real0 = realP1[0]; float imag0 = imagP1[0]; // Complex multiply VectorMath::zvmul(realP1, imagP1, realP2, imagP2, realP1, imagP1, halfSize); // Multiply the packed DC/nyquist component realP1[0] = real0 * realP2[0]; imagP1[0] = imag0 * imagP2[0]; } double FFTFrame::extractAverageGroupDelay() { float* realP = realData(); float* imagP = imagData(); double aveSum = 0.0; double weightSum = 0.0; double lastPhase = 0.0; int halfSize = fftSize() / 2; const double kSamplePhaseDelay = (2.0 * piDouble) / double(fftSize()); // Calculate weighted average group delay for (int i = 0; i < halfSize; i++) { std::complex<double> c(realP[i], imagP[i]); double mag = abs(c); double phase = arg(c); double deltaPhase = phase - lastPhase; lastPhase = phase; // Unwrap if (deltaPhase < -piDouble) deltaPhase += 2.0 * piDouble; if (deltaPhase > piDouble) deltaPhase -= 2.0 * piDouble; aveSum += mag * deltaPhase; weightSum += mag; } // Note how we invert the phase delta wrt frequency since this is how group delay is defined double ave = aveSum / weightSum; double aveSampleDelay = -ave / kSamplePhaseDelay; // Leave 20 sample headroom (for leading edge of impulse) if (aveSampleDelay > 20.0) aveSampleDelay -= 20.0; // Remove average group delay (minus 20 samples for headroom) addConstantGroupDelay(-aveSampleDelay); // Remove DC offset realP[0] = 0.0f; return aveSampleDelay; } void FFTFrame::addConstantGroupDelay(double sampleFrameDelay) { int halfSize = fftSize() / 2; float* realP = realData(); float* imagP = imagData(); const double kSamplePhaseDelay = (2.0 * piDouble) / double(fftSize()); double phaseAdj = -sampleFrameDelay * kSamplePhaseDelay; // Add constant group delay for (int i = 1; i < halfSize; i++) { std::complex<double> c(realP[i], imagP[i]); double mag = abs(c); double phase = arg(c); phase += i * phaseAdj; std::complex<double> c2 = std::polar(mag, phase); realP[i] = static_cast<float>(c2.real()); imagP[i] = static_cast<float>(c2.imag()); } } #ifndef NDEBUG void FFTFrame::print() { FFTFrame& frame = *this; float* realP = frame.realData(); float* imagP = frame.imagData(); LOG(WebAudio, "**** \n"); LOG(WebAudio, "DC = %f : nyquist = %f\n", realP[0], imagP[0]); int n = m_FFTSize / 2; for (int i = 1; i < n; i++) { double mag = std::hypot(realP[i], imagP[i]); double phase = atan2(realP[i], imagP[i]); LOG(WebAudio, "[%d] (%f %f)\n", i, mag, phase); } LOG(WebAudio, "****\n"); } #endif // NDEBUG } // namespace WebCore #endif // ENABLE(WEB_AUDIO)
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Tue Jun 26 22:36:42 PDT 2012--> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Jackson-datatype-JODA 2.0.4 API </TITLE> <SCRIPT type="text/javascript"> targetPage = "" + window.location.search; if (targetPage != "" && targetPage != "undefined") targetPage = targetPage.substring(1); if (targetPage.indexOf(":") != -1) targetPage = "undefined"; function loadFrames() { if (targetPage != "" && targetPage != "undefined") top.classFrame.location = top.targetPage; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <FRAMESET cols="20%,80%" title="" onLoad="top.loadFrames()"> <FRAMESET rows="30%,70%" title="" onLoad="top.loadFrames()"> <FRAME src="overview-frame.html" name="packageListFrame" title="All Packages"> <FRAME src="allclasses-frame.html" name="packageFrame" title="All classes and interfaces (except non-static nested types)"> </FRAMESET> <FRAME src="overview-summary.html" name="classFrame" title="Package, class and interface descriptions" scrolling="yes"> <NOFRAMES> <H2> Frame Alert</H2> <P> This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. <BR> Link to<A HREF="overview-summary.html">Non-frame version.</A> </NOFRAMES> </FRAMESET> </HTML>
{ "pile_set_name": "Github" }
# label.tcl -- # # This demonstration script creates a toplevel window containing # several label widgets. # # RCS: @(#) $Id: label.tcl,v 1.6 2004/12/21 11:56:35 dkf Exp $ if {![info exists widgetDemo]} { error "This script should be run from the \"widget\" demo." } package require Tk set w .label catch {destroy $w} toplevel $w wm title $w "Label Demonstration" wm iconname $w "label" positionWindow $w label $w.msg -font $font -wraplength 4i -justify left -text "Five labels are displayed below: three textual ones on the left, and a bitmap label and a text label on the right. Labels are pretty boring because you can't do anything with them." pack $w.msg -side top ## See Code / Dismiss buttons set btns [addSeeDismiss $w.buttons $w] pack $btns -side bottom -fill x frame $w.left frame $w.right pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both label $w.left.l1 -text "First label" label $w.left.l2 -text "Second label, raised" -relief raised label $w.left.l3 -text "Third label, sunken" -relief sunken pack $w.left.l1 $w.left.l2 $w.left.l3 -side top -expand yes -pady 2 -anchor w # Main widget program sets variable tk_demoDirectory label $w.right.bitmap -borderwidth 2 -relief sunken \ -bitmap @[file join $tk_demoDirectory images face.xbm] label $w.right.caption -text "Tcl/Tk Proprietor" pack $w.right.bitmap $w.right.caption -side top
{ "pile_set_name": "Github" }
/* * PCI Express PCI Hot Plug Driver * * Copyright (C) 1995,2001 Compaq Computer Corporation * Copyright (C) 2001 Greg Kroah-Hartman ([email protected]) * Copyright (C) 2001 IBM Corp. * Copyright (C) 2003-2004 Intel Corporation * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Send feedback to <[email protected]>,<[email protected]> * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/signal.h> #include <linux/jiffies.h> #include <linux/timer.h> #include <linux/pci.h> #include <linux/interrupt.h> #include <linux/time.h> #include <linux/slab.h> #include "../pci.h" #include "pciehp.h" static inline struct pci_dev *ctrl_dev(struct controller *ctrl) { return ctrl->pcie->port; } static irqreturn_t pcie_isr(int irq, void *dev_id); static void start_int_poll_timer(struct controller *ctrl, int sec); /* This is the interrupt polling timeout function. */ static void int_poll_timeout(unsigned long data) { struct controller *ctrl = (struct controller *)data; /* Poll for interrupt events. regs == NULL => polling */ pcie_isr(0, ctrl); init_timer(&ctrl->poll_timer); if (!pciehp_poll_time) pciehp_poll_time = 2; /* default polling interval is 2 sec */ start_int_poll_timer(ctrl, pciehp_poll_time); } /* This function starts the interrupt polling timer. */ static void start_int_poll_timer(struct controller *ctrl, int sec) { /* Clamp to sane value */ if ((sec <= 0) || (sec > 60)) sec = 2; ctrl->poll_timer.function = &int_poll_timeout; ctrl->poll_timer.data = (unsigned long)ctrl; ctrl->poll_timer.expires = jiffies + sec * HZ; add_timer(&ctrl->poll_timer); } static inline int pciehp_request_irq(struct controller *ctrl) { int retval, irq = ctrl->pcie->irq; /* Install interrupt polling timer. Start with 10 sec delay */ if (pciehp_poll_mode) { init_timer(&ctrl->poll_timer); start_int_poll_timer(ctrl, 10); return 0; } /* Installs the interrupt handler */ retval = request_irq(irq, pcie_isr, IRQF_SHARED, MY_NAME, ctrl); if (retval) ctrl_err(ctrl, "Cannot get irq %d for the hotplug controller\n", irq); return retval; } static inline void pciehp_free_irq(struct controller *ctrl) { if (pciehp_poll_mode) del_timer_sync(&ctrl->poll_timer); else free_irq(ctrl->pcie->irq, ctrl); } static int pcie_poll_cmd(struct controller *ctrl, int timeout) { struct pci_dev *pdev = ctrl_dev(ctrl); u16 slot_status; while (true) { pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status); if (slot_status == (u16) ~0) { ctrl_info(ctrl, "%s: no response from device\n", __func__); return 0; } if (slot_status & PCI_EXP_SLTSTA_CC) { pcie_capability_write_word(pdev, PCI_EXP_SLTSTA, PCI_EXP_SLTSTA_CC); return 1; } if (timeout < 0) break; msleep(10); timeout -= 10; } return 0; /* timeout */ } static void pcie_wait_cmd(struct controller *ctrl) { unsigned int msecs = pciehp_poll_mode ? 2500 : 1000; unsigned long duration = msecs_to_jiffies(msecs); unsigned long cmd_timeout = ctrl->cmd_started + duration; unsigned long now, timeout; int rc; /* * If the controller does not generate notifications for command * completions, we never need to wait between writes. */ if (NO_CMD_CMPL(ctrl)) return; if (!ctrl->cmd_busy) return; /* * Even if the command has already timed out, we want to call * pcie_poll_cmd() so it can clear PCI_EXP_SLTSTA_CC. */ now = jiffies; if (time_before_eq(cmd_timeout, now)) timeout = 1; else timeout = cmd_timeout - now; if (ctrl->slot_ctrl & PCI_EXP_SLTCTL_HPIE && ctrl->slot_ctrl & PCI_EXP_SLTCTL_CCIE) rc = wait_event_timeout(ctrl->queue, !ctrl->cmd_busy, timeout); else rc = pcie_poll_cmd(ctrl, jiffies_to_msecs(timeout)); /* * Controllers with errata like Intel CF118 don't generate * completion notifications unless the power/indicator/interlock * control bits are changed. On such controllers, we'll emit this * timeout message when we wait for completion of commands that * don't change those bits, e.g., commands that merely enable * interrupts. */ if (!rc) ctrl_info(ctrl, "Timeout on hotplug command %#06x (issued %u msec ago)\n", ctrl->slot_ctrl, jiffies_to_msecs(jiffies - ctrl->cmd_started)); } static void pcie_do_write_cmd(struct controller *ctrl, u16 cmd, u16 mask, bool wait) { struct pci_dev *pdev = ctrl_dev(ctrl); u16 slot_ctrl; mutex_lock(&ctrl->ctrl_lock); /* * Always wait for any previous command that might still be in progress */ pcie_wait_cmd(ctrl); pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &slot_ctrl); if (slot_ctrl == (u16) ~0) { ctrl_info(ctrl, "%s: no response from device\n", __func__); goto out; } slot_ctrl &= ~mask; slot_ctrl |= (cmd & mask); ctrl->cmd_busy = 1; smp_mb(); pcie_capability_write_word(pdev, PCI_EXP_SLTCTL, slot_ctrl); ctrl->cmd_started = jiffies; ctrl->slot_ctrl = slot_ctrl; /* * Optionally wait for the hardware to be ready for a new command, * indicating completion of the above issued command. */ if (wait) pcie_wait_cmd(ctrl); out: mutex_unlock(&ctrl->ctrl_lock); } /** * pcie_write_cmd - Issue controller command * @ctrl: controller to which the command is issued * @cmd: command value written to slot control register * @mask: bitmask of slot control register to be modified */ static void pcie_write_cmd(struct controller *ctrl, u16 cmd, u16 mask) { pcie_do_write_cmd(ctrl, cmd, mask, true); } /* Same as above without waiting for the hardware to latch */ static void pcie_write_cmd_nowait(struct controller *ctrl, u16 cmd, u16 mask) { pcie_do_write_cmd(ctrl, cmd, mask, false); } bool pciehp_check_link_active(struct controller *ctrl) { struct pci_dev *pdev = ctrl_dev(ctrl); u16 lnk_status; bool ret; pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnk_status); ret = !!(lnk_status & PCI_EXP_LNKSTA_DLLLA); if (ret) ctrl_dbg(ctrl, "%s: lnk_status = %x\n", __func__, lnk_status); return ret; } static void __pcie_wait_link_active(struct controller *ctrl, bool active) { int timeout = 1000; if (pciehp_check_link_active(ctrl) == active) return; while (timeout > 0) { msleep(10); timeout -= 10; if (pciehp_check_link_active(ctrl) == active) return; } ctrl_dbg(ctrl, "Data Link Layer Link Active not %s in 1000 msec\n", active ? "set" : "cleared"); } static void pcie_wait_link_active(struct controller *ctrl) { __pcie_wait_link_active(ctrl, true); } static bool pci_bus_check_dev(struct pci_bus *bus, int devfn) { u32 l; int count = 0; int delay = 1000, step = 20; bool found = false; do { found = pci_bus_read_dev_vendor_id(bus, devfn, &l, 0); count++; if (found) break; msleep(step); delay -= step; } while (delay > 0); if (count > 1 && pciehp_debug) printk(KERN_DEBUG "pci %04x:%02x:%02x.%d id reading try %d times with interval %d ms to get %08x\n", pci_domain_nr(bus), bus->number, PCI_SLOT(devfn), PCI_FUNC(devfn), count, step, l); return found; } int pciehp_check_link_status(struct controller *ctrl) { struct pci_dev *pdev = ctrl_dev(ctrl); bool found; u16 lnk_status; /* * Data Link Layer Link Active Reporting must be capable for * hot-plug capable downstream port. But old controller might * not implement it. In this case, we wait for 1000 ms. */ if (ctrl->link_active_reporting) pcie_wait_link_active(ctrl); else msleep(1000); /* wait 100ms before read pci conf, and try in 1s */ msleep(100); found = pci_bus_check_dev(ctrl->pcie->port->subordinate, PCI_DEVFN(0, 0)); pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnk_status); ctrl_dbg(ctrl, "%s: lnk_status = %x\n", __func__, lnk_status); if ((lnk_status & PCI_EXP_LNKSTA_LT) || !(lnk_status & PCI_EXP_LNKSTA_NLW)) { ctrl_err(ctrl, "link training error: status %#06x\n", lnk_status); return -1; } pcie_update_link_speed(ctrl->pcie->port->subordinate, lnk_status); if (!found) return -1; return 0; } static int __pciehp_link_set(struct controller *ctrl, bool enable) { struct pci_dev *pdev = ctrl_dev(ctrl); u16 lnk_ctrl; pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &lnk_ctrl); if (enable) lnk_ctrl &= ~PCI_EXP_LNKCTL_LD; else lnk_ctrl |= PCI_EXP_LNKCTL_LD; pcie_capability_write_word(pdev, PCI_EXP_LNKCTL, lnk_ctrl); ctrl_dbg(ctrl, "%s: lnk_ctrl = %x\n", __func__, lnk_ctrl); return 0; } static int pciehp_link_enable(struct controller *ctrl) { return __pciehp_link_set(ctrl, true); } void pciehp_get_attention_status(struct slot *slot, u8 *status) { struct controller *ctrl = slot->ctrl; struct pci_dev *pdev = ctrl_dev(ctrl); u16 slot_ctrl; pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &slot_ctrl); ctrl_dbg(ctrl, "%s: SLOTCTRL %x, value read %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_ctrl); switch (slot_ctrl & PCI_EXP_SLTCTL_AIC) { case PCI_EXP_SLTCTL_ATTN_IND_ON: *status = 1; /* On */ break; case PCI_EXP_SLTCTL_ATTN_IND_BLINK: *status = 2; /* Blink */ break; case PCI_EXP_SLTCTL_ATTN_IND_OFF: *status = 0; /* Off */ break; default: *status = 0xFF; break; } } void pciehp_get_power_status(struct slot *slot, u8 *status) { struct controller *ctrl = slot->ctrl; struct pci_dev *pdev = ctrl_dev(ctrl); u16 slot_ctrl; pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &slot_ctrl); ctrl_dbg(ctrl, "%s: SLOTCTRL %x value read %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_ctrl); switch (slot_ctrl & PCI_EXP_SLTCTL_PCC) { case PCI_EXP_SLTCTL_PWR_ON: *status = 1; /* On */ break; case PCI_EXP_SLTCTL_PWR_OFF: *status = 0; /* Off */ break; default: *status = 0xFF; break; } } void pciehp_get_latch_status(struct slot *slot, u8 *status) { struct pci_dev *pdev = ctrl_dev(slot->ctrl); u16 slot_status; pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status); *status = !!(slot_status & PCI_EXP_SLTSTA_MRLSS); } void pciehp_get_adapter_status(struct slot *slot, u8 *status) { struct pci_dev *pdev = ctrl_dev(slot->ctrl); u16 slot_status; pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status); *status = !!(slot_status & PCI_EXP_SLTSTA_PDS); } int pciehp_query_power_fault(struct slot *slot) { struct pci_dev *pdev = ctrl_dev(slot->ctrl); u16 slot_status; pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status); return !!(slot_status & PCI_EXP_SLTSTA_PFD); } void pciehp_set_attention_status(struct slot *slot, u8 value) { struct controller *ctrl = slot->ctrl; u16 slot_cmd; if (!ATTN_LED(ctrl)) return; switch (value) { case 0: /* turn off */ slot_cmd = PCI_EXP_SLTCTL_ATTN_IND_OFF; break; case 1: /* turn on */ slot_cmd = PCI_EXP_SLTCTL_ATTN_IND_ON; break; case 2: /* turn blink */ slot_cmd = PCI_EXP_SLTCTL_ATTN_IND_BLINK; break; default: return; } pcie_write_cmd_nowait(ctrl, slot_cmd, PCI_EXP_SLTCTL_AIC); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_cmd); } void pciehp_green_led_on(struct slot *slot) { struct controller *ctrl = slot->ctrl; if (!PWR_LED(ctrl)) return; pcie_write_cmd_nowait(ctrl, PCI_EXP_SLTCTL_PWR_IND_ON, PCI_EXP_SLTCTL_PIC); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, PCI_EXP_SLTCTL_PWR_IND_ON); } void pciehp_green_led_off(struct slot *slot) { struct controller *ctrl = slot->ctrl; if (!PWR_LED(ctrl)) return; pcie_write_cmd_nowait(ctrl, PCI_EXP_SLTCTL_PWR_IND_OFF, PCI_EXP_SLTCTL_PIC); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, PCI_EXP_SLTCTL_PWR_IND_OFF); } void pciehp_green_led_blink(struct slot *slot) { struct controller *ctrl = slot->ctrl; if (!PWR_LED(ctrl)) return; pcie_write_cmd_nowait(ctrl, PCI_EXP_SLTCTL_PWR_IND_BLINK, PCI_EXP_SLTCTL_PIC); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, PCI_EXP_SLTCTL_PWR_IND_BLINK); } int pciehp_power_on_slot(struct slot *slot) { struct controller *ctrl = slot->ctrl; struct pci_dev *pdev = ctrl_dev(ctrl); u16 slot_status; int retval; /* Clear sticky power-fault bit from previous power failures */ pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status); if (slot_status & PCI_EXP_SLTSTA_PFD) pcie_capability_write_word(pdev, PCI_EXP_SLTSTA, PCI_EXP_SLTSTA_PFD); ctrl->power_fault_detected = 0; pcie_write_cmd(ctrl, PCI_EXP_SLTCTL_PWR_ON, PCI_EXP_SLTCTL_PCC); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, PCI_EXP_SLTCTL_PWR_ON); retval = pciehp_link_enable(ctrl); if (retval) ctrl_err(ctrl, "%s: Can not enable the link!\n", __func__); return retval; } void pciehp_power_off_slot(struct slot *slot) { struct controller *ctrl = slot->ctrl; pcie_write_cmd(ctrl, PCI_EXP_SLTCTL_PWR_OFF, PCI_EXP_SLTCTL_PCC); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, PCI_EXP_SLTCTL_PWR_OFF); } static irqreturn_t pcie_isr(int irq, void *dev_id) { struct controller *ctrl = (struct controller *)dev_id; struct pci_dev *pdev = ctrl_dev(ctrl); struct pci_bus *subordinate = pdev->subordinate; struct pci_dev *dev; struct slot *slot = ctrl->slot; u16 detected, intr_loc; u8 present; bool link; /* * In order to guarantee that all interrupt events are * serviced, we need to re-inspect Slot Status register after * clearing what is presumed to be the last pending interrupt. */ intr_loc = 0; do { pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &detected); if (detected == (u16) ~0) { ctrl_info(ctrl, "%s: no response from device\n", __func__); return IRQ_HANDLED; } detected &= (PCI_EXP_SLTSTA_ABP | PCI_EXP_SLTSTA_PFD | PCI_EXP_SLTSTA_PDC | PCI_EXP_SLTSTA_CC | PCI_EXP_SLTSTA_DLLSC); detected &= ~intr_loc; intr_loc |= detected; if (!intr_loc) return IRQ_NONE; if (detected) pcie_capability_write_word(pdev, PCI_EXP_SLTSTA, intr_loc); } while (detected); ctrl_dbg(ctrl, "pending interrupts %#06x from Slot Status\n", intr_loc); /* Check Command Complete Interrupt Pending */ if (intr_loc & PCI_EXP_SLTSTA_CC) { ctrl->cmd_busy = 0; smp_mb(); wake_up(&ctrl->queue); } if (subordinate) { list_for_each_entry(dev, &subordinate->devices, bus_list) { if (dev->ignore_hotplug) { ctrl_dbg(ctrl, "ignoring hotplug event %#06x (%s requested no hotplug)\n", intr_loc, pci_name(dev)); return IRQ_HANDLED; } } } if (!(intr_loc & ~PCI_EXP_SLTSTA_CC)) return IRQ_HANDLED; /* Check Attention Button Pressed */ if (intr_loc & PCI_EXP_SLTSTA_ABP) { ctrl_info(ctrl, "Button pressed on Slot(%s)\n", slot_name(slot)); pciehp_queue_interrupt_event(slot, INT_BUTTON_PRESS); } /* Check Presence Detect Changed */ if (intr_loc & PCI_EXP_SLTSTA_PDC) { pciehp_get_adapter_status(slot, &present); ctrl_info(ctrl, "Card %spresent on Slot(%s)\n", present ? "" : "not ", slot_name(slot)); pciehp_queue_interrupt_event(slot, present ? INT_PRESENCE_ON : INT_PRESENCE_OFF); } /* Check Power Fault Detected */ if ((intr_loc & PCI_EXP_SLTSTA_PFD) && !ctrl->power_fault_detected) { ctrl->power_fault_detected = 1; ctrl_err(ctrl, "Power fault on slot %s\n", slot_name(slot)); pciehp_queue_interrupt_event(slot, INT_POWER_FAULT); } if (intr_loc & PCI_EXP_SLTSTA_DLLSC) { link = pciehp_check_link_active(ctrl); ctrl_info(ctrl, "slot(%s): Link %s event\n", slot_name(slot), link ? "Up" : "Down"); pciehp_queue_interrupt_event(slot, link ? INT_LINK_UP : INT_LINK_DOWN); } return IRQ_HANDLED; } static void pcie_enable_notification(struct controller *ctrl) { u16 cmd, mask; /* * TBD: Power fault detected software notification support. * * Power fault detected software notification is not enabled * now, because it caused power fault detected interrupt storm * on some machines. On those machines, power fault detected * bit in the slot status register was set again immediately * when it is cleared in the interrupt service routine, and * next power fault detected interrupt was notified again. */ /* * Always enable link events: thus link-up and link-down shall * always be treated as hotplug and unplug respectively. Enable * presence detect only if Attention Button is not present. */ cmd = PCI_EXP_SLTCTL_DLLSCE; if (ATTN_BUTTN(ctrl)) cmd |= PCI_EXP_SLTCTL_ABPE; else cmd |= PCI_EXP_SLTCTL_PDCE; if (!pciehp_poll_mode) cmd |= PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE; mask = (PCI_EXP_SLTCTL_PDCE | PCI_EXP_SLTCTL_ABPE | PCI_EXP_SLTCTL_PFDE | PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE | PCI_EXP_SLTCTL_DLLSCE); pcie_write_cmd_nowait(ctrl, cmd, mask); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, cmd); } void pcie_reenable_notification(struct controller *ctrl) { /* * Clear both Presence and Data Link Layer Changed to make sure * those events still fire after we have re-enabled them. */ pcie_capability_write_word(ctrl->pcie->port, PCI_EXP_SLTSTA, PCI_EXP_SLTSTA_PDC | PCI_EXP_SLTSTA_DLLSC); pcie_enable_notification(ctrl); } static void pcie_disable_notification(struct controller *ctrl) { u16 mask; mask = (PCI_EXP_SLTCTL_PDCE | PCI_EXP_SLTCTL_ABPE | PCI_EXP_SLTCTL_MRLSCE | PCI_EXP_SLTCTL_PFDE | PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE | PCI_EXP_SLTCTL_DLLSCE); pcie_write_cmd(ctrl, 0, mask); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, 0); } /* * pciehp has a 1:1 bus:slot relationship so we ultimately want a secondary * bus reset of the bridge, but at the same time we want to ensure that it is * not seen as a hot-unplug, followed by the hot-plug of the device. Thus, * disable link state notification and presence detection change notification * momentarily, if we see that they could interfere. Also, clear any spurious * events after. */ int pciehp_reset_slot(struct slot *slot, int probe) { struct controller *ctrl = slot->ctrl; struct pci_dev *pdev = ctrl_dev(ctrl); u16 stat_mask = 0, ctrl_mask = 0; if (probe) return 0; if (!ATTN_BUTTN(ctrl)) { ctrl_mask |= PCI_EXP_SLTCTL_PDCE; stat_mask |= PCI_EXP_SLTSTA_PDC; } ctrl_mask |= PCI_EXP_SLTCTL_DLLSCE; stat_mask |= PCI_EXP_SLTSTA_DLLSC; pcie_write_cmd(ctrl, 0, ctrl_mask); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, 0); if (pciehp_poll_mode) del_timer_sync(&ctrl->poll_timer); pci_reset_bridge_secondary_bus(ctrl->pcie->port); pcie_capability_write_word(pdev, PCI_EXP_SLTSTA, stat_mask); pcie_write_cmd_nowait(ctrl, ctrl_mask, ctrl_mask); ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__, pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, ctrl_mask); if (pciehp_poll_mode) int_poll_timeout(ctrl->poll_timer.data); return 0; } int pcie_init_notification(struct controller *ctrl) { if (pciehp_request_irq(ctrl)) return -1; pcie_enable_notification(ctrl); ctrl->notification_enabled = 1; return 0; } void pcie_shutdown_notification(struct controller *ctrl) { if (ctrl->notification_enabled) { pcie_disable_notification(ctrl); pciehp_free_irq(ctrl); ctrl->notification_enabled = 0; } } static int pcie_init_slot(struct controller *ctrl) { struct slot *slot; slot = kzalloc(sizeof(*slot), GFP_KERNEL); if (!slot) return -ENOMEM; slot->wq = alloc_workqueue("pciehp-%u", 0, 0, PSN(ctrl)); if (!slot->wq) goto abort; slot->ctrl = ctrl; mutex_init(&slot->lock); mutex_init(&slot->hotplug_lock); INIT_DELAYED_WORK(&slot->work, pciehp_queue_pushbutton_work); ctrl->slot = slot; return 0; abort: kfree(slot); return -ENOMEM; } static void pcie_cleanup_slot(struct controller *ctrl) { struct slot *slot = ctrl->slot; destroy_workqueue(slot->wq); kfree(slot); } static inline void dbg_ctrl(struct controller *ctrl) { struct pci_dev *pdev = ctrl->pcie->port; u16 reg16; if (!pciehp_debug) return; ctrl_info(ctrl, "Slot Capabilities : 0x%08x\n", ctrl->slot_cap); pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &reg16); ctrl_info(ctrl, "Slot Status : 0x%04x\n", reg16); pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &reg16); ctrl_info(ctrl, "Slot Control : 0x%04x\n", reg16); } #define FLAG(x, y) (((x) & (y)) ? '+' : '-') struct controller *pcie_init(struct pcie_device *dev) { struct controller *ctrl; u32 slot_cap, link_cap; struct pci_dev *pdev = dev->port; ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL); if (!ctrl) { dev_err(&dev->device, "%s: Out of memory\n", __func__); goto abort; } ctrl->pcie = dev; pcie_capability_read_dword(pdev, PCI_EXP_SLTCAP, &slot_cap); ctrl->slot_cap = slot_cap; mutex_init(&ctrl->ctrl_lock); init_waitqueue_head(&ctrl->queue); dbg_ctrl(ctrl); /* Check if Data Link Layer Link Active Reporting is implemented */ pcie_capability_read_dword(pdev, PCI_EXP_LNKCAP, &link_cap); if (link_cap & PCI_EXP_LNKCAP_DLLLARC) ctrl->link_active_reporting = 1; /* Clear all remaining event bits in Slot Status register */ pcie_capability_write_word(pdev, PCI_EXP_SLTSTA, PCI_EXP_SLTSTA_ABP | PCI_EXP_SLTSTA_PFD | PCI_EXP_SLTSTA_MRLSC | PCI_EXP_SLTSTA_PDC | PCI_EXP_SLTSTA_CC | PCI_EXP_SLTSTA_DLLSC); ctrl_info(ctrl, "Slot #%d AttnBtn%c PwrCtrl%c MRL%c AttnInd%c PwrInd%c HotPlug%c Surprise%c Interlock%c NoCompl%c LLActRep%c\n", (slot_cap & PCI_EXP_SLTCAP_PSN) >> 19, FLAG(slot_cap, PCI_EXP_SLTCAP_ABP), FLAG(slot_cap, PCI_EXP_SLTCAP_PCP), FLAG(slot_cap, PCI_EXP_SLTCAP_MRLSP), FLAG(slot_cap, PCI_EXP_SLTCAP_AIP), FLAG(slot_cap, PCI_EXP_SLTCAP_PIP), FLAG(slot_cap, PCI_EXP_SLTCAP_HPC), FLAG(slot_cap, PCI_EXP_SLTCAP_HPS), FLAG(slot_cap, PCI_EXP_SLTCAP_EIP), FLAG(slot_cap, PCI_EXP_SLTCAP_NCCS), FLAG(link_cap, PCI_EXP_LNKCAP_DLLLARC)); if (pcie_init_slot(ctrl)) goto abort_ctrl; return ctrl; abort_ctrl: kfree(ctrl); abort: return NULL; } void pciehp_release_ctrl(struct controller *ctrl) { pcie_cleanup_slot(ctrl); kfree(ctrl); }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (c) 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <animated-vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt"> <aapt:attr name="android:drawable"> <vector android:height="24dp" android:width="24dp" android:viewportHeight="24" android:viewportWidth="24"> <group android:name="_R_G"> <group android:name="_R_G_L_1_G" android:translateX="-18.79" android:translateY="-18.292" android:pivotX="30.79" android:pivotY="30.292" android:scaleX="0.2798" android:scaleY="0.2798"> <path android:name="_R_G_L_1_G_D_0_P_0" android:fillColor="#ffde03" android:fillAlpha="1" android:fillType="nonZero" android:pathData=" M50.81 30.34 C50.81,24.34 48.89,19.22 45.04,14.98 C41.18,10.74 36.45,8.63 30.83,8.63 C25.22,8.63 20.48,10.74 16.63,14.98 C12.78,19.22 10.85,24.34 10.85,30.34 C10.85,36.34 12.78,41.45 16.63,45.65 C20.48,49.86 25.22,51.96 30.83,51.96 C36.45,51.96 41.18,49.86 45.04,45.65 C48.89,41.45 50.81,36.34 50.81,30.34c M52.51 51.72 C46.63,57.46 39.39,60.33 30.79,60.33 C22.19,60.33 14.95,57.46 9.07,51.72 C3.19,45.98 0.25,38.84 0.25,30.29 C0.25,21.75 3.19,14.6 9.07,8.86 C14.95,3.12 22.19,0.25 30.79,0.25 C39.39,0.25 46.63,3.12 52.51,8.86 C58.39,14.6 61.33,21.75 61.33,30.29 C61.33,38.84 58.39,45.98 52.51,51.72c "/> </group> <group android:name="_R_G_L_0_G_N_2_T_0" android:translateX="-18.79" android:translateY="-18.292" android:pivotX="30.79" android:pivotY="30.292" android:scaleX="0.2798" android:scaleY="0.2798"> <group android:name="_R_G_L_0_G" android:translateX="22.095" android:translateY="21.277"> <path android:name="_R_G_L_0_G_D_0_P_0" android:fillColor="#ffde03" android:fillAlpha="1" android:fillType="nonZero" android:pathData=" M16.89 8.57 C16.89,3.98 13.17,0.25 8.57,0.25 C3.98,0.25 0.25,3.98 0.25,8.57 C0.25,13.17 3.98,16.89 8.57,16.89 C13.17,16.89 16.89,13.17 16.89,8.57c "/> </group> </group> </group> <group android:name="time_group"/> </vector> </aapt:attr> <target android:name="_R_G_L_1_G_D_0_P_0"> <aapt:attr name="android:animation"> <set android:ordering="together"> <objectAnimator android:propertyName="fillColor" android:duration="167" android:startOffset="0" android:valueFrom="#ffde03" android:valueTo="#ffffff" android:valueType="colorType"> <aapt:attr name="android:interpolator"> <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0"/> </aapt:attr> </objectAnimator> </set> </aapt:attr> </target> <target android:name="_R_G_L_0_G_D_0_P_0"> <aapt:attr name="android:animation"> <set android:ordering="together"> <objectAnimator android:propertyName="fillColor" android:duration="167" android:startOffset="0" android:valueFrom="#ffde03" android:valueTo="#ffffff" android:valueType="colorType"> <aapt:attr name="android:interpolator"> <pathInterpolator android:pathData="M 0.0,0.0 c0.167,0.167 0.833,0.833 1.0,1.0"/> </aapt:attr> </objectAnimator> </set> </aapt:attr> </target> <target android:name="time_group"> <aapt:attr name="android:animation"> <set android:ordering="together"> <objectAnimator android:propertyName="translateX" android:duration="183" android:startOffset="0" android:valueFrom="0" android:valueTo="1" android:valueType="floatType"/> </set> </aapt:attr> </target> </animated-vector>
{ "pile_set_name": "Github" }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConfirmationPopup : MonoBehaviour { public TMPro.TextMeshProUGUI Text; public Pop YesPop; public Pop NoPop; public MenuButton YesButton; public MenuButton NoButton; public CanvasGroup BackgroundCanvasGroup; public Pop PopupPop; private System.Action Callback; private System.Action CancelCallback; private bool IsOpen = false; private float OpenPhase = 0f; void OnEnable() { } void Start() { gameObject.SetActive(false); BackgroundCanvasGroup.alpha = 0f; NoButton.OnClick += Hide; YesButton.OnClick += () => { Callback?.Invoke(); Hide(); }; } public void Hide() { if (IsOpen) { Controller.Instance.PlayPopoutSound(); IsOpen = false; StartCoroutine(Close()); CancelCallback?.Invoke(); } } public void Show(string text, System.Action callback, System.Action cancel) { if (!IsOpen) { IsOpen = true; Text.text = text; CancelCallback = cancel; Callback = callback; gameObject.SetActive(true); StartCoroutine(Open()); } } IEnumerator Open() { PopupPop.PopUp(); yield return new WaitForSeconds(0.1f); YesPop.PopUp(); yield return new WaitForSeconds(0.1f); NoPop.PopUp(); } IEnumerator Close() { NoPop.PopOut(); yield return new WaitForSeconds(0.1f); YesPop.PopOut(); yield return new WaitForSeconds(0.1f); PopupPop.PopOut(); yield return new WaitForSeconds(0.4f); gameObject.SetActive(false); } // Update is called once per frame void Update() { if (IsOpen && OpenPhase < 1f) OpenPhase = Mathf.Min(1f, OpenPhase + Time.deltaTime * 2f); if (!IsOpen && OpenPhase > 0f) OpenPhase = Mathf.Max(0f, OpenPhase - Time.deltaTime * 2f); BackgroundCanvasGroup.alpha = OpenPhase; } }
{ "pile_set_name": "Github" }
{ "name": "Fark, Inc", "displayName": "Fark", "properties": [ "fark.net" ], "prevalence": { "tracking": 0, "nonTracking": 0.0000294, "total": 0.0000294 } }
{ "pile_set_name": "Github" }
package edu.stanford.bmir.protege.web.shared.shortform; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableMap; import edu.stanford.bmir.protege.web.shared.DataFactory; import edu.stanford.bmir.protege.web.shared.entity.OWLAnnotationPropertyData; import org.semanticweb.owlapi.model.IRI; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Optional; import static org.semanticweb.owlapi.vocab.OWLRDFVocabulary.RDFS_LABEL; /** * Matthew Horridge * Stanford Center for Biomedical Informatics Research * 17 Jul 2018 */ @AutoValue @GwtCompatible(serializable = true) @JsonInclude(JsonInclude.Include.NON_EMPTY) public abstract class DictionaryLanguageData { private static final String PROPERTY_IRI = "propertyIri"; private static final String LANGUAGE_TAG = "lang"; private DictionaryLanguage dictionaryLanguage = null; @Nonnull public static DictionaryLanguageData get(@Nullable IRI propertyIri, @Nonnull String browserText, @Nullable String lang) { String normalisedLang; if(lang == null) { normalisedLang = ""; } else { normalisedLang = lang.toLowerCase(); } return new AutoValue_DictionaryLanguageData(propertyIri, browserText, normalisedLang); } @JsonCreator @Nonnull public static DictionaryLanguageData get(@Nullable @JsonProperty(PROPERTY_IRI) IRI propertyIri, @Nonnull @JsonProperty(LANGUAGE_TAG) String languageTag) { return get(propertyIri, getBrowserText(propertyIri), languageTag); } public static DictionaryLanguageData localName() { return get(null, ""); } public static DictionaryLanguageData rdfsLabel(@Nonnull String languageTag) { return get(RDFS_LABEL.getIRI(), languageTag); } private static String getBrowserText(@Nullable IRI propertyIri) { if(propertyIri == null) { return ""; } return WellKnownLabellingIris.get(propertyIri) .map(WellKnownLabellingIris::getPrefixedName) .orElse(propertyIri.toString()); } @Nonnull public static DictionaryLanguageData getRdfsLabelWithLang(@Nonnull String lang) { return get(RDFS_LABEL.getIRI(), RDFS_LABEL.getPrefixedName(), lang); } @JsonProperty(PROPERTY_IRI) @Nullable public abstract IRI getAnnotationPropertyIri(); @JsonIgnore @Nonnull public abstract String getAnnotationPropertyBrowserText(); @JsonProperty(LANGUAGE_TAG) @Nonnull public abstract String getLanguageTag(); @JsonIgnore @Nonnull public DictionaryLanguage getDictionaryLanguage() { if(dictionaryLanguage == null) { dictionaryLanguage = createDictionaryLanguage(); } return dictionaryLanguage; } @JsonIgnore @Nonnull public Optional<OWLAnnotationPropertyData> getAnnotationPropertyData() { IRI propertyIri = getAnnotationPropertyIri(); if(propertyIri == null) { return Optional.empty(); } return Optional.of( OWLAnnotationPropertyData.get( DataFactory.getOWLAnnotationProperty(propertyIri), ImmutableMap.of( createDictionaryLanguage(), getBrowserText(propertyIri) ) ) ); } private DictionaryLanguage createDictionaryLanguage() { IRI propertyIri = getAnnotationPropertyIri(); if(propertyIri == null) { return LocalNameDictionaryLanguage.get(); } else { return AnnotationAssertionDictionaryLanguage.get(propertyIri, getLanguageTag()); } } @JsonIgnore public boolean isAnnotationBased() { return getAnnotationPropertyIri() != null; } }
{ "pile_set_name": "Github" }
// Copyright 2017 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.module('goog.iter.es6Test'); goog.setTestOnly('goog.iter.es6Test'); const testSuite = goog.require('goog.testing.testSuite'); const {ShimIterable} = goog.require('goog.iter.es6'); const {range, toArray} = goog.require('goog.iter'); goog.require('goog.testing.jsunit'); /** @return {!Iterator<number>} */ function* gen() { yield* [1, 3, 5]; } /** @return {!ShimIterable<number>} */ function fromEs6Iterator() { return ShimIterable.of(gen()); } /** @return {!ShimIterable<number>} */ function fromEs6Iterable() { return ShimIterable.of({ [Symbol.iterator]() { return gen(); } }); } /** @return {!ShimIterable<number>} */ function fromGoogIterator() { return ShimIterable.of(range(1, 6, 2)); } /** @return {!ShimIterable<number>} */ function fromGoogIterable() { return ShimIterable.of({ __iterator__() { return range(1, 6, 2); } }); } testSuite({ // Start with ES6 testEs6IterableAsIterable() { const iter = fromEs6Iterable(); assertArrayEquals([1, 3, 5], toArray(iter)); assertArrayEquals([1, 3, 5], [...iter]); assertArrayEquals([1, 3, 5], toArray(iter)); assertArrayEquals([1, 3, 5], [...iter]); }, testEs6IterableToEs6Iterator() { assertArrayEquals([1, 3, 5], toArray(fromEs6Iterable().toEs6())); assertArrayEquals([1, 3, 5], [...fromEs6Iterable().toEs6()]); }, testEs6IterableToGoogIterator() { assertArrayEquals([1, 3, 5], toArray(fromEs6Iterable().toGoog())); assertArrayEquals([1, 3, 5], [...fromEs6Iterable().toGoog()]); }, testEs6IteratorAsIterable() { assertArrayEquals([1, 3, 5], toArray(fromEs6Iterator())); assertArrayEquals([1, 3, 5], [...fromEs6Iterator()]); }, testEs6IteratorToEs6Iterator() { assertArrayEquals([1, 3, 5], toArray(fromEs6Iterator().toEs6())); assertArrayEquals([1, 3, 5], [...fromEs6Iterator().toEs6()]); }, testEs6IteratorToGoogIterator() { assertArrayEquals([1, 3, 5], toArray(fromEs6Iterator().toGoog())); assertArrayEquals([1, 3, 5], [...fromEs6Iterator().toGoog()]); }, // Start with Goog testGoogIterableAsIterable() { const iter = fromGoogIterable(); assertArrayEquals([1, 3, 5], toArray(iter)); assertArrayEquals([1, 3, 5], [...iter]); assertArrayEquals([1, 3, 5], toArray(iter)); assertArrayEquals([1, 3, 5], [...iter]); }, testGoogIterableToEs6Iterator() { assertArrayEquals([1, 3, 5], toArray(fromGoogIterable().toEs6())); assertArrayEquals([1, 3, 5], [...fromGoogIterable().toEs6()]); }, testGoogIterableToGoogIterator() { assertArrayEquals([1, 3, 5], toArray(fromGoogIterable().toGoog())); assertArrayEquals([1, 3, 5], [...fromGoogIterable().toGoog()]); }, testGoogIteratorAsIterable() { assertArrayEquals([1, 3, 5], toArray(fromGoogIterator())); assertArrayEquals([1, 3, 5], [...fromGoogIterator()]); }, testGoogIteratorToEs6Iterator() { assertArrayEquals([1, 3, 5], toArray(fromGoogIterator().toEs6())); assertArrayEquals([1, 3, 5], [...fromGoogIterator().toEs6()]); }, testGoogIteratorToGoogIterator() { assertArrayEquals([1, 3, 5], toArray(fromGoogIterator().toGoog())); assertArrayEquals([1, 3, 5], [...fromGoogIterator().toGoog()]); }, // Misc tests testMultipleConversions() { const iter = fromGoogIterable(); assertArrayEquals([1, 3, 5], [...iter.toEs6()]); assertArrayEquals([1, 3, 5], [...iter.toGoog()]); assertArrayEquals([1, 3, 5], [...iter.toGoog().toEs6()]); assertArrayEquals([1, 3, 5], [...iter.toEs6().toGoog()]); }, testExhaustedAfterConversionToIterator() { let iter = fromGoogIterable().toEs6(); assertArrayEquals([1, 3, 5], [...iter.toEs6()]); assertArrayEquals([], [...iter]); iter = fromGoogIterable().toEs6(); assertArrayEquals([1, 3, 5], [...iter.toGoog()]); assertArrayEquals([], [...iter]); iter = fromGoogIterable().toGoog(); assertArrayEquals([1, 3, 5], [...iter.toEs6()]); assertArrayEquals([], [...iter]); iter = fromGoogIterable().toGoog(); assertArrayEquals([1, 3, 5], [...iter.toGoog()]); assertArrayEquals([], [...iter]); }, });
{ "pile_set_name": "Github" }
:020000023000CC :10FC000001C0F3C0112484B790E890936100109272 :10FC10006100882369F0982F9A70923049F081FF33 :10FC200002C097EF94BF282E80E002D10C94000010 :10FC300085E08093810082E08093D00088E180930A :10FC4000D1008BE08093D40086E08093D2008EE0D8 :10FC5000EFD0279A84E02DE53DEF91E030938500C9 :10FC60002093840096BBB09BFECF1F9AA89540912D :10FC7000D00047FD02C0815089F7CED0813479F49D :10FC8000CBD0C82FDBD0C23811F480E004C088E0AC :10FC9000C13809F083E0B9D080E1B7D0EECF82342B :10FCA00019F484E1D3D0F8CF853411F485E0FACF8C :10FCB000853581F4B1D0E82EAFD0F82E87FF07C08C :10FCC0008BB781608BBFEE0CFF1CB8D0E5CF8BB734 :10FCD0008E7FF8CF863579F49FD08D3451F49CD047 :10FCE000CBB79AD0C170880F8C2B8BBF81E0AED080 :10FCF000CCCF83E0FCCF843609F046C08DD0C82F2E :10FD0000D0E0DC2FCC2788D0C82B86D0D82E5E013F :10FD10008EEFB81A00E012E04801EFEF8E1A9E0A4B :10FD20007BD0F801808384018A149B04A9F786D0D4 :10FD3000F5E410E000E0DF1609F150E040E063E098 :10FD4000C70153D08701C12C92E0D92EF601419111 :10FD500051916F0161E0C80148D00E5F1F4F22979B :10FD6000A9F750E040E065E0C7013FD095CF608142 :10FD7000C8018E0D9F1D79D00F5F1F4FF801FE5FE8 :10FD8000C017D107A1F788CF843701F545D0C82F18 :10FD9000D0E0DC2FCC2740D0C82B3ED0D82E4ED080 :10FDA0008701F5E4DF120BC0CE0DDF1DC80155D071 :10FDB0002CD00F5F1F4FC017D107C1F76DCFF801CF :10FDC00087918F0122D02197D1F766CF853739F4FB :10FDD00035D08EE11AD088E918D081E05CCF81352A :10FDE00009F073CF88E024D070CFFC010A0167BF0F :10FDF000E895112407B600FCFDCF667029F0452B6D :10FE000019F481E187BFE89508959091D00095FF9E :10FE1000FCCF8093D60008958091D00087FFFCCF5F :10FE20008091D00084FD01C0A8958091D6000895EE :10FE3000E0E6F0E098E1908380830895EDDF803282 :10FE400019F088E0F5DFFFCF84E1DFCFCF93C82F33 :10FE5000E3DFC150E9F7CF91F1CFF999FECF92BD21 :10FE600081BDF89A992780B50895262FF999FECF7C :10FE70001FBA92BD81BD20BD0FB6F894FA9AF99AC7 :06FE80000FBE019608957B :02FFFE000008F9 :040000033000FC00CD :00000001FF
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">JavaWebsocketClient</string> </resources>
{ "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. #pragma once #include "runtime/datetime-parser-common.h" #include <string> #include <unordered_set> #include <unordered_map> #include "gutil/macros.h" namespace impala { namespace datetime_parse_util { /// This class is responsible for splitting a datetime format string into tokens following /// the ISO:SQL:2016 standard. For acceptable tokens please see the design document /// attached to IMPALA-4018. You can also get a good impression of the available tokens by /// checking VALID_TOKENS member and IsSeparator() function of this class. class IsoSqlFormatTokenizer { public: IsoSqlFormatTokenizer(DateTimeFormatContext* dt_ctx, CastDirection cast_mode, bool time_toks) : dt_ctx_(dt_ctx), cast_mode_(cast_mode), accept_time_toks_(time_toks), fm_modifier_active_(false) {} void Reset(DateTimeFormatContext* dt_ctx, CastDirection cast_mode, bool time_toks) { dt_ctx_ = dt_ctx; cast_mode_ = cast_mode; accept_time_toks_ = time_toks; used_tokens_.clear(); } /// Performs parsing of 'dt_ctx_.fmt' format string. During the process this populates /// 'dt_ctx_' with metadata about the format string such as tokens found in the string. FormatTokenizationResult Tokenize(); /// Returns true if '*current_pos' points to a valid separator. If /// 'read_escaped_single_quotes' is true then escaped single quotes are also taken as /// valid separators. In this case '*current_pos' is advanced from the escaping /// backslash to the single quote. static bool IsSeparator(const char** current_pos, const char* str_end, bool read_escaped_single_quotes = true); private: /// Stores metadata about a specific token type. struct TokenItem { TokenItem(DateTimeFormatTokenType t, bool dt, bool tt) : type(t), date_token(dt), time_token(tt) {} DateTimeFormatTokenType type; bool date_token; bool time_token; }; /// This holds all the valid tokens accepted by this parser. When a format string is /// being parsed the substrings are checked against this member to decide if they are /// valid tokens or not. /// Note, token matching is case-insensitive even though this member contains /// upper-case names only. static const std::unordered_map<std::string, TokenItem> VALID_TOKENS; /// Keeps the maximum token lengths for tokens where the token length doesn't equal to /// the length of the datetime pattern. E.g. "HH12" is 4 chars long, however expects /// maximum 2 digits as "10". static const std::unordered_map<std::string, int> SPECIAL_LENGTHS; /// This has to be in line with the longest string in VALID_TOKENS; static const unsigned MAX_TOKEN_SIZE; /// To be on the safe side this introduces a max length limit for the input format /// strings. static const int MAX_FORMAT_LENGTH; /// When parsing is in progress this contains the format tokens that we have found in /// the input format string so far. std::unordered_set<std::string> used_tokens_; /// The context that is used for the input of the parsing. It is also populated during /// the parsing process. Not owned by this class. /// Note, that 'dt_ctx_->fmt' is a null-terminated string so it's safe to use string /// functions that make this assumption. DateTimeFormatContext* dt_ctx_; /// Decides whether this is a 'datetime to string' or a 'string to datetime' cast. CastDirection cast_mode_; bool accept_time_toks_; /// True when the FM modifier has to be applied to the following non-separator token. /// It is set back to false once applied on a token. bool fm_modifier_active_; /// Iterates through all the consecutive separator characters from a given pointer /// 'current' and saves them to 'dt_ctx_'. void ProcessSeparators(const char** current); /// Identifies the next token using VALID_TOKENS and saves it to 'dt_ctx_'. Finds the /// longest possible match. FormatTokenizationResult ProcessNextToken(const char** current_pos); /// Checks if the token has special length in 'SPECIAL_LENGTHS'. If finds a special /// length then returns that, otherwise returns the length of 'token'. int GetMaxTokenLength(const std::string& token) const; /// Checks if 'token' is present in 'used_tokens_'; bool IsUsedToken(const std::string& token) const; /// Checks if any of the meridiem indicators are present in 'used_tokens_'. bool IsMeridiemIndicatorProvided() const; /// Checks if the end product of the parsing contains format tokens that collide with /// each other like YYYY and RR. FormatTokenizationResult CheckIncompatibilities() const; /// Checks if '*current_pos' points to an FX modifier and advances '*current_pos' after /// the FX modifier. Sets 'dt_ctx_->fx_modifier' to true if '*current_pos' points to an /// FX modifier. Call this when '*current_pos' points to the first character of the /// format string. void ProcessFXModifier(const char** current_pos); /// Returns true if 'current_pos' points to either a double quote or to a backslash /// that is followed by a double quote. static bool IsStartOfTextToken(const char* current_pos); /// Finds the end of the text token and saves metadata about the token into 'dt_ctx_'. /// This has to be called when '*current_pos' points to the beginning of a text token /// or in other words if IsStartOfTextToken(*current_pos) is true. As a side effect /// 'current_pos' is advanced right after the closing double qoute of the text token. FormatTokenizationResult ProcessTextToken(const char** current_pos, const char* str_begin, const char* str_end); // Starting from 'str_start' finds the closing quotation mark of the text token even // if it's escaped. 'str_start' has to point to the first character of the text token // right after the opening quote. Returns a pointer pointing right after the closing // double quote of the text token or nullptr if the text token is unclosed. static const char* FindEndOfTextToken(const char* str_start, const char* str_end, bool is_escaped); }; } }
{ "pile_set_name": "Github" }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/cert/internal/verify_name_match.h" #include "net/der/input.h" // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { net::der::Input in(data, size); std::string normalized_der; bool success = net::NormalizeName(in, &normalized_der); if (success) { // If the input was successfully normalized, re-normalizing it should // produce the same output again. std::string renormalized_der; bool renormalize_success = net::NormalizeName(net::der::Input(&normalized_der), &renormalized_der); CHECK(renormalize_success); CHECK_EQ(normalized_der, renormalized_der); } return 0; }
{ "pile_set_name": "Github" }
[IIO Oscilloscope] plugin.AD936X Advanced.detached=0 plugin.DMM.detached=0 plugin.Debug.detached=0 plugin.Spectrum Analyzer.detached=0 plugin.AD936X.detached=0 startup_version_check=0 test=1 [IIO Oscilloscope - Capture Window1] test.message = Please ensure RX_IN <-> TX_OUT domain=fft sample_count=400 fft_size=16384 fft_avg=16 fft_pwr_offset=0.000000 graph_type=Lines show_grid=1 enable_auto_scale=1 user_y_axis_max=5.298330 user_y_axis_min=-111.264938 x_axis_min=-0.767906 x_axis_max=16.126032 y_axis_min=-111.435539 y_axis_max=5.306454 line_thickness = 1 plot_title = ADI IIO Oscilloscope - Capture1 show_capture_options = 1 plot_width = 1011 plot_height = 877 plot_x_pos=887 plot_y_pos=38 cf-ad9361-lpc.expanded=1 cf-ad9361-lpc.active=1 cf-ad9361-lpc.trigger_enabled=0 cf-ad9361-lpc.voltage0.enabled=0 cf-ad9361-lpc.voltage0.color_red=35328 cf-ad9361-lpc.voltage0.color_green=57856 cf-ad9361-lpc.voltage0.color_blue=13312 cf-ad9361-lpc.voltage0.math_apply_inverse_funct=0 cf-ad9361-lpc.voltage0.math_apply_multiply_funct=0 cf-ad9361-lpc.voltage0.math_apply_add_funct=0 cf-ad9361-lpc.voltage0.math_multiply_value=0.000000 cf-ad9361-lpc.voltage0.math_add_value=0.000000 cf-ad9361-lpc.voltage1.enabled=0 cf-ad9361-lpc.voltage1.color_red=61184 cf-ad9361-lpc.voltage1.color_green=10496 cf-ad9361-lpc.voltage1.color_blue=10496 cf-ad9361-lpc.voltage1.math_apply_inverse_funct=0 cf-ad9361-lpc.voltage1.math_apply_multiply_funct=0 cf-ad9361-lpc.voltage1.math_apply_add_funct=0 cf-ad9361-lpc.voltage1.math_multiply_value=0.000000 cf-ad9361-lpc.voltage1.math_add_value=0.000000 cf-ad9361-lpc.voltage2.enabled=0 cf-ad9361-lpc.voltage2.color_red=29184 cf-ad9361-lpc.voltage2.color_green=40704 cf-ad9361-lpc.voltage2.color_blue=52992 cf-ad9361-lpc.voltage2.math_apply_inverse_funct=0 cf-ad9361-lpc.voltage2.math_apply_multiply_funct=0 cf-ad9361-lpc.voltage2.math_apply_add_funct=0 cf-ad9361-lpc.voltage2.math_multiply_value=0.000000 cf-ad9361-lpc.voltage2.math_add_value=0.000000 cf-ad9361-lpc.voltage3.enabled=1 cf-ad9361-lpc.voltage3.color_red=64512 cf-ad9361-lpc.voltage3.color_green=44800 cf-ad9361-lpc.voltage3.color_blue=15872 cf-ad9361-lpc.voltage3.math_apply_inverse_funct=0 cf-ad9361-lpc.voltage3.math_apply_multiply_funct=0 cf-ad9361-lpc.voltage3.math_apply_add_funct=0 cf-ad9361-lpc.voltage3.math_multiply_value=0.000000 cf-ad9361-lpc.voltage3.math_add_value=0.000000 Math.expanded=0 Math.active=0 marker_type = Peak Markers marker.0 = 0 marker.1 = 0 marker.2 = 0 marker.3 = 0 marker.4 = 0 marker.5 = 0 marker.6 = 0 marker.7 = 0 marker.8 = 0 marker.9 = 0 capture_started=1 [AD936X Advanced] debug.ad9361-phy.adi,txmon-2-lo-cm = 48 debug.ad9361-phy.adi,txmon-1-lo-cm = 48 debug.ad9361-phy.adi,txmon-2-front-end-gain = 2 debug.ad9361-phy.adi,txmon-1-front-end-gain = 2 debug.ad9361-phy.adi,txmon-duration = 8192 debug.ad9361-phy.adi,txmon-delay = 511 debug.ad9361-phy.adi,txmon-one-shot-mode-enable = 0 debug.ad9361-phy.adi,txmon-dc-tracking-enable = 0 debug.ad9361-phy.adi,txmon-high-gain = 24 debug.ad9361-phy.adi,txmon-low-gain = 0 debug.ad9361-phy.adi,txmon-low-high-thresh = 37000 debug.ad9361-phy.adi,aux-dac2-tx-delay-us = 0 debug.ad9361-phy.adi,aux-dac2-rx-delay-us = 0 debug.ad9361-phy.adi,aux-dac2-active-in-alert-enable = 0 debug.ad9361-phy.adi,aux-dac2-active-in-tx-enable = 0 debug.ad9361-phy.adi,aux-dac2-active-in-rx-enable = 0 debug.ad9361-phy.adi,aux-dac2-default-value-mV = 0 debug.ad9361-phy.adi,aux-dac1-tx-delay-us = 0 debug.ad9361-phy.adi,aux-dac1-rx-delay-us = 0 debug.ad9361-phy.adi,aux-dac1-active-in-alert-enable = 0 debug.ad9361-phy.adi,aux-dac1-active-in-tx-enable = 0 debug.ad9361-phy.adi,aux-dac1-active-in-rx-enable = 0 debug.ad9361-phy.adi,aux-dac1-default-value-mV = 0 debug.ad9361-phy.adi,aux-dac-manual-mode-enable = 1 debug.ad9361-phy.adi,aux-adc-decimation = 256 debug.ad9361-phy.adi,aux-adc-rate = 40000000 debug.ad9361-phy.adi,temp-sense-decimation = 256 debug.ad9361-phy.adi,temp-sense-periodic-measurement-enable = 1 debug.ad9361-phy.adi,temp-sense-offset-signed = 206 debug.ad9361-phy.adi,temp-sense-measurement-interval-ms = 1000 debug.ad9361-phy.adi,elna-gaintable-all-index-enable = 0 debug.ad9361-phy.adi,elna-rx2-gpo1-control-enable = 0 debug.ad9361-phy.adi,elna-rx1-gpo0-control-enable = 0 debug.ad9361-phy.adi,elna-bypass-loss-mdB = 0 debug.ad9361-phy.adi,elna-gain-mdB = 0 debug.ad9361-phy.adi,elna-settling-delay-ns = 0 debug.ad9361-phy.adi,ctrl-outs-enable-mask = 255 debug.ad9361-phy.adi,ctrl-outs-index = 0 debug.ad9361-phy.adi,rssi-duration = 1000 debug.ad9361-phy.adi,rssi-wait = 1 debug.ad9361-phy.adi,rssi-delay = 1 debug.ad9361-phy.adi,rssi-restart-mode = 3 debug.ad9361-phy.adi,fagc-power-measurement-duration-in-state5 = 64 debug.ad9361-phy.adi,fagc-rst-gla-if-en-agc-pulled-high-mode = 0 debug.ad9361-phy.adi,fagc-rst-gla-en-agc-pulled-high-enable = 0 debug.ad9361-phy.adi,fagc-rst-gla-large-lmt-overload-enable = 1 debug.ad9361-phy.adi,fagc-rst-gla-large-adc-overload-enable = 1 debug.ad9361-phy.adi,fagc-energy-lost-stronger-sig-gain-lock-exit-cnt = 8 debug.ad9361-phy.adi,fagc-rst-gla-engergy-lost-sig-thresh-below-ll = 10 debug.ad9361-phy.adi,fagc-rst-gla-engergy-lost-goto-optim-gain-enable = 1 debug.ad9361-phy.adi,fagc-rst-gla-engergy-lost-sig-thresh-exceeded-enable = 1 debug.ad9361-phy.adi,fagc-rst-gla-stronger-sig-thresh-above-ll = 10 debug.ad9361-phy.adi,fagc-optimized-gain-offset = 5 debug.ad9361-phy.adi,fagc-rst-gla-stronger-sig-thresh-exceeded-enable = 1 debug.ad9361-phy.adi,fagc-use-last-lock-level-for-set-gain-enable = 1 debug.ad9361-phy.adi,fagc-gain-index-type-after-exit-rx-mode = 0 debug.ad9361-phy.adi,fagc-gain-increase-after-gain-lock-enable = 0 debug.ad9361-phy.adi,fagc-final-overrange-count = 3 debug.ad9361-phy.adi,fagc-lmt-final-settling-steps = 1 debug.ad9361-phy.adi,fagc-lpf-final-settling-steps = 1 debug.ad9361-phy.adi,fagc-lock-level-gain-increase-upper-limit = 5 debug.ad9361-phy.adi,fagc-lock-level-lmt-gain-increase-enable = 1 debug.ad9361-phy.adi,fagc-lp-thresh-increment-steps = 1 debug.ad9361-phy.adi,fagc-lp-thresh-increment-time = 5 debug.ad9361-phy.adi,fagc-allow-agc-gain-increase-enable = 0 debug.ad9361-phy.adi,fagc-state-wait-time-ns = 260 debug.ad9361-phy.adi,fagc-dec-pow-measurement-duration = 64 debug.ad9361-phy.adi,agc-immed-gain-change-if-large-lmt-overload-enable = 0 debug.ad9361-phy.adi,agc-immed-gain-change-if-large-adc-overload-enable = 0 debug.ad9361-phy.adi,agc-gain-update-interval-us = 1000 debug.ad9361-phy.adi,agc-sync-for-gain-counter-enable = 0 debug.ad9361-phy.adi,agc-dig-gain-step-size = 4 debug.ad9361-phy.adi,agc-dig-saturation-exceed-counter = 3 debug.ad9361-phy.adi,agc-lmt-overload-large-inc-steps = 2 debug.ad9361-phy.adi,agc-lmt-overload-small-exceed-counter = 10 debug.ad9361-phy.adi,agc-lmt-overload-large-exceed-counter = 10 debug.ad9361-phy.adi,agc-adc-lmt-small-overload-prevent-gain-inc-enable = 0 debug.ad9361-phy.adi,agc-adc-large-overload-inc-steps = 2 debug.ad9361-phy.adi,agc-adc-large-overload-exceed-counter = 10 debug.ad9361-phy.adi,agc-adc-small-overload-exceed-counter = 10 debug.ad9361-phy.adi,agc-outer-thresh-low-inc-steps = 2 debug.ad9361-phy.adi,agc-outer-thresh-low = 18 debug.ad9361-phy.adi,agc-inner-thresh-low-inc-steps = 1 debug.ad9361-phy.adi,agc-inner-thresh-low = 12 debug.ad9361-phy.adi,agc-inner-thresh-high-dec-steps = 1 debug.ad9361-phy.adi,agc-inner-thresh-high = 10 debug.ad9361-phy.adi,agc-outer-thresh-high-dec-steps = 2 debug.ad9361-phy.adi,agc-outer-thresh-high = 5 debug.ad9361-phy.adi,agc-attack-delay-extra-margin-us = 1 debug.ad9361-phy.adi,mgc-split-table-ctrl-inp-gain-mode = 0 debug.ad9361-phy.adi,mgc-dec-gain-step = 2 debug.ad9361-phy.adi,mgc-inc-gain-step = 2 debug.ad9361-phy.adi,mgc-rx2-ctrl-inp-enable = 0 debug.ad9361-phy.adi,mgc-rx1-ctrl-inp-enable = 0 debug.ad9361-phy.adi,gc-max-dig-gain = 15 debug.ad9361-phy.adi,gc-dig-gain-enable = 0 debug.ad9361-phy.adi,gc-low-power-thresh = 24 debug.ad9361-phy.adi,gc-dec-pow-measurement-duration = 8192 debug.ad9361-phy.adi,gc-lmt-overload-low-thresh = 704 debug.ad9361-phy.adi,gc-lmt-overload-high-thresh = 800 debug.ad9361-phy.adi,gc-adc-large-overload-thresh = 58 debug.ad9361-phy.adi,gc-adc-small-overload-thresh = 47 debug.ad9361-phy.adi,gc-adc-ovr-sample-size = 4 debug.ad9361-phy.adi,gc-rx2-mode = 2 debug.ad9361-phy.adi,gc-rx1-mode = 2 debug.ad9361-phy.adi,update-tx-gain-in-alert-enable = 0 debug.ad9361-phy.adi,qec-tracking-slow-mode-enable = 0 debug.ad9361-phy.adi,dc-offset-count-low-range = 50 debug.ad9361-phy.adi,dc-offset-count-high-range = 40 debug.ad9361-phy.adi,dc-offset-attenuation-low-range = 5 debug.ad9361-phy.adi,dc-offset-attenuation-high-range = 6 debug.ad9361-phy.adi,dc-offset-tracking-update-event-mask = 5 debug.ad9361-phy.adi,clk-output-mode-select = 0 debug.ad9361-phy.adi,xo-disable-use-ext-refclk-enable = 0 debug.ad9361-phy.adi,external-rx-lo-enable = 0 debug.ad9361-phy.adi,external-tx-lo-enable = 0 debug.ad9361-phy.adi,tx-rf-port-input-select = 0 debug.ad9361-phy.adi,rx-rf-port-input-select = 0 debug.ad9361-phy.adi,split-gain-table-mode-enable = 0 debug.ad9361-phy.adi,tx-fastlock-pincontrol-enable = 0 debug.ad9361-phy.adi,rx-fastlock-pincontrol-enable = 0 debug.ad9361-phy.adi,rx-fastlock-delay-ns = 0 debug.ad9361-phy.adi,tx-fastlock-delay-ns = 0 debug.ad9361-phy.adi,tdd-skip-vco-cal-enable = 0 debug.ad9361-phy.adi,ensm-enable-txnrx-control-enable = 0 debug.ad9361-phy.adi,ensm-enable-pin-pulse-mode-enable = 0 debug.ad9361-phy.adi,frequency-division-duplex-mode-enable = 1 [AD936X] load_fir_filter_file = /usr/local/lib/osc/filters/LTE20_MHz.ftr dds_mode_tx1 = 0 dds_mode_tx2 = 0 tx_channel_0 = 0 tx_channel_1 = 0 tx_channel_2 = 0 tx_channel_3 = 0 dac_buf_filename = (null) global_settings_show = 1 tx_show = 1 rx_show = 1 fpga_show = 1 ad9361-phy.out_altvoltage1_TX_LO_frequency = 370000000 ad9361-phy.out_altvoltage1_TX_LO_external = 0 ad9361-phy.out_voltage_rf_bandwidth = 19365438 ad9361-phy.out_voltage_sampling_frequency = 30720000 ad9361-phy.out_voltage_rf_bandwidth = 19365438 ad9361-phy.out_voltage_sampling_frequency = 30720000 ad9361-phy.in_voltage_bb_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_rf_bandwidth = 19365514 ad9361-phy.in_voltage_rf_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_quadrature_tracking_en = 1 ad9361-phy.in_voltage1_hardwaregain = 1.000000 dB ad9361-phy.in_voltage1_gain_control_mode = manual ad9361-phy.in_voltage_bb_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_rf_bandwidth = 19365514 ad9361-phy.in_voltage_rf_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_quadrature_tracking_en = 1 ad9361-phy.out_altvoltage0_RX_LO_frequency = 340000000 ad9361-phy.out_altvoltage0_RX_LO_external = 0 ad9361-phy.in_voltage0_gain_control_mode = manual ad9361-phy.in_voltage0_rf_port_select = A_BALANCED ad9361-phy.in_voltage0_hardwaregain = 1.000000 dB ad9361-phy.in_voltage_bb_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_rf_bandwidth = 19365514 ad9361-phy.in_voltage_rf_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_quadrature_tracking_en = 1 ad9361-phy.out_voltage1_hardwaregain = -25.000000 dB ad9361-phy.out_voltage_rf_bandwidth = 19365438 ad9361-phy.out_voltage_sampling_frequency = 30720000 ad9361-phy.out_voltage0_rf_port_select = A ad9361-phy.out_voltage0_hardwaregain = -25.000000 dB ad9361-phy.out_voltage_rf_bandwidth = 19365438 ad9361-phy.out_voltage_sampling_frequency = 30720000 ad9361-phy.trx_rate_governor = nominal ad9361-phy.dcxo_tune_coarse = 8 ad9361-phy.dcxo_tune_fine = 5920 ad9361-phy.ensm_mode = fdd cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_phase = 90000 cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_frequency = 2000186 cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_raw = 0 cf-ad9361-dds-core-lpc.out_altvoltage5_TX2_I_F2_phase = 90000 cf-ad9361-dds-core-lpc.out_altvoltage5_TX2_I_F2_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage5_TX2_I_F2_raw = 0 cf-ad9361-dds-core-lpc.out_altvoltage5_TX2_I_F2_frequency = 999859 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_frequency = 2000186 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_phase = 90000 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_raw = 0 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_frequency = 2000186 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_raw = 0 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_phase = 0 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage3_TX1_Q_F2_raw = 0 cf-ad9361-dds-core-lpc.out_altvoltage3_TX1_Q_F2_phase = 0 cf-ad9361-dds-core-lpc.out_altvoltage3_TX1_Q_F2_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage3_TX1_Q_F2_frequency = 9279985 cf-ad9361-dds-core-lpc.out_altvoltage7_TX2_Q_F2_raw = 0 cf-ad9361-dds-core-lpc.out_altvoltage7_TX2_Q_F2_phase = 0 cf-ad9361-dds-core-lpc.out_altvoltage7_TX2_Q_F2_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage7_TX2_Q_F2_frequency = 999859 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_raw = 0 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_phase = 0 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_frequency = 2000186 cf-ad9361-dds-core-lpc.out_altvoltage1_TX1_I_F2_frequency = 9279985 cf-ad9361-dds-core-lpc.out_altvoltage1_TX1_I_F2_raw = 0 cf-ad9361-dds-core-lpc.out_altvoltage1_TX1_I_F2_phase = 90000 cf-ad9361-dds-core-lpc.out_altvoltage1_TX1_I_F2_scale = 0.000000 ad9361-phy.out_voltage_filter_fir_en = 1 ad9361-phy.in_voltage_filter_fir_en = 1 ad9361-phy.in_out_voltage_filter_fir_en = 1 ad9361-phy.in_voltage1_hardwaregain = 1.000000 dB SYNC_RELOAD = 1 [IIO Oscilloscope - Capture Window1] # check noise floor capture_started = 1 cycle = 8000 # look at the markers test.marker.5 = -120.0 -90.0 test.marker.6 = -120.0 -90.0 test.marker.7 = -120.0 -90.0 test.marker.8 = -120.0 -90.0 test.marker.9 = -120.0 -90.0 capture_started=0 # destroy plot, otherwise it keeps running as we continue destroy_plot = 1 [AD936X Advanced] debug.ad9361-phy.adi,txmon-2-lo-cm = 48 debug.ad9361-phy.adi,txmon-1-lo-cm = 48 debug.ad9361-phy.adi,txmon-2-front-end-gain = 2 debug.ad9361-phy.adi,txmon-1-front-end-gain = 2 debug.ad9361-phy.adi,txmon-duration = 8192 debug.ad9361-phy.adi,txmon-delay = 511 debug.ad9361-phy.adi,txmon-one-shot-mode-enable = 0 debug.ad9361-phy.adi,txmon-dc-tracking-enable = 0 debug.ad9361-phy.adi,txmon-high-gain = 24 debug.ad9361-phy.adi,txmon-low-gain = 0 debug.ad9361-phy.adi,txmon-low-high-thresh = 37000 debug.ad9361-phy.adi,gpo3-tx-delay-us = 0 debug.ad9361-phy.adi,gpo3-rx-delay-us = 0 debug.ad9361-phy.adi,gpo2-tx-delay-us = 0 debug.ad9361-phy.adi,gpo2-rx-delay-us = 0 debug.ad9361-phy.adi,gpo1-tx-delay-us = 0 debug.ad9361-phy.adi,gpo1-rx-delay-us = 0 debug.ad9361-phy.adi,gpo0-tx-delay-us = 0 debug.ad9361-phy.adi,gpo0-rx-delay-us = 0 debug.ad9361-phy.adi,gpo3-slave-tx-enable = 0 debug.ad9361-phy.adi,gpo3-slave-rx-enable = 0 debug.ad9361-phy.adi,gpo2-slave-tx-enable = 0 debug.ad9361-phy.adi,gpo2-slave-rx-enable = 0 debug.ad9361-phy.adi,gpo1-slave-tx-enable = 0 debug.ad9361-phy.adi,gpo1-slave-rx-enable = 0 debug.ad9361-phy.adi,gpo0-slave-tx-enable = 0 debug.ad9361-phy.adi,gpo0-slave-rx-enable = 0 debug.ad9361-phy.adi,gpo3-inactive-state-high-enable = 0 debug.ad9361-phy.adi,gpo2-inactive-state-high-enable = 0 debug.ad9361-phy.adi,gpo1-inactive-state-high-enable = 0 debug.ad9361-phy.adi,gpo0-inactive-state-high-enable = 0 debug.ad9361-phy.adi,gpo-manual-mode-enable-mask = 0 debug.ad9361-phy.adi,gpo-manual-mode-enable = 0 debug.ad9361-phy.adi,aux-dac2-tx-delay-us = 0 debug.ad9361-phy.adi,aux-dac2-rx-delay-us = 0 debug.ad9361-phy.adi,aux-dac2-active-in-alert-enable = 0 debug.ad9361-phy.adi,aux-dac2-active-in-tx-enable = 0 debug.ad9361-phy.adi,aux-dac2-active-in-rx-enable = 0 debug.ad9361-phy.adi,aux-dac2-default-value-mV = 0 debug.ad9361-phy.adi,aux-dac1-tx-delay-us = 0 debug.ad9361-phy.adi,aux-dac1-rx-delay-us = 0 debug.ad9361-phy.adi,aux-dac1-active-in-alert-enable = 0 debug.ad9361-phy.adi,aux-dac1-active-in-tx-enable = 0 debug.ad9361-phy.adi,aux-dac1-active-in-rx-enable = 0 debug.ad9361-phy.adi,aux-dac1-default-value-mV = 0 debug.ad9361-phy.adi,aux-dac-manual-mode-enable = 1 debug.ad9361-phy.adi,aux-adc-decimation = 256 debug.ad9361-phy.adi,aux-adc-rate = 40000000 debug.ad9361-phy.adi,temp-sense-decimation = 256 debug.ad9361-phy.adi,temp-sense-periodic-measurement-enable = 1 debug.ad9361-phy.adi,temp-sense-offset-signed = 206 debug.ad9361-phy.adi,temp-sense-measurement-interval-ms = 1000 debug.ad9361-phy.adi,elna-gaintable-all-index-enable = 0 debug.ad9361-phy.adi,elna-rx2-gpo1-control-enable = 0 debug.ad9361-phy.adi,elna-rx1-gpo0-control-enable = 0 debug.ad9361-phy.adi,elna-bypass-loss-mdB = 0 debug.ad9361-phy.adi,elna-gain-mdB = 0 debug.ad9361-phy.adi,elna-settling-delay-ns = 0 debug.ad9361-phy.adi,ctrl-outs-enable-mask = 255 debug.ad9361-phy.adi,ctrl-outs-index = 0 debug.ad9361-phy.adi,rssi-duration = 1000 debug.ad9361-phy.adi,rssi-wait = 1 debug.ad9361-phy.adi,rssi-delay = 1 debug.ad9361-phy.adi,rssi-restart-mode = 3 debug.ad9361-phy.adi,fagc-power-measurement-duration-in-state5 = 64 debug.ad9361-phy.adi,fagc-rst-gla-if-en-agc-pulled-high-mode = 0 debug.ad9361-phy.adi,fagc-rst-gla-en-agc-pulled-high-enable = 0 debug.ad9361-phy.adi,fagc-rst-gla-large-lmt-overload-enable = 1 debug.ad9361-phy.adi,fagc-rst-gla-large-adc-overload-enable = 1 debug.ad9361-phy.adi,fagc-energy-lost-stronger-sig-gain-lock-exit-cnt = 8 debug.ad9361-phy.adi,fagc-rst-gla-engergy-lost-sig-thresh-below-ll = 10 debug.ad9361-phy.adi,fagc-rst-gla-engergy-lost-goto-optim-gain-enable = 1 debug.ad9361-phy.adi,fagc-rst-gla-engergy-lost-sig-thresh-exceeded-enable = 1 debug.ad9361-phy.adi,fagc-rst-gla-stronger-sig-thresh-above-ll = 10 debug.ad9361-phy.adi,fagc-optimized-gain-offset = 5 debug.ad9361-phy.adi,fagc-rst-gla-stronger-sig-thresh-exceeded-enable = 1 debug.ad9361-phy.adi,fagc-use-last-lock-level-for-set-gain-enable = 1 debug.ad9361-phy.adi,fagc-gain-index-type-after-exit-rx-mode = 0 debug.ad9361-phy.adi,fagc-gain-increase-after-gain-lock-enable = 0 debug.ad9361-phy.adi,fagc-final-overrange-count = 3 debug.ad9361-phy.adi,fagc-lmt-final-settling-steps = 1 debug.ad9361-phy.adi,fagc-lpf-final-settling-steps = 1 debug.ad9361-phy.adi,fagc-lock-level-gain-increase-upper-limit = 5 debug.ad9361-phy.adi,fagc-lock-level-lmt-gain-increase-enable = 1 debug.ad9361-phy.adi,fagc-lp-thresh-increment-steps = 1 debug.ad9361-phy.adi,fagc-lp-thresh-increment-time = 5 debug.ad9361-phy.adi,fagc-allow-agc-gain-increase-enable = 0 debug.ad9361-phy.adi,fagc-state-wait-time-ns = 260 debug.ad9361-phy.adi,fagc-dec-pow-measurement-duration = 64 debug.ad9361-phy.adi,agc-immed-gain-change-if-large-lmt-overload-enable = 0 debug.ad9361-phy.adi,agc-immed-gain-change-if-large-adc-overload-enable = 0 debug.ad9361-phy.adi,agc-gain-update-interval-us = 1000 debug.ad9361-phy.adi,agc-sync-for-gain-counter-enable = 0 debug.ad9361-phy.adi,agc-dig-gain-step-size = 4 debug.ad9361-phy.adi,agc-dig-saturation-exceed-counter = 3 debug.ad9361-phy.adi,agc-lmt-overload-large-inc-steps = 2 debug.ad9361-phy.adi,agc-lmt-overload-small-exceed-counter = 10 debug.ad9361-phy.adi,agc-lmt-overload-large-exceed-counter = 10 debug.ad9361-phy.adi,agc-adc-lmt-small-overload-prevent-gain-inc-enable = 0 debug.ad9361-phy.adi,agc-adc-large-overload-inc-steps = 2 debug.ad9361-phy.adi,agc-adc-large-overload-exceed-counter = 10 debug.ad9361-phy.adi,agc-adc-small-overload-exceed-counter = 10 debug.ad9361-phy.adi,agc-outer-thresh-low-inc-steps = 2 debug.ad9361-phy.adi,agc-outer-thresh-low = 18 debug.ad9361-phy.adi,agc-inner-thresh-low-inc-steps = 1 debug.ad9361-phy.adi,agc-inner-thresh-low = 12 debug.ad9361-phy.adi,agc-inner-thresh-high-dec-steps = 1 debug.ad9361-phy.adi,agc-inner-thresh-high = 10 debug.ad9361-phy.adi,agc-outer-thresh-high-dec-steps = 2 debug.ad9361-phy.adi,agc-outer-thresh-high = 5 debug.ad9361-phy.adi,agc-attack-delay-extra-margin-us = 1 debug.ad9361-phy.adi,mgc-split-table-ctrl-inp-gain-mode = 0 debug.ad9361-phy.adi,mgc-dec-gain-step = 2 debug.ad9361-phy.adi,mgc-inc-gain-step = 2 debug.ad9361-phy.adi,mgc-rx2-ctrl-inp-enable = 0 debug.ad9361-phy.adi,mgc-rx1-ctrl-inp-enable = 0 debug.ad9361-phy.adi,gc-max-dig-gain = 15 debug.ad9361-phy.adi,gc-dig-gain-enable = 0 debug.ad9361-phy.adi,gc-low-power-thresh = 24 debug.ad9361-phy.adi,gc-dec-pow-measurement-duration = 8192 debug.ad9361-phy.adi,gc-lmt-overload-low-thresh = 704 debug.ad9361-phy.adi,gc-lmt-overload-high-thresh = 800 debug.ad9361-phy.adi,gc-adc-large-overload-thresh = 58 debug.ad9361-phy.adi,gc-adc-small-overload-thresh = 47 debug.ad9361-phy.adi,gc-adc-ovr-sample-size = 4 debug.ad9361-phy.adi,gc-rx2-mode = 2 debug.ad9361-phy.adi,gc-rx1-mode = 2 debug.ad9361-phy.adi,update-tx-gain-in-alert-enable = 0 debug.ad9361-phy.adi,qec-tracking-slow-mode-enable = 0 debug.ad9361-phy.adi,dc-offset-count-low-range = 50 debug.ad9361-phy.adi,dc-offset-count-high-range = 40 debug.ad9361-phy.adi,dc-offset-attenuation-low-range = 5 debug.ad9361-phy.adi,dc-offset-attenuation-high-range = 6 debug.ad9361-phy.adi,dc-offset-tracking-update-event-mask = 5 debug.ad9361-phy.adi,clk-output-mode-select = 0 debug.ad9361-phy.adi,xo-disable-use-ext-refclk-enable = 0 debug.ad9361-phy.adi,external-rx-lo-enable = 0 debug.ad9361-phy.adi,external-tx-lo-enable = 0 debug.ad9361-phy.adi,tx-rf-port-input-select = 0 debug.ad9361-phy.adi,rx-rf-port-input-select = 0 debug.ad9361-phy.adi,split-gain-table-mode-enable = 0 debug.ad9361-phy.adi,tx-fastlock-pincontrol-enable = 0 debug.ad9361-phy.adi,rx-fastlock-pincontrol-enable = 0 debug.ad9361-phy.adi,rx-fastlock-delay-ns = 0 debug.ad9361-phy.adi,tx-fastlock-delay-ns = 0 debug.ad9361-phy.adi,tdd-skip-vco-cal-enable = 0 debug.ad9361-phy.adi,tdd-use-dual-synth-mode-enable = 0 debug.ad9361-phy.adi,ensm-enable-txnrx-control-enable = 0 debug.ad9361-phy.adi,ensm-enable-pin-pulse-mode-enable = 0 debug.ad9361-phy.adi,frequency-division-duplex-mode-enable = 1 # 2 MHz tone [AD936X] ad9361-phy.out_altvoltage1_TX_LO_frequency = 2400000000 ad9361-phy.out_altvoltage1_TX_LO_external = 0 ad9361-phy.out_voltage_rf_bandwidth = 19365438 ad9361-phy.out_voltage_filter_fir_en = 0 ad9361-phy.out_voltage_sampling_frequency = 30720000 ad9361-phy.out_voltage_rf_bandwidth = 19365438 ad9361-phy.out_voltage_filter_fir_en = 0 ad9361-phy.out_voltage_sampling_frequency = 30720000 ad9361-phy.in_voltage_bb_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_rf_bandwidth = 19365514 ad9361-phy.in_voltage_rf_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_quadrature_tracking_en = 1 ad9361-phy.in_voltage_filter_fir_en = 0 ad9361-phy.in_voltage1_hardwaregain = 1.000000 dB ad9361-phy.in_voltage1_gain_control_mode = manual ad9361-phy.in_voltage_bb_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_rf_bandwidth = 19365514 ad9361-phy.in_voltage_rf_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_quadrature_tracking_en = 1 ad9361-phy.in_voltage_filter_fir_en = 0 ad9361-phy.out_altvoltage0_RX_LO_frequency = 2400000000 ad9361-phy.out_altvoltage0_RX_LO_external = 0 ad9361-phy.in_voltage0_gain_control_mode = manual ad9361-phy.in_voltage0_rf_port_select = A_BALANCED ad9361-phy.in_voltage0_hardwaregain = 1.000000 dB ad9361-phy.in_voltage_bb_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_rf_bandwidth = 19365514 ad9361-phy.in_voltage_rf_dc_offset_tracking_en = 1 ad9361-phy.in_voltage_quadrature_tracking_en = 1 ad9361-phy.in_voltage_filter_fir_en = 0 ad9361-phy.out_voltage1_hardwaregain = -20.000000 dB ad9361-phy.out_voltage_rf_bandwidth = 19365438 ad9361-phy.out_voltage_filter_fir_en = 0 ad9361-phy.out_voltage_sampling_frequency = 30720000 ad9361-phy.out_voltage0_rf_port_select = A ad9361-phy.out_voltage0_hardwaregain = -20.000000 dB ad9361-phy.out_voltage_rf_bandwidth = 19365438 ad9361-phy.out_voltage_filter_fir_en = 0 ad9361-phy.out_voltage_sampling_frequency = 30720000 ad9361-phy.trx_rate_governor = nominal ad9361-phy.dcxo_tune_coarse = 8 ad9361-phy.dcxo_tune_fine = 5920 ad9361-phy.ensm_mode = fdd ad9361-phy.in_out_voltage_filter_fir_en = 0 cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_phase = 90000 cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_scale = 1.000000 cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_frequency = 2000186 cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_raw = 1 cf-ad9361-dds-core-lpc.out_altvoltage5_TX2_I_F2_phase = 90000 cf-ad9361-dds-core-lpc.out_altvoltage5_TX2_I_F2_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage5_TX2_I_F2_raw = 1 cf-ad9361-dds-core-lpc.out_altvoltage5_TX2_I_F2_frequency = 999859 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_frequency = 2000186 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_phase = 90000 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_scale = 1.000000 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_raw = 1 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_frequency = 2000186 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_raw = 1 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_phase = 0 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_scale = 1.000000 cf-ad9361-dds-core-lpc.out_altvoltage3_TX1_Q_F2_raw = 1 cf-ad9361-dds-core-lpc.out_altvoltage3_TX1_Q_F2_phase = 0 cf-ad9361-dds-core-lpc.out_altvoltage3_TX1_Q_F2_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage3_TX1_Q_F2_frequency = 9279985 cf-ad9361-dds-core-lpc.out_altvoltage7_TX2_Q_F2_raw = 1 cf-ad9361-dds-core-lpc.out_altvoltage7_TX2_Q_F2_phase = 0 cf-ad9361-dds-core-lpc.out_altvoltage7_TX2_Q_F2_scale = 0.000000 cf-ad9361-dds-core-lpc.out_altvoltage7_TX2_Q_F2_frequency = 999859 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_raw = 1 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_phase = 0 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_scale = 1.000000 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_frequency = 2000186 cf-ad9361-dds-core-lpc.out_altvoltage1_TX1_I_F2_frequency = 9279985 cf-ad9361-dds-core-lpc.out_altvoltage1_TX1_I_F2_raw = 1 cf-ad9361-dds-core-lpc.out_altvoltage1_TX1_I_F2_phase = 90000 cf-ad9361-dds-core-lpc.out_altvoltage1_TX1_I_F2_scale = 0.000000 load_fir_filter_file = dds_mode_tx1 = 1 dds_mode_tx2 = 1 dac_buf_filename = (null) tx_channel_0 = 0 tx_channel_1 = 0 tx_channel_2 = 0 tx_channel_3 = 0 up_down_converter = 0 global_settings_show = 1 tx_show = 1 rx_show = 1 fpga_show = 1 [IIO Oscilloscope - Capture Window1] domain=fft sample_count=400 fft_size=16384 fft_avg=16 fft_pwr_offset=0.000000 graph_type=Lines show_grid=1 enable_auto_scale=1 user_y_axis_max=5.625473 user_y_axis_min=-118.134926 x_axis_min=-16.895906 x_axis_max=16.894032 y_axis_min=-117.590523 y_axis_max=5.599549 line_thickness = 1 plot_title = ADI IIO Oscilloscope - Capture1 show_capture_options = 1 plot_width = 1011 plot_height = 802 plot_x_pos=887 plot_y_pos=38 cf-ad9361-lpc.expanded=1 cf-ad9361-lpc.active=1 cf-ad9361-lpc.trigger_enabled=0 cf-ad9361-lpc.voltage0.enabled=0 cf-ad9361-lpc.voltage0.color_red=35328 cf-ad9361-lpc.voltage0.color_green=57856 cf-ad9361-lpc.voltage0.color_blue=13312 cf-ad9361-lpc.voltage0.math_apply_inverse_funct=0 cf-ad9361-lpc.voltage0.math_apply_multiply_funct=0 cf-ad9361-lpc.voltage0.math_apply_add_funct=0 cf-ad9361-lpc.voltage0.math_multiply_value=0.000000 cf-ad9361-lpc.voltage0.math_add_value=0.000000 cf-ad9361-lpc.voltage1.enabled=0 cf-ad9361-lpc.voltage1.color_red=61184 cf-ad9361-lpc.voltage1.color_green=10496 cf-ad9361-lpc.voltage1.color_blue=10496 cf-ad9361-lpc.voltage1.math_apply_inverse_funct=0 cf-ad9361-lpc.voltage1.math_apply_multiply_funct=0 cf-ad9361-lpc.voltage1.math_apply_add_funct=0 cf-ad9361-lpc.voltage1.math_multiply_value=0.000000 cf-ad9361-lpc.voltage1.math_add_value=0.000000 cf-ad9361-lpc.voltage2.enabled=1 cf-ad9361-lpc.voltage2.color_red=29184 cf-ad9361-lpc.voltage2.color_green=40704 cf-ad9361-lpc.voltage2.color_blue=52992 cf-ad9361-lpc.voltage2.math_apply_inverse_funct=0 cf-ad9361-lpc.voltage2.math_apply_multiply_funct=0 cf-ad9361-lpc.voltage2.math_apply_add_funct=0 cf-ad9361-lpc.voltage2.math_multiply_value=0.000000 cf-ad9361-lpc.voltage2.math_add_value=0.000000 cf-ad9361-lpc.voltage3.enabled=1 cf-ad9361-lpc.voltage3.color_red=64512 cf-ad9361-lpc.voltage3.color_green=44800 cf-ad9361-lpc.voltage3.color_blue=15872 cf-ad9361-lpc.voltage3.math_apply_inverse_funct=0 cf-ad9361-lpc.voltage3.math_apply_multiply_funct=0 cf-ad9361-lpc.voltage3.math_apply_add_funct=0 cf-ad9361-lpc.voltage3.math_multiply_value=0.000000 cf-ad9361-lpc.voltage3.math_add_value=0.000000 Math.expanded=0 Math.active=0 marker_type = Single Tone Markers marker.0 = 9163 marker.1 = 8192 marker.2 = 10135 marker.3 = 11106 marker.4 = 12078 marker.5 = 13049 capture_started=1 cycle = 8000 # look at the markers - Fundamental test.marker.0 = -20.0 0.0 # DC test.marker.1 = -120.0 -55.0 # 2st Harmonic test.marker.2 = -120.0 -55.0 # 3nd Harmonic test.marker.3 = -90.0 -40.0 # 4th Harmonic test.marker.4 = -120.0 -55.0 # 5th Harmonic test.marker.5 = -90.0 -40.0 [AD936X] # 8 MHz tone cf-ad9361-dds-core-lpc.out_altvoltage0_TX1_I_F1_frequency = 8000278 cf-ad9361-dds-core-lpc.out_altvoltage4_TX2_I_F1_frequency = 8000278 cf-ad9361-dds-core-lpc.out_altvoltage6_TX2_Q_F1_frequency = 8000278 cf-ad9361-dds-core-lpc.out_altvoltage2_TX1_Q_F1_frequency = 8000278 SYNC_RELOAD = 1 [IIO Oscilloscope - Capture Window1] cycle = 8000 # look at the markers - Fundamental test.marker.0 = -20.0 0.0 # DC test.marker.1 = -120.0 -55.0 # 2st Harmonic test.marker.2 = -120.0 -45.0 # 3nd Harmonic test.marker.3 = -120.0 -45.0 # 4th Harmonic test.marker.4 = -130.0 -80.0 # 5th Harmonic test.marker.5 = -120.0 -60.0 test.message = All tests passed - Ship it quit = 1
{ "pile_set_name": "Github" }
<math> <mrow> <mtable> <mtr> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0 </mtd> </mtr> <mtr> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0.9 </mtd> <mtd> 0 </mtd> </mtr> <mtr> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0.9 </mtd> <mtd> 0 </mtd> </mtr> <mtr> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 1 </mtd> <mtd> 0 </mtd> </mtr> <mtr> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 0 </mtd> <mtd> 1 </mtd> </mtr> </mtable> </mrow> </math>
{ "pile_set_name": "Github" }
############################################################################### # Copyright (c) 2016, 2016 IBM Corp. and others # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License 2.0 which accompanies this # distribution and is available at https://www.eclipse.org/legal/epl-2.0/ # or the Apache License, Version 2.0 which accompanies this distribution and # is available at https://www.apache.org/licenses/LICENSE-2.0. # # This Source Code may also be made available under the following # Secondary Licenses when the conditions for such availability set # forth in the Eclipse Public License, v. 2.0 are satisfied: GNU # General Public License, version 2 with the GNU Classpath # Exception [1] and GNU General Public License, version 2 with the # OpenJDK Assembly Exception [2]. # # [1] https://www.gnu.org/software/classpath/license.html # [2] http://openjdk.java.net/legal/assembly-exception.html # # SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception ############################################################################### HOST_ARCH=x HOST_SUBARCH=amd64 HOST_BITS=64 OS=linux C_COMPILER=clang TOOLCHAIN=gnu
{ "pile_set_name": "Github" }
//----------------------------------------------------------------------- // <copyright file="MatrixMath.cs" company="MyToolkit"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/MyToolkit/MyToolkit/blob/master/LICENSE.md</license> // <author>Rico Suter, [email protected]</author> //----------------------------------------------------------------------- using System; using System.Linq; namespace MyToolkit.Mathematics { public static class MatrixMath { public static void Copy(this Matrix source, Matrix target) { if (source.Rows != target.Rows) throw new ArgumentException("row count does not match"); if (source.Columns != target.Columns) throw new ArgumentException("column count does not match"); for (var row = 0; row < source.Rows; row++) { for (var col = 0; col < source.Columns; col++) target[row, col] = source[row, col]; } } public static Matrix DeleteColumn(this Matrix matrix, int columnToDelete) { if (columnToDelete >= matrix.Columns) throw new ArgumentException("column does not exist"); var newMatrix = new double[matrix.Rows, matrix.Columns - 1]; for (var row = 0; row < matrix.Rows; row++) { var targetCol = 0; for (var col = 0; col < matrix.Columns; col++) { if (col != columnToDelete) { newMatrix[row, targetCol] = matrix[row, col]; targetCol++; } } } return new Matrix(newMatrix, false); } public static Matrix DeleteRow(this Matrix matrix, int rowToDelete) { if (rowToDelete >= matrix.Rows) throw new ArgumentException("row does not exist"); var targetRow = 0; var newMatrix = new double[matrix.Rows - 1, matrix.Columns]; for (var row = 0; row < matrix.Rows; row++) { if (row != rowToDelete) { for (var col = 0; col < matrix.Columns; col++) newMatrix[targetRow, col] = matrix[row, col]; targetRow++; } } return new Matrix(newMatrix, false); } public static Matrix Divide(this Matrix matrix, double divisor) { var result = new double[matrix.Rows, matrix.Columns]; for (var row = 0; row < matrix.Rows; row++) { for (var col = 0; col < matrix.Columns; col++) result[row, col] = matrix[row, col] / divisor; } return new Matrix(result, false); } public static double DotProduct(this Matrix a, Matrix b) { if (!a.IsVector || !b.IsVector) throw new ArgumentException("two vectors expected"); //var length = a.Data.GetLength(0); //if ((length != a.Data.GetLength(1) && a.Data.GetLength(1) != 1) || (b.Data.GetLength(0) != a.Data.GetLength(1) && a.Data.GetLength(0) != 1)) // throw new ArgumentException(); //if (length != b.Data.GetLength(1)) // throw new ArgumentException("vectors don't have same length"); //var result = 0.0; //for (var i = 0; i < length; i++) // result += a.Data[i, 0] * b.Data[0, i]; //return result; var aArray = a.ToPackedArray(); var bArray = b.ToPackedArray(); if (aArray.Length != bArray.Length) throw new ArgumentException("vectors don't have same length"); var result = 0.0; for (var i = 0; i < aArray.Length; i++) result += aArray[i] * bArray[i]; return result; } public static Matrix Multiply(this Matrix a, double factor) { var result = new double[a.Rows, a.Columns]; for (var row = 0; row < a.Rows; row++) { for (var col = 0; col < a.Columns; col++) result[row, col] = a[row, col] * factor; } return new Matrix(result, false); } public static Matrix Multiply(this Matrix a, Matrix b) { if (a.Columns != b.Rows) throw new ArgumentException("a.Columns != b.Rows"); var result = new double[a.Rows, b.Columns]; for (var row = 0; row < a.Rows; row++) { for (var column = 0; column < b.Columns; column++) { var value = 0.0; for (var i = 0; i < a.Columns; i++) value += a[row, i] * b[i, column]; result[row, column] = value; } } return new Matrix(result, false); } public static Matrix Add(this Matrix a, Matrix b) { if (a.Rows != b.Rows) throw new ArgumentException("row count does not match"); if (a.Columns != b.Columns) throw new ArgumentException("column count does not match"); var result = new double[a.Rows, a.Columns]; for (var resultRow = 0; resultRow < a.Rows; resultRow++) { for (var resultCol = 0; resultCol < a.Columns; resultCol++) result[resultRow, resultCol] = a[resultRow, resultCol] + b[resultRow, resultCol]; } return new Matrix(result, false); } public static Matrix Subtract(this Matrix a, Matrix b) { if (a.Rows != b.Rows) throw new ArgumentException("row count does not match"); if (a.Columns != b.Columns) throw new ArgumentException("column count does not match"); var result = new double[a.Rows, a.Columns]; for (var resultRow = 0; resultRow < a.Rows; resultRow++) { for (var resultCol = 0; resultCol < a.Columns; resultCol++) result[resultRow, resultCol] = a[resultRow, resultCol] - b[resultRow, resultCol]; } return new Matrix(result, false); } public static Matrix Transpose(this Matrix input) { var inverseMatrix = new double[input.Columns, input.Rows]; for (var r = 0; r < input.Rows; r++) { for (var c = 0; c < input.Columns; c++) inverseMatrix[c, r] = input[r, c]; } return new Matrix(inverseMatrix, false); } public static double VectorLength(this Matrix input) { if (!input.IsVector) throw new ArgumentException("input is not a vector"); var v = input.ToPackedArray(); return Math.Sqrt(v.Sum(t => Math.Pow(t, 2))); } } }
{ "pile_set_name": "Github" }
import Foundation class AppUserAccount { enum DefaultsKeys: String { case UserAccountKey } // MARK: - Initializers let defaults: UserDefaults init(defaults: UserDefaults) { self.defaults = defaults } init() { self.defaults = UserDefaults.standard } // MARK: - Properties var name: String? { get { let key = defaults.string(forKey: DefaultsKeys.UserAccountKey.rawValue) return key } set(newName) { guard let name = newName else { defaults.removeObject(forKey: DefaultsKeys.UserAccountKey.rawValue) defaults.synchronize() return } defaults.set(name, forKey: DefaultsKeys.UserAccountKey.rawValue) defaults.synchronize() } } }
{ "pile_set_name": "Github" }
// // CornerLineAnimationViewController.swift // AnimaExample // // Created by Satoshi Nagasaka on 2017/04/24. // Copyright © 2017 satoshin21. All rights reserved. // import Foundation import Anima class CornerLineAnimationViewController: UIViewController { @IBOutlet weak var animaView: UIView! override func viewDidLoad() { super.viewDidLoad() let size = AnimaType.scaleBy(2.0) let cornerRadius = AnimaType.cornerRadius(25) let borderColor = AnimaType.borderColor(.white) let borderWidth = AnimaType.borderWidth(5) animaView.layer .anima .then(group: [size, cornerRadius, borderColor, borderWidth], options: [.timingFunction(.easeOutCubic),.duration(1.5), .autoreverse, .repeat(count: .infinity)]) .fire() } }
{ "pile_set_name": "Github" }
{ "SX1301_conf": { "lorawan_public": true, "clksrc": 1, /* radio_1 provides clock to concentrator */ "antenna_gain": 0, /* antenna gain, in dBi */ "radio_0": { "enable": true, "type": "SX1257", "freq": 867500000, "rssi_offset": -166.0, "tx_enable": true, "tx_freq_min": 863000000, "tx_freq_max": 870000000 }, "radio_1": { "enable": true, "type": "SX1257", "freq": 868500000, "rssi_offset": -166.0, "tx_enable": false }, "chan_multiSF_0": { /* Lora MAC channel, 125kHz, all SF, 868.1 MHz */ "enable": true, "radio": 1, "if": -400000 }, "chan_multiSF_1": { /* Lora MAC channel, 125kHz, all SF, 868.3 MHz */ "enable": true, "radio": 1, "if": -200000 }, "chan_multiSF_2": { /* Lora MAC channel, 125kHz, all SF, 868.5 MHz */ "enable": true, "radio": 1, "if": 0 }, "chan_multiSF_3": { /* Lora MAC channel, 125kHz, all SF, 867.1 MHz */ "enable": true, "radio": 0, "if": -400000 }, "chan_multiSF_4": { /* Lora MAC channel, 125kHz, all SF, 867.3 MHz */ "enable": true, "radio": 0, "if": -200000 }, "chan_multiSF_5": { /* Lora MAC channel, 125kHz, all SF, 867.5 MHz */ "enable": true, "radio": 0, "if": 0 }, "chan_multiSF_6": { /* Lora MAC channel, 125kHz, all SF, 867.7 MHz */ "enable": true, "radio": 0, "if": 200000 }, "chan_multiSF_7": { /* Lora MAC channel, 125kHz, all SF, 867.9 MHz */ "enable": true, "radio": 0, "if": 400000 }, "chan_Lora_std": { /* Lora MAC channel, 250kHz, SF7, 868.3 MHz */ "enable": true, "radio": 1, "if": -200000, "bandwidth": 250000, "spread_factor": 7 }, "chan_FSK": { /* FSK 50kbps channel, 868.8 MHz */ "enable": true, "radio": 1, "if": 300000, "bandwidth": 125000, "datarate": 50000 }, "tx_lut_0": { /* TX gain table, index 0 */ "pa_gain": 0, "mix_gain": 8, "rf_power": -6, "dig_gain": 0 }, "tx_lut_1": { /* TX gain table, index 1 */ "pa_gain": 0, "mix_gain": 10, "rf_power": -3, "dig_gain": 0 }, "tx_lut_2": { /* TX gain table, index 2 */ "pa_gain": 0, "mix_gain": 12, "rf_power": 0, "dig_gain": 0 }, "tx_lut_3": { /* TX gain table, index 3 */ "pa_gain": 1, "mix_gain": 8, "rf_power": 3, "dig_gain": 0 }, "tx_lut_4": { /* TX gain table, index 4 */ "pa_gain": 1, "mix_gain": 10, "rf_power": 6, "dig_gain": 0 }, "tx_lut_5": { /* TX gain table, index 5 */ "pa_gain": 1, "mix_gain": 12, "rf_power": 10, "dig_gain": 0 }, "tx_lut_6": { /* TX gain table, index 6 */ "pa_gain": 1, "mix_gain": 13, "rf_power": 11, "dig_gain": 0 }, "tx_lut_7": { /* TX gain table, index 7 */ "pa_gain": 2, "mix_gain": 9, "rf_power": 12, "dig_gain": 0 }, "tx_lut_8": { /* TX gain table, index 8 */ "pa_gain": 1, "mix_gain": 15, "rf_power": 13, "dig_gain": 0 }, "tx_lut_9": { /* TX gain table, index 9 */ "pa_gain": 2, "mix_gain": 10, "rf_power": 14, "dig_gain": 0 }, "tx_lut_10": { /* TX gain table, index 10 */ "pa_gain": 2, "mix_gain": 11, "rf_power": 16, "dig_gain": 0 }, "tx_lut_11": { /* TX gain table, index 11 */ "pa_gain": 3, "mix_gain": 9, "rf_power": 20, "dig_gain": 0 } }, "gateway_conf": { "gateway_ID": "AA555A0000000000", /* change with default server address/ports, or overwrite in local_conf.json */ "server_address": "localhost", "serv_port_up": 1680, "serv_port_down": 1680, /* adjust the following parameters for your network */ "keepalive_interval": 10, "stat_interval": 30, "push_timeout_ms": 100, /* forward only valid packets */ "forward_crc_valid": true, "forward_crc_error": false, "forward_crc_disabled": false } }
{ "pile_set_name": "Github" }
--- title: NdisFilterTimedPauseComplete rule (ndis) description: The NdisFilterTimedPauseComplete verifies three things The FilterPause function will be completed in 10 seconds or less.The FilterPause function must not fail.The FilterPause function must not complete twice. ms.assetid: 60B926CC-E2C4-42B8-8555-5E620DCDDAFC ms.date: 05/21/2018 keywords: ["NdisFilterTimedPauseComplete rule (ndis)"] topic_type: - apiref api_name: - NdisFilterTimedPauseComplete api_type: - NA ms.localizationpriority: medium --- # NdisFilterTimedPauseComplete rule (ndis) The **NdisFilterTimedPauseComplete** verifies three things: - The [*FilterPause*](/windows-hardware/drivers/ddi/ndis/nc-ndis-filter_pause) function will be completed in 10 seconds or less. - The [*FilterPause*](/windows-hardware/drivers/ddi/ndis/nc-ndis-filter_pause) function must not fail. - The [*FilterPause*](/windows-hardware/drivers/ddi/ndis/nc-ndis-filter_pause) function must not complete twice. **Driver model: NDIS** **Bug check(s) found with this rule**: [**Bug Check 0xC4: DRIVER\_VERIFIER\_DETECTED\_VIOLATION**](../debugger/bug-check-0xc4--driver-verifier-detected-violation.md) ( 0x00092010) How to test ----------- <table> <colgroup> <col width="100%" /> </colgroup> <thead> <tr class="header"> <th align="left">At run time</th> </tr> </thead> <tbody> <tr class="odd"> <td align="left"><p>Run <a href="/windows-hardware/drivers/devtest/driver-verifier" data-raw-source="[Driver Verifier](./driver-verifier.md)">Driver Verifier</a> and select the <a href="/windows-hardware/drivers/devtest/ndis-wifi-verification" data-raw-source="[NDIS/WIFI verification](./ndis-wifi-verification.md)">NDIS/WIFI verification</a> option. This rule is also tested with the <a href="/windows-hardware/drivers/devtest/ddi-compliance-checking" data-raw-source="[DDI compliance checking](./ddi-compliance-checking.md)">DDI compliance checking</a> option.</p></td> </tr> </tbody> </table>
{ "pile_set_name": "Github" }
{ "cluster.put_settings": { "documentation": "https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cluster-update-settings.html", "methods": ["PUT"], "url": { "path": "/_cluster/settings", "paths": ["/_cluster/settings"], "parts": {}, "params": { "flat_settings": { "type": "boolean", "description": "Return settings in flat format (default: false)" }, "master_timeout": { "type" : "time", "description" : "Explicit operation timeout for connection to master node" }, "timeout": { "type" : "time", "description" : "Explicit operation timeout" } } }, "body": { "description": "The settings to be updated. Can be either `transient` or `persistent` (survives cluster restart)." } } }
{ "pile_set_name": "Github" }
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ #ifndef LUA_OBJECT_MATERIAL_H #define LUA_OBJECT_MATERIAL_H // NOTE: some implementation is done in LuaMaterial.cpp typedef int GLint; typedef unsigned int GLuint; typedef float GLfloat; typedef unsigned int GLenum; #include <algorithm> #include <cassert> #include <vector> class CSolidObject; class LuaMatBin; /******************************************************************************/ /******************************************************************************/ enum LuaObjType { LUAOBJ_UNIT = 0, LUAOBJ_FEATURE = 1, LUAOBJ_LAST = 2, }; enum LuaMatType { //FIXME move deferred here LUAMAT_ALPHA = 0, LUAMAT_OPAQUE = 1, LUAMAT_ALPHA_REFLECT = 2, LUAMAT_OPAQUE_REFLECT = 3, LUAMAT_SHADOW = 4, LUAMAT_TYPE_COUNT = 5, }; /******************************************************************************/ class LuaMatRef { friend class LuaMatHandler; public: LuaMatRef() = default; LuaMatRef(const LuaMatRef&); LuaMatRef& operator=(const LuaMatRef&); ~LuaMatRef(); void Reset(); void AddUnit(CSolidObject*); void AddFeature(CSolidObject*); bool IsActive() const { return (bin != nullptr); } const LuaMatBin* GetBin() const { return bin; } LuaMatBin* GetBin() { return bin; } private: LuaMatRef(LuaMatBin* _bin); private: LuaMatBin* bin = nullptr; // can be NULL }; /******************************************************************************/ class LuaObjectMaterial { public: bool SetLODCount(unsigned int count); bool SetLastLOD(unsigned int count); inline const unsigned int GetLODCount() const { return lodCount; } inline const unsigned int GetLastLOD() const { return lastLOD; } inline bool IsActive(unsigned int lod) const { if (lod >= lodCount) return false; return lodMats[lod].IsActive(); } inline LuaMatRef* GetMaterial(unsigned int lod) { if (lod >= lodCount) return nullptr; return &lodMats[lod]; } inline const LuaMatRef* GetMaterial(unsigned int lod) const { if (lod >= lodCount) return nullptr; return &lodMats[lod]; } private: unsigned int lodCount = 0; unsigned int lastLOD = 0; std::vector<LuaMatRef> lodMats; }; /******************************************************************************/ struct LuaObjectMaterialData { public: bool Enabled() const { return (lodCount > 0); } bool ValidLOD(unsigned int lod) const { return (lod < lodCount); } const LuaObjectMaterial* GetLuaMaterials() const { return &luaMats[0]; } const LuaObjectMaterial* GetLuaMaterial(LuaMatType type) const { return &luaMats[type]; } LuaObjectMaterial* GetLuaMaterial(LuaMatType type) { return &luaMats[type]; } const LuaMatRef* GetLODMatRef(LuaMatType type) const { const LuaObjectMaterial* mat = GetLuaMaterial(type); const LuaMatRef* lodMat = mat->GetMaterial(currentLOD); return lodMat; } LuaMatRef* GetLODMatRef(LuaMatType type) { LuaObjectMaterial* mat = GetLuaMaterial(type); LuaMatRef* lodMat = mat->GetMaterial(currentLOD); return lodMat; } void UpdateCurrentLOD(LuaObjType objType, float lodDist, LuaMatType matType) { SetCurrentLOD(CalcCurrentLOD(objType, lodDist, luaMats[matType].GetLastLOD())); } unsigned int CalcCurrentLOD(LuaObjType objType, float lodDist, unsigned int lastLOD) const { if (lastLOD >= lodCount) return 0; // positive values only! const float lpp = std::max(0.0f, lodDist * GLOBAL_LOD_FACTORS[objType]); for (/* no-op */; (lastLOD != 0 && lpp <= lodLengths[lastLOD]); lastLOD--) { } return lastLOD; } unsigned int SetCurrentLOD(unsigned int lod) { return (currentLOD = lod); } unsigned int GetLODCount() const { return lodCount; } unsigned int GetCurrentLOD() const { return currentLOD; } float GetLODLength(unsigned int lod) const { return lodLengths[lod]; } void PushLODCount(unsigned int tmpCount) { lodStack.push_back(lodCount); lodCount = tmpCount; } void PopLODCount() { lodCount = lodStack.back(); lodStack.pop_back(); } void SetLODCount(unsigned int count) { const unsigned int oldCount = lodCount; lodLengths.resize(lodCount = count); for (unsigned int i = oldCount; i < lodCount; i++) { lodLengths[i] = -1.0f; } for (int m = 0; m < LUAMAT_TYPE_COUNT; m++) { luaMats[m].SetLODCount(lodCount); } } void SetLODLength(unsigned int lod, float length) { if (lod >= lodCount) return; lodLengths[lod] = length; } bool AddObjectForLOD(CSolidObject* o, LuaObjType objType, LuaMatType matType, float lodDist) { if (!Enabled()) return false; LuaObjectMaterial* objMat = GetLuaMaterial(matType); LuaMatRef* lodMat = objMat->GetMaterial(SetCurrentLOD(CalcCurrentLOD(objType, lodDist, objMat->GetLastLOD()))); if ((lodMat != nullptr) && lodMat->IsActive()) { switch (objType) { case LUAOBJ_UNIT : { lodMat->AddUnit (o); } break; case LUAOBJ_FEATURE: { lodMat->AddFeature(o); } break; default : { assert(false); } break; } return true; } return false; } static void SetGlobalLODFactor(LuaObjType objType, float lodFactor) { GLOBAL_LOD_FACTORS[objType] = lodFactor; } private: static float GLOBAL_LOD_FACTORS[LUAOBJ_LAST]; // equal to lodLengths.size(); if non-zero, then at least // one LOD-level has been assigned a custom Lua material unsigned int lodCount = 0; // which LuaMatRef should be used unsigned int currentLOD = 0; // length-per-pixel; see CalcCurrentLOD std::vector<float> lodLengths; std::vector<unsigned int> lodStack; LuaObjectMaterial luaMats[LUAMAT_TYPE_COUNT]; }; /******************************************************************************/ /******************************************************************************/ #endif /* LUA_OBJECT_MATERIAL_H */
{ "pile_set_name": "Github" }
var convert = require('./convert'), func = convert('flip', require('../flip'), require('./_falseOptions')); func.placeholder = require('./placeholder'); module.exports = func;
{ "pile_set_name": "Github" }
//===- llvm/ADT/SmallPtrSet.h - 'Normally small' pointer set ----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the SmallPtrSet class. See the doxygen comment for // SmallPtrSetImplBase for more details on the algorithm used. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_SMALLPTRSET_H #define LLVM_ADT_SMALLPTRSET_H #include "llvm/ADT/EpochTracker.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ReverseIteration.h" #include "llvm/Support/type_traits.h" #include <cassert> #include <cstddef> #include <cstdlib> #include <cstring> #include <initializer_list> #include <iterator> #include <utility> namespace llvm { /// SmallPtrSetImplBase - This is the common code shared among all the /// SmallPtrSet<>'s, which is almost everything. SmallPtrSet has two modes, one /// for small and one for large sets. /// /// Small sets use an array of pointers allocated in the SmallPtrSet object, /// which is treated as a simple array of pointers. When a pointer is added to /// the set, the array is scanned to see if the element already exists, if not /// the element is 'pushed back' onto the array. If we run out of space in the /// array, we grow into the 'large set' case. SmallSet should be used when the /// sets are often small. In this case, no memory allocation is used, and only /// light-weight and cache-efficient scanning is used. /// /// Large sets use a classic exponentially-probed hash table. Empty buckets are /// represented with an illegal pointer value (-1) to allow null pointers to be /// inserted. Tombstones are represented with another illegal pointer value /// (-2), to allow deletion. The hash table is resized when the table is 3/4 or /// more. When this happens, the table is doubled in size. /// class SmallPtrSetImplBase : public DebugEpochBase { friend class SmallPtrSetIteratorImpl; protected: /// SmallArray - Points to a fixed size set of buckets, used in 'small mode'. const void **SmallArray; /// CurArray - This is the current set of buckets. If equal to SmallArray, /// then the set is in 'small mode'. const void **CurArray; /// CurArraySize - The allocated size of CurArray, always a power of two. unsigned CurArraySize; /// Number of elements in CurArray that contain a value or are a tombstone. /// If small, all these elements are at the beginning of CurArray and the rest /// is uninitialized. unsigned NumNonEmpty; /// Number of tombstones in CurArray. unsigned NumTombstones; // Helpers to copy and move construct a SmallPtrSet. SmallPtrSetImplBase(const void **SmallStorage, const SmallPtrSetImplBase &that); SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize, SmallPtrSetImplBase &&that); explicit SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize) : SmallArray(SmallStorage), CurArray(SmallStorage), CurArraySize(SmallSize), NumNonEmpty(0), NumTombstones(0) { assert(SmallSize && (SmallSize & (SmallSize-1)) == 0 && "Initial size must be a power of two!"); } ~SmallPtrSetImplBase() { if (!isSmall()) free(CurArray); } public: using size_type = unsigned; SmallPtrSetImplBase &operator=(const SmallPtrSetImplBase &) = delete; LLVM_NODISCARD bool empty() const { return size() == 0; } size_type size() const { return NumNonEmpty - NumTombstones; } void clear() { incrementEpoch(); // If the capacity of the array is huge, and the # elements used is small, // shrink the array. if (!isSmall()) { if (size() * 4 < CurArraySize && CurArraySize > 32) return shrink_and_clear(); // Fill the array with empty markers. memset(CurArray, -1, CurArraySize * sizeof(void *)); } NumNonEmpty = 0; NumTombstones = 0; } protected: static void *getTombstoneMarker() { return reinterpret_cast<void*>(-2); } static void *getEmptyMarker() { // Note that -1 is chosen to make clear() efficiently implementable with // memset and because it's not a valid pointer value. return reinterpret_cast<void*>(-1); } const void **EndPointer() const { return isSmall() ? CurArray + NumNonEmpty : CurArray + CurArraySize; } /// insert_imp - This returns true if the pointer was new to the set, false if /// it was already in the set. This is hidden from the client so that the /// derived class can check that the right type of pointer is passed in. std::pair<const void *const *, bool> insert_imp(const void *Ptr) { if (isSmall()) { // Check to see if it is already in the set. const void **LastTombstone = nullptr; for (const void **APtr = SmallArray, **E = SmallArray + NumNonEmpty; APtr != E; ++APtr) { const void *Value = *APtr; if (Value == Ptr) return std::make_pair(APtr, false); if (Value == getTombstoneMarker()) LastTombstone = APtr; } // Did we find any tombstone marker? if (LastTombstone != nullptr) { *LastTombstone = Ptr; --NumTombstones; incrementEpoch(); return std::make_pair(LastTombstone, true); } // Nope, there isn't. If we stay small, just 'pushback' now. if (NumNonEmpty < CurArraySize) { SmallArray[NumNonEmpty++] = Ptr; incrementEpoch(); return std::make_pair(SmallArray + (NumNonEmpty - 1), true); } // Otherwise, hit the big set case, which will call grow. } return insert_imp_big(Ptr); } /// erase_imp - If the set contains the specified pointer, remove it and /// return true, otherwise return false. This is hidden from the client so /// that the derived class can check that the right type of pointer is passed /// in. bool erase_imp(const void * Ptr) { const void *const *P = find_imp(Ptr); if (P == EndPointer()) return false; const void **Loc = const_cast<const void **>(P); assert(*Loc == Ptr && "broken find!"); *Loc = getTombstoneMarker(); NumTombstones++; return true; } /// Returns the raw pointer needed to construct an iterator. If element not /// found, this will be EndPointer. Otherwise, it will be a pointer to the /// slot which stores Ptr; const void *const * find_imp(const void * Ptr) const { if (isSmall()) { // Linear search for the item. for (const void *const *APtr = SmallArray, *const *E = SmallArray + NumNonEmpty; APtr != E; ++APtr) if (*APtr == Ptr) return APtr; return EndPointer(); } // Big set case. auto *Bucket = FindBucketFor(Ptr); if (*Bucket == Ptr) return Bucket; return EndPointer(); } private: bool isSmall() const { return CurArray == SmallArray; } std::pair<const void *const *, bool> insert_imp_big(const void *Ptr); const void * const *FindBucketFor(const void *Ptr) const; void shrink_and_clear(); /// Grow - Allocate a larger backing store for the buckets and move it over. void Grow(unsigned NewSize); protected: /// swap - Swaps the elements of two sets. /// Note: This method assumes that both sets have the same small size. void swap(SmallPtrSetImplBase &RHS); void CopyFrom(const SmallPtrSetImplBase &RHS); void MoveFrom(unsigned SmallSize, SmallPtrSetImplBase &&RHS); private: /// Code shared by MoveFrom() and move constructor. void MoveHelper(unsigned SmallSize, SmallPtrSetImplBase &&RHS); /// Code shared by CopyFrom() and copy constructor. void CopyHelper(const SmallPtrSetImplBase &RHS); }; /// SmallPtrSetIteratorImpl - This is the common base class shared between all /// instances of SmallPtrSetIterator. class SmallPtrSetIteratorImpl { protected: const void *const *Bucket; const void *const *End; public: explicit SmallPtrSetIteratorImpl(const void *const *BP, const void*const *E) : Bucket(BP), End(E) { if (shouldReverseIterate()) { RetreatIfNotValid(); return; } AdvanceIfNotValid(); } bool operator==(const SmallPtrSetIteratorImpl &RHS) const { return Bucket == RHS.Bucket; } bool operator!=(const SmallPtrSetIteratorImpl &RHS) const { return Bucket != RHS.Bucket; } protected: /// AdvanceIfNotValid - If the current bucket isn't valid, advance to a bucket /// that is. This is guaranteed to stop because the end() bucket is marked /// valid. void AdvanceIfNotValid() { assert(Bucket <= End); while (Bucket != End && (*Bucket == SmallPtrSetImplBase::getEmptyMarker() || *Bucket == SmallPtrSetImplBase::getTombstoneMarker())) ++Bucket; } void RetreatIfNotValid() { assert(Bucket >= End); while (Bucket != End && (Bucket[-1] == SmallPtrSetImplBase::getEmptyMarker() || Bucket[-1] == SmallPtrSetImplBase::getTombstoneMarker())) { --Bucket; } } }; /// SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet. template <typename PtrTy> class SmallPtrSetIterator : public SmallPtrSetIteratorImpl, DebugEpochBase::HandleBase { using PtrTraits = PointerLikeTypeTraits<PtrTy>; public: using value_type = PtrTy; using reference = PtrTy; using pointer = PtrTy; using difference_type = std::ptrdiff_t; using iterator_category = std::forward_iterator_tag; explicit SmallPtrSetIterator(const void *const *BP, const void *const *E, const DebugEpochBase &Epoch) : SmallPtrSetIteratorImpl(BP, E), DebugEpochBase::HandleBase(&Epoch) {} // Most methods provided by baseclass. const PtrTy operator*() const { assert(isHandleInSync() && "invalid iterator access!"); if (shouldReverseIterate()) { assert(Bucket > End); return PtrTraits::getFromVoidPointer(const_cast<void *>(Bucket[-1])); } assert(Bucket < End); return PtrTraits::getFromVoidPointer(const_cast<void*>(*Bucket)); } inline SmallPtrSetIterator& operator++() { // Preincrement assert(isHandleInSync() && "invalid iterator access!"); if (shouldReverseIterate()) { --Bucket; RetreatIfNotValid(); return *this; } ++Bucket; AdvanceIfNotValid(); return *this; } SmallPtrSetIterator operator++(int) { // Postincrement SmallPtrSetIterator tmp = *this; ++*this; return tmp; } }; /// RoundUpToPowerOfTwo - This is a helper template that rounds N up to the next /// power of two (which means N itself if N is already a power of two). template<unsigned N> struct RoundUpToPowerOfTwo; /// RoundUpToPowerOfTwoH - If N is not a power of two, increase it. This is a /// helper template used to implement RoundUpToPowerOfTwo. template<unsigned N, bool isPowerTwo> struct RoundUpToPowerOfTwoH { enum { Val = N }; }; template<unsigned N> struct RoundUpToPowerOfTwoH<N, false> { enum { // We could just use NextVal = N+1, but this converges faster. N|(N-1) sets // the right-most zero bits to one all at once, e.g. 0b0011000 -> 0b0011111. Val = RoundUpToPowerOfTwo<(N|(N-1)) + 1>::Val }; }; template<unsigned N> struct RoundUpToPowerOfTwo { enum { Val = RoundUpToPowerOfTwoH<N, (N&(N-1)) == 0>::Val }; }; /// A templated base class for \c SmallPtrSet which provides the /// typesafe interface that is common across all small sizes. /// /// This is particularly useful for passing around between interface boundaries /// to avoid encoding a particular small size in the interface boundary. template <typename PtrType> class SmallPtrSetImpl : public SmallPtrSetImplBase { using ConstPtrType = typename add_const_past_pointer<PtrType>::type; using PtrTraits = PointerLikeTypeTraits<PtrType>; using ConstPtrTraits = PointerLikeTypeTraits<ConstPtrType>; protected: // Constructors that forward to the base. SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl &that) : SmallPtrSetImplBase(SmallStorage, that) {} SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize, SmallPtrSetImpl &&that) : SmallPtrSetImplBase(SmallStorage, SmallSize, std::move(that)) {} explicit SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize) : SmallPtrSetImplBase(SmallStorage, SmallSize) {} public: using iterator = SmallPtrSetIterator<PtrType>; using const_iterator = SmallPtrSetIterator<PtrType>; using key_type = ConstPtrType; using value_type = PtrType; SmallPtrSetImpl(const SmallPtrSetImpl &) = delete; /// Inserts Ptr if and only if there is no element in the container equal to /// Ptr. The bool component of the returned pair is true if and only if the /// insertion takes place, and the iterator component of the pair points to /// the element equal to Ptr. std::pair<iterator, bool> insert(PtrType Ptr) { auto p = insert_imp(PtrTraits::getAsVoidPointer(Ptr)); return std::make_pair(makeIterator(p.first), p.second); } /// erase - If the set contains the specified pointer, remove it and return /// true, otherwise return false. bool erase(PtrType Ptr) { return erase_imp(PtrTraits::getAsVoidPointer(Ptr)); } /// count - Return 1 if the specified pointer is in the set, 0 otherwise. size_type count(ConstPtrType Ptr) const { return find(Ptr) != end() ? 1 : 0; } iterator find(ConstPtrType Ptr) const { return makeIterator(find_imp(ConstPtrTraits::getAsVoidPointer(Ptr))); } template <typename IterT> void insert(IterT I, IterT E) { for (; I != E; ++I) insert(*I); } void insert(std::initializer_list<PtrType> IL) { insert(IL.begin(), IL.end()); } iterator begin() const { if (shouldReverseIterate()) return makeIterator(EndPointer() - 1); return makeIterator(CurArray); } iterator end() const { return makeIterator(EndPointer()); } private: /// Create an iterator that dereferences to same place as the given pointer. iterator makeIterator(const void *const *P) const { if (shouldReverseIterate()) return iterator(P == EndPointer() ? CurArray : P + 1, CurArray, *this); return iterator(P, EndPointer(), *this); } }; /// Equality comparison for SmallPtrSet. /// /// Iterates over elements of LHS confirming that each value from LHS is also in /// RHS, and that no additional values are in RHS. template <typename PtrType> bool operator==(const SmallPtrSetImpl<PtrType> &LHS, const SmallPtrSetImpl<PtrType> &RHS) { if (LHS.size() != RHS.size()) return false; for (const auto *KV : LHS) if (!RHS.count(KV)) return false; return true; } /// Inequality comparison for SmallPtrSet. /// /// Equivalent to !(LHS == RHS). template <typename PtrType> bool operator!=(const SmallPtrSetImpl<PtrType> &LHS, const SmallPtrSetImpl<PtrType> &RHS) { return !(LHS == RHS); } /// SmallPtrSet - This class implements a set which is optimized for holding /// SmallSize or less elements. This internally rounds up SmallSize to the next /// power of two if it is not already a power of two. See the comments above /// SmallPtrSetImplBase for details of the algorithm. template<class PtrType, unsigned SmallSize> class SmallPtrSet : public SmallPtrSetImpl<PtrType> { // In small mode SmallPtrSet uses linear search for the elements, so it is // not a good idea to choose this value too high. You may consider using a // DenseSet<> instead if you expect many elements in the set. static_assert(SmallSize <= 32, "SmallSize should be small"); using BaseT = SmallPtrSetImpl<PtrType>; // Make sure that SmallSize is a power of two, round up if not. enum { SmallSizePowTwo = RoundUpToPowerOfTwo<SmallSize>::Val }; /// SmallStorage - Fixed size storage used in 'small mode'. const void *SmallStorage[SmallSizePowTwo]; public: SmallPtrSet() : BaseT(SmallStorage, SmallSizePowTwo) {} SmallPtrSet(const SmallPtrSet &that) : BaseT(SmallStorage, that) {} SmallPtrSet(SmallPtrSet &&that) : BaseT(SmallStorage, SmallSizePowTwo, std::move(that)) {} template<typename It> SmallPtrSet(It I, It E) : BaseT(SmallStorage, SmallSizePowTwo) { this->insert(I, E); } SmallPtrSet(std::initializer_list<PtrType> IL) : BaseT(SmallStorage, SmallSizePowTwo) { this->insert(IL.begin(), IL.end()); } SmallPtrSet<PtrType, SmallSize> & operator=(const SmallPtrSet<PtrType, SmallSize> &RHS) { if (&RHS != this) this->CopyFrom(RHS); return *this; } SmallPtrSet<PtrType, SmallSize> & operator=(SmallPtrSet<PtrType, SmallSize> &&RHS) { if (&RHS != this) this->MoveFrom(SmallSizePowTwo, std::move(RHS)); return *this; } SmallPtrSet<PtrType, SmallSize> & operator=(std::initializer_list<PtrType> IL) { this->clear(); this->insert(IL.begin(), IL.end()); return *this; } /// swap - Swaps the elements of two sets. void swap(SmallPtrSet<PtrType, SmallSize> &RHS) { SmallPtrSetImplBase::swap(RHS); } }; } // end namespace llvm namespace std { /// Implement std::swap in terms of SmallPtrSet swap. template<class T, unsigned N> inline void swap(llvm::SmallPtrSet<T, N> &LHS, llvm::SmallPtrSet<T, N> &RHS) { LHS.swap(RHS); } } // end namespace std #endif // LLVM_ADT_SMALLPTRSET_H
{ "pile_set_name": "Github" }
import 'package:angel_route/angel_route.dart'; import 'package:test/test.dart'; void main() { test('resolve / on /', () { var router = Router() ..group('/', (router) { router.group('/', (router) { router.get('/', 'ok'); }); }); expect(router.resolveAbsolute('/'), isNotNull); }); }
{ "pile_set_name": "Github" }
/* packet-http.c * Routines for HTTP packet disassembly * RFC 1945 (HTTP/1.0) * RFC 2616 (HTTP/1.1) * * Guy Harris <[email protected]> * * Copyright 2004, Jerry Talkington <[email protected]> * Copyright 2002, Tim Potter <[email protected]> * Copyright 1999, Andrew Tridgell <[email protected]> * * $Id: packet-http.c 42372 2012-05-01 02:42:51Z wmeier $ * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <glib.h> #include <epan/conversation.h> #include <epan/packet.h> #include <epan/strutil.h> #include <epan/base64.h> #include <epan/emem.h> #include <epan/stats_tree.h> #include <epan/req_resp_hdrs.h> #include "packet-http.h" #include "packet-tcp.h" #include "packet-ssl.h" #include <epan/prefs.h> #include <epan/expert.h> #include <epan/uat.h> typedef enum _http_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_NOTIFICATION, HTTP_OTHERS } http_type_t; #include <epan/tap.h> static int http_tap = -1; static int http_eo_tap = -1; static int proto_http = -1; static int hf_http_notification = -1; static int hf_http_response = -1; static int hf_http_request = -1; static int hf_http_basic = -1; static int hf_http_request_method = -1; static int hf_http_request_uri = -1; static int hf_http_request_full_uri = -1; static int hf_http_version = -1; static int hf_http_response_code = -1; static int hf_http_response_phrase = -1; static int hf_http_authorization = -1; static int hf_http_proxy_authenticate = -1; static int hf_http_proxy_authorization = -1; static int hf_http_proxy_connect_host = -1; static int hf_http_proxy_connect_port = -1; static int hf_http_www_authenticate = -1; static int hf_http_content_type = -1; static int hf_http_content_length_header = -1; static int hf_http_content_length = -1; static int hf_http_content_encoding = -1; static int hf_http_transfer_encoding = -1; static int hf_http_upgrade = -1; static int hf_http_user_agent = -1; static int hf_http_host = -1; static int hf_http_connection = -1; static int hf_http_cookie = -1; static int hf_http_accept = -1; static int hf_http_referer = -1; static int hf_http_accept_language = -1; static int hf_http_accept_encoding = -1; static int hf_http_date = -1; static int hf_http_cache_control = -1; static int hf_http_server = -1; static int hf_http_location = -1; static int hf_http_sec_websocket_accept = -1; static int hf_http_sec_websocket_extensions = -1; static int hf_http_sec_websocket_key = -1; static int hf_http_sec_websocket_protocol = -1; static int hf_http_sec_websocket_version = -1; static int hf_http_set_cookie = -1; static int hf_http_last_modified = -1; static int hf_http_x_forwarded_for = -1; static gint ett_http = -1; static gint ett_http_ntlmssp = -1; static gint ett_http_kerberos = -1; static gint ett_http_request = -1; static gint ett_http_chunked_response = -1; static gint ett_http_chunk_data = -1; static gint ett_http_encoded_entity = -1; static gint ett_http_header_item = -1; static dissector_handle_t data_handle; static dissector_handle_t media_handle; static dissector_handle_t websocket_handle; static dissector_handle_t http_handle; /* Stuff for generation/handling of fields for custom HTTP headers */ typedef struct _header_field_t { gchar* header_name; gchar* header_desc; } header_field_t; static header_field_t* header_fields = NULL; static guint num_header_fields = 0; static GHashTable* header_fields_hash = NULL; static void header_fields_update_cb(void *r, const char **err) { header_field_t *rec = r; char c; if (rec->header_name == NULL) { *err = ep_strdup_printf("Header name can't be empty"); return; } g_strstrip(rec->header_name); if (rec->header_name[0] == 0) { *err = ep_strdup_printf("Header name can't be empty"); return; } /* Check for invalid characters (to avoid asserting out when * registering the field). */ c = proto_check_field_name(rec->header_name); if (c) { *err = ep_strdup_printf("Header name can't contain '%c'", c); return; } *err = NULL; } static void * header_fields_copy_cb(void* n, const void* o, size_t siz _U_) { header_field_t* new_rec = n; const header_field_t* old_rec = o; if (old_rec->header_name) { new_rec->header_name = g_strdup(old_rec->header_name); } else { new_rec->header_name = NULL; } if (old_rec->header_desc) { new_rec->header_desc = g_strdup(old_rec->header_desc); } else { new_rec->header_desc = NULL; } return new_rec; } static void header_fields_free_cb(void*r) { header_field_t* rec = r; if (rec->header_name) g_free(rec->header_name); if (rec->header_desc) g_free(rec->header_desc); } UAT_CSTRING_CB_DEF(header_fields, header_name, header_field_t) UAT_CSTRING_CB_DEF(header_fields, header_desc, header_field_t) /* * desegmentation of HTTP headers * (when we are over TCP or another protocol providing the desegmentation API) */ static gboolean http_desegment_headers = TRUE; /* * desegmentation of HTTP bodies * (when we are over TCP or another protocol providing the desegmentation API) * TODO let the user filter on content-type the bodies he wants desegmented */ static gboolean http_desegment_body = TRUE; /* * De-chunking of content-encoding: chunk entity bodies. */ static gboolean http_dechunk_body = TRUE; /* * Decompression of zlib encoded entities. */ #ifdef HAVE_LIBZ static gboolean http_decompress_body = TRUE; #else static gboolean http_decompress_body = FALSE; #endif #define TCP_PORT_DAAP 3689 /* Simple Service Discovery Protocol * SSDP is implemented atop HTTP (yes, it really *does* run over UDP). * SSDP is the discovery protocol of Universal Plug and Play * UPnP http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf */ #define TCP_PORT_SSDP 1900 #define UDP_PORT_SSDP 1900 /* * tcp and ssl ports * * 2710 is the XBT BitTorrent tracker */ #define TCP_DEFAULT_RANGE "80,3128,3132,5985,8080,8088,11371,1900,2869,2710" #define SSL_DEFAULT_RANGE "443" static range_t *global_http_tcp_range = NULL; static range_t *global_http_ssl_range = NULL; static range_t *http_tcp_range = NULL; static range_t *http_ssl_range = NULL; typedef void (*ReqRespDissector)(tvbuff_t*, proto_tree*, int, const guchar*, const guchar*, http_conv_t *); /* * Structure holding information from headers needed by main * HTTP dissector code. */ typedef struct { char *content_type; char *content_type_parameters; gboolean have_content_length; gint64 content_length; char *content_encoding; char *transfer_encoding; } headers_t; static int is_http_request_or_reply(const gchar *data, int linelen, http_type_t *type, ReqRespDissector *reqresp_dissector, http_conv_t *conv_data); static int chunked_encoding_dissector(tvbuff_t **tvb_ptr, packet_info *pinfo, proto_tree *tree, int offset); static void process_header(tvbuff_t *tvb, int offset, int next_offset, const guchar *line, int linelen, int colon_offset, packet_info *pinfo, proto_tree *tree, headers_t *eh_ptr, http_conv_t *conv_data); static gint find_header_hf_value(tvbuff_t *tvb, int offset, guint header_len); static gboolean check_auth_ntlmssp(proto_item *hdr_item, tvbuff_t *tvb, packet_info *pinfo, gchar *value); static gboolean check_auth_basic(proto_item *hdr_item, tvbuff_t *tvb, gchar *value); static gboolean check_auth_kerberos(proto_item *hdr_item, tvbuff_t *tvb, packet_info *pinfo, const gchar *value); static dissector_table_t port_subdissector_table; static dissector_table_t media_type_subdissector_table; static heur_dissector_list_t heur_subdissector_list; static dissector_handle_t ntlmssp_handle; static dissector_handle_t gssapi_handle; /* --- HTTP Status Codes */ /* Note: The reference for uncommented entries is RFC 2616 */ static const value_string vals_status_code[] = { { 100, "Continue" }, { 101, "Switching Protocols" }, { 102, "Processing" }, /* RFC 2518 */ { 199, "Informational - Others" }, { 200, "OK"}, { 201, "Created"}, { 202, "Accepted"}, { 203, "Non-authoritative Information"}, { 204, "No Content"}, { 205, "Reset Content"}, { 206, "Partial Content"}, { 207, "Multi-Status"}, /* RFC 4918 */ { 226, "IM Used"}, /* RFC 3229 */ { 299, "Success - Others"}, { 300, "Multiple Choices"}, { 301, "Moved Permanently"}, { 302, "Found"}, { 303, "See Other"}, { 304, "Not Modified"}, { 305, "Use Proxy"}, { 307, "Temporary Redirect"}, { 399, "Redirection - Others"}, { 400, "Bad Request"}, { 401, "Unauthorized"}, { 402, "Payment Required"}, { 403, "Forbidden"}, { 404, "Not Found"}, { 405, "Method Not Allowed"}, { 406, "Not Acceptable"}, { 407, "Proxy Authentication Required"}, { 408, "Request Time-out"}, { 409, "Conflict"}, { 410, "Gone"}, { 411, "Length Required"}, { 412, "Precondition Failed"}, { 413, "Request Entity Too Large"}, { 414, "Request-URI Too Long"}, { 415, "Unsupported Media Type"}, { 416, "Requested Range Not Satisfiable"}, { 417, "Expectation Failed"}, { 418, "I'm a teapot"}, /* RFC 2324 */ { 422, "Unprocessable Entity"}, /* RFC 4918 */ { 423, "Locked"}, /* RFC 4918 */ { 424, "Failed Dependency"}, /* RFC 4918 */ { 426, "Upgrade Required"}, /* RFC 2817 */ { 428, "Precondition Required"}, /* RFC 6585 */ { 429, "Too Many Requests"}, /* RFC 6585 */ { 431, "Request Header Fields Too Large"}, /* RFC 6585 */ { 499, "Client Error - Others"}, { 500, "Internal Server Error"}, { 501, "Not Implemented"}, { 502, "Bad Gateway"}, { 503, "Service Unavailable"}, { 504, "Gateway Time-out"}, { 505, "HTTP Version not supported"}, { 507, "Insufficient Storage"}, /* RFC 4918 */ { 511, "Network Authentication Required"}, /* RFC 6585 */ { 599, "Server Error - Others"}, { 0, NULL} }; static const gchar* st_str_reqs = "HTTP Requests by Server"; static const gchar* st_str_reqs_by_srv_addr = "HTTP Requests by Server Address"; static const gchar* st_str_reqs_by_http_host = "HTTP Requests by HTTP Host"; static const gchar* st_str_resps_by_srv_addr = "HTTP Responses by Server Address"; static int st_node_reqs = -1; static int st_node_reqs_by_srv_addr = -1; static int st_node_reqs_by_http_host = -1; static int st_node_resps_by_srv_addr = -1; /* HTTP/Load Distribution stats init function */ static void http_reqs_stats_tree_init(stats_tree* st) { st_node_reqs = stats_tree_create_node(st, st_str_reqs, 0, TRUE); st_node_reqs_by_srv_addr = stats_tree_create_node(st, st_str_reqs_by_srv_addr, st_node_reqs, TRUE); st_node_reqs_by_http_host = stats_tree_create_node(st, st_str_reqs_by_http_host, st_node_reqs, TRUE); st_node_resps_by_srv_addr = stats_tree_create_node(st, st_str_resps_by_srv_addr, 0, TRUE); } /* HTTP/Load Distribution stats packet function */ static int http_reqs_stats_tree_packet(stats_tree* st, packet_info* pinfo, epan_dissect_t* edt _U_, const void* p) { const http_info_value_t* v = p; int reqs_by_this_host; int reqs_by_this_addr; int resps_by_this_addr; int i = v->response_code; gchar *ip_str; if (v->request_method) { ip_str = ep_address_to_str(&pinfo->dst); tick_stat_node(st, st_str_reqs, 0, FALSE); tick_stat_node(st, st_str_reqs_by_srv_addr, st_node_reqs, TRUE); tick_stat_node(st, st_str_reqs_by_http_host, st_node_reqs, TRUE); reqs_by_this_addr = tick_stat_node(st, ip_str, st_node_reqs_by_srv_addr, TRUE); if (v->http_host) { reqs_by_this_host = tick_stat_node(st, v->http_host, st_node_reqs_by_http_host, TRUE); tick_stat_node(st, ip_str, reqs_by_this_host, FALSE); tick_stat_node(st, v->http_host, reqs_by_this_addr, FALSE); } return 1; } else if (i != 0) { ip_str = ep_address_to_str(&pinfo->src); tick_stat_node(st, st_str_resps_by_srv_addr, 0, FALSE); resps_by_this_addr = tick_stat_node(st, ip_str, st_node_resps_by_srv_addr, TRUE); if ( (i>100)&&(i<400) ) { tick_stat_node(st, "OK", resps_by_this_addr, FALSE); } else { tick_stat_node(st, "KO", resps_by_this_addr, FALSE); } return 1; } return 0; } static int st_node_requests_by_host = -1; static const gchar *st_str_requests_by_host = "HTTP Requests by HTTP Host"; /* HTTP/Requests stats init function */ static void http_req_stats_tree_init(stats_tree* st) { st_node_requests_by_host = stats_tree_create_node(st, st_str_requests_by_host, 0, TRUE); } /* HTTP/Requests stats packet function */ static int http_req_stats_tree_packet(stats_tree* st, packet_info* pinfo _U_, epan_dissect_t* edt _U_, const void* p) { const http_info_value_t* v = p; int reqs_by_this_host; if (v->request_method) { tick_stat_node(st, st_str_requests_by_host, 0, FALSE); if (v->http_host) { reqs_by_this_host = tick_stat_node(st, v->http_host, st_node_requests_by_host, TRUE); if (v->request_uri) { tick_stat_node(st, v->request_uri, reqs_by_this_host, TRUE); } } return 1; } return 0; } static const gchar *st_str_packets = "Total HTTP Packets"; static const gchar *st_str_requests = "HTTP Request Packets"; static const gchar *st_str_responses = "HTTP Response Packets"; static const gchar *st_str_resp_broken = "???: broken"; static const gchar *st_str_resp_100 = "1xx: Informational"; static const gchar *st_str_resp_200 = "2xx: Success"; static const gchar *st_str_resp_300 = "3xx: Redirection"; static const gchar *st_str_resp_400 = "4xx: Client Error"; static const gchar *st_str_resp_500 = "5xx: Server Error"; static const gchar *st_str_other = "Other HTTP Packets"; static int st_node_packets = -1; static int st_node_requests = -1; static int st_node_responses = -1; static int st_node_resp_broken = -1; static int st_node_resp_100 = -1; static int st_node_resp_200 = -1; static int st_node_resp_300 = -1; static int st_node_resp_400 = -1; static int st_node_resp_500 = -1; static int st_node_other = -1; /* HTTP/Packet Counter stats init function */ static void http_stats_tree_init(stats_tree* st) { st_node_packets = stats_tree_create_node(st, st_str_packets, 0, TRUE); st_node_requests = stats_tree_create_pivot(st, st_str_requests, st_node_packets); st_node_responses = stats_tree_create_node(st, st_str_responses, st_node_packets, TRUE); st_node_resp_broken = stats_tree_create_node(st, st_str_resp_broken, st_node_responses, TRUE); st_node_resp_100 = stats_tree_create_node(st, st_str_resp_100, st_node_responses, TRUE); st_node_resp_200 = stats_tree_create_node(st, st_str_resp_200, st_node_responses, TRUE); st_node_resp_300 = stats_tree_create_node(st, st_str_resp_300, st_node_responses, TRUE); st_node_resp_400 = stats_tree_create_node(st, st_str_resp_400, st_node_responses, TRUE); st_node_resp_500 = stats_tree_create_node(st, st_str_resp_500, st_node_responses, TRUE); st_node_other = stats_tree_create_node(st, st_str_other, st_node_packets,FALSE); } /* HTTP/Packet Counter stats packet function */ static int http_stats_tree_packet(stats_tree* st, packet_info* pinfo _U_, epan_dissect_t* edt _U_, const void* p) { const http_info_value_t* v = p; guint i = v->response_code; int resp_grp; const gchar *resp_str; gchar str[64]; tick_stat_node(st, st_str_packets, 0, FALSE); if (i) { tick_stat_node(st, st_str_responses, st_node_packets, FALSE); if ( (i<100)||(i>=600) ) { resp_grp = st_node_resp_broken; resp_str = st_str_resp_broken; } else if (i<200) { resp_grp = st_node_resp_100; resp_str = st_str_resp_100; } else if (i<300) { resp_grp = st_node_resp_200; resp_str = st_str_resp_200; } else if (i<400) { resp_grp = st_node_resp_300; resp_str = st_str_resp_300; } else if (i<500) { resp_grp = st_node_resp_400; resp_str = st_str_resp_400; } else { resp_grp = st_node_resp_500; resp_str = st_str_resp_500; } tick_stat_node(st, resp_str, st_node_responses, FALSE); g_snprintf(str, sizeof(str), "%u %s", i, val_to_str(i, vals_status_code, "Unknown (%d)")); tick_stat_node(st, str, resp_grp, FALSE); } else if (v->request_method) { stats_tree_tick_pivot(st,st_node_requests,v->request_method); } else { tick_stat_node(st, st_str_other, st_node_packets, FALSE); } return 1; } static void dissect_http_ntlmssp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, const char *line) { tvbuff_t *ntlmssp_tvb; ntlmssp_tvb = base64_to_tvb(tvb, line); add_new_data_source(pinfo, ntlmssp_tvb, "NTLMSSP / GSSAPI Data"); if (tvb_strneql(ntlmssp_tvb, 0, "NTLMSSP", 7) == 0) call_dissector(ntlmssp_handle, ntlmssp_tvb, pinfo, tree); else call_dissector(gssapi_handle, ntlmssp_tvb, pinfo, tree); } static void dissect_http_kerberos(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, const char *line) { tvbuff_t *kerberos_tvb; kerberos_tvb = base64_to_tvb(tvb, line + 9); /* skip 'Kerberos ' which is 9 chars */ add_new_data_source(pinfo, kerberos_tvb, "Kerberos Data"); call_dissector(gssapi_handle, kerberos_tvb, pinfo, tree); } static http_conv_t * get_http_conversation_data(packet_info *pinfo) { conversation_t *conversation; http_conv_t *conv_data; conversation = find_or_create_conversation(pinfo); /* Retrieve information from conversation * or add it if it isn't there yet */ conv_data = conversation_get_proto_data(conversation, proto_http); if(!conv_data) { /* Setup the conversation structure itself */ conv_data = se_alloc0(sizeof(http_conv_t)); conversation_add_proto_data(conversation, proto_http, conv_data); } return conv_data; } /* * TODO: remove this ugly global variable. * XXX: do we really want to have to pass this from one function to another? */ static http_info_value_t *stat_info; static int dissect_http_message(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, http_conv_t *conv_data) { const char *proto_tag; proto_tree *http_tree = NULL; proto_item *ti = NULL; proto_item *hidden_item; const guchar *line; gint next_offset; const guchar *linep, *lineend; int orig_offset; int first_linelen, linelen; gboolean is_request_or_reply; gboolean saw_req_resp_or_header; guchar c; http_type_t http_type; proto_item *hdr_item = NULL; ReqRespDissector reqresp_dissector; proto_tree *req_tree; int colon_offset; headers_t headers; int datalen; int reported_datalen = -1; dissector_handle_t handle; gboolean dissected = FALSE; /*guint i;*/ /*http_info_value_t *si;*/ http_eo_t *eo_info; /* * Is this a request or response? * * Note that "tvb_find_line_end()" will return a value that * is not longer than what's in the buffer, so the * "tvb_get_ptr()" call won't throw an exception. */ first_linelen = tvb_find_line_end(tvb, offset, tvb_ensure_length_remaining(tvb, offset), &next_offset, FALSE); /* * Is the first line a request or response? */ line = tvb_get_ptr(tvb, offset, first_linelen); http_type = HTTP_OTHERS; /* type not known yet */ is_request_or_reply = is_http_request_or_reply((const gchar *)line, first_linelen, &http_type, NULL, conv_data); if (is_request_or_reply) { /* * Yes, it's a request or response. * Do header desegmentation if we've been told to, * and do body desegmentation if we've been told to and * we find a Content-Length header. */ if (!req_resp_hdrs_do_reassembly(tvb, offset, pinfo, http_desegment_headers, http_desegment_body)) { /* * More data needed for desegmentation. */ return -1; } } stat_info = ep_alloc(sizeof(http_info_value_t)); stat_info->framenum = pinfo->fd->num; stat_info->response_code = 0; stat_info->request_method = NULL; stat_info->request_uri = NULL; stat_info->http_host = NULL; switch (pinfo->match_uint) { case TCP_PORT_SSDP: /* TCP_PORT_SSDP = UDP_PORT_SSDP */ proto_tag = "SSDP"; break; case TCP_PORT_DAAP: proto_tag = "DAAP"; break; default: proto_tag = "HTTP"; break; } if (check_col(pinfo->cinfo, COL_PROTOCOL)) col_set_str(pinfo->cinfo, COL_PROTOCOL, proto_tag); if (check_col(pinfo->cinfo, COL_INFO)) { /* * Put the first line from the buffer into the summary * if it's an HTTP request or reply (but leave out the * line terminator). * Otherwise, just call it a continuation. * * Note that "tvb_find_line_end()" will return a value that * is not longer than what's in the buffer, so the * "tvb_get_ptr()" call won't throw an exception. */ if (is_request_or_reply) { line = tvb_get_ptr(tvb, offset, first_linelen); col_add_fstr(pinfo->cinfo, COL_INFO, "%s ", format_text(line, first_linelen)); } else col_set_str(pinfo->cinfo, COL_INFO, "Continuation or non-HTTP traffic"); } orig_offset = offset; if (tree) { ti = proto_tree_add_item(tree, proto_http, tvb, offset, -1, ENC_NA); http_tree = proto_item_add_subtree(ti, ett_http); } /* * Process the packet data, a line at a time. */ http_type = HTTP_OTHERS; /* type not known yet */ headers.content_type = NULL; /* content type not known yet */ headers.content_type_parameters = NULL; /* content type parameters too */ headers.have_content_length = FALSE; /* content length not known yet */ headers.content_length = 0; /* content length set to 0 (avoid a gcc warning) */ headers.content_encoding = NULL; /* content encoding not known yet */ headers.transfer_encoding = NULL; /* transfer encoding not known yet */ saw_req_resp_or_header = FALSE; /* haven't seen anything yet */ while (tvb_reported_length_remaining(tvb, offset) != 0) { /* * Find the end of the line. * XXX - what if we don't find it because the packet * is cut short by a snapshot length or the header is * split across TCP segments? How much dissection should * we do on it? */ linelen = tvb_find_line_end(tvb, offset, tvb_ensure_length_remaining(tvb, offset), &next_offset, FALSE); if (linelen < 0) return -1; /* * Get a buffer that refers to the line. */ line = tvb_get_ptr(tvb, offset, linelen); lineend = line + linelen; colon_offset = -1; /* * OK, does it look like an HTTP request or response? */ reqresp_dissector = NULL; is_request_or_reply = is_http_request_or_reply((const gchar *)line, linelen, &http_type, &reqresp_dissector, conv_data); if (is_request_or_reply) goto is_http; /* * No. Does it look like a blank line (as would appear * at the end of an HTTP request)? */ if (linelen == 0) goto is_http; /* Yes. */ /* * No. Does it look like a header? */ linep = line; colon_offset = offset; while (linep < lineend) { c = *linep++; /* * This must be a CHAR to be part of a token; that * means it must be ASCII. */ if (!isascii(c)) break; /* not ASCII, thus not a CHAR */ /* * This mustn't be a CTL to be part of a token. * * XXX - what about leading LWS on continuation * lines of a header? */ if (iscntrl(c)) break; /* CTL, not part of a header */ /* * This mustn't be a SEP to be part of a token; * a ':' ends the token, everything else is an * indication that this isn't a header. */ switch (c) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': /* * It's a separator, so it's not part of a * token, so it's not a field name for the * beginning of a header. * * (We don't have to check for HT; that's * already been ruled out by "iscntrl()".) */ goto not_http; case ':': /* * This ends the token; we consider this * to be a header. */ goto is_http; default: colon_offset++; break; } } /* * We haven't seen the colon, but everything else looks * OK for a header line. * * If we've already seen an HTTP request or response * line, or a header line, and we're at the end of * the tvbuff, we assume this is an incomplete header * line. (We quit this loop after seeing a blank line, * so if we've seen a request or response line, or a * header line, this is probably more of the request * or response we're presumably seeing. There is some * risk of false positives, but the same applies for * full request or response lines or header lines, * although that's less likely.) * * We throw an exception in that case, by checking for * the existence of the next byte after the last one * in the line. If it exists, "tvb_ensure_bytes_exist()" * throws no exception, and we fall through to the * "not HTTP" case. If it doesn't exist, * "tvb_ensure_bytes_exist()" will throw the appropriate * exception. */ if (saw_req_resp_or_header) tvb_ensure_bytes_exist(tvb, offset, linelen + 1); not_http: /* * We don't consider this part of an HTTP request or * reply, so we don't display it. * (Yeah, that means we don't display, say, a text/http * page, but you can get that from the data pane.) */ break; is_http: /* * Process this line. */ if (linelen == 0) { /* * This is a blank line, which means that * whatever follows it isn't part of this * request or reply. */ proto_tree_add_text(http_tree, tvb, offset, next_offset - offset, "%s", tvb_format_text(tvb, offset, next_offset - offset)); offset = next_offset; break; } /* * Not a blank line - either a request, a reply, or a header * line. */ saw_req_resp_or_header = TRUE; if (is_request_or_reply) { char *text = tvb_format_text(tvb, offset, next_offset - offset); if (tree) { hdr_item = proto_tree_add_text(http_tree, tvb, offset, next_offset - offset, "%s", text); } expert_add_info_format(pinfo, hdr_item, PI_SEQUENCE, PI_CHAT, "%s", text); if (reqresp_dissector) { if (tree) req_tree = proto_item_add_subtree(hdr_item, ett_http_request); else req_tree = NULL; reqresp_dissector(tvb, req_tree, offset, line, lineend, conv_data); } } else { /* * Header. */ process_header(tvb, offset, next_offset, line, linelen, colon_offset, pinfo, http_tree, &headers, conv_data); } offset = next_offset; } if (tree && stat_info->http_host && stat_info->request_uri) { proto_item *e_ti; gchar* hostname = g_strstrip(g_strdup(stat_info->http_host)); size_t size = strlen("http://") + strlen(hostname) + strlen(stat_info->request_uri) + 1; char *uri = ep_alloc(size); g_snprintf(uri, (gulong)size, "%s://%s%s", "http", /* XXX, https? */ hostname, stat_info->request_uri); g_free(hostname); e_ti = proto_tree_add_string(http_tree, hf_http_request_full_uri, tvb, 0, 0, uri); PROTO_ITEM_SET_URL(e_ti); PROTO_ITEM_SET_GENERATED(e_ti); } if (tree) { switch (http_type) { case HTTP_NOTIFICATION: hidden_item = proto_tree_add_boolean(http_tree, hf_http_notification, tvb, 0, 0, 1); PROTO_ITEM_SET_HIDDEN(hidden_item); break; case HTTP_RESPONSE: hidden_item = proto_tree_add_boolean(http_tree, hf_http_response, tvb, 0, 0, 1); PROTO_ITEM_SET_HIDDEN(hidden_item); break; case HTTP_REQUEST: hidden_item = proto_tree_add_boolean(http_tree, hf_http_request, tvb, 0, 0, 1); PROTO_ITEM_SET_HIDDEN(hidden_item); break; case HTTP_OTHERS: default: break; } } /* * If a content length was supplied, the amount of data to be * processed as HTTP payload is the minimum of the content * length and the amount of data remaining in the frame. * * If a message is received with both a Transfer-Encoding * header field and a Content-Length header field, the latter * MUST be ignored. * * If no content length was supplied (or if a bad content length * was supplied), the amount of data to be processed is the amount * of data remaining in the frame. * * If there was no Content-Length entity header, we should * accumulate all data until the end of the connection. * That'd require that the TCP dissector call subdissectors * for all frames with FIN, even if they contain no data, * which would require subdissectors to deal intelligently * with empty segments. * * According to RFC 2616, however, 1xx responses, 204 responses, * and 304 responses MUST NOT include a message body; if no * content length is specified for them, we don't attempt to * dissect the body. * * XXX - it says the same about responses to HEAD requests; * unless there's a way to determine from the response * whether it's a response to a HEAD request, we have to * keep information about the request and associate that with * the response in order to handle that. */ datalen = tvb_length_remaining(tvb, offset); if (headers.have_content_length && headers.content_length != -1 && headers.transfer_encoding == NULL) { if (datalen > headers.content_length) datalen = (int)headers.content_length; /* * XXX - limit the reported length in the tvbuff we'll * hand to a subdissector to be no greater than the * content length. * * We really need both unreassembled and "how long it'd * be if it were reassembled" lengths for tvbuffs, so * that we throw the appropriate exceptions for * "not enough data captured" (running past the length), * "packet needed reassembly" (within the length but * running past the unreassembled length), and * "packet is malformed" (running past the reassembled * length). */ reported_datalen = tvb_reported_length_remaining(tvb, offset); if (reported_datalen > headers.content_length) reported_datalen = (int)headers.content_length; } else { switch (http_type) { case HTTP_REQUEST: /* * Requests have no content if there's no * Content-Length header and no Transfer-Encoding * header. */ if (headers.transfer_encoding == NULL) datalen = 0; else reported_datalen = -1; break; case HTTP_RESPONSE: if ((stat_info->response_code/100) == 1 || stat_info->response_code == 204 || stat_info->response_code == 304) datalen = 0; /* no content! */ else { /* * XXX - responses to HEAD requests, * and possibly other responses, * "MUST NOT" include a * message-body. */ reported_datalen = -1; } break; default: /* * XXX - what about HTTP_NOTIFICATION? */ reported_datalen = -1; break; } } if (datalen > 0) { /* * There's stuff left over; process it. */ tvbuff_t *next_tvb; void *save_private_data = NULL; gboolean private_data_changed = FALSE; gint chunks_decoded = 0; /* * Create a tvbuff for the payload. * * The amount of data to be processed that's * available in the tvbuff is "datalen", which * is the minimum of the amount of data left in * the tvbuff and any specified content length. * * The amount of data to be processed that's in * this frame, regardless of whether it was * captured or not, is "reported_datalen", * which, if no content length was specified, * is -1, i.e. "to the end of the frame. */ next_tvb = tvb_new_subset(tvb, offset, datalen, reported_datalen); /* * Check if Websocket */ if (conv_data->upgrade != NULL && g_ascii_strcasecmp(conv_data->upgrade, "WebSocket") == 0) { call_dissector_only(websocket_handle, next_tvb, pinfo, tree); goto body_dissected; } /* * Handle *transfer* encodings other than "identity". */ if (headers.transfer_encoding != NULL && g_ascii_strcasecmp(headers.transfer_encoding, "identity") != 0) { if (http_dechunk_body && (g_ascii_strncasecmp(headers.transfer_encoding, "chunked", 7) == 0)) { chunks_decoded = chunked_encoding_dissector( &next_tvb, pinfo, http_tree, 0); if (chunks_decoded <= 0) { /* * The chunks weren't reassembled, * or there was a single zero * length chunk. */ goto body_dissected; } else { /* * Add a new data source for the * de-chunked data. */ #if 0 /* Handled in chunked_encoding_dissector() */ tvb_set_child_real_data_tvbuff(tvb, next_tvb); #endif add_new_data_source(pinfo, next_tvb, "De-chunked entity body"); } } else { /* * We currently can't handle, for example, * "gzip", "compress", or "deflate" as * *transfer* encodings; just handle them * as data for now. */ call_dissector(data_handle, next_tvb, pinfo, http_tree); goto body_dissected; } } /* * At this point, any chunked *transfer* coding has been removed * (the entity body has been dechunked) so it can be presented * for the following operation (*content* encoding), or it has * been been handed off to the data dissector. * * Handle *content* encodings other than "identity" (which * shouldn't appear in a Content-Encoding header, but * we handle it in any case). */ if (headers.content_encoding != NULL && g_ascii_strcasecmp(headers.content_encoding, "identity") != 0) { /* * We currently can't handle, for example, "compress"; * just handle them as data for now. * * After July 7, 2004 the LZW patent expires, so support * might be added then. However, I don't think that * anybody ever really implemented "compress", due to * the aforementioned patent. */ tvbuff_t *uncomp_tvb = NULL; proto_item *e_ti = NULL; proto_tree *e_tree = NULL; if (http_decompress_body && (g_ascii_strcasecmp(headers.content_encoding, "gzip") == 0 || g_ascii_strcasecmp(headers.content_encoding, "deflate") == 0 || g_ascii_strcasecmp(headers.content_encoding, "x-gzip") == 0 || g_ascii_strcasecmp(headers.content_encoding, "x-deflate") == 0)) { uncomp_tvb = tvb_child_uncompress(tvb, next_tvb, 0, tvb_length(next_tvb)); } /* * Add the encoded entity to the protocol tree */ e_ti = proto_tree_add_text(http_tree, next_tvb, 0, tvb_length(next_tvb), "Content-encoded entity body (%s): %u bytes", headers.content_encoding, tvb_length(next_tvb)); e_tree = proto_item_add_subtree(e_ti, ett_http_encoded_entity); if (uncomp_tvb != NULL) { /* * Decompression worked */ /* XXX - Don't free this, since it's possible * that the data was only partially * decompressed, such as when desegmentation * isn't enabled. * tvb_free(next_tvb); */ proto_item_append_text(e_ti, " -> %u bytes", tvb_length(uncomp_tvb)); next_tvb = uncomp_tvb; add_new_data_source(pinfo, next_tvb, "Uncompressed entity body"); } else { proto_item_append_text(e_ti, " [Error: Decompression failed]"); call_dissector(data_handle, next_tvb, pinfo, e_tree); goto body_dissected; } } /* * Note that a new data source is added for the entity body * only if it was content-encoded and/or transfer-encoded. */ /* Save values for the Export Object GUI feature if we have * an active listener to process it (which happens when * the export object window is open). */ if(have_tap_listener(http_eo_tap)) { eo_info = ep_alloc(sizeof(http_eo_t)); eo_info->hostname = conv_data->http_host; eo_info->filename = conv_data->request_uri; eo_info->content_type = headers.content_type; eo_info->payload_len = tvb_length(next_tvb); eo_info->payload_data = tvb_get_ptr(next_tvb, 0, eo_info->payload_len); tap_queue_packet(http_eo_tap, pinfo, eo_info); } /* * Do subdissector checks. * * First, if we have a Content-Type value, check whether * there's a subdissector for that media type. */ handle = NULL; if (headers.content_type != NULL) { /* * We didn't find any subdissector that * registered for the port, and we have a * Content-Type value. Is there any subdissector * for that content type? */ save_private_data = pinfo->private_data; private_data_changed = TRUE; if (headers.content_type_parameters) pinfo->private_data = ep_strdup(headers.content_type_parameters); else pinfo->private_data = NULL; /* * Calling the string handle for the media type * dissector table will set pinfo->match_string * to headers.content_type for us. */ pinfo->match_string = headers.content_type; handle = dissector_get_string_handle( media_type_subdissector_table, headers.content_type); if (handle == NULL && strncmp(headers.content_type, "multipart/", sizeof("multipart/")-1) == 0) { /* Try to decode the unknown multipart subtype anyway */ handle = dissector_get_string_handle( media_type_subdissector_table, "multipart/"); } } /* * Now, if we didn't find such a subdissector, check * whether some subdissector asked that they be called * if HTTP traffic was on some particular port. This * handles protocols that use HTTP syntax but don't have * a media type and instead use a specified port. */ if (handle == NULL) { handle = dissector_get_uint_handle(port_subdissector_table, pinfo->match_uint); } if (handle != NULL) { /* * We have a subdissector - call it. */ dissected = call_dissector_only(handle, next_tvb, pinfo, tree); if (!dissected) expert_add_info_format(pinfo, http_tree, PI_MALFORMED, PI_NOTE, "HTTP body subdissector failed, trying heuristic subdissector"); } if (!dissected) { /* * We don't have a subdissector or we have one and it did not * dissect the payload - try the heuristic subdissectors. */ dissected = dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree); } if (dissected) { /* * The subdissector dissected the body. * Fix up the top-level item so that it doesn't * include the stuff for that protocol. */ if (ti != NULL) proto_item_set_len(ti, offset); } else { if (headers.content_type != NULL) { /* * Calling the default media handle if there is a content-type that * wasn't handled above. */ call_dissector(media_handle, next_tvb, pinfo, tree); } else { /* Call the default data dissector */ call_dissector(data_handle, next_tvb, pinfo, http_tree); } } body_dissected: /* * Do *not* attempt at freeing the private data; * it may be in use by subdissectors. */ if (private_data_changed) /*restore even NULL value*/ pinfo->private_data = save_private_data; /* * We've processed "datalen" bytes worth of data * (which may be no data at all); advance the * offset past whatever data we've processed. */ offset += datalen; } tap_queue_packet(http_tap, pinfo, stat_info); return offset - orig_offset; } /* This can be used to dissect an HTTP request until such time * that a more complete dissector is written for that HTTP request. * This simple dissector only puts the request method, URI, and * protocol version into a sub-tree. */ static void basic_request_dissector(tvbuff_t *tvb, proto_tree *tree, int offset, const guchar *line, const guchar *lineend, http_conv_t *conv_data) { const guchar *next_token; gchar *request_uri; int tokenlen; /* The first token is the method. */ tokenlen = get_token_len(line, lineend, &next_token); if (tokenlen == 0) return; proto_tree_add_item(tree, hf_http_request_method, tvb, offset, tokenlen, ENC_ASCII|ENC_NA); if ((next_token - line) > 2 && next_token[-1] == ' ' && next_token[-2] == ' ') { /* Two spaces in a now indicates empty URI, so roll back one here */ next_token--; } offset += (int) (next_token - line); line = next_token; /* The next token is the URI. */ tokenlen = get_token_len(line, lineend, &next_token); /* Save the request URI for various later uses */ request_uri = (gchar *)tvb_get_ephemeral_string(tvb, offset, tokenlen); stat_info->request_uri = ep_strdup(request_uri); conv_data->request_uri = se_strdup(request_uri); proto_tree_add_string(tree, hf_http_request_uri, tvb, offset, tokenlen, request_uri); offset += (int) (next_token - line); line = next_token; /* Everything to the end of the line is the version. */ tokenlen = (int) (lineend - line); proto_tree_add_item(tree, hf_http_version, tvb, offset, tokenlen, ENC_ASCII|ENC_NA); } static void basic_response_dissector(tvbuff_t *tvb, proto_tree *tree, int offset, const guchar *line, const guchar *lineend, http_conv_t *conv_data _U_) { const guchar *next_token; int tokenlen; gchar response_code_chars[4]; /* * The first token is the HTTP Version. */ tokenlen = get_token_len(line, lineend, &next_token); if (tokenlen == 0) return; proto_tree_add_item(tree, hf_http_version, tvb, offset, tokenlen, ENC_ASCII|ENC_NA); /* Advance to the start of the next token. */ offset += (int) (next_token - line); line = next_token; /* * The second token is the Status Code. */ tokenlen = get_token_len(line, lineend, &next_token); if (tokenlen < 3) return; /* The Status Code characters must be copied into a null-terminated * buffer for strtoul() to parse them into an unsigned integer value. */ memcpy(response_code_chars, line, 3); response_code_chars[3] = '\0'; stat_info->response_code = conv_data->response_code = strtoul(response_code_chars, NULL, 10); proto_tree_add_uint(tree, hf_http_response_code, tvb, offset, 3, stat_info->response_code); /* Advance to the start of the next token. */ offset += (int) (next_token - line); line = next_token; /* * The remaining tokens in the line comprise the Reason Phrase. */ tokenlen = (int) (lineend - line); if (tokenlen < 1) return; proto_tree_add_item(tree, hf_http_response_phrase, tvb, offset, tokenlen, ENC_ASCII|ENC_NA); } #if 0 /* XXX: Replaced by code creating the "Dechunked" tvb O(N) rather tan O(N^2) */ /* * Dissect the http data chunks and add them to the tree. */ static int chunked_encoding_dissector(tvbuff_t **tvb_ptr, packet_info *pinfo, proto_tree *tree, int offset) { guint8 *chunk_string = NULL; guint32 chunk_size = 0; gint chunk_offset = 0; guint32 datalen = 0; gint linelen = 0; gint chunks_decoded = 0; tvbuff_t *tvb = NULL; tvbuff_t *new_tvb = NULL; gint chunked_data_size = 0; proto_tree *subtree = NULL; proto_item *ti = NULL; if (tvb_ptr == NULL || *tvb_ptr == NULL) { return 0; } tvb = *tvb_ptr; datalen = tvb_reported_length_remaining(tvb, offset); if (tree) { ti = proto_tree_add_text(tree, tvb, offset, datalen, "HTTP chunked response"); subtree = proto_item_add_subtree(ti, ett_http_chunked_response); } while (datalen != 0) { proto_item *chunk_ti = NULL; proto_tree *chunk_subtree = NULL; tvbuff_t *data_tvb = NULL; /* */ gchar *c = NULL; guint8 *raw_data; gint raw_len = 0; linelen = tvb_find_line_end(tvb, offset, -1, &chunk_offset, TRUE); if (linelen <= 0) { /* Can't get the chunk size line */ break; } chunk_string = tvb_get_ephemeral_string(tvb, offset, linelen); if (chunk_string == NULL) { /* Can't get the chunk size line */ break; } c = (gchar*) chunk_string; /* * We don't care about the extensions. */ if ((c = strchr(c, ';'))) { *c = '\0'; } chunk_size = strtol((gchar*)chunk_string, NULL, 16); if (chunk_size > datalen) { /* * The chunk size is more than what's in the tvbuff, * so either the user hasn't enabled decoding, or all * of the segments weren't captured. */ chunk_size = datalen; } #if 0 else if (new_tvb == NULL) { new_tvb = tvb_new_composite(); } if (new_tvb != NULL && chunk_size != 0) { tvbuff_t *chunk_tvb = NULL; chunk_tvb = tvb_new_subset(tvb, chunk_offset, chunk_size, datalen); tvb_composite_append(new_tvb, chunk_tvb); } #endif chunked_data_size += chunk_size; raw_data = g_malloc(chunked_data_size); raw_len = 0; if (new_tvb != NULL) { raw_len = tvb_length_remaining(new_tvb, 0); tvb_memcpy(new_tvb, raw_data, 0, raw_len); tvb_free(new_tvb); } tvb_memcpy(tvb, (guint8 *)(raw_data + raw_len), chunk_offset, chunk_size); /* Don't create a new tvb if we have a single chunk with * a size of zero (meaning it is the end of the chunks). */ if(chunked_data_size > 0) { new_tvb = tvb_new_real_data(raw_data, chunked_data_size, chunked_data_size); tvb_set_free_cb(new_tvb, g_free); } if (subtree) { if(chunk_size == 0) { chunk_ti = proto_tree_add_text(subtree, tvb, offset, chunk_offset - offset + chunk_size + 2, "End of chunked encoding"); } else { chunk_ti = proto_tree_add_text(subtree, tvb, offset, chunk_offset - offset + chunk_size + 2, "Data chunk (%u octets)", chunk_size); } chunk_subtree = proto_item_add_subtree(chunk_ti, ett_http_chunk_data); proto_tree_add_text(chunk_subtree, tvb, offset, chunk_offset - offset, "Chunk size: %u octets", chunk_size); data_tvb = tvb_new_subset(tvb, chunk_offset, chunk_size, chunk_size); /* * XXX - just use "proto_tree_add_text()"? * This means that, in TShark, you get * the entire chunk dumped out in hex, * in addition to whatever dissection is * done on the reassembled data. */ call_dissector(data_handle, data_tvb, pinfo, chunk_subtree); proto_tree_add_text(chunk_subtree, tvb, chunk_offset + chunk_size, 2, "Chunk boundary"); } chunks_decoded++; offset = chunk_offset + chunk_size + 2; datalen = tvb_reported_length_remaining(tvb, offset); } if (new_tvb != NULL) { /* Placeholder for the day that composite tvbuffer's will work. tvb_composite_finalize(new_tvb); / * tvb_set_reported_length(new_tvb, chunked_data_size); * / */ /* * XXX - Don't free this, since the tvbuffer that was passed * may be used if the data spans multiple frames and reassembly * isn't enabled. * tvb_free(*tvb_ptr); */ *tvb_ptr = new_tvb; } else { /* * We didn't create a new tvb, so don't allow sub dissectors * try to decode the non-existent entity body. */ chunks_decoded = -1; } return chunks_decoded; } #else /* * Dissect the http data chunks and add them to the tree. */ static int chunked_encoding_dissector(tvbuff_t **tvb_ptr, packet_info *pinfo, proto_tree *tree, int offset) { tvbuff_t *tvb; guint32 datalen; guint32 orig_datalen; gint chunks_decoded; gint chunked_data_size; proto_tree *subtree; guint8 *raw_data; gint raw_len; if ((tvb_ptr == NULL) || (*tvb_ptr == NULL)) { return 0; } tvb = *tvb_ptr; datalen = tvb_reported_length_remaining(tvb, offset); subtree = NULL; if (tree) { proto_item *ti; ti = proto_tree_add_text(tree, tvb, offset, datalen, "HTTP chunked response"); subtree = proto_item_add_subtree(ti, ett_http_chunked_response); } /* Dechunk the "chunked response" to a new memory buffer */ orig_datalen = datalen; raw_data = g_malloc(datalen); raw_len = 0; chunks_decoded = 0; chunked_data_size = 0; while (datalen != 0) { tvbuff_t *data_tvb; guint32 chunk_size; gint chunk_offset; guint8 *chunk_string; gint linelen; gchar *c; linelen = tvb_find_line_end(tvb, offset, -1, &chunk_offset, TRUE); if (linelen <= 0) { /* Can't get the chunk size line */ break; } chunk_string = tvb_get_ephemeral_string(tvb, offset, linelen); if (chunk_string == NULL) { /* Can't get the chunk size line */ break; } c = (gchar*)chunk_string; /* * We don't care about the extensions. */ if ((c = strchr(c, ';'))) { *c = '\0'; } chunk_size = strtol((gchar*)chunk_string, NULL, 16); if (chunk_size > datalen) { /* * The chunk size is more than what's in the tvbuff, * so either the user hasn't enabled decoding, or all * of the segments weren't captured. */ chunk_size = datalen; } chunked_data_size += chunk_size; DISSECTOR_ASSERT((raw_len+chunk_size) <= orig_datalen); tvb_memcpy(tvb, (guint8 *)(raw_data + raw_len), chunk_offset, chunk_size); raw_len += chunk_size; if (subtree) { proto_item *chunk_ti; proto_tree *chunk_subtree; if(chunk_size == 0) { chunk_ti = proto_tree_add_text(subtree, tvb, offset, chunk_offset - offset + chunk_size + 2, "End of chunked encoding"); } else { chunk_ti = proto_tree_add_text(subtree, tvb, offset, chunk_offset - offset + chunk_size + 2, "Data chunk (%u octets)", chunk_size); } chunk_subtree = proto_item_add_subtree(chunk_ti, ett_http_chunk_data); proto_tree_add_text(chunk_subtree, tvb, offset, chunk_offset - offset, "Chunk size: %u octets", chunk_size); data_tvb = tvb_new_subset(tvb, chunk_offset, chunk_size, datalen); /* * XXX - just use "proto_tree_add_text()"? * This means that, in TShark, you get * the entire chunk dumped out in hex, * in addition to whatever dissection is * done on the reassembled data. */ call_dissector(data_handle, data_tvb, pinfo, chunk_subtree); proto_tree_add_text(chunk_subtree, tvb, chunk_offset + chunk_size, 2, "Chunk boundary"); } chunks_decoded++; offset = chunk_offset + 2 + chunk_size; /* beginning of next chunk */ datalen = tvb_reported_length_remaining(tvb, offset); } if (chunked_data_size > 0) { tvbuff_t *new_tvb; new_tvb = tvb_new_child_real_data(tvb, raw_data, chunked_data_size, chunked_data_size); tvb_set_free_cb(new_tvb, g_free); *tvb_ptr = new_tvb; } else { /* * There was no actual chunk data, so don't allow sub dissectors * try to decode the non-existent entity body. */ g_free(raw_data); chunks_decoded = -1; } return chunks_decoded; } #endif /* Call a subdissector to handle HTTP CONNECT's traffic */ static void http_payload_subdissector(tvbuff_t *tvb, proto_tree *tree, packet_info *pinfo, http_conv_t *conv_data) { guint32 *ptr = NULL; guint32 dissect_as, saved_port; gchar **strings; /* An array for splitting the request URI into hostname and port */ proto_item *item; proto_tree *proxy_tree; /* Grab the destination port number from the request URI to find the right subdissector */ strings = g_strsplit(conv_data->request_uri, ":", 2); if(strings[0] != NULL && strings[1] != NULL) { /* * The string was successfully split in two * Create a proxy-connect subtree */ if(tree) { item = proto_tree_add_item(tree, proto_http, tvb, 0, -1, ENC_NA); proxy_tree = proto_item_add_subtree(item, ett_http); item = proto_tree_add_string(proxy_tree, hf_http_proxy_connect_host, tvb, 0, 0, strings[0]); PROTO_ITEM_SET_GENERATED(item); item = proto_tree_add_uint(proxy_tree, hf_http_proxy_connect_port, tvb, 0, 0, strtol(strings[1], NULL, 10) ); PROTO_ITEM_SET_GENERATED(item); } /* We're going to get stuck in a loop if we let process_tcp_payload call us, so call the data dissector instead for proxy connections to http ports. */ dissect_as = (int)strtol(strings[1], NULL, 10); /* Convert string to a base-10 integer */ if (value_is_in_range(http_tcp_range, dissect_as)) { call_dissector(data_handle, tvb, pinfo, tree); } else { /* set pinfo->{src/dst port} and call the TCP sub-dissector lookup */ if ( !ptr && value_is_in_range(http_tcp_range, pinfo->destport) ) ptr = &pinfo->destport; else ptr = &pinfo->srcport; /* Increase pinfo->can_desegment because we are traversing * http and want to preserve desegmentation functionality for * the proxied protocol */ if( pinfo->can_desegment>0 ) pinfo->can_desegment++; saved_port = *ptr; *ptr = dissect_as; decode_tcp_ports(tvb, 0, pinfo, tree, pinfo->srcport, pinfo->destport, NULL); *ptr = saved_port; } } g_strfreev(strings); /* Free the result of g_strsplit() above */ } /* * XXX - this won't handle HTTP 0.9 replies, but they're all data * anyway. */ static int is_http_request_or_reply(const gchar *data, int linelen, http_type_t *type, ReqRespDissector *reqresp_dissector, http_conv_t *conv_data) { int isHttpRequestOrReply = FALSE; /* * From RFC 2774 - An HTTP Extension Framework * * Support the command prefix that identifies the presence of * a "mandatory" header. */ if (linelen >= 2 && strncmp(data, "M-", 2) == 0) { data += 2; linelen -= 2; } /* * From draft-cohen-gena-client-01.txt, available from the uPnP forum: * NOTIFY, SUBSCRIBE, UNSUBSCRIBE * * From draft-ietf-dasl-protocol-00.txt, a now vanished Microsoft draft: * SEARCH */ if (linelen >= 5 && strncmp(data, "HTTP/", 5) == 0) { *type = HTTP_RESPONSE; isHttpRequestOrReply = TRUE; /* response */ if (reqresp_dissector) *reqresp_dissector = basic_response_dissector; } else { const guchar * ptr = (const guchar *)data; int indx = 0; /* Look for the space following the Method */ while (indx < linelen) { if (*ptr == ' ') break; else { ptr++; indx++; } } /* Check the methods that have same length */ switch (indx) { case 3: if (strncmp(data, "GET", indx) == 0 || strncmp(data, "PUT", indx) == 0) { *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } else if (strncmp(data, "ICY", indx) == 0) { *type = HTTP_RESPONSE; isHttpRequestOrReply = TRUE; } break; case 4: if (strncmp(data, "COPY", indx) == 0 || strncmp(data, "HEAD", indx) == 0 || strncmp(data, "LOCK", indx) == 0 || strncmp(data, "MOVE", indx) == 0 || strncmp(data, "POLL", indx) == 0 || strncmp(data, "POST", indx) == 0) { *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; case 5: if (strncmp(data, "BCOPY", indx) == 0 || strncmp(data, "BMOVE", indx) == 0 || strncmp(data, "MKCOL", indx) == 0 || strncmp(data, "TRACE", indx) == 0 || strncmp(data, "LABEL", indx) == 0 || /* RFC 3253 8.2 */ strncmp(data, "MERGE", indx) == 0) { /* RFC 3253 11.2 */ *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; case 6: if (strncmp(data, "DELETE", indx) == 0 || strncmp(data, "SEARCH", indx) == 0 || strncmp(data, "UNLOCK", indx) == 0 || strncmp(data, "REPORT", indx) == 0 || /* RFC 3253 3.6 */ strncmp(data, "UPDATE", indx) == 0) { /* RFC 3253 7.1 */ *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } else if (strncmp(data, "NOTIFY", indx) == 0) { *type = HTTP_NOTIFICATION; isHttpRequestOrReply = TRUE; } break; case 7: if (strncmp(data, "BDELETE", indx) == 0 || strncmp(data, "CONNECT", indx) == 0 || strncmp(data, "OPTIONS", indx) == 0 || strncmp(data, "CHECKIN", indx) == 0) { /* RFC 3253 4.4, 9.4 */ *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; case 8: if (strncmp(data, "PROPFIND", indx) == 0 || strncmp(data, "CHECKOUT", indx) == 0 || /* RFC 3253 4.3, 9.3 */ strncmp(data, "CCM_POST", indx) == 0) { *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; case 9: if (strncmp(data, "SUBSCRIBE", indx) == 0) { *type = HTTP_NOTIFICATION; isHttpRequestOrReply = TRUE; } else if (strncmp(data, "PROPPATCH", indx) == 0 || strncmp(data, "BPROPFIND", indx) == 0) { *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; case 10: if (strncmp(data, "BPROPPATCH", indx) == 0 || strncmp(data, "UNCHECKOUT", indx) == 0 || /* RFC 3253 4.5 */ strncmp(data, "MKACTIVITY", indx) == 0) { /* RFC 3253 13.5 */ *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; case 11: if (strncmp(data, "MKWORKSPACE", indx) == 0 || /* RFC 3253 6.3 */ strncmp(data, "RPC_CONNECT", indx) == 0 || /* [MS-RPCH] 2.1.1.1.1 */ strncmp(data, "RPC_IN_DATA", indx) == 0) { /* [MS-RPCH] 2.1.2.1.1 */ *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } else if (strncmp(data, "UNSUBSCRIBE", indx) == 0) { *type = HTTP_NOTIFICATION; isHttpRequestOrReply = TRUE; } break; case 12: if (strncmp(data, "RPC_OUT_DATA", indx) == 0) { /* [MS-RPCH] 2.1.2.1.2 */ *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; case 15: if (strncmp(data, "VERSION-CONTROL", indx) == 0) { /* RFC 3253 3.5 */ *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; case 16: if (strncmp(data, "BASELINE-CONTROL", indx) == 0) { /* RFC 3253 12.6 */ *type = HTTP_REQUEST; isHttpRequestOrReply = TRUE; } break; default: break; } if (isHttpRequestOrReply && reqresp_dissector) { *reqresp_dissector = basic_request_dissector; stat_info->request_method = ep_strndup(data, indx+1); conv_data->request_method = se_strndup(data, indx+1); } } return isHttpRequestOrReply; } /* * Process headers. */ typedef struct { const char *name; gint *hf; int special; } header_info; #define HDR_NO_SPECIAL 0 #define HDR_AUTHORIZATION 1 #define HDR_AUTHENTICATE 2 #define HDR_CONTENT_TYPE 3 #define HDR_CONTENT_LENGTH 4 #define HDR_CONTENT_ENCODING 5 #define HDR_TRANSFER_ENCODING 6 #define HDR_HOST 7 #define HDR_UPGRADE 8 static const header_info headers[] = { { "Authorization", &hf_http_authorization, HDR_AUTHORIZATION }, { "Proxy-Authorization", &hf_http_proxy_authorization, HDR_AUTHORIZATION }, { "Proxy-Authenticate", &hf_http_proxy_authenticate, HDR_AUTHENTICATE }, { "WWW-Authenticate", &hf_http_www_authenticate, HDR_AUTHENTICATE }, { "Content-Type", &hf_http_content_type, HDR_CONTENT_TYPE }, { "Content-Length", &hf_http_content_length_header, HDR_CONTENT_LENGTH }, { "Content-Encoding", &hf_http_content_encoding, HDR_CONTENT_ENCODING }, { "Transfer-Encoding", &hf_http_transfer_encoding, HDR_TRANSFER_ENCODING }, { "Upgrade", &hf_http_upgrade, HDR_UPGRADE }, { "User-Agent", &hf_http_user_agent, HDR_NO_SPECIAL }, { "Host", &hf_http_host, HDR_HOST }, { "Connection", &hf_http_connection, HDR_NO_SPECIAL }, { "Cookie", &hf_http_cookie, HDR_NO_SPECIAL }, { "Accept", &hf_http_accept, HDR_NO_SPECIAL }, { "Referer", &hf_http_referer, HDR_NO_SPECIAL }, { "Accept-Language", &hf_http_accept_language, HDR_NO_SPECIAL }, { "Accept-Encoding", &hf_http_accept_encoding, HDR_NO_SPECIAL }, { "Date", &hf_http_date, HDR_NO_SPECIAL }, { "Cache-Control", &hf_http_cache_control, HDR_NO_SPECIAL }, { "Server", &hf_http_server, HDR_NO_SPECIAL }, { "Location", &hf_http_location, HDR_NO_SPECIAL }, { "Sec-WebSocket-Accept", &hf_http_sec_websocket_accept, HDR_NO_SPECIAL }, { "Sec-WebSocket-Extensions", &hf_http_sec_websocket_extensions, HDR_NO_SPECIAL }, { "Sec-WebSocket-Key", &hf_http_sec_websocket_key, HDR_NO_SPECIAL }, { "Sec-WebSocket-Protocol", &hf_http_sec_websocket_protocol, HDR_NO_SPECIAL }, { "Sec-WebSocket-Version", &hf_http_sec_websocket_version, HDR_NO_SPECIAL }, { "Set-Cookie", &hf_http_set_cookie, HDR_NO_SPECIAL }, { "Last-Modified", &hf_http_last_modified, HDR_NO_SPECIAL }, { "X-Forwarded-For", &hf_http_x_forwarded_for, HDR_NO_SPECIAL }, }; /* * */ static gint* get_hf_for_header(char* header_name) { gint* hf_id = NULL; if (header_fields_hash) { hf_id = (gint*) g_hash_table_lookup(header_fields_hash, header_name); } else { hf_id = NULL; } return hf_id; } /* * */ static void header_fields_initialize_cb(void) { static hf_register_info* hf; gint* hf_id; guint i; gchar* header_name; if (header_fields_hash && hf) { guint hf_size = g_hash_table_size (header_fields_hash); /* Unregister all fields */ for (i = 0; i < hf_size; i++) { proto_unregister_field (proto_http, *(hf[i].p_id)); g_free (hf[i].p_id); g_free ((char *) hf[i].hfinfo.name); g_free ((char *) hf[i].hfinfo.abbrev); g_free ((char *) hf[i].hfinfo.blurb); } g_hash_table_destroy (header_fields_hash); g_free (hf); header_fields_hash = NULL; } if (num_header_fields) { header_fields_hash = g_hash_table_new(g_str_hash, g_str_equal); hf = g_malloc0(sizeof(hf_register_info) * num_header_fields); for (i = 0; i < num_header_fields; i++) { hf_id = g_malloc(sizeof(gint)); *hf_id = -1; header_name = g_strdup(header_fields[i].header_name); hf[i].p_id = hf_id; hf[i].hfinfo.name = header_name; hf[i].hfinfo.abbrev = g_strdup_printf("http.header.%s", header_name); hf[i].hfinfo.type = FT_STRING; hf[i].hfinfo.display = BASE_NONE; hf[i].hfinfo.strings = NULL; hf[i].hfinfo.blurb = g_strdup(header_fields[i].header_desc); hf[i].hfinfo.same_name_prev = NULL; hf[i].hfinfo.same_name_next = NULL; g_hash_table_insert(header_fields_hash, header_name, hf_id); } proto_register_field_array(proto_http, hf, num_header_fields); } } static void process_header(tvbuff_t *tvb, int offset, int next_offset, const guchar *line, int linelen, int colon_offset, packet_info *pinfo, proto_tree *tree, headers_t *eh_ptr, http_conv_t *conv_data) { int len; int line_end_offset; int header_len; gint hf_index; guchar c; int value_offset; int value_len; char *value; char *header_name; char *p; guchar *up; proto_item *hdr_item; int i; int* hf_id; len = next_offset - offset; line_end_offset = offset + linelen; header_len = colon_offset - offset; header_name = se_strndup(&line[0], header_len); hf_index = find_header_hf_value(tvb, offset, header_len); /* * Skip whitespace after the colon. */ value_offset = colon_offset + 1; while (value_offset < line_end_offset && ((c = line[value_offset - offset]) == ' ' || c == '\t')) value_offset++; /* * Fetch the value. */ value_len = line_end_offset - value_offset; value = ep_strndup(&line[value_offset - offset], value_len); if (hf_index == -1) { /* * Not a header we know anything about. * Check if a HF generated from UAT information exists. */ hf_id = get_hf_for_header(header_name); if (tree) { if (!hf_id) { proto_tree_add_text(tree, tvb, offset, len, "%s", format_text(line, len)); } else { proto_tree_add_string_format(tree, *hf_id, tvb, offset, len, value, "%s", format_text(line, len)); } } } else { /* * Add it to the protocol tree as a particular field, * but display the line as is. */ if (tree) { header_field_info *hfinfo; guint32 tmp; hfinfo = proto_registrar_get_nth(*headers[hf_index].hf); switch(hfinfo->type){ case FT_UINT8: case FT_UINT16: case FT_UINT24: case FT_UINT32: case FT_INT8: case FT_INT16: case FT_INT24: case FT_INT32: tmp=strtol(value, NULL, 10); hdr_item = proto_tree_add_uint(tree, *headers[hf_index].hf, tvb, offset, len, tmp); break; default: hdr_item = proto_tree_add_string_format(tree, *headers[hf_index].hf, tvb, offset, len, value, "%s", format_text(line, len)); } } else hdr_item = NULL; /* * Do any special processing that particular headers * require. */ switch (headers[hf_index].special) { case HDR_AUTHORIZATION: if (check_auth_ntlmssp(hdr_item, tvb, pinfo, value)) break; /* dissected NTLMSSP */ if (check_auth_basic(hdr_item, tvb, value)) break; /* dissected basic auth */ check_auth_kerberos(hdr_item, tvb, pinfo, value); break; case HDR_AUTHENTICATE: if (check_auth_ntlmssp(hdr_item, tvb, pinfo, value)) break; /* dissected NTLMSSP */ check_auth_kerberos(hdr_item, tvb, pinfo, value); break; case HDR_CONTENT_TYPE: eh_ptr->content_type = (gchar*) ep_memdup((guint8*)value,value_len + 1); for (i = 0; i < value_len; i++) { c = value[i]; if (c == ';' || isspace(c)) { /* * End of subtype - either * white space or a ";" * separating the subtype from * a parameter. */ break; } /* * Map the character to lower case; * content types are case-insensitive. */ eh_ptr->content_type[i] = tolower(eh_ptr->content_type[i]); } eh_ptr->content_type[i] = '\0'; /* * Now find the start of the optional parameters; * skip the optional white space and the semicolon * if this has not been done before. */ i++; while (i < value_len) { c = eh_ptr->content_type[i]; if (c == ';' || isspace(c)) /* Skip till start of parameters */ i++; else break; } if (i < value_len) eh_ptr->content_type_parameters = eh_ptr->content_type + i; else eh_ptr->content_type_parameters = NULL; break; case HDR_CONTENT_LENGTH: errno = 0; eh_ptr->content_length = g_ascii_strtoll(value, &p, 10); up = (guchar *)p; if (eh_ptr->content_length < 0 || p == value || errno == ERANGE || (*up != '\0' && !isspace(*up))) { /* * Content length not valid; pretend * we don't have it. */ eh_ptr->have_content_length = FALSE; } else { proto_tree *header_tree; proto_item *tree_item; /* * We do have a valid content length. */ eh_ptr->have_content_length = TRUE; header_tree = proto_item_add_subtree(hdr_item, ett_http_header_item); tree_item = proto_tree_add_uint64(header_tree, hf_http_content_length, tvb, offset, len, eh_ptr->content_length); PROTO_ITEM_SET_GENERATED(tree_item); } break; case HDR_CONTENT_ENCODING: eh_ptr->content_encoding = ep_strndup(value, value_len); break; case HDR_TRANSFER_ENCODING: eh_ptr->transfer_encoding = ep_strndup(value, value_len); break; case HDR_HOST: stat_info->http_host = ep_strndup(value, value_len); conv_data->http_host = se_strndup(value, value_len); break; case HDR_UPGRADE: conv_data->upgrade = se_strndup(value, value_len); break; } } } /* Returns index of header tag in headers */ static gint find_header_hf_value(tvbuff_t *tvb, int offset, guint header_len) { guint i; for (i = 0; i < array_length(headers); i++) { if (header_len == strlen(headers[i].name) && tvb_strncaseeql(tvb, offset, headers[i].name, header_len) == 0) return i; } return -1; } /* * Dissect Microsoft's abomination called NTLMSSP over HTTP. */ static gboolean check_auth_ntlmssp(proto_item *hdr_item, tvbuff_t *tvb, packet_info *pinfo, gchar *value) { static const char *ntlm_headers[] = { "NTLM ", "Negotiate ", NULL }; const char **header; size_t hdrlen; proto_tree *hdr_tree; /* * Check for NTLM credentials and challenge; those can * occur with WWW-Authenticate. */ for (header = &ntlm_headers[0]; *header != NULL; header++) { hdrlen = strlen(*header); if (strncmp(value, *header, hdrlen) == 0) { if (hdr_item != NULL) { hdr_tree = proto_item_add_subtree(hdr_item, ett_http_ntlmssp); } else hdr_tree = NULL; value += hdrlen; dissect_http_ntlmssp(tvb, pinfo, hdr_tree, value); return TRUE; } } return FALSE; } /* * Dissect HTTP Basic authorization. */ static gboolean check_auth_basic(proto_item *hdr_item, tvbuff_t *tvb, gchar *value) { static const char *basic_headers[] = { "Basic ", NULL }; const char **header; size_t hdrlen; proto_tree *hdr_tree; size_t len; for (header = &basic_headers[0]; *header != NULL; header++) { hdrlen = strlen(*header); if (strncmp(value, *header, hdrlen) == 0) { if (hdr_item != NULL) { hdr_tree = proto_item_add_subtree(hdr_item, ett_http_ntlmssp); } else hdr_tree = NULL; value += hdrlen; len = epan_base64_decode(value); value[len] = '\0'; proto_tree_add_string(hdr_tree, hf_http_basic, tvb, 0, 0, value); return TRUE; } } return FALSE; } static gboolean check_auth_kerberos(proto_item *hdr_item, tvbuff_t *tvb, packet_info *pinfo, const gchar *value) { proto_tree *hdr_tree; if (strncmp(value, "Kerberos ", 9) == 0) { if (hdr_item != NULL) { hdr_tree = proto_item_add_subtree(hdr_item, ett_http_kerberos); } else hdr_tree = NULL; dissect_http_kerberos(tvb, pinfo, hdr_tree, value); return TRUE; } return FALSE; } static void dissect_http(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { http_conv_t *conv_data; int offset = 0; int len; /* * Check if this is proxied connection and if so, hand of dissection to the * payload-dissector. * Response code 200 means "OK" and strncmp() == 0 means the strings match exactly */ conv_data = get_http_conversation_data(pinfo); if(pinfo->fd->num >= conv_data->startframe && conv_data->response_code == 200 && conv_data->request_method && strncmp(conv_data->request_method, "CONNECT", 7) == 0 && conv_data->request_uri) { if(conv_data->startframe == 0 && !pinfo->fd->flags.visited) conv_data->startframe = pinfo->fd->num; http_payload_subdissector(tvb, tree, pinfo, conv_data); } else { while (tvb_reported_length_remaining(tvb, offset) != 0) { len = dissect_http_message(tvb, offset, pinfo, tree, conv_data); if (len == -1) break; offset += len; /* * OK, we've set the Protocol and Info columns for the * first HTTP message; set a fence so that subsequent * HTTP messages don't overwrite the Info column. */ if (check_col(pinfo->cinfo, COL_INFO)) col_set_fence(pinfo->cinfo, COL_INFO); } } } static void dissect_http_udp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { http_conv_t *conv_data; conv_data = get_http_conversation_data(pinfo); dissect_http_message(tvb, 0, pinfo, tree, conv_data); } static void range_delete_http_tcp_callback(guint32 port) { dissector_delete_uint("tcp.port", port, http_handle); } static void range_add_http_tcp_callback(guint32 port) { dissector_add_uint("tcp.port", port, http_handle); } static void range_delete_http_ssl_callback(guint32 port) { ssl_dissector_delete(port, "http", TRUE); } static void range_add_http_ssl_callback(guint32 port) { ssl_dissector_add(port, "http", TRUE); } static void reinit_http(void) { range_foreach(http_tcp_range, range_delete_http_tcp_callback); g_free(http_tcp_range); http_tcp_range = range_copy(global_http_tcp_range); range_foreach(http_tcp_range, range_add_http_tcp_callback); range_foreach(http_ssl_range, range_delete_http_ssl_callback); g_free(http_ssl_range); http_ssl_range = range_copy(global_http_ssl_range); range_foreach(http_ssl_range, range_add_http_ssl_callback); } void proto_register_http(void) { static hf_register_info hf[] = { { &hf_http_notification, { "Notification", "http.notification", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "TRUE if HTTP notification", HFILL }}, { &hf_http_response, { "Response", "http.response", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "TRUE if HTTP response", HFILL }}, { &hf_http_request, { "Request", "http.request", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "TRUE if HTTP request", HFILL }}, { &hf_http_basic, { "Credentials", "http.authbasic", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_http_request_method, { "Request Method", "http.request.method", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Request Method", HFILL }}, { &hf_http_request_uri, { "Request URI", "http.request.uri", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Request-URI", HFILL }}, { &hf_http_version, { "Request Version", "http.request.version", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Request HTTP-Version", HFILL }}, { &hf_http_request_full_uri, { "Full request URI", "http.request.full_uri", FT_STRING, BASE_NONE, NULL, 0x0, "The full requested URI (including host name)", HFILL }}, { &hf_http_response_code, { "Status Code", "http.response.code", FT_UINT16, BASE_DEC, NULL, 0x0, "HTTP Response Status Code", HFILL }}, { &hf_http_response_phrase, { "Response Phrase", "http.response.phrase", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Response Reason Phrase", HFILL }}, { &hf_http_authorization, { "Authorization", "http.authorization", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Authorization header", HFILL }}, { &hf_http_proxy_authenticate, { "Proxy-Authenticate", "http.proxy_authenticate", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Proxy-Authenticate header", HFILL }}, { &hf_http_proxy_authorization, { "Proxy-Authorization", "http.proxy_authorization", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Proxy-Authorization header", HFILL }}, { &hf_http_proxy_connect_host, { "Proxy-Connect-Hostname", "http.proxy_connect_host", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Proxy Connect Hostname", HFILL }}, { &hf_http_proxy_connect_port, { "Proxy-Connect-Port", "http.proxy_connect_port", FT_UINT16, BASE_DEC, NULL, 0x0, "HTTP Proxy Connect Port", HFILL }}, { &hf_http_www_authenticate, { "WWW-Authenticate", "http.www_authenticate", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP WWW-Authenticate header", HFILL }}, { &hf_http_content_type, { "Content-Type", "http.content_type", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Content-Type header", HFILL }}, { &hf_http_content_length_header, { "Content-Length", "http.content_length_header", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Content-Length header", HFILL }}, { &hf_http_content_length, { "Content length", "http.content_length", FT_UINT64, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_http_content_encoding, { "Content-Encoding", "http.content_encoding", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Content-Encoding header", HFILL }}, { &hf_http_transfer_encoding, { "Transfer-Encoding", "http.transfer_encoding", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Transfer-Encoding header", HFILL }}, { &hf_http_upgrade, { "Upgrade", "http.upgrade", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Upgrade header", HFILL }}, { &hf_http_user_agent, { "User-Agent", "http.user_agent", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP User-Agent header", HFILL }}, { &hf_http_host, { "Host", "http.host", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Host", HFILL }}, { &hf_http_connection, { "Connection", "http.connection", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Connection", HFILL }}, { &hf_http_cookie, { "Cookie", "http.cookie", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Cookie", HFILL }}, { &hf_http_accept, { "Accept", "http.accept", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Accept", HFILL }}, { &hf_http_referer, { "Referer", "http.referer", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Referer", HFILL }}, { &hf_http_accept_language, { "Accept-Language", "http.accept_language", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Accept Language", HFILL }}, { &hf_http_accept_encoding, { "Accept Encoding", "http.accept_encoding", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Accept Encoding", HFILL }}, { &hf_http_date, { "Date", "http.date", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Date", HFILL }}, { &hf_http_cache_control, { "Cache-Control", "http.cache_control", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Cache Control", HFILL }}, { &hf_http_server, { "Server", "http.server", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Server", HFILL }}, { &hf_http_location, { "Location", "http.location", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Location", HFILL }}, { &hf_http_sec_websocket_accept, { "Sec-WebSocket-Accept", "http.sec_websocket_accept", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_http_sec_websocket_extensions, { "Sec-WebSocket-Extensions", "http.sec_websocket_extensions", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_http_sec_websocket_key, { "Sec-WebSocket-Key", "http.sec_websocket_key", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_http_sec_websocket_protocol, { "Sec-WebSocket-Protocol", "http.sec_websocket_protocol", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_http_sec_websocket_version, { "Sec-WebSocket-Version", "http.sec_websocket_version", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_http_set_cookie, { "Set-Cookie", "http.set_cookie", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Set Cookie", HFILL }}, { &hf_http_last_modified, { "Last-Modified", "http.last_modified", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP Last Modified", HFILL }}, { &hf_http_x_forwarded_for, { "X-Forwarded-For", "http.x_forwarded_for", FT_STRING, BASE_NONE, NULL, 0x0, "HTTP X-Forwarded-For", HFILL }} }; static gint *ett[] = { &ett_http, &ett_http_ntlmssp, &ett_http_kerberos, &ett_http_request, &ett_http_chunked_response, &ett_http_chunk_data, &ett_http_encoded_entity, &ett_http_header_item }; /* UAT for header fields */ static uat_field_t custom_header_uat_fields[] = { UAT_FLD_CSTRING(header_fields, header_name, "Header name", "HTTP header name"), UAT_FLD_CSTRING(header_fields, header_desc, "Field desc", "Description of the value contained in the header"), UAT_END_FIELDS }; module_t *http_module; uat_t* headers_uat; proto_http = proto_register_protocol("Hypertext Transfer Protocol", "HTTP", "http"); proto_register_field_array(proto_http, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); register_dissector("http", dissect_http, proto_http); http_module = prefs_register_protocol(proto_http, reinit_http); prefs_register_bool_preference(http_module, "desegment_headers", "Reassemble HTTP headers spanning multiple TCP segments", "Whether the HTTP dissector should reassemble headers " "of a request spanning multiple TCP segments. " "To use this option, you must also enable " "\"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.", &http_desegment_headers); prefs_register_bool_preference(http_module, "desegment_body", "Reassemble HTTP bodies spanning multiple TCP segments", "Whether the HTTP dissector should use the " "\"Content-length:\" value, if present, to reassemble " "the body of a request spanning multiple TCP segments, " "and reassemble chunked data spanning multiple TCP segments. " "To use this option, you must also enable " "\"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.", &http_desegment_body); prefs_register_bool_preference(http_module, "dechunk_body", "Reassemble chunked transfer-coded bodies", "Whether to reassemble bodies of entities that are transferred " "using the \"Transfer-Encoding: chunked\" method", &http_dechunk_body); #ifdef HAVE_LIBZ prefs_register_bool_preference(http_module, "decompress_body", "Uncompress entity bodies", "Whether to uncompress entity bodies that are compressed " "using \"Content-Encoding: \"", &http_decompress_body); #endif prefs_register_obsolete_preference(http_module, "tcp_alternate_port"); range_convert_str(&global_http_tcp_range, TCP_DEFAULT_RANGE, 65535); http_tcp_range = range_empty(); prefs_register_range_preference(http_module, "tcp.port", "TCP Ports", "TCP Ports range", &global_http_tcp_range, 65535); range_convert_str(&global_http_ssl_range, SSL_DEFAULT_RANGE, 65535); http_ssl_range = range_empty(); prefs_register_range_preference(http_module, "ssl.port", "SSL/TLS Ports", "SSL/TLS Ports range", &global_http_ssl_range, 65535); /* UAT */ headers_uat = uat_new("Custom HTTP headers fields Table", sizeof(header_field_t), "custom_http_header_fields", TRUE, (void*) &header_fields, &num_header_fields, UAT_CAT_FIELDS, NULL, header_fields_copy_cb, header_fields_update_cb, header_fields_free_cb, header_fields_initialize_cb, custom_header_uat_fields ); prefs_register_uat_preference(http_module, "custom_http_header_fields", "Custom HTTP headers fields", "A table to define custom HTTP header for which fields can be setup and used for filtering/data extraction etc.", headers_uat); http_handle = create_dissector_handle(dissect_http, proto_http); /* * Dissectors shouldn't register themselves in this table; * instead, they should call "http_dissector_add()", and * we'll register the port number they specify as a port * for HTTP, and register them in our subdissector table. * * This only works for protocols such as IPP that run over * HTTP on a specific non-HTTP port. */ port_subdissector_table = register_dissector_table("http.port", "TCP port for protocols using HTTP", FT_UINT16, BASE_DEC); /* * Dissectors can register themselves in this table. * It's just "media_type", not "http.content_type", because * it's an Internet media type, usable by other protocols as well. */ media_type_subdissector_table = register_dissector_table("media_type", "Internet media type", FT_STRING, BASE_NONE); /* * Heuristic dissectors SHOULD register themselves in * this table using the standard heur_dissector_add() * function. */ register_heur_dissector_list("http", &heur_subdissector_list); /* * Register for tapping */ http_tap = register_tap("http"); /* HTTP statistics tap */ http_eo_tap = register_tap("http_eo"); /* HTTP Export Object tap */ } /* * Called by dissectors for protocols that run atop HTTP/TCP. */ void http_dissector_add(guint32 port, dissector_handle_t handle) { /* * Register ourselves as the handler for that port number * over TCP. */ dissector_add_uint("tcp.port", port, http_handle); /* * And register them in *our* table for that port. */ dissector_add_uint("http.port", port, handle); } void proto_reg_handoff_http(void) { dissector_handle_t http_udp_handle; data_handle = find_dissector("data"); media_handle = find_dissector("media"); websocket_handle = find_dissector("websocket"); /* * XXX - is there anything to dissect in the body of an SSDP * request or reply? I.e., should there be an SSDP dissector? */ http_udp_handle = create_dissector_handle(dissect_http_udp, proto_http); dissector_add_uint("udp.port", UDP_PORT_SSDP, http_udp_handle); ntlmssp_handle = find_dissector("ntlmssp"); gssapi_handle = find_dissector("gssapi"); stats_tree_register("http", "http", "HTTP/Packet Counter", 0, http_stats_tree_packet, http_stats_tree_init, NULL ); stats_tree_register("http", "http_req", "HTTP/Requests", 0, http_req_stats_tree_packet, http_req_stats_tree_init, NULL ); stats_tree_register("http", "http_srv", "HTTP/Load Distribution",0, http_reqs_stats_tree_packet, http_reqs_stats_tree_init, NULL ); } /* * Content-Type: message/http */ static gint proto_message_http = -1; static gint ett_message_http = -1; static void dissect_message_http(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_tree *subtree; proto_item *ti; gint offset = 0, next_offset; gint len; col_append_str(pinfo->cinfo, COL_INFO, " (message/http)"); if (tree) { ti = proto_tree_add_item(tree, proto_message_http, tvb, 0, -1, ENC_NA); subtree = proto_item_add_subtree(ti, ett_message_http); while (tvb_reported_length_remaining(tvb, offset) != 0) { len = tvb_find_line_end(tvb, offset, tvb_ensure_length_remaining(tvb, offset), &next_offset, FALSE); if (len == -1) break; proto_tree_add_text(subtree, tvb, offset, next_offset - offset, "%s", tvb_format_text(tvb, offset, len)); offset = next_offset; } } } void proto_register_message_http(void) { static gint *ett[] = { &ett_message_http, }; proto_message_http = proto_register_protocol( "Media Type: message/http", "message/http", "message-http" ); proto_register_subtree_array(ett, array_length(ett)); } void proto_reg_handoff_message_http(void) { dissector_handle_t message_http_handle; message_http_handle = create_dissector_handle(dissect_message_http, proto_message_http); dissector_add_string("media_type", "message/http", message_http_handle); reinit_http(); }
{ "pile_set_name": "Github" }
config DRM_EXYNOS tristate "DRM Support for Samsung SoC EXYNOS Series" depends on DRM && PLAT_SAMSUNG select DRM_KMS_HELPER select FB_CFB_FILLRECT select FB_CFB_COPYAREA select FB_CFB_IMAGEBLIT select VT_HW_CONSOLE_BINDING if FRAMEBUFFER_CONSOLE help Choose this option if you have a Samsung SoC EXYNOS chipset. If M is selected the module will be called exynosdrm. config DRM_EXYNOS_FIMD bool "Exynos DRM FIMD" depends on DRM_EXYNOS && !FB_S3C help Choose this option if you want to use Exynos FIMD for DRM. config DRM_EXYNOS_HDMI bool "Exynos DRM HDMI" depends on DRM_EXYNOS && !VIDEO_SAMSUNG_S5P_TV help Choose this option if you want to use Exynos HDMI for DRM. config DRM_EXYNOS_VIDI bool "Exynos DRM Virtual Display" depends on DRM_EXYNOS help Choose this option if you want to use Exynos VIDI for DRM.
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <!--圆角半径--> <corners android:radius="100dp" /> <!--背景颜色--> <solid android:color="@color/white" /> </shape>
{ "pile_set_name": "Github" }
/** * * WARNING! This file was autogenerated by: * _ _ _ _ __ __ * | | | | | | |\ \ / / * | | | | |_| | \ V / * | | | | _ | / \ * | |_| | | | |/ /^\ \ * \___/\_| |_/\/ \/ * * This file was autogenerated by UnrealHxGenerator using UHT definitions. * It only includes UPROPERTYs and UFUNCTIONs. Do not modify it! * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix **/ package unreal.animgraph; /** WARNING: This type was defined as MinimalAPI on its declaration. Because of that, its properties/methods are inaccessible Editor node for FABRIK IK skeletal controller **/ @:umodule("AnimGraph") @:glueCppIncludes("AnimGraphNode_Fabrik.h") @:uextern @:uclass extern class UAnimGraphNode_Fabrik extends unreal.animgraph.UAnimGraphNode_SkeletalControlBase { @:uproperty public var Node : unreal.animgraphruntime.FAnimNode_Fabrik; }
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <CoreSuggestionsUI/SGEventSuggestionBase.h> #import <CoreSuggestionsUI/SuggestedEventPopoverControllerDelegate-Protocol.h> @class NSImage, NSString; @interface SGEventSuggestion : SGEventSuggestionBase <SuggestedEventPopoverControllerDelegate> { NSImage *_calendarImage; } + (id)calendarImage; - (void).cxx_destruct; - (id)suggestionImage; - (void)suggestedEventPopoverController:(id)arg1 wantsToIgnoreSuggestedEvent:(id)arg2; - (void)suggestedEventPopoverController:(id)arg1 wantsToCommitSuggestedEvent:(id)arg2 asEvent:(id)arg3; - (void)cancelSuggestedEventPopoverController:(id)arg1; - (void)_dismissViewController:(id)arg1 andSignalCompletionWithResult:(BOOL)arg2; - (id)suggestionPrimaryAction; - (id)suggestionAttributedSubtitle; - (id)suggestionPrimaryActionViewController; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
{ "pile_set_name": "Github" }
// The MIT License (MIT) // // Copyright (c) 2015, 2017 Arian Fornaris // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: The above copyright notice and this permission // notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. package phasereditor.canvas.core; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.LinkedHashSet; import java.util.Set; import java.util.stream.Collectors; import org.eclipse.swt.graphics.RGB; import org.json.JSONArray; import org.json.JSONObject; /** * @author arian * */ public class StateSettings { public static final String SCALE_MODE_NO_SCALE = "NO_SCALE"; public static final RGB DEFAULT_STAGE_BG_COLOR = new RGB(0, 0, 0); public static String[] SCALE_MODES = { SCALE_MODE_NO_SCALE, "SHOW_ALL", "RESIZE", "USER_SCALE" }; private String _scaleMode = SCALE_MODE_NO_SCALE; private boolean _pageAlignHorizontally; private boolean _pageAlignVertically; private RGB _stageBackgroundColor = DEFAULT_STAGE_BG_COLOR; private PhysicsType _physicsSystem = PhysicsType.NONE; private boolean _rendererRoundPixels; private boolean _autoLoad = true; private boolean _isPreloader = false; private String _preloadSpriteId = null; private PreloadSpriteDirection _preloadSprite_direction = PreloadSpriteDirection.HORIZONTAL; private Set<LoadPack> _loadPack = new LinkedHashSet<>(); public static class LoadPack { private String _file; private String _section; public LoadPack(String file, String section) { super(); _file = file; _section = section; } public String getFile() { return _file; } public void setFile(String file) { _file = file; } public String getSection() { return _section; } public void setSection(String section) { _section = section; } public static String toString(Set<LoadPack> value) { if (value == null) { return "[]"; } String join = value.stream().map(e -> e.getSection()).collect(Collectors.joining(",")); return "[" + join + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_file == null) ? 0 : _file.hashCode()); result = prime * result + ((_section == null) ? 0 : _section.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LoadPack other = (LoadPack) obj; if (_file == null) { if (other._file != null) return false; } else if (!_file.equals(other._file)) return false; if (_section == null) { if (other._section != null) return false; } else if (!_section.equals(other._section)) return false; return true; } } public enum PreloadSpriteDirection { HORIZONTAL, VERTICAL } public void write(JSONObject data) { data.put("scaleMode", _scaleMode, SCALE_MODE_NO_SCALE); data.put("pageAlignHorizontally", _pageAlignHorizontally, false); data.put("pageAlignVertically", _pageAlignVertically, false); EditorSettings.writeColor(data, "stageBackgroundColor", _stageBackgroundColor); data.put("physicsSystem", _physicsSystem.name(), PhysicsType.NONE.name()); data.put("rendererRoundPixels", _rendererRoundPixels, false); data.put("autoLoad", _autoLoad); data.put("isPreloader", _isPreloader, false); data.put("preloadSpriteId", _preloadSpriteId); data.put("preloadSprite_direction", _preloadSprite_direction.ordinal()); { JSONArray list = new JSONArray(); for (LoadPack section : _loadPack) { JSONObject obj = new JSONObject(); obj.put("file", section.getFile()); obj.put("section", section.getSection()); list.put(obj); } data.put("load.pack", list); } } public void read(JSONObject data) { _scaleMode = data.optString("scaleMode", SCALE_MODE_NO_SCALE); _pageAlignHorizontally = data.optBoolean("pageAlignHorizontally", false); _pageAlignVertically = data.optBoolean("pageAlignVertically", false); _stageBackgroundColor = EditorSettings.readColor(data, "stageBackgroundColor", DEFAULT_STAGE_BG_COLOR); { String name = data.optString("physicsSystem", PhysicsType.NONE.name()); _physicsSystem = PhysicsType.valueOf(name); } _rendererRoundPixels = data.optBoolean("rendererRoundPixels", false); _autoLoad = data.optBoolean("autoLoad", true); _isPreloader = data.optBoolean("isPreloader"); _preloadSpriteId = data.optString("preloadSpriteId"); { _preloadSprite_direction = PreloadSpriteDirection.values()[data.optInt("preloadSprite_direction", 0)]; } { JSONArray list = data.optJSONArray("load.pack"); LinkedHashSet<LoadPack> loadpack = new LinkedHashSet<>(); if (list != null) { for (int i = 0; i < list.length(); i++) { JSONObject obj = list.getJSONObject(i); loadpack.add(new LoadPack(obj.getString("file"), obj.getString("section"))); } } _loadPack = loadpack; } } public Set<LoadPack> getLoadPack() { return _loadPack; } public void setLoadPack(Set<LoadPack> loadPack) { _loadPack = loadPack; } public boolean isAutoLoad() { return _autoLoad; } public void setAutoLoad(boolean autoLoad) { _autoLoad = autoLoad; } public boolean isPreloader() { return _isPreloader; } public void setPreloader(boolean isPreloader) { _isPreloader = isPreloader; } public String getPreloadSpriteId() { return _preloadSpriteId; } public void setPreloadSpriteId(String preloadSpriteId) { _preloadSpriteId = preloadSpriteId; } public PreloadSpriteDirection getPreloadSprite_direction() { return _preloadSprite_direction; } public void setPreloadSprite_direction(PreloadSpriteDirection preloadSprite_direction) { _preloadSprite_direction = preloadSprite_direction; } public boolean isRendererRoundPixels() { return _rendererRoundPixels; } public void setRendererRoundPixels(boolean rendererRoundPixels) { _rendererRoundPixels = rendererRoundPixels; firePropertyChange("rendererRoundPixels"); } public String getScaleMode() { return _scaleMode; } public void setScaleMode(String scaleMode) { _scaleMode = scaleMode; firePropertyChange("scaleMode"); } public boolean isPageAlignHorizontally() { return _pageAlignHorizontally; } public void setPageAlignHorizontally(boolean pageAlignHorizontally) { _pageAlignHorizontally = pageAlignHorizontally; firePropertyChange("pageAlignHorizontally"); } public boolean isPageAlignVertically() { return _pageAlignVertically; } public void setPageAlignVertically(boolean pageAlignVertically) { _pageAlignVertically = pageAlignVertically; firePropertyChange("pageAlignVertically"); } public RGB getStageBackgroundColor() { return _stageBackgroundColor; } public void setStageBackgroundColor(RGB stageBackgroundColor) { _stageBackgroundColor = stageBackgroundColor; firePropertyChange("stageBackgroundColor"); } public PhysicsType getPhysicsSystem() { return _physicsSystem; } public void setPhysicsSystem(PhysicsType physicsSystem) { _physicsSystem = physicsSystem; firePropertyChange("physicsSystem"); } private transient final PropertyChangeSupport support = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener l) { support.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { support.removePropertyChangeListener(l); } public void addPropertyChangeListener(String property, PropertyChangeListener l) { support.addPropertyChangeListener(property, l); } public void removePropertyChangeListener(String property, PropertyChangeListener l) { support.removePropertyChangeListener(property, l); } public void firePropertyChange(String property) { support.firePropertyChange(property, true, false); } }
{ "pile_set_name": "Github" }
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 import ( authorizationapi "k8s.io/api/authorization/v1" ) // The SubjectAccessReviewExpansion interface allows manually adding extra methods to the AuthorizationInterface. type SubjectAccessReviewExpansion interface { Create(sar *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReview, err error) } func (c *subjectAccessReviews) Create(sar *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReview, err error) { result = &authorizationapi.SubjectAccessReview{} err = c.client.Post(). Resource("subjectaccessreviews"). Body(sar). Do(). Into(result) return }
{ "pile_set_name": "Github" }
-2458173121:LMT:0:6720 348884520:SAST:0:5400 1248312600:SAST:0:7200 15721200:SAST:1:10800 15728400:SAST:0:7200 15721200:SAST:1:10800 1:SAST:0:7200
{ "pile_set_name": "Github" }
using System; using System.Reflection; namespace MvcSiteMapProvider.Reflection { /// <summary> /// Extensions to the System.Object data type. /// </summary> /// <remarks> /// Source: http://stackoverflow.com/questions/1565734/is-it-possible-to-set-private-property-via-reflection#answer-1565766 /// </remarks> public static class ObjectExtensions { /// <summary> /// Returns a _private_ Property Value from a given Object. Uses Reflection. /// Throws a ArgumentOutOfRangeException if the Property is not found. /// </summary> /// <typeparam name="T">Type of the Property</typeparam> /// <param name="obj">Object from where the Property Value is located</param> /// <param name="propertyName">Propertyname as string.</param> /// <returns>PropertyValue</returns> public static T GetPrivatePropertyValue<T>(this object obj, string propertyName) { if (obj == null) throw new ArgumentNullException("obj"); PropertyInfo pi = obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (pi == null) throw new ArgumentOutOfRangeException("propertyName", string.Format(Resources.Messages.ObjectPropertyNotFound, propertyName, obj.GetType().FullName)); return (T)pi.GetValue(obj, null); } /// <summary> /// Returns a private Field Value from a given Object. Uses Reflection. /// Throws a ArgumentOutOfRangeException if the Field is not found. /// </summary> /// <typeparam name="T">Type of the Field</typeparam> /// <param name="obj">Object from where the Field Value is located</param> /// <param name="fieldName">Propertyname as string.</param> /// <returns>PropertyValue</returns> public static T GetPrivateFieldValue<T>(this object obj, string fieldName) { if (obj == null) throw new ArgumentNullException("obj"); Type t = obj.GetType(); FieldInfo fi = null; while (fi == null && t != null) { fi = t.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); t = t.BaseType; } if (fi == null) throw new ArgumentOutOfRangeException("fieldName", string.Format(Resources.Messages.ObjectFieldNotFound, fieldName, obj.GetType().FullName)); return (T)fi.GetValue(obj); } } }
{ "pile_set_name": "Github" }
{ "package": "com.google.android.apps.cloudconsole", "verified": true, "authors": [ "simonsmh" ], "last_update": { "timestamp": 1573909761 }, "recommendation": "@unnecessary", "behaviors": [ "@standard" ] }
{ "pile_set_name": "Github" }
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/python/framework/python_op_gen.h" #include <stdio.h> #include <sstream> #include <unordered_map> #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_def.pb.h" #include "tensorflow/core/framework/op_def_util.h" #include "tensorflow/core/framework/op_gen_lib.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/lib/gtl/stl_util.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace { const int kRightMargin = 78; bool IsPythonReserved(const string& s) { static const std::set<string>* const kPythonReserved = new std::set<string>( {// Keywords in Python, from: // import keyword // print keyword.kwlist "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield", // Built-in functions and types in Python, from: // [x for x in dir(__builtins__) if not x[0].islower()] "ArithmeticError", "AssertionError", "AttributeError", "BaseException", "BufferError", "BytesWarning", "DeprecationWarning", "EOFError", "Ellipsis", "EnvironmentError", "Exception", "False", "FloatingPointError", "FutureWarning", "GeneratorExit", "IOError", "ImportError", "ImportWarning", "IndentationError", "IndexError", "KeyError", "KeyboardInterrupt", "LookupError", "MemoryError", "NameError", "None", "NotImplemented", "NotImplementedError", "OSError", "OverflowError", "PendingDeprecationWarning", "ReferenceError", "RuntimeError", "RuntimeWarning", "StandardError", "StopIteration", "SyntaxError", "SyntaxWarning", "SystemError", "SystemExit", "TabError", "True", "TypeError", "UnboundLocalError", "UnicodeDecodeError", "UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError", "UnicodeWarning", "UserWarning", "ValueError", "Warning", "ZeroDivisionError", "__debug__", "__doc__", "__import__", "__name__", "__package__", // Imports and symbols used in the generated code: "_op_def_lib", "text_format", "op_def_pb2", "op_def_library", "ops"}); return kPythonReserved->count(s) > 0; } // Add a _ to the end of s if necessary to avoid a Python keyword or built-in. string AvoidPythonReserved(const string& s) { if (IsPythonReserved(s)) return strings::StrCat(s, "_"); return s; } // Indent the first line by "initial" spaces and all following lines // by "rest" spaces. string Indent(int initial, int rest, StringPiece in) { // TODO(josh11b): Also word-wrapping? string copy(in.data(), in.size()); str_util::StripTrailingWhitespace(&copy); std::vector<string> v = str_util::Split(copy, '\n'); string result; bool first = true; for (const string& line : v) { if (first) { result = strings::StrCat(Spaces(initial), line, "\n"); first = false; } else { if (line.empty()) { strings::StrAppend(&result, "\n"); } else { strings::StrAppend(&result, Spaces(rest), line, "\n"); } } } return result; } // Adds append to *dest, with a space if the first line will be <= width, // or a newline otherwise. void AppendWithinWidth(string* dest, StringPiece append, int width) { auto first_line = append.find('\n'); if (first_line == string::npos) first_line = append.size(); if (dest->size() + first_line + 1 /* space */ > static_cast<size_t>(width)) { strings::StrAppend(dest, "\n", append); } else { strings::StrAppend(dest, " ", append); } } // Like DataTypeString() but uses the Python names for the // float types. string PythonDataTypeString(DataType dtype) { switch (dtype) { case DT_FLOAT: return "float32"; case DT_DOUBLE: return "float64"; default: return DataTypeString(dtype); } } string TypeString(DataType dtype, bool ref) { if (ref) { return strings::StrCat("mutable `", PythonDataTypeString(dtype), "`"); } else { return strings::StrCat("`", PythonDataTypeString(dtype), "`"); } } string TypeListString(const AttrValue& value) { string ret; for (int t : value.list().type()) { if (!ret.empty()) strings::StrAppend(&ret, ", "); DataType dtype = static_cast<DataType>(t); if (IsRefType(dtype)) { strings::StrAppend(&ret, PythonDataTypeString(RemoveRefType(dtype)), " mutable"); } else { strings::StrAppend(&ret, "`", PythonDataTypeString(dtype), "`"); } } return ret; } string SingleTensorName(DataType dtype, bool is_ref) { const string type_str = TypeString(dtype, is_ref); return strings::StrCat("A `Tensor` of type ", type_str, "."); } const char kUnknownTensorType[] = {"A `Tensor`."}; string ArgTypeName(const OpDef& op_def, const OpDef::ArgDef& arg, const std::unordered_map<string, string>& inferred_attrs, bool is_output) { if (!arg.number_attr().empty()) { // N Tensors with the same type const string* original_arg = gtl::FindOrNull(inferred_attrs, arg.number_attr()); string prefix; if (original_arg == nullptr) { prefix = strings::StrCat("A list of `", arg.number_attr(), "`"); } else if (*original_arg == arg.name()) { const OpDef::AttrDef* attr = FindAttr(arg.number_attr(), op_def); if (attr->has_minimum() && attr->minimum() > 0) { prefix = strings::StrCat("A list of at least ", attr->minimum()); } else { prefix = "A list of"; } } else { prefix = strings::StrCat( "A list with the same number of `Tensor` objects as `", AvoidPythonReserved(*original_arg), "` of"); } if (arg.type() != DT_INVALID) { return strings::StrCat(prefix, " `Tensor` objects of type ", TypeString(arg.type(), arg.is_ref()), "."); } else { original_arg = gtl::FindOrNull(inferred_attrs, arg.type_attr()); if (arg.is_ref()) { strings::StrAppend(&prefix, " mutable"); } if (original_arg == nullptr) { return strings::StrCat(prefix, " `Tensor` objects of type ", arg.type_attr(), "."); } else if (*original_arg == arg.name()) { const OpDef::AttrDef* attr = FindAttr(arg.type_attr(), op_def); if (attr->has_allowed_values()) { return strings::StrCat(prefix, " `Tensor` objects of the same type in: ", TypeListString(attr->allowed_values()), "."); } else { return strings::StrCat(prefix, " `Tensor` objects of the same type."); } } else { return strings::StrCat(prefix, " `Tensor` objects of the same type as ", AvoidPythonReserved(*original_arg), "."); } } } else if (!arg.type_attr().empty() || !arg.type_list_attr().empty()) { const bool is_list = !arg.type_list_attr().empty(); const string attr_name = is_list ? arg.type_list_attr() : arg.type_attr(); const OpDef::AttrDef* attr = FindAttr(attr_name, op_def); const string mutable_str = arg.is_ref() ? "mutable " : ""; const string prefix = is_list ? strings::StrCat("A list of ", mutable_str, "`Tensor` objects") : strings::StrCat("A ", mutable_str, "`Tensor`"); const string* original_arg = gtl::FindOrNull(inferred_attrs, attr_name); if (original_arg == nullptr) { return strings::StrCat(prefix, " of type `", attr_name, "`."); } else if (*original_arg == arg.name()) { if (attr->has_allowed_values()) { if (is_list) { return strings::StrCat(prefix, " with types from: ", TypeListString(attr->allowed_values()), "."); } else { return strings::StrCat( prefix, is_output ? ". Has one of the following types: " : ". Must be one of the following types: ", TypeListString(attr->allowed_values()), "."); } } else { return strings::StrCat(prefix, "."); } } else { return strings::StrCat(prefix, is_output ? ". Has the same type as `" : ". Must have the same type as `", AvoidPythonReserved(*original_arg), "`."); } } else { return SingleTensorName(arg.type(), arg.is_ref()); } } static string GetReturns(const OpDef& op_def, const std::vector<string>& output_type_string) { string result; DCHECK_EQ(op_def.output_arg_size(), output_type_string.size()); const int num_outs = op_def.output_arg_size(); strings::Appendf(&result, "\n Returns:\n"); if (num_outs == 0) { strings::Appendf(&result, " The created Operation.\n"); } else { if (num_outs == 1) { StringPiece description = op_def.output_arg(0).description(); if (ConsumeEquals(&description)) { // Skip the generated type info. strings::Appendf(&result, "%s", Indent(4, 4, description).c_str()); } else { // Special case of one output, don't use the name of the output unless // there is no description. string desc = output_type_string.empty() ? kUnknownTensorType : output_type_string[0]; if (desc == kUnknownTensorType) { // Special case where we don't understand how the output tensor type // depends on the input tensor types, just use the output arg // description if we can. if (!description.empty()) { desc = op_def.output_arg(0).description(); } else if (!op_def.output_arg(0).name().empty()) { desc = strings::StrCat(" The ", op_def.output_arg(0).name(), " `Tensor`."); } } else if (!description.empty()) { AppendWithinWidth(&desc, description, kRightMargin - 4 /* indent */); } strings::Appendf(&result, "%s", Indent(4, 4, desc).c_str()); } } else { std::vector<string> out_names(num_outs); for (int i = 0; i < num_outs; ++i) { if (!op_def.output_arg(i).name().empty()) { out_names[i] = op_def.output_arg(i).name(); } else { out_names[i] = strings::StrCat("output", i); } } strings::Appendf(&result, " A tuple of `Tensor` objects (%s).\n", str_util::Join(out_names, ", ").c_str()); for (int i = 0; i < num_outs; ++i) { string desc = strings::StrCat(out_names[i], ": "); StringPiece description = op_def.output_arg(i).description(); if (ConsumeEquals(&description)) { // Skip the generated type info. strings::StrAppend(&desc, description); } else { const string type = static_cast<size_t>(i) < output_type_string.size() ? output_type_string[i] : kUnknownTensorType; if (!description.empty()) { if (type == kUnknownTensorType) { // Special case where we don't understand how the output tensor // type depends on the input tensor types, so we just use the // output arg description. strings::StrAppend(&desc, description); } else { strings::StrAppend(&desc, type, " ", description); } } else { strings::StrAppend(&desc, type); } } strings::Appendf(&result, "%s", Indent(4, 6, desc).c_str()); } } } return result; } string StringToPython(const string& str) { return strings::StrCat("\"", str_util::CEscape(str), "\""); } string DataTypeToPython(DataType dtype) { return strings::StrCat("tf.", PythonDataTypeString(dtype)); } string ShapeToPython(const TensorShapeProto& shape) { string python = "["; for (const auto& dim : shape.dim()) { if (python.size() > 1) strings::StrAppend(&python, ", "); if (!dim.name().empty()) { strings::StrAppend(&python, "(", StringToPython(dim.name()), ", ", dim.size(), ")"); } else { strings::StrAppend(&python, dim.size()); } } strings::StrAppend(&python, "]"); return python; } string AttrListToPython(const AttrValue& value) { string ret; if (value.list().s_size() > 0) { for (int i = 0; i < value.list().s_size(); ++i) { if (i > 0) strings::StrAppend(&ret, ", "); strings::StrAppend(&ret, StringToPython(value.list().s(i))); } } else if (value.list().i_size() > 0) { for (int i = 0; i < value.list().i_size(); ++i) { if (i > 0) strings::StrAppend(&ret, ", "); strings::StrAppend(&ret, value.list().i(i)); } } else if (value.list().f_size() > 0) { for (int i = 0; i < value.list().f_size(); ++i) { if (i > 0) strings::StrAppend(&ret, ", "); strings::StrAppend(&ret, value.list().f(i)); } } else if (value.list().b_size() > 0) { for (int i = 0; i < value.list().b_size(); ++i) { if (i > 0) strings::StrAppend(&ret, ", "); strings::StrAppend(&ret, value.list().b(i) ? "True" : "False"); } } else if (value.list().type_size() > 0) { for (int i = 0; i < value.list().type_size(); ++i) { if (i > 0) strings::StrAppend(&ret, ", "); strings::StrAppend(&ret, DataTypeToPython(value.list().type(i))); } } else if (value.list().shape_size() > 0) { for (int i = 0; i < value.list().shape_size(); ++i) { if (i > 0) strings::StrAppend(&ret, ", "); strings::StrAppend(&ret, ShapeToPython(value.list().shape(i))); } } return ret; } string AttrValueToPython(const string& type, const AttrValue& value) { if (type == "string") { return StringToPython(value.s()); } else if (type == "int") { return strings::StrCat(value.i()); } else if (type == "float") { return strings::StrCat(value.f()); } else if (type == "bool") { return value.b() ? "True" : "False"; } else if (type == "type") { return DataTypeToPython(value.type()); } else if (type == "shape") { return ShapeToPython(value.shape()); } else { return strings::StrCat("[", AttrListToPython(value), "]"); } } static string GetPythonOp(const OpDef& op_def, bool is_hidden, string op_name) { string result; // Map from attr name to the first input arg it is inferred from. std::unordered_map<string, string> inferred_attrs; // This has all the input args followed by those attrs that don't have // defaults. std::vector<string> args_no_default; // The parameters with defaults (these have to be listed after those without). // No input args are included, just attrs and the graph ("g") parameter. std::vector<string> args_with_defaults; for (int i = 0; i < op_def.input_arg_size(); ++i) { const auto& arg(op_def.input_arg(i)); args_no_default.push_back(arg.name()); if (!arg.type_attr().empty()) { gtl::InsertIfNotPresent(&inferred_attrs, arg.type_attr(), arg.name()); } else if (!arg.type_list_attr().empty()) { gtl::InsertIfNotPresent(&inferred_attrs, arg.type_list_attr(), arg.name()); } if (!arg.number_attr().empty()) { gtl::InsertIfNotPresent(&inferred_attrs, arg.number_attr(), arg.name()); } } for (int i = 0; i < op_def.attr_size(); ++i) { const auto& attr(op_def.attr(i)); // Do not add inferred attrs to the Python function signature. if (inferred_attrs.find(attr.name()) == inferred_attrs.end()) { if (attr.has_default_value()) { args_with_defaults.push_back(attr.name()); } else { args_no_default.push_back(attr.name()); } } } // Save the list of attr parameters (attrs that won't be inferred), // those with defaults go at the end. std::vector<string> attrs; // Get the attrs in the order we want by taking the attrs without defaults // from the end of args_no_default, and adding args_no_default (before // "g" gets added to args_no_default, so it only has attrs). attrs.reserve(args_no_default.size() - op_def.input_arg_size() + args_with_defaults.size()); attrs.insert(attrs.end(), args_no_default.begin() + op_def.input_arg_size(), args_no_default.end()); attrs.insert(attrs.end(), args_with_defaults.begin(), args_with_defaults.end()); std::vector<string> param_names; param_names.reserve(args_no_default.size() + args_with_defaults.size()); string parameters; for (const string& name : args_no_default) { if (!parameters.empty()) strings::StrAppend(&parameters, ", "); const string param = AvoidPythonReserved(name); strings::StrAppend(&parameters, param); param_names.push_back(param); } for (const string& name : args_with_defaults) { if (!parameters.empty()) strings::StrAppend(&parameters, ", "); const string param = AvoidPythonReserved(name); strings::StrAppend(&parameters, param, "=None"); param_names.push_back(param); } const bool has_args = args_no_default.size() + args_with_defaults.size() > 0; const string lower_op_name = strings::StrCat(is_hidden ? "_" : "", op_name); // Prepare the list of output names const int num_outs = op_def.output_arg_size(); std::vector<string> out_names(num_outs); for (int i = 0; i < num_outs; ++i) { if (!op_def.output_arg(i).name().empty()) { out_names[i] = op_def.output_arg(i).name(); } else { out_names[i] = strings::StrCat("output", i); } } string out_names_list = strings::StrCat("[\"", str_util::Join(out_names, "\", \""), "\"]"); // Provide the output names as a Python list string lower_op_name_outputs = strings::StrCat("_", lower_op_name, "_outputs"); const string outputs_prefix = strings::StrCat(lower_op_name_outputs, " = "); strings::Appendf( &result, "%s\n", WordWrap(outputs_prefix, out_names_list, kRightMargin).c_str()); strings::Appendf(&result, "\n\n"); // Prepare a NamedTuple type to hold the outputs, if there are multiple if (num_outs > 1) { const string tuple_type_prefix = strings::StrCat("_", op_def.name(), "Output = collections.namedtuple("); const string tuple_type_suffix = strings::StrCat( "\"", op_def.name(), "\", ", lower_op_name_outputs, ")"); strings::Appendf( &result, "%s\n", WordWrap(tuple_type_prefix, tuple_type_suffix, kRightMargin).c_str()); strings::Appendf(&result, "\n\n"); } // Print: def Function(parameters): const string def_prefix = strings::StrCat("def ", lower_op_name, "("); const string def_suffix = strings::StrCat(parameters, has_args ? ", " : "", "name=None):"); strings::Appendf(&result, "%s\n", WordWrap(def_prefix, def_suffix, kRightMargin).c_str()); // Format the Op's descriptions so that it can be a Python docstring. string comment; if (op_def.summary().empty()) { comment = "TODO: add doc.\n"; } else { comment = strings::StrCat(op_def.summary(), "\n"); if (!op_def.description().empty()) { strings::StrAppend(&comment, "\n", Indent(2, 2, op_def.description())); } } strings::Appendf(&result, " r\"\"\"%s\n Args:\n", comment.c_str()); // Inputs for (int i = 0; i < op_def.input_arg_size(); ++i) { const auto& arg(op_def.input_arg(i)); StringPiece description = op_def.input_arg(i).description(); string desc; if (ConsumeEquals(&description)) { // Skip the generated type info. desc = strings::StrCat(param_names[i], ": "); } else { desc = strings::StrCat(param_names[i], ": ", ArgTypeName(op_def, arg, inferred_attrs, false)); } if (!description.empty()) { AppendWithinWidth(&desc, description, kRightMargin - 4 /* indent */); } strings::Appendf(&result, "%s", Indent(4, 6, desc).c_str()); } // Attrs for (const string& name : attrs) { const auto& attr = *FindAttr(name, op_def); string desc = strings::StrCat(AvoidPythonReserved(name), ": "); static const char* const kAttrTypeName[][2] = { {"string", "`string`"}, {"list(string)", "list of `strings`"}, {"int", "`int`"}, {"list(int)", "list of `ints`"}, {"float", "`float`"}, {"list(float)", "list of `floats`"}, {"bool", "`bool`"}, {"list(bool)", "list of `bools`"}, {"type", "`tf.DType`"}, {"list(type)", "list of `tf.DTypes`"}, {"shape", "`tf.TensorShape` or list of `ints`"}, {"list(shape)", "list of shapes (each a `tf.TensorShape` or list of `ints`)"}, }; for (size_t i = 0; i < TF_ARRAYSIZE(kAttrTypeName); ++i) { if (attr.type() == kAttrTypeName[i][0]) { string s; if (attr.has_default_value()) { s = strings::StrCat("optional ", kAttrTypeName[i][1]); } else { s = kAttrTypeName[i][1]; } if (s[0] == 'o' || (s[0] == '`' && (s[1] == 'i' || s[1] == 'o'))) { strings::StrAppend(&desc, "An ", s); } else { strings::StrAppend(&desc, "A ", s); } break; } } if (attr.has_allowed_values()) { strings::StrAppend(&desc, " from: `", AttrListToPython(attr.allowed_values()), "`"); } if (attr.has_minimum()) { if (attr.type() == "int") { strings::StrAppend(&desc, " that is `>= ", attr.minimum(), "`"); } else if (attr.minimum() > 0) { strings::StrAppend(&desc, " that has length `>= ", attr.minimum(), "`"); } } strings::StrAppend(&desc, "."); if (attr.has_default_value()) { strings::StrAppend(&desc, " Defaults to `", AttrValueToPython(attr.type(), attr.default_value()), "`."); } if (!attr.description().empty()) { AppendWithinWidth(&desc, attr.description(), kRightMargin - 4 /* indent */); } strings::Appendf(&result, "%s", Indent(4, 6, desc).c_str()); } strings::Appendf(&result, " name: A name for the operation (optional).\n"); std::vector<string> output_type_string; output_type_string.reserve(op_def.output_arg_size()); for (int i = 0; i < op_def.output_arg_size(); ++i) { output_type_string.push_back( ArgTypeName(op_def, op_def.output_arg(i), inferred_attrs, true)); } strings::StrAppend(&result, GetReturns(op_def, output_type_string)); string return_prefix = strings::StrCat(" result = _op_def_lib.apply_op("); string return_args = strings::StrCat("\"", op_def.name(), "\", "); for (size_t i = 0; i < param_names.size(); ++i) { strings::StrAppend(&return_args, param_names[i], "=", param_names[i], ", "); } strings::StrAppend(&return_args, "name=name)"); strings::Appendf(&result, " \"\"\"\n%s\n", // Wrap the arguments, and indent to the (. WordWrap(return_prefix, return_args, kRightMargin).c_str()); if (num_outs <= 1) { strings::Appendf(&result, " return result\n"); } else { string return_tuple = strings::StrCat(" return _", op_def.name(), "Output._make(result)\n"); strings::Appendf(&result, "%s", return_tuple.c_str()); } strings::Appendf(&result, "\n\n"); return result; } void GenerateLowerCaseOpName(const string& str, string* result) { char joiner = '_'; int last_index = str.size() - 1; for (int i = 0; i <= last_index; ++i) { char c = str[i]; // Emit a joiner only if a previous-lower-to-now-upper or a // now-upper-to-next-lower transition happens. if (isupper(c) && (i > 0)) { if (islower(str[i - 1]) || ((i < last_index) && islower(str[i + 1]))) { result->push_back(joiner); } } result->push_back(tolower(c)); } } } // namespace string GetPythonOps(const OpList& ops, const string& hidden_ops, bool require_shapes) { string result; // Header // TODO(josh11b): Mention the library for which wrappers are being generated. strings::Appendf(&result, R"("""Python wrappers around Brain. This file is MACHINE GENERATED! Do not edit. """ import collections from google.protobuf import text_format from tensorflow.core.framework import op_def_pb2 from tensorflow.python.framework import op_def_registry from tensorflow.python.framework import ops from tensorflow.python.framework import op_def_library )"); std::vector<string> hidden_vec = str_util::Split(hidden_ops, ','); // We'll make a copy of ops that filters out descriptions. OpList cleaned_ops; auto out = cleaned_ops.mutable_op(); out->Reserve(ops.op_size()); for (const auto& op_def : ops.op()) { bool is_hidden = false; for (const string& hidden : hidden_vec) { if (op_def.name() == hidden) { is_hidden = true; break; } } // PrintPythonOp(op_def, is_hidden, op_def.name()); string lower_case_name; GenerateLowerCaseOpName(op_def.name(), &lower_case_name); // When users create custom python wrappers, they may link in the // default op registry by accident, and because they can't // enumerate all 'hidden' symbols, this guard is to prevent // instantiating a python reserved word in their wrapper. if (!is_hidden && IsPythonReserved(lower_case_name)) { continue; } strings::StrAppend(&result, GetPythonOp(op_def, is_hidden, lower_case_name)); if (!require_shapes) { strings::Appendf(&result, "ops.RegisterShape(\"%s\")(None)\n", op_def.name().c_str()); } auto added = out->Add(); *added = op_def; RemoveNonDeprecationDescriptionsFromOpDef(added); } strings::Appendf(&result, R"(def _InitOpDefLibrary(): op_list = op_def_pb2.OpList() text_format.Merge(_InitOpDefLibrary.op_list_ascii, op_list) op_def_registry.register_op_list(op_list) op_def_lib = op_def_library.OpDefLibrary() op_def_lib.add_op_list(op_list) return op_def_lib _InitOpDefLibrary.op_list_ascii = """%s""" _op_def_lib = _InitOpDefLibrary() )", cleaned_ops.DebugString().c_str()); return result; } void PrintPythonOps(const OpList& ops, const string& hidden_ops, bool require_shapes) { printf("%s", GetPythonOps(ops, hidden_ops, require_shapes).c_str()); } string GetAllPythonOps(const char* hidden, bool require_shapes) { OpList ops; OpRegistry::Global()->Export(false, &ops); return GetPythonOps(ops, hidden, require_shapes); } string GetPythonWrappers(const char* op_wrapper_buf, size_t op_wrapper_len) { string op_list_str(op_wrapper_buf, op_wrapper_len); OpList ops; ops.ParseFromString(op_list_str); return GetPythonOps(ops, "", false); } } // namespace tensorflow
{ "pile_set_name": "Github" }
# Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx1536m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true
{ "pile_set_name": "Github" }
package logrus import ( "context" "io" "time" ) var ( // std is the name of the standard logger in stdlib `log` std = New() ) func StandardLogger() *Logger { return std } // SetOutput sets the standard logger output. func SetOutput(out io.Writer) { std.SetOutput(out) } // SetFormatter sets the standard logger formatter. func SetFormatter(formatter Formatter) { std.SetFormatter(formatter) } // SetReportCaller sets whether the standard logger will include the calling // method as a field. func SetReportCaller(include bool) { std.SetReportCaller(include) } // SetLevel sets the standard logger level. func SetLevel(level Level) { std.SetLevel(level) } // GetLevel returns the standard logger level. func GetLevel() Level { return std.GetLevel() } // IsLevelEnabled checks if the log level of the standard logger is greater than the level param func IsLevelEnabled(level Level) bool { return std.IsLevelEnabled(level) } // AddHook adds a hook to the standard logger hooks. func AddHook(hook Hook) { std.AddHook(hook) } // WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. func WithError(err error) *Entry { return std.WithField(ErrorKey, err) } // WithContext creates an entry from the standard logger and adds a context to it. func WithContext(ctx context.Context) *Entry { return std.WithContext(ctx) } // WithField creates an entry from the standard logger and adds a field to // it. If you want multiple fields, use `WithFields`. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithField(key string, value interface{}) *Entry { return std.WithField(key, value) } // WithFields creates an entry from the standard logger and adds multiple // fields to it. This is simply a helper for `WithField`, invoking it // once for each field. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithFields(fields Fields) *Entry { return std.WithFields(fields) } // WithTime creats an entry from the standard logger and overrides the time of // logs generated with it. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithTime(t time.Time) *Entry { return std.WithTime(t) } // Trace logs a message at level Trace on the standard logger. func Trace(args ...interface{}) { std.Trace(args...) } // Debug logs a message at level Debug on the standard logger. func Debug(args ...interface{}) { std.Debug(args...) } // Print logs a message at level Info on the standard logger. func Print(args ...interface{}) { std.Print(args...) } // Info logs a message at level Info on the standard logger. func Info(args ...interface{}) { std.Info(args...) } // Warn logs a message at level Warn on the standard logger. func Warn(args ...interface{}) { std.Warn(args...) } // Warning logs a message at level Warn on the standard logger. func Warning(args ...interface{}) { std.Warning(args...) } // Error logs a message at level Error on the standard logger. func Error(args ...interface{}) { std.Error(args...) } // Panic logs a message at level Panic on the standard logger. func Panic(args ...interface{}) { std.Panic(args...) } // Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatal(args ...interface{}) { std.Fatal(args...) } // Tracef logs a message at level Trace on the standard logger. func Tracef(format string, args ...interface{}) { std.Tracef(format, args...) } // Debugf logs a message at level Debug on the standard logger. func Debugf(format string, args ...interface{}) { std.Debugf(format, args...) } // Printf logs a message at level Info on the standard logger. func Printf(format string, args ...interface{}) { std.Printf(format, args...) } // Infof logs a message at level Info on the standard logger. func Infof(format string, args ...interface{}) { std.Infof(format, args...) } // Warnf logs a message at level Warn on the standard logger. func Warnf(format string, args ...interface{}) { std.Warnf(format, args...) } // Warningf logs a message at level Warn on the standard logger. func Warningf(format string, args ...interface{}) { std.Warningf(format, args...) } // Errorf logs a message at level Error on the standard logger. func Errorf(format string, args ...interface{}) { std.Errorf(format, args...) } // Panicf logs a message at level Panic on the standard logger. func Panicf(format string, args ...interface{}) { std.Panicf(format, args...) } // Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatalf(format string, args ...interface{}) { std.Fatalf(format, args...) } // Traceln logs a message at level Trace on the standard logger. func Traceln(args ...interface{}) { std.Traceln(args...) } // Debugln logs a message at level Debug on the standard logger. func Debugln(args ...interface{}) { std.Debugln(args...) } // Println logs a message at level Info on the standard logger. func Println(args ...interface{}) { std.Println(args...) } // Infoln logs a message at level Info on the standard logger. func Infoln(args ...interface{}) { std.Infoln(args...) } // Warnln logs a message at level Warn on the standard logger. func Warnln(args ...interface{}) { std.Warnln(args...) } // Warningln logs a message at level Warn on the standard logger. func Warningln(args ...interface{}) { std.Warningln(args...) } // Errorln logs a message at level Error on the standard logger. func Errorln(args ...interface{}) { std.Errorln(args...) } // Panicln logs a message at level Panic on the standard logger. func Panicln(args ...interface{}) { std.Panicln(args...) } // Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatalln(args ...interface{}) { std.Fatalln(args...) }
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2011 Eric Niebler Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) This is an auto-generated file. Do not edit! ==============================================================================*/ namespace boost { namespace fusion { template <typename T0> struct vector1; template <typename T0 , typename T1> struct vector2; template <typename T0 , typename T1 , typename T2> struct vector3; template <typename T0 , typename T1 , typename T2 , typename T3> struct vector4; template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4> struct vector5; template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5> struct vector6; template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6> struct vector7; template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7> struct vector8; template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8> struct vector9; template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9> struct vector10; }}
{ "pile_set_name": "Github" }
<html><head><title>検索</title> <LINK REL="stylesheet" TYPE="text/css" HREF="../../sakura.css"> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> </head> <body> <small> Sakura-Editor Macro Reference </small> <h2>検索</h2> <ul> <li><a href = "./S_SearchDialog.html">S_SearchDialog</a></li> <li><a href = "./S_SearchNext.html">S_SearchNext</a></li> <li><a href = "./S_SearchPrev.html">S_SearchPrev</a></li> <li><a href = "./S_ReplaceDialog.html">S_ReplaceDialog</a></li> <li><a href = "./S_Replace.html">S_Replace</a></li> <li><a href = "./S_ReplaceAll.html">S_ReplaceAll</a></li> <li><a href = "./S_SearchClearMark.html">S_SearchClearMark</a></li> <li><a href = "./S_SearchStartPos.html">S_SearchStartPos</a></li> <li><a href = "./S_Grep.html">S_Grep</a></li> <li><a href = "./S_Jump.html">S_Jump</a></li> <li><a href = "./S_Outline.html">S_Outline</a></li> <li><a href = "./S_TagJump.html">S_TagJump</a></li> <li><a href = "./S_TagJumpBack.html">S_TagJumpBack</a></li> <li><a href = "./S_TagMake.html">S_TagMake</a></li> <li><a href = "./S_DirectTagJump.html">S_DirectTagJump</a></li> <li><a href = "./S_Compare.html">S_Compare</a></li> <li><a href = "./S_DiffDialog.html">S_DiffDialog</a></li> <li><a href = "./S_Diff.html">S_Diff</a></li> <li><a href = "./S_DiffNext.html">S_DiffNext</a></li> <li><a href = "./S_DiffPrev.html">S_DiffPrev</a></li> <li><a href = "./S_DiffReset.html">S_DiffReset</a></li> <li><a href = "./S_BracketPair.html">S_BracketPair</a></li> <li><a href = "./S_BookmarkSet.html">S_BookmarkSet</a></li> <li><a href = "./S_BookmarkNext.html">S_BookmarkNext</a></li> <li><a href = "./S_BookmarkPrev.html">S_BookmarkPrev</a></li> <li><a href = "./S_BookmarkReset.html">S_BookmarkReset</a></li> <li><a href = "./S_BookmarkView.html">S_BookmarkView</a></li> <li><a href = "./S_BookmarkPattern.html">S_BookmarkPattern</a></li> </ul> </body></html>
{ "pile_set_name": "Github" }
# file GENERATED by distutils, do NOT edit setup.py tensorboardcolab/__init__.py tensorboardcolab/callbacks.py tensorboardcolab/core.py
{ "pile_set_name": "Github" }
/* * Copyright (c) 2010-2011 Lockheed Martin Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.eurekastreams.web.client.ui.pages.start; import java.util.ArrayList; import java.util.List; import org.eurekastreams.server.action.request.start.RenameTabRequest; import org.eurekastreams.server.domain.GadgetDefinition; import org.eurekastreams.server.domain.Tab; import org.eurekastreams.server.domain.TabTemplate; import org.eurekastreams.web.client.events.GadgetAddedToStartPageEvent; import org.eurekastreams.web.client.events.Observer; import org.eurekastreams.web.client.events.UpdateHistoryEvent; import org.eurekastreams.web.client.events.data.UpdatedStartPageLayoutResponseEvent; import org.eurekastreams.web.client.events.data.UpdatedStartPageTabNameResponseEvent; import org.eurekastreams.web.client.history.CreateUrlRequest; import org.eurekastreams.web.client.jsni.GadgetMetaDataFetcher; import org.eurekastreams.web.client.jsni.WidgetJSNIFacadeImpl; import org.eurekastreams.web.client.model.StartTabsModel; import org.eurekastreams.web.client.ui.Session; import org.eurekastreams.web.client.ui.common.tabs.SimpleTab; import org.eurekastreams.web.client.ui.pages.master.StaticResourceBundle; import org.eurekastreams.web.client.ui.pages.start.layouts.TabLayoutSelectorPanel; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; /** * The start page tab extends the simpletab and adds a menu and the ability to rename, delete, and change layout. * */ public class StartPageTab extends SimpleTab { /** * The tab layout selector panel. */ TabLayoutSelectorPanel tabLayoutSelectorPanel; /** * The textbox the user inserts a new tab name or rename into. */ TextBox textBox = new TextBox(); /** * The domain model object the tabcomposite gets its info from. */ Tab tab = null; /** * The tab menu bar. */ MenuBar menuItems = new MenuBar(true); /** * The menu. */ MenuBar menu = new MenuBar(); /** * JSNI Facade. */ WidgetJSNIFacadeImpl jSNIFacade = new WidgetJSNIFacadeImpl(); /** * The remove item. */ MenuItem removeItem; /** * Am I active? */ boolean isActive = false; /** * No Blur. */ boolean noBlur = false; /** * The empty constructor is used for making a tabcomposite with now tab entity. The result is a tabcomposite with a * new text box in it. */ public StartPageTab() { super("+"); textBox.addStyleName(StaticResourceBundle.INSTANCE.coreCss().newTabTextbox()); textBox.setMaxLength(TabTemplate.MAX_TAB_NAME_LENGTH); getPanel().add(textBox); textBox.setVisible(false); textBox.setText("New Tab"); getFocusPanel().addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { textBox.setText("New Tab"); textBox.setVisible(true); textBox.selectAll(); textBox.setFocus(true); getLabel().setVisible(false); } }); textBox.addBlurHandler(new BlurHandler() { public void onBlur(final BlurEvent event) { if (!noBlur) { StartTabsModel.getInstance().insert(textBox.getText()); } noBlur = false; } }); textBox.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(final KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { noBlur = true; StartTabsModel.getInstance().insert(textBox.getText()); } if (event.getCharCode() == KeyCodes.KEY_ESCAPE) { noBlur = true; textBox.setVisible(false); getLabel().setVisible(true); } } }); } /** * This constructor makes a tabcomposite with a tab entity. * * @param inTab * the domain model object to populate the tab composite with. */ public StartPageTab(final Tab inTab) { super(inTab.getTabName()); setContents(new StartPageTabContent(inTab)); tab = inTab; menu.addItem("X", menuItems); menu.addStyleName(StaticResourceBundle.INSTANCE.coreCss().tabMenu()); getPanel().add(menu); textBox.addStyleName(StaticResourceBundle.INSTANCE.coreCss().newTabTextbox()); textBox.setMaxLength(TabTemplate.MAX_TAB_NAME_LENGTH); textBox.addBlurHandler(new BlurHandler() { public void onBlur(final BlurEvent event) { tab.setTabName(textBox.getText()); StartTabsModel.getInstance().rename(new RenameTabRequest(tab.getId(), textBox.getText())); getPanel().remove(textBox); getPanel().add(getLabel()); getPanel().add(menu); } }); textBox.addKeyUpHandler(new KeyUpHandler() { public void onKeyUp(final KeyUpEvent ev) { if (ev.getNativeKeyCode() == KeyCodes.KEY_ENTER && !ev.isAnyModifierKeyDown()) { tab.setTabName(textBox.getText()); StartTabsModel.getInstance().rename(new RenameTabRequest(tab.getId(), textBox.getText())); } } }); menuItems.addItem("Change Layout", new Command() { public void execute() { ((StartPageTabContent) getContents()).showTabLayoutSelector(); } }); menuItems.addItem("Rename Tab", new Command() { public void execute() { getPanel().remove(getLabel()); getPanel().remove(menu); getPanel().add(textBox); textBox.setText(getLabel().getText()); textBox.setFocus(true); textBox.setSelectionRange(0, textBox.getText().length()); } }); removeItem = new MenuItem("Remove", new Command() { public void execute() { StartTabsModel.getInstance().delete(tab); } }); menuItems.addItem(removeItem); Session.getInstance().getEventBus().addObserver(UpdatedStartPageTabNameResponseEvent.class, new Observer<UpdatedStartPageTabNameResponseEvent>() { public void update(final UpdatedStartPageTabNameResponseEvent event) { if (event.getResponse() == tab.getId()) { getLabel().setText(textBox.getText()); getPanel().remove(textBox); getPanel().add(getLabel()); getPanel().add(menu); } } }); Session.getInstance().getEventBus().addObserver(UpdatedStartPageLayoutResponseEvent.class, new Observer<UpdatedStartPageLayoutResponseEvent>() { public void update(final UpdatedStartPageLayoutResponseEvent event) { if (event.getResponse().getId() == tab.getId()) { ((StartPageTabContent) getContents()).renderGadgetContainer(event.getResponse()); ((StartPageTabContent) getContents()).renderGadgets(); ((StartPageTabContent) getContents()).refreshGadgetMetadata(); } } }); Session.getInstance().getEventBus().addObserver(GadgetAddedToStartPageEvent.class, new Observer<GadgetAddedToStartPageEvent>() { public void update(final GadgetAddedToStartPageEvent event) { if (isActive) { ((StartPageTabContent) getContents()).insertGadget(event.getGadget(), true); Session.getInstance().getEventBus().notifyObservers( new UpdateHistoryEvent(new CreateUrlRequest("action", null, false))); // fetch metadata again to force reevaluation of metadata // (for making sure "edit settings" is hidden, if necessary) List<GadgetDefinition> gadgetDefList = new ArrayList<GadgetDefinition>(); gadgetDefList.add(event.getGadget().getGadgetDefinition()); (new GadgetMetaDataFetcher(gadgetDefList)).fetchMetaData(); } } }); } /** * @return tab the tab. */ public Tab getTab() { return tab; } /** * Disable the remove button. */ public void disableRemove() { menuItems.removeItem(removeItem); } /** * Enable the remove button. */ public void enableRemove() { menuItems.addItem(removeItem); } /** * Set's the tab's CSS style to be inactive. */ @Override public void unSelect() { super.unSelect(); isActive = false; if (getContents() != null && getContents() instanceof StartPageTabContent) { ((StartPageTabContent) getContents()).hideTabLayoutSelector(); } } @Override public void select() { super.select(); isActive = true; Session.getInstance().setPageTitle(tab.getTabName()); if (getContents() != null && getContents() instanceof StartPageTabContent) { ((StartPageTabContent) getContents()).renderGadgets(); if (((StartPageTabContent) getContents()).isAnyGadgetMaximized()) { RootPanel.get().addStyleName(StaticResourceBundle.INSTANCE.coreCss().maximizedGadget()); } else { RootPanel.get().removeStyleName(StaticResourceBundle.INSTANCE.coreCss().maximizedGadget()); } } } @Override public String getIdentifier() { if (tab == null) { return null; } else { return String.valueOf(tab.getId()); } } /** * Get the textbox. * * @return the textbox. */ public TextBox getTextBox() { return textBox; } }
{ "pile_set_name": "Github" }
import Immutable from "immutable"; import PropTypes from "prop-types"; import React, { PureComponent, Component} from "react"; import { Collection, CellMeasurer, CellMeasurerCache, createMasonryCellPositioner, Masonry, AutoSizer, WindowScroller, } from 'react-virtualized'; import styles from 'react-virtualized/styles.css'; // only needs to be imported once import { Card, Image, Header, Divider, Item, Loader, Dimmer, Container, Label, Popup, Segment, Button, Icon, Rating} from 'semantic-ui-react'; import { connect } from "react-redux"; import {fetchAutoAlbumsList} from '../actions/albumsActions' import { BrowserRouter as Router, Route, Link } from 'react-router-dom' import {fetchPeopleAlbums, fetchAutoAlbums, generateAutoAlbums} from '../actions/albumsActions' import {fetchCountStats,fetchPhotoScanStatus, fetchAutoAlbumProcessingStatus} from '../actions/utilActions' import {Server, serverAddress} from '../api_client/apiClient' const month2month = { "01":"January", "02":"February", "03":"March", "04":"April", "05":"May", "06":"June", "07":"July", "08":"August", "09":"September", "10":"October", "11":"November", "12":"December" } export class AlbumsAutoListCardView extends Component { constructor(props){ super(props) this.insertMonthCardsIntoAlbumsList = this.insertMonthCardsIntoAlbumsList.bind(this) } insertMonthCardsIntoAlbumsList(){ var newAlbumsList = [] this.props.albumsAutoList.map(function(album){ if (newAlbumsList.length>0){ var lastMonth = newAlbumsList[newAlbumsList.length-1].timestamp.split('T')[0].split('-').slice(0,2).join('-') var thisMonth = album.timestamp.split('T')[0].split('-').slice(0,2).join('-') if (lastMonth==thisMonth) { newAlbumsList.push(album) } else { newAlbumsList.push(thisMonth) newAlbumsList.push(album) } } else { var newMonth = album.timestamp.split('T')[0].split('-').slice(0,2).join('-') newAlbumsList.push(newMonth) newAlbumsList.push(album) } }) return newAlbumsList } render() { if (this.props.fetchedAlbumsAutoList) { var albumListWithMonthCards = this.insertMonthCardsIntoAlbumsList() return ( <div style={{padding:"10px"}}> <AlbumsAutoListHeader/> <AlbumsAutoListCards albums={albumListWithMonthCards}/> </div> ) } else { return ( <div style={{padding:"10px"}}> <AlbumsAutoListHeader/> <Dimmer active> <Loader active> Loading Event Albums List... Might take a while if not cached in the server. </Loader> </Dimmer> </div> ) } } } export class MonthCard extends Component { render() { return ( <div style={{ width:'150px', height:'300px'}}> <div style={{position:'absolute',top:'100px',textAlign:'center'}}> <Header as='h1'> <Header.Content> {month2month[this.props.month.split('-')[1]]} <Header.Subheader as='h1' textAlign="center"> {this.props.month.split('-')[0]} </Header.Subheader> </Header.Content> </Header> </div> </div> ) } } export class AlbumAutoCard extends Component { render() { var numPeople = this.props.album.people.length var albumId = this.props.album.people.id if (this.props.album.people.length > 0) { var mappedPeopleIcons = this.props.album.people.map(function(person){ return ( <Image height={30} width={30} shape='circular' src={serverAddress+person.face_url}/> ) }) mappedPeopleIcons = ( <Image.Group>{mappedPeopleIcons}</Image.Group> ) } else { // empty placeholder so the extra portion (with face icons) of the cards line up var mappedPeopleIcons = (<div style={{height:'30px', width:'30px', verticalAlign:'middle'}}></div>) } return ( <div style={{ border:'1px solid #dddddd', width:'150px', height:'300px', borderRadius: "0.3rem"}}> <Image as={Link} to={`/albums/autoview/${this.props.album.id}`} height={200} width={150} src={serverAddress+this.props.album.cover_photo_url}/> <div style={{padding:'10px'}}> <span style={{fontSize:'15',fontWeight:'bold'}}>{this.props.album.title}</span><br/> <div style={{paddingTop:'5px'}}> <span style={{color:'grey'}}>{this.props.album.timestamp.split('T')[0]}</span> </div> <div style={{paddingTop:'5px', textAlign:'right',top:'240px',position:'absolute'}}> <span style={{color:'grey',fontWeight:'bold'}}>{this.props.album.photo_count} Photos</span> </div> <div style={{paddingTop:'5px', textAlign:'right',top:'260px',position:'absolute'}}> <Popup trigger={ <span style={{ color:'grey', fontWeight:'bold'}}> {this.props.album.people.length} People </span>} content={mappedPeopleIcons} basic/> </div> <div style={{paddingTop:'5px', textAlign:'right',top:'260px',left:'120px',position:'absolute'}}> <Rating icon='heart' defaultRating={0} maxRating={1} /> </div> </div> </div> ) } } export class AlbumsAutoListHeader extends Component { componentWillMount() { this.props.dispatch(fetchAutoAlbumsList()) var _dispatch = this.props.dispatch var intervalId = setInterval(function(){ _dispatch(fetchPhotoScanStatus()) _dispatch(fetchAutoAlbumProcessingStatus()) },2000 ) this.setState({intervalId:intervalId}) } componentWillUnmount() { clearInterval(this.state.intervalId) } handleAutoAlbumGen = e => this.props.dispatch(generateAutoAlbums()) render() { return ( <div> <div style={{width:'100%', textAlign:'center', paddingTop:'20px'}}> <Icon.Group size='huge'> <Icon inverted circular name='image'/> <Icon inverted circular corner name='wizard'/> </Icon.Group> </div> <Header as='h2' icon textAlign='center'> <Header.Content> Events <Header.Subheader>View automatically generated event albums</Header.Subheader> </Header.Content> </Header> <Divider hidden/> <div> <Button onClick={this.handleAutoAlbumGen} loading={this.props.statusAutoAlbumProcessing.status} disabled={ this.props.statusAutoAlbumProcessing.status|| this.props.statusPhotoScan.status|| this.props.generatingAlbumsAuto|| this.props.scanningPhotos } fluid color='blue'> <Icon name='wizard'/>Generate More </Button> </div> </div> ) } } export class AlbumsAutoListCards extends PureComponent { constructor(props, context) { super(props, context); this._columnCount = 0; this._cache = new CellMeasurerCache({ defaultHeight: 10, defaultWidth: 150, fixedWidth: true }); this._columnHeights = {}; this.state = { columnWidth: 150, height: 200, gutterSize: 10, windowScrollerEnabled: true }; this._cellRenderer = this._cellRenderer.bind(this); this._onResize = this._onResize.bind(this); this._renderAutoSizer = this._renderAutoSizer.bind(this); this._renderMasonry = this._renderMasonry.bind(this); this._setMasonryRef = this._setMasonryRef.bind(this); } render() { const { columnWidth, height, gutterSize, windowScrollerEnabled } = this.state; let child; if (windowScrollerEnabled) { child = ( <WindowScroller> {this._renderAutoSizer} </WindowScroller> ); } else { child = this._renderAutoSizer({ height }); } return ( <div style={{paddingTop:'10px'}}>{child}</div> ); } _calculateColumnCount() { const { columnWidth, gutterSize } = this.state; this._columnCount = Math.floor(this._width / (columnWidth + gutterSize)); } _cellRenderer({ index, key, parent, style }) { const { columnWidth } = this.state; if (typeof(this.props.albums[index])=='object'){ return ( <CellMeasurer cache={this._cache} index={index} key={key} parent={parent}> <div className={styles.Cell} style={{ ...style, width: columnWidth }} > <div style={{ }}/> <AlbumAutoCard album={this.props.albums[index]}/> </div> </CellMeasurer> ); } else { return ( <CellMeasurer cache={this._cache} index={index} key={key} parent={parent}> <div className={styles.Cell} style={{ ...style, width: columnWidth }} > <div style={{ }}/> <MonthCard month={this.props.albums[index]}/> </div> </CellMeasurer> ) } } _initCellPositioner() { if (typeof this._cellPositioner === "undefined") { const { columnWidth, gutterSize } = this.state; this._cellPositioner = createMasonryCellPositioner({ cellMeasurerCache: this._cache, columnCount: this._columnCount, columnWidth, spacer: gutterSize }); } } _onResize({ width }) { this._width = width; this._columnHeights = {}; this._calculateColumnCount(); this._resetCellPositioner(); this._masonry.recomputeCellPositions(); } _renderAutoSizer({ height, scrollTop }) { this._height = height; this._scrollTop = scrollTop; return ( <AutoSizer disableHeight onResize={this._onResize} scrollTop={this._scrollTop} > {this._renderMasonry} </AutoSizer> ); } _renderMasonry({ width }) { this._width = width; this._calculateColumnCount(); this._initCellPositioner(); const { height, windowScrollerEnabled } = this.state; console.log(height) return ( <div style={{paddingLeft:'10px'}}> <Masonry autoHeight={windowScrollerEnabled} cellCount={this.props.albumsAutoList.length} cellMeasurerCache={this._cache} cellPositioner={this._cellPositioner} cellRenderer={this._cellRenderer} height={windowScrollerEnabled ? this._height : height} ref={this._setMasonryRef} scrollTop={this._scrollTop} width={width}/> </div> ); } _resetCellPositioner() { const { columnWidth, gutterSize } = this.state; this._cellPositioner.reset({ columnCount: this._columnCount, columnWidth, spacer: gutterSize }); } _setMasonryRef(ref) { this._masonry = ref; } } AlbumsAutoListCardView = connect((store)=>{ return { albumsAutoList: store.albums.albumsAutoList, fetchingAlbumsAutoList: store.albums.fetchingAlbumsAutoList, fetchedAlbumsAutoList: store.albums.fetchedAlbumsAutoList, generatingAlbumsAuto: store.albums.generatingAlbumsAuto, generatedAlbumsAuto: store.albums.generatedAlbumsAuto, statusAutoAlbumProcessing: store.util.statusAutoAlbumProcessing, statusPhotoScan: store.util.statusPhotoScan, scanningPhotos: store.photos.scanningPhotos, } })(AlbumsAutoListCardView) AlbumsAutoListCards = connect((store)=>{ return { albumsAutoList: store.albums.albumsAutoList, fetchingAlbumsAutoList: store.albums.fetchingAlbumsAutoList, fetchedAlbumsAutoList: store.albums.fetchedAlbumsAutoList, generatingAlbumsAuto: store.albums.generatingAlbumsAuto, generatedAlbumsAuto: store.albums.generatedAlbumsAuto, statusAutoAlbumProcessing: store.util.statusAutoAlbumProcessing, statusPhotoScan: store.util.statusPhotoScan, scanningPhotos: store.photos.scanningPhotos, } })(AlbumsAutoListCards) AlbumsAutoListHeader = connect((store)=>{ return { albumsAutoList: store.albums.albumsAutoList, fetchingAlbumsAutoList: store.albums.fetchingAlbumsAutoList, fetchedAlbumsAutoList: store.albums.fetchedAlbumsAutoList, generatingAlbumsAuto: store.albums.generatingAlbumsAuto, generatedAlbumsAuto: store.albums.generatedAlbumsAuto, statusAutoAlbumProcessing: store.util.statusAutoAlbumProcessing, statusPhotoScan: store.util.statusPhotoScan, scanningPhotos: store.photos.scanningPhotos, } })(AlbumsAutoListHeader)
{ "pile_set_name": "Github" }
package org.springframework.web.filter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * This class doesn't inherits Filter directly.. */ public class RequestContextFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { } protected void doFilterInternal( HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { } }
{ "pile_set_name": "Github" }
package com.haroldadmin.moonshot.services.spacex.v4 import com.haroldadmin.cnradapter.NetworkResponse import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import retrofit2.http.GET import java.time.ZonedDateTime enum class DatePrecision { half, quarter, year, month, day, hour } @JsonClass(generateAdapter = true) data class Launch( @Json(name="id") val id: String, @Json(name="flight_number") val flightNumber: Int, @Json(name="name") val name: String, @Json(name="date_utc") val launchDateUTC: ZonedDateTime, @Json(name="date_local") val launchDateLocal: ZonedDateTime, @Json(name="date_unix") val launchDateUnix: Long, @Json(name="date_precision") val datePrecision: DatePrecision, @Json(name="static_fire_date_utc") val staticFireDateUTC: ZonedDateTime?, @Json(name="static_fire_date_unix") val staticFireDateUnix: Long?, @Json(name="tdb") val tbd: Boolean?, @Json(name="net") val net: Boolean?, @Json(name="window") val window: Int?, @Json(name="rocket") val rocketID: String?, @Json(name="success") val success: Boolean?, @Json(name="failures") val failures: List<String>, @Json(name="upcoming") val upcoming: Boolean, @Json(name="details") val details: String?, @Json(name="fairings") val fairings: Fairings?, @Json(name="crew") val crewIDs: List<String>, @Json(name="ships") val shipIDs: List<String>, @Json(name="capsules") val capsuleIDs: List<String>, @Json(name="payloads") val payloadIDs: List<String>, @Json(name="launchpad") val launchpadID: String?, @Json(name="cores") val cores: List<Core>, @Json(name="links") val links: Links?, @Json(name="auto_update") val autoUpdate: Boolean? ) { @JsonClass(generateAdapter = true) data class Fairings( @Json(name="reused") val reused: Boolean?, @Json(name="recovery_attempt") val recoveryAttempted: Boolean?, @Json(name="recovered") val recovered: Boolean?, @Json(name="ships") val shipIDs: List<String> ) @JsonClass(generateAdapter = true) data class Core( @Json(name="core") val id: String?, @Json(name="flight") val flight: Int?, @Json(name="gridfins") val gridfins: Boolean?, @Json(name="legs") val legs: Boolean?, @Json(name="reused") val reused: Boolean?, @Json(name="landing_attempt") val landingAttempt: Boolean?, @Json(name="landing_success") val landingSuccess: Boolean?, @Json(name="landing_type") val landingType: String?, @Json(name="landpad") val landpadID: String? ) @JsonClass(generateAdapter = true) data class Links( @Json(name="patch") val patch: Patch?, @Json(name="reddit") val reddit: Reddit?, @Json(name="flickr") val flickr: Flickr?, @Json(name="presskit") val presskit: String?, @Json(name="webcast") val webcast: String?, @Json(name="youtube_id") val youtubeID: String?, @Json(name="article") val article: String?, @Json(name="wikipedia") val wikipedia: String? ) { @JsonClass(generateAdapter = true) data class Patch( @Json(name="small") val small: String?, @Json(name="large") val large: String? ) @JsonClass(generateAdapter = true) data class Reddit( @Json(name="campaign") val campaign: String?, @Json(name="launch") val launch: String?, @Json(name="media") val media: String?, @Json(name="recovery") val recovery: String? ) @JsonClass(generateAdapter = true) data class Flickr( @Json(name="small") val small: List<String>, @Json(name="original") val original: List<String> ) } } interface LaunchesService { @GET("launches") suspend fun all(): NetworkResponse<List<Launch>, String> @GET("launches/{id}") suspend fun one(id: String): NetworkResponse<Launch, String> @GET("launches/past") suspend fun past(): NetworkResponse<List<Launch>, String> @GET("launches/upcoming") suspend fun upcoming(): NetworkResponse<List<Launch>, String> @GET("launches/latest") suspend fun latest(): NetworkResponse<Launch, String> @GET("launches/next") suspend fun next(): NetworkResponse<Launch, String> }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { ContainerModule } from "inversify"; import { TYPES } from "../../base/types"; import { CenterCommand, CenterKeyboardListener, FitToScreenCommand } from "./center-fit"; import { ViewportCommand } from "./viewport"; import { ScrollMouseListener } from "./scroll"; import { ZoomMouseListener } from "./zoom"; const viewportModule = new ContainerModule(bind => { bind(TYPES.ICommand).toConstructor(CenterCommand); bind(TYPES.ICommand).toConstructor(FitToScreenCommand); bind(TYPES.ICommand).toConstructor(ViewportCommand); bind(TYPES.KeyListener).to(CenterKeyboardListener); bind(TYPES.MouseListener).to(ScrollMouseListener); bind(TYPES.MouseListener).to(ZoomMouseListener); }); export default viewportModule;
{ "pile_set_name": "Github" }
{ "name": "typescript-action", "version": "0.0.0", "private": true, "description": "TypeScript template action", "main": "lib/main.js", "scripts": { "build": "tsc", "format": "prettier --write **/*.ts", "format-check": "prettier --check **/*.ts", "lint": "eslint src/**/*.ts", "package": "ncc build --source-map --license licenses.txt", "test": "jest", "all": "npm run build && npm run format && npm run lint && npm run package && npm test" }, "repository": { "type": "git", "url": "git+https://github.com/actions/typescript-action.git" }, "keywords": [ "actions", "node", "setup" ], "author": "", "license": "MIT", "dependencies": { "@actions/core": "^1.2.5" }, "devDependencies": { "@types/jest": "^26.0.10", "@types/node": "^14.10.0", "@typescript-eslint/parser": "^3.10.1", "@vercel/ncc": "^0.23.0", "eslint": "^7.8.1", "eslint-plugin-github": "^4.1.1", "eslint-plugin-jest": "^23.20.0", "jest": "^24.9.0", "jest-circus": "^26.4.2", "js-yaml": "^3.14.0", "prettier": "2.1.1", "ts-jest": "^24.3.0", "typescript": "^4.0.2" } }
{ "pile_set_name": "Github" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SimpleStackPanel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SimpleStackPanel")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
{ "pile_set_name": "Github" }
env GO111MODULE=on [short] skip # -mod=readonly must not resolve missing modules nor update go.mod # # TODO(bcmills): 'go list' should suffice, but today it does not fail due to # unresolved imports. When that is fixed, use 'go list' instead of 'go list all'. env GOFLAGS=-mod=readonly go mod edit -fmt cp go.mod go.mod.empty ! go list all stderr 'import lookup disabled by -mod=readonly' cmp go.mod go.mod.empty # update go.mod - go get allowed go get rsc.io/quote grep rsc.io/quote go.mod # update go.mod - go mod tidy allowed cp go.mod.empty go.mod go mod tidy # -mod=readonly must succeed once go.mod is up-to-date... go list # ... even if it needs downloads go clean -modcache go list # -mod=readonly should reject inconsistent go.mod files # (ones that would be rewritten). go mod edit -require rsc.io/[email protected] cp go.mod go.mod.inconsistent ! go list stderr 'go: updates to go.mod needed, disabled by -mod=readonly' cmp go.mod go.mod.inconsistent -- go.mod -- module m go 1.20 -- x.go -- package x import _ "rsc.io/quote"
{ "pile_set_name": "Github" }
#RUN: not llc -march=aarch64 -run-pass=none -verify-machineinstrs -o /dev/null %s 2>&1 | FileCheck %s # REQUIRES: global-isel, aarch64-registered-target --- name: test_select legalized: true regBankSelected: false selected: false tracksRegLiveness: true liveins: body: | bb.0: %0:_(s32) = G_CONSTANT i32 0 %1:_(s32) = G_CONSTANT i32 1 %2:_(s1) = G_CONSTANT i32 0 %3:_(<2 x s32>) = G_IMPLICIT_DEF %4:_(<4 x s32>) = G_IMPLICIT_DEF %5:_(<2 x s1>) = G_IMPLICIT_DEF %6:_(<4 x s1>) = G_IMPLICIT_DEF ; CHECK: Bad machine code: operand types must be all-vector or all-scalar %7:_(s32) = G_SELECT %5, %0, %1 ; CHECK: Bad machine code: operand types must preserve number of vector elements %8:_(<2 x s32>) = G_SELECT %6, %3, %3 ; CHECK: Bad machine code: operand types must preserve number of vector elements %9:_(<4 x s32>) = G_SELECT %5, %4, %4 ...
{ "pile_set_name": "Github" }
#!/usr/bin/env node var argv = require('yargs') .string('x', 'y') .argv ; console.dir([ argv.x, argv.y ]); /* Turns off numeric coercion: ./node string.js -x 000123 -y 9876 [ '000123', '9876' ] */
{ "pile_set_name": "Github" }
// // Copyright (C) OpenSim Ltd. // // 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 // 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/>. // package inet.power.base; import inet.power.contract.ICcEnergyGenerator; // // This is an abstract base module for current based energy generator models. // It defines shared signals and statistics. // // @see ~CcEnergyConsumerBase, ~CcEnergySourceBase, ~CcEnergySinkBase, ~CcEnergyStorageBase // @author Levente Meszaros // simple CcEnergyGeneratorBase like ICcEnergyGenerator { parameters: @display("i=block/plug"); @signal[currentGenerationChanged]; @statistic[currentGeneration](title="Current generation"; source=currentGenerationChanged; record=vector; interpolationmode=sample-hold); }
{ "pile_set_name": "Github" }
.flow-on .mod-pray .dropdown-input{ width: 171px; } .flow-on .mod-pray-h12 .dropdown-input{ width: 131px; } /*TODO find a better solution*/ /*.flow-on .mod-pray .dropdown-list{ width: 201px!important; } .flow-on .mod-pray-h12 .dropdown-list{ width: 162px!important; }*/
{ "pile_set_name": "Github" }
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package flowcontrol import ( "sync" "time" "k8s.io/apimachinery/pkg/util/clock" "k8s.io/utils/integer" ) type backoffEntry struct { backoff time.Duration lastUpdate time.Time } type Backoff struct { sync.RWMutex Clock clock.Clock defaultDuration time.Duration maxDuration time.Duration perItemBackoff map[string]*backoffEntry } func NewFakeBackOff(initial, max time.Duration, tc *clock.FakeClock) *Backoff { return &Backoff{ perItemBackoff: map[string]*backoffEntry{}, Clock: tc, defaultDuration: initial, maxDuration: max, } } func NewBackOff(initial, max time.Duration) *Backoff { return &Backoff{ perItemBackoff: map[string]*backoffEntry{}, Clock: clock.RealClock{}, defaultDuration: initial, maxDuration: max, } } // Get the current backoff Duration func (p *Backoff) Get(id string) time.Duration { p.RLock() defer p.RUnlock() var delay time.Duration entry, ok := p.perItemBackoff[id] if ok { delay = entry.backoff } return delay } // move backoff to the next mark, capping at maxDuration func (p *Backoff) Next(id string, eventTime time.Time) { p.Lock() defer p.Unlock() entry, ok := p.perItemBackoff[id] if !ok || hasExpired(eventTime, entry.lastUpdate, p.maxDuration) { entry = p.initEntryUnsafe(id) } else { delay := entry.backoff * 2 // exponential entry.backoff = time.Duration(integer.Int64Min(int64(delay), int64(p.maxDuration))) } entry.lastUpdate = p.Clock.Now() } // Reset forces clearing of all backoff data for a given key. func (p *Backoff) Reset(id string) { p.Lock() defer p.Unlock() delete(p.perItemBackoff, id) } // Returns True if the elapsed time since eventTime is smaller than the current backoff window func (p *Backoff) IsInBackOffSince(id string, eventTime time.Time) bool { p.RLock() defer p.RUnlock() entry, ok := p.perItemBackoff[id] if !ok { return false } if hasExpired(eventTime, entry.lastUpdate, p.maxDuration) { return false } return p.Clock.Since(eventTime) < entry.backoff } // Returns True if time since lastupdate is less than the current backoff window. func (p *Backoff) IsInBackOffSinceUpdate(id string, eventTime time.Time) bool { p.RLock() defer p.RUnlock() entry, ok := p.perItemBackoff[id] if !ok { return false } if hasExpired(eventTime, entry.lastUpdate, p.maxDuration) { return false } return eventTime.Sub(entry.lastUpdate) < entry.backoff } // Garbage collect records that have aged past maxDuration. Backoff users are expected // to invoke this periodically. func (p *Backoff) GC() { p.Lock() defer p.Unlock() now := p.Clock.Now() for id, entry := range p.perItemBackoff { if now.Sub(entry.lastUpdate) > p.maxDuration*2 { // GC when entry has not been updated for 2*maxDuration delete(p.perItemBackoff, id) } } } func (p *Backoff) DeleteEntry(id string) { p.Lock() defer p.Unlock() delete(p.perItemBackoff, id) } // Take a lock on *Backoff, before calling initEntryUnsafe func (p *Backoff) initEntryUnsafe(id string) *backoffEntry { entry := &backoffEntry{backoff: p.defaultDuration} p.perItemBackoff[id] = entry return entry } // After 2*maxDuration we restart the backoff factor to the beginning func hasExpired(eventTime time.Time, lastUpdate time.Time, maxDuration time.Duration) bool { return eventTime.Sub(lastUpdate) > maxDuration*2 // consider stable if it's ok for twice the maxDuration }
{ "pile_set_name": "Github" }