text
stringlengths
2
99.9k
meta
dict
module.exports = { description: 'using typeof is does not trigger global side-effects' };
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0 // // Copyright (c) 2018 MediaTek Inc. // Author: Weiyi Lu <[email protected]> #include <linux/clk-provider.h> #include <linux/platform_device.h> #include "clk-mtk.h" #include "clk-gate.h" #include <dt-bindings/clock/mt8183-clk.h> static const struct mtk_gate_regs cam_cg_regs = { .set_ofs = 0x4, .clr_ofs = 0x8, .sta_ofs = 0x0, }; #define GATE_CAM(_id, _name, _parent, _shift) \ GATE_MTK(_id, _name, _parent, &cam_cg_regs, _shift, \ &mtk_clk_gate_ops_setclr) static const struct mtk_gate cam_clks[] = { GATE_CAM(CLK_CAM_LARB6, "cam_larb6", "cam_sel", 0), GATE_CAM(CLK_CAM_DFP_VAD, "cam_dfp_vad", "cam_sel", 1), GATE_CAM(CLK_CAM_LARB3, "cam_larb3", "cam_sel", 2), GATE_CAM(CLK_CAM_CAM, "cam_cam", "cam_sel", 6), GATE_CAM(CLK_CAM_CAMTG, "cam_camtg", "cam_sel", 7), GATE_CAM(CLK_CAM_SENINF, "cam_seninf", "cam_sel", 8), GATE_CAM(CLK_CAM_CAMSV0, "cam_camsv0", "cam_sel", 9), GATE_CAM(CLK_CAM_CAMSV1, "cam_camsv1", "cam_sel", 10), GATE_CAM(CLK_CAM_CAMSV2, "cam_camsv2", "cam_sel", 11), GATE_CAM(CLK_CAM_CCU, "cam_ccu", "cam_sel", 12), }; static int clk_mt8183_cam_probe(struct platform_device *pdev) { struct clk_onecell_data *clk_data; struct device_node *node = pdev->dev.of_node; clk_data = mtk_alloc_clk_data(CLK_CAM_NR_CLK); mtk_clk_register_gates(node, cam_clks, ARRAY_SIZE(cam_clks), clk_data); return of_clk_add_provider(node, of_clk_src_onecell_get, clk_data); } static const struct of_device_id of_match_clk_mt8183_cam[] = { { .compatible = "mediatek,mt8183-camsys", }, {} }; static struct platform_driver clk_mt8183_cam_drv = { .probe = clk_mt8183_cam_probe, .driver = { .name = "clk-mt8183-cam", .of_match_table = of_match_clk_mt8183_cam, }, }; builtin_platform_driver(clk_mt8183_cam_drv);
{ "pile_set_name": "Github" }
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QLOGGINGCATEGORY_H #define QLOGGINGCATEGORY_H #include <QtCore/qglobal.h> #include <QtCore/qdebug.h> QT_BEGIN_NAMESPACE class Q_CORE_EXPORT QLoggingCategory { Q_DISABLE_COPY(QLoggingCategory) public: // ### Qt 6: Merge constructors explicit QLoggingCategory(const char *category); QLoggingCategory(const char *category, QtMsgType severityLevel); ~QLoggingCategory(); bool isEnabled(QtMsgType type) const; void setEnabled(QtMsgType type, bool enable); #ifdef Q_ATOMIC_INT8_IS_SUPPORTED bool isDebugEnabled() const { return bools.enabledDebug.load(); } bool isInfoEnabled() const { return bools.enabledInfo.load(); } bool isWarningEnabled() const { return bools.enabledWarning.load(); } bool isCriticalEnabled() const { return bools.enabledCritical.load(); } #else bool isDebugEnabled() const { return enabled.load() >> DebugShift & 1; } bool isInfoEnabled() const { return enabled.load() >> InfoShift & 1; } bool isWarningEnabled() const { return enabled.load() >> WarningShift & 1; } bool isCriticalEnabled() const { return enabled.load() >> CriticalShift & 1; } #endif const char *categoryName() const { return name; } // allows usage of both factory method and variable in qCX macros QLoggingCategory &operator()() { return *this; } const QLoggingCategory &operator()() const { return *this; } static QLoggingCategory *defaultCategory(); typedef void (*CategoryFilter)(QLoggingCategory*); static CategoryFilter installFilter(CategoryFilter); static void setFilterRules(const QString &rules); private: void init(const char *category, QtMsgType severityLevel); Q_DECL_UNUSED_MEMBER void *d; // reserved for future use const char *name; #ifdef Q_BIG_ENDIAN enum { DebugShift = 0, WarningShift = 8, CriticalShift = 16, InfoShift = 24 }; #else enum { DebugShift = 24, WarningShift = 16, CriticalShift = 8, InfoShift = 0}; #endif struct AtomicBools { #ifdef Q_ATOMIC_INT8_IS_SUPPORTED QBasicAtomicInteger<bool> enabledDebug; QBasicAtomicInteger<bool> enabledWarning; QBasicAtomicInteger<bool> enabledCritical; QBasicAtomicInteger<bool> enabledInfo; #endif }; union { AtomicBools bools; QBasicAtomicInt enabled; }; Q_DECL_UNUSED_MEMBER bool placeholder[4]; // reserved for future use }; #define Q_DECLARE_LOGGING_CATEGORY(name) \ extern const QLoggingCategory &name(); #if defined(Q_COMPILER_VARIADIC_MACROS) || defined(Q_MOC_RUN) #define Q_LOGGING_CATEGORY(name, ...) \ const QLoggingCategory &name() \ { \ static const QLoggingCategory category(__VA_ARGS__); \ return category; \ } #define qCDebug(category, ...) \ for (bool qt_category_enabled = category().isDebugEnabled(); qt_category_enabled; qt_category_enabled = false) \ QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, category().categoryName()).debug(__VA_ARGS__) #define qCInfo(category, ...) \ for (bool qt_category_enabled = category().isInfoEnabled(); qt_category_enabled; qt_category_enabled = false) \ QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, category().categoryName()).info(__VA_ARGS__) #define qCWarning(category, ...) \ for (bool qt_category_enabled = category().isWarningEnabled(); qt_category_enabled; qt_category_enabled = false) \ QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, category().categoryName()).warning(__VA_ARGS__) #define qCCritical(category, ...) \ for (bool qt_category_enabled = category().isCriticalEnabled(); qt_category_enabled; qt_category_enabled = false) \ QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, category().categoryName()).critical(__VA_ARGS__) #else // defined(Q_COMPILER_VARIADIC_MACROS) || defined(Q_MOC_RUN) // Optional msgType argument not supported #define Q_LOGGING_CATEGORY(name, string) \ const QLoggingCategory &name() \ { \ static const QLoggingCategory category(string); \ return category; \ } // check for enabled category inside QMessageLogger. #define qCDebug qDebug #define qCInfo qInfo #define qCWarning qWarning #define qCCritical qCritical #endif // Q_COMPILER_VARIADIC_MACROS || defined(Q_MOC_RUN) #if defined(QT_NO_DEBUG_OUTPUT) # undef qCDebug # define qCDebug(category) QT_NO_QDEBUG_MACRO() #endif #if defined(QT_NO_INFO_OUTPUT) # undef qCInfo # define qCInfo(category) QT_NO_QDEBUG_MACRO() #endif #if defined(QT_NO_WARNING_OUTPUT) # undef qCWarning # define qCWarning(category) QT_NO_QDEBUG_MACRO() #endif QT_END_NAMESPACE #endif // QLOGGINGCATEGORY_H
{ "pile_set_name": "Github" }
/* * Copyright (c) 2018, Texas Instruments Incorporated - http://www.ti.com/ * 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 the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT 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. */ /** * \addtogroup cc13xx-cc26xx-cpu * @{ * * \file * Startup file for GCC for CC13xx/CC26xx. */ /*---------------------------------------------------------------------------*/ /* Check if compiler is GNU Compiler. */ #if !(defined(__GNUC__)) #error "startup_cc13xx_cc26xx_gcc.c: Unsupported compiler!" #endif /*---------------------------------------------------------------------------*/ #include <string.h> #include <ti/devices/DeviceFamily.h> #include DeviceFamily_constructPath(inc/hw_types.h) #include DeviceFamily_constructPath(driverlib/interrupt.h) #include DeviceFamily_constructPath(driverlib/setup.h) /*---------------------------------------------------------------------------*/ /* Forward declaration of the default fault handlers. */ void resetISR(void); static void nmiISR(void); static void faultISR(void); static void defaultHandler(void); static void busFaultHandler(void); /*---------------------------------------------------------------------------*/ /* * External declaration for the reset handler that is to be called when the * processor is started. */ extern void _c_int00(void); /* The entry point for the application. */ extern int main(void); /*---------------------------------------------------------------------------*/ /* Linker variable that marks the top of stack. */ extern unsigned long _stack_end; /* * The vector table. Note that the proper constructs must be placed on this to * ensure that it ends up at physical address 0x0000.0000. */ __attribute__((section(".resetVecs"))) __attribute__((used)) static void(*const resetVectors[16])(void) = { (void(*)(void))((uint32_t)&_stack_end), /* The initial stack pointer */ resetISR, /* The reset handler */ nmiISR, /* The NMI handler */ faultISR, /* The hard fault handler */ defaultHandler, /* The MPU fault handler */ busFaultHandler, /* The bus fault handler */ defaultHandler, /* The usage fault handler */ 0, /* Reserved */ 0, /* Reserved */ 0, /* Reserved */ 0, /* Reserved */ defaultHandler, /* SVCall handler */ defaultHandler, /* Debug monitor handler */ 0, /* Reserved */ defaultHandler, /* The PendSV handler */ defaultHandler /* The SysTick handler */ }; /*---------------------------------------------------------------------------*/ /* * The following are arrays of pointers to constructor functions that need to * be called during startup to initialize global objects. */ extern void (*__init_array_start[])(void); extern void (*__init_array_end[])(void); /* The following global variable is required for C++ support. */ void *__dso_handle = (void *)&__dso_handle; /*---------------------------------------------------------------------------*/ /* * The following are constructs created by the linker, indicating where the * the "data" and "bss" segments reside in memory. The initializers for the * for the "data" segment resides immediately following the "text" segment. */ extern uint32_t __bss_start__; extern uint32_t __bss_end__; extern uint32_t __data_load__; extern uint32_t __data_start__; extern uint32_t __data_end__; /*---------------------------------------------------------------------------*/ /* * \brief Entry point of the startup code. * * Initialize the .data and .bss sections, and call main. */ void localProgramStart(void) { uint32_t *bs; uint32_t *be; uint32_t *dl; uint32_t *ds; uint32_t *de; uint32_t count; uint32_t i; IntMasterDisable(); /* Final trim of device */ SetupTrimDevice(); /* initiailize .bss to zero */ bs = &__bss_start__; be = &__bss_end__; while(bs < be) { *bs = 0; bs++; } /* relocate the .data section */ dl = &__data_load__; ds = &__data_start__; de = &__data_end__; if(dl != ds) { while(ds < de) { *ds = *dl; dl++; ds++; } } /* Run any constructors */ count = (uint32_t)(__init_array_end - __init_array_start); for(i = 0; i < count; i++) { __init_array_start[i](); } /* Call the application's entry point. */ main(); /* If we ever return signal Error */ faultISR(); } /*---------------------------------------------------------------------------*/ /* * \brief Reset ISR. * * This is the code that gets called when the processor first starts execution * following a reset event. Only the absolutely necessary set is performed, * after which the application supplied entry() routine is called. Any fancy * actions (such as making decisions based on the reset cause register, and * resetting the bits in that register) are left solely in the hands of the * application. */ void __attribute__((naked)) resetISR(void) { __asm__ __volatile__ ( "movw r0, #:lower16:resetVectors \n" "movt r0, #:upper16:resetVectors \n" "ldr r0, [r0] \n" "mov sp, r0 \n" "bx %0 \n" : /* output */ : /* input */ "r"(localProgramStart) ); } /*---------------------------------------------------------------------------*/ /* * \brief Non-Maskable Interrupt (NMI) ISR. * * This is the code that gets called when the processor receives a NMI. This * simply enters an infinite loop, preserving the system state for examination * by a debugger. */ static void nmiISR(void) { /* Enter an infinite loop. */ for(;;) { /* hang */ } } /*---------------------------------------------------------------------------*/ /* * \brief Debug stack pointer. * \param sp Stack pointer. * * Provide a view into the CPU state from the provided stack pointer. */ static void debugHardfault(uint32_t *sp) { volatile uint32_t r0; /**< R0 register */ volatile uint32_t r1; /**< R1 register */ volatile uint32_t r2; /**< R2 register */ volatile uint32_t r3; /**< R3 register */ volatile uint32_t r12; /**< R12 register */ volatile uint32_t lr; /**< LR register */ volatile uint32_t pc; /**< PC register */ volatile uint32_t psr; /**< PSR register */ (void)(r0 = sp[0]); (void)(r1 = sp[1]); (void)(r2 = sp[2]); (void)(r3 = sp[3]); (void)(r12 = sp[4]); (void)(lr = sp[5]); (void)(pc = sp[6]); (void)(psr = sp[7]); /* Enter an infinite loop. */ for(;;) { /* hang */ } } /*---------------------------------------------------------------------------*/ /* * \brief CPU Fault ISR. * * This is the code that gets called when the processor receives a fault * interrupt. Setup a call to debugStackPointer with the current stack pointer. * The stack pointer in this case would be the CPU state which caused the CPU * fault. */ static void faultISR(void) { __asm__ __volatile__ ( "tst lr, #4 \n" "ite eq \n" "mrseq r0, msp \n" "mrsne r0, psp \n" "bx %0 \n" : /* output */ : /* input */ "r"(debugHardfault) ); } /*---------------------------------------------------------------------------*/ /* Dummy variable */ volatile int x__; /* * \brief Bus Fault Handler. * * This is the code that gets called when the processor receives an unexpected * interrupt. This simply enters an infinite loop, preserving the system state * for examination by a debugger. */ static void busFaultHandler(void) { x__ = 0; /* Enter an infinite loop. */ for(;;) { /* hang */ } } /*---------------------------------------------------------------------------*/ /* * \brief Default Handler. * * This is the code that gets called when the processor receives an unexpected * interrupt. This simply enters an infinite loop, preserving the system state * for examination by a debugger. */ static void defaultHandler(void) { /* Enter an infinite loop. */ for(;;) { /* hang */ } } /*---------------------------------------------------------------------------*/ /* * \brief Finalize object function. * * This function is called by __libc_fini_array which gets called when exit() * is called. In order to support exit(), an empty _fini() stub function is * required. */ void _fini(void) { /* Function body left empty intentionally */ } /*---------------------------------------------------------------------------*/ /** @} */
{ "pile_set_name": "Github" }
KMail is a state-of-the-art email client that integrates well with widely used email providers like GMail. It provides many tools and features to maximize your productivity and makes working with large email accounts easy and fast. KMail supports a large variety of email protocols - POP3, IMAP, Microsoft Exchange (EWS) and more.
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package charmap import ( "testing" "golang.org/x/text/encoding" "golang.org/x/text/encoding/internal" "golang.org/x/text/encoding/internal/enctest" "golang.org/x/text/transform" ) func dec(e encoding.Encoding) (dir string, t transform.Transformer, err error) { return "Decode", e.NewDecoder(), nil } func encASCIISuperset(e encoding.Encoding) (dir string, t transform.Transformer, err error) { return "Encode", e.NewEncoder(), internal.ErrASCIIReplacement } func encEBCDIC(e encoding.Encoding) (dir string, t transform.Transformer, err error) { return "Encode", e.NewEncoder(), internal.RepertoireError(0x3f) } func TestNonRepertoire(t *testing.T) { testCases := []struct { init func(e encoding.Encoding) (string, transform.Transformer, error) e encoding.Encoding src, want string }{ {dec, Windows1252, "\x81", "\ufffd"}, {encEBCDIC, CodePage037, "갂", ""}, {encEBCDIC, CodePage1047, "갂", ""}, {encEBCDIC, CodePage1047, "a¤갂", "\x81\x9F"}, {encEBCDIC, CodePage1140, "갂", ""}, {encEBCDIC, CodePage1140, "a€갂", "\x81\x9F"}, {encASCIISuperset, Windows1252, "갂", ""}, {encASCIISuperset, Windows1252, "a갂", "a"}, {encASCIISuperset, Windows1252, "\u00E9갂", "\xE9"}, } for _, tc := range testCases { dir, tr, wantErr := tc.init(tc.e) dst, _, err := transform.String(tr, tc.src) if err != wantErr { t.Errorf("%s %v(%q): got %v; want %v", dir, tc.e, tc.src, err, wantErr) } if got := string(dst); got != tc.want { t.Errorf("%s %v(%q):\ngot %q\nwant %q", dir, tc.e, tc.src, got, tc.want) } } } func TestBasics(t *testing.T) { testCases := []struct { e encoding.Encoding encoded string utf8 string }{{ e: CodePage037, encoded: "\xc8\x51\xba\x93\xcf", utf8: "Hé[lõ", }, { e: CodePage437, encoded: "H\x82ll\x93 \x9d\xa7\xf4\x9c\xbe", utf8: "Héllô ¥º⌠£╛", }, { e: CodePage866, encoded: "H\xf3\xd3o \x98\xfd\x9f\xdd\xa1", utf8: "Hє╙o Ш¤Я▌б", }, { e: CodePage1047, encoded: "\xc8\x54\x93\x93\x9f", utf8: "Hèll¤", }, { e: CodePage1140, encoded: "\xc8\x9f\x93\x93\xcf", utf8: "H€llõ", }, { e: ISO8859_2, encoded: "Hel\xe5\xf5", utf8: "Helĺő", }, { e: ISO8859_3, encoded: "He\xbd\xd4", utf8: "He½Ô", }, { e: ISO8859_4, encoded: "Hel\xb6\xf8", utf8: "Helļø", }, { e: ISO8859_5, encoded: "H\xd7\xc6o", utf8: "HзЦo", }, { e: ISO8859_6, encoded: "Hel\xc2\xc9", utf8: "Helآة", }, { e: ISO8859_7, encoded: "H\xeel\xebo", utf8: "Hξlλo", }, { e: ISO8859_8, encoded: "Hel\xf5\xed", utf8: "Helץם", }, { e: ISO8859_9, encoded: "\xdeayet", utf8: "Şayet", }, { e: ISO8859_10, encoded: "H\xea\xbfo", utf8: "Hęŋo", }, { e: ISO8859_13, encoded: "H\xe6l\xf9o", utf8: "Hęlło", }, { e: ISO8859_14, encoded: "He\xfe\xd0o", utf8: "HeŷŴo", }, { e: ISO8859_15, encoded: "H\xa4ll\xd8", utf8: "H€llØ", }, { e: ISO8859_16, encoded: "H\xe6ll\xbd", utf8: "Hællœ", }, { e: KOI8R, encoded: "He\x93\xad\x9c", utf8: "He⌠╜°", }, { e: KOI8U, encoded: "He\x93\xad\x9c", utf8: "He⌠ґ°", }, { e: Macintosh, encoded: "He\xdf\xd7", utf8: "Hefl◊", }, { e: MacintoshCyrillic, encoded: "He\xbe\x94", utf8: "HeЊФ", }, { e: Windows874, encoded: "He\xb7\xf0", utf8: "Heท๐", }, { e: Windows1250, encoded: "He\xe5\xe5o", utf8: "Heĺĺo", }, { e: Windows1251, encoded: "H\xball\xfe", utf8: "Hєllю", }, { e: Windows1252, encoded: "H\xe9ll\xf4 \xa5\xbA\xae\xa3\xd0", utf8: "Héllô ¥º®£Ð", }, { e: Windows1253, encoded: "H\xe5ll\xd6", utf8: "HεllΦ", }, { e: Windows1254, encoded: "\xd0ello", utf8: "Ğello", }, { e: Windows1255, encoded: "He\xd4o", utf8: "Heװo", }, { e: Windows1256, encoded: "H\xdbllo", utf8: "Hغllo", }, { e: Windows1257, encoded: "He\xeflo", utf8: "Heļlo", }, { e: Windows1258, encoded: "Hell\xf5", utf8: "Hellơ", }, { e: XUserDefined, encoded: "\x00\x40\x7f\x80\xab\xff", utf8: "\u0000\u0040\u007f\uf780\uf7ab\uf7ff", }} for _, tc := range testCases { enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, "", "") } } var windows1255TestCases = []struct { b byte ok bool r rune }{ {'\x00', true, '\u0000'}, {'\x1a', true, '\u001a'}, {'\x61', true, '\u0061'}, {'\x7f', true, '\u007f'}, {'\x80', true, '\u20ac'}, {'\x95', true, '\u2022'}, {'\xa0', true, '\u00a0'}, {'\xc0', true, '\u05b0'}, {'\xfc', true, '\ufffd'}, {'\xfd', true, '\u200e'}, {'\xfe', true, '\u200f'}, {'\xff', true, '\ufffd'}, {encoding.ASCIISub, false, '\u0400'}, {encoding.ASCIISub, false, '\u2603'}, {encoding.ASCIISub, false, '\U0001f4a9'}, } func TestDecodeByte(t *testing.T) { for _, tc := range windows1255TestCases { if !tc.ok { continue } got := Windows1255.DecodeByte(tc.b) want := tc.r if got != want { t.Errorf("DecodeByte(%#02x): got %#08x, want %#08x", tc.b, got, want) } } } func TestEncodeRune(t *testing.T) { for _, tc := range windows1255TestCases { // There can be multiple tc.b values that map to tc.r = '\ufffd'. if tc.r == '\ufffd' { continue } gotB, gotOK := Windows1255.EncodeRune(tc.r) wantB, wantOK := tc.b, tc.ok if gotB != wantB || gotOK != wantOK { t.Errorf("EncodeRune(%#08x): got (%#02x, %t), want (%#02x, %t)", tc.r, gotB, gotOK, wantB, wantOK) } } } func TestFiles(t *testing.T) { enctest.TestFile(t, Windows1252) } func BenchmarkEncoding(b *testing.B) { enctest.Benchmark(b, Windows1252) }
{ "pile_set_name": "Github" }
# defusedxml # # Copyright (c) 2013 by Christian Heimes <[email protected]> # Licensed to PSF under a Contributor Agreement. # See https://www.python.org/psf/license for licensing details. """Defused xml.sax.expatreader """ from __future__ import print_function, absolute_import from xml.sax.expatreader import ExpatParser as _ExpatParser from .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden __origin__ = "xml.sax.expatreader" class DefusedExpatParser(_ExpatParser): """Defused SAX driver for the pyexpat C module.""" def __init__( self, namespaceHandling=0, bufsize=2 ** 16 - 20, forbid_dtd=False, forbid_entities=True, forbid_external=True, ): _ExpatParser.__init__(self, namespaceHandling, bufsize) self.forbid_dtd = forbid_dtd self.forbid_entities = forbid_entities self.forbid_external = forbid_external def defused_start_doctype_decl(self, name, sysid, pubid, has_internal_subset): raise DTDForbidden(name, sysid, pubid) def defused_entity_decl( self, name, is_parameter_entity, value, base, sysid, pubid, notation_name ): raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name) def defused_unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): # expat 1.2 raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name) # pragma: no cover def defused_external_entity_ref_handler(self, context, base, sysid, pubid): raise ExternalReferenceForbidden(context, base, sysid, pubid) def reset(self): _ExpatParser.reset(self) parser = self._parser if self.forbid_dtd: parser.StartDoctypeDeclHandler = self.defused_start_doctype_decl if self.forbid_entities: parser.EntityDeclHandler = self.defused_entity_decl parser.UnparsedEntityDeclHandler = self.defused_unparsed_entity_decl if self.forbid_external: parser.ExternalEntityRefHandler = self.defused_external_entity_ref_handler def create_parser(*args, **kwargs): return DefusedExpatParser(*args, **kwargs)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <module type="WEB_MODULE" version="4"> <component name="NewModuleRootManager"> <content url="file://$MODULE_DIR$"> <excludeFolder url="file://$MODULE_DIR$/.babel-cache" /> <excludeFolder url="file://$MODULE_DIR$/.cache" /> <excludeFolder url="file://$MODULE_DIR$/.idea" /> <excludeFolder url="file://$MODULE_DIR$/.pub" /> <excludeFolder url="file://$MODULE_DIR$/build" /> <excludeFolder url="file://$MODULE_DIR$/dist" /> <excludeFolder url="file://$MODULE_DIR$/legacy" /> <excludeFolder url="file://$MODULE_DIR$/node_modules" /> <excludeFolder url="file://$MODULE_DIR$/packages" /> <excludeFolder url="file://$MODULE_DIR$/static/dist" /> <excludeFolder url="file://$MODULE_DIR$/template/static" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Dart SDK" level="application" /> <orderEntry type="library" name="Timings Modules" level="project" /> <orderEntry type="library" name="lodash-DefinitelyTyped" level="application" /> </component> </module>
{ "pile_set_name": "Github" }
%% Translation of GIT committish: 7073ab2d033f82eb797d6fcefd3cd18c98fb3d63 texidocit = " Per ridurre la dimensione del cerchio di @code{\\flageolet}, usare la seguente funzione Scheme. " doctitleit = "Modifica della dimensione del segno di \\flageolet"
{ "pile_set_name": "Github" }
package com.akexorcist.googledirection.util import com.akexorcist.googledirection.DirectionCallback import com.akexorcist.googledirection.model.Direction import com.akexorcist.googledirection.request.DirectionRequest import com.akexorcist.googledirection.request.DirectionTask /** * Kotlin extension method for direction request execution. * * @param onDirectionSuccess The function of the successful direction request. * @param onDirectionFailure The function of the failure direction request. * @return The task for direction request. * @since 1.2.0 */ fun DirectionRequest.execute( onDirectionSuccess: ((Direction?) -> Unit)? = null, onDirectionFailure: ((Throwable) -> Unit)? = null ): DirectionTask = execute(object : DirectionCallback { override fun onDirectionSuccess(direction: Direction?) { onDirectionSuccess?.invoke(direction) } override fun onDirectionFailure(t: Throwable) { onDirectionFailure?.invoke(t) } })
{ "pile_set_name": "Github" }
{ "_args": [ [ { "raw": "mkdirp@^0.5.0", "scope": null, "escapedName": "mkdirp", "name": "mkdirp", "rawSpec": "^0.5.0", "spec": ">=0.5.0 <0.6.0", "type": "range" }, "/Users/chengwei/kafka-doc-zh/doc/zh/node_modules/vinyl-fs" ] ], "_from": "mkdirp@>=0.5.0 <0.6.0", "_id": "[email protected]", "_inCache": true, "_location": "/mkdirp", "_nodeVersion": "2.0.0", "_npmUser": { "name": "substack", "email": "[email protected]" }, "_npmVersion": "2.9.0", "_phantomChildren": {}, "_requested": { "raw": "mkdirp@^0.5.0", "scope": null, "escapedName": "mkdirp", "name": "mkdirp", "rawSpec": "^0.5.0", "spec": ">=0.5.0 <0.6.0", "type": "range" }, "_requiredBy": [ "/vinyl-fs" ], "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", "_shasum": "30057438eac6cf7f8c4767f38648d6697d75c903", "_shrinkwrap": null, "_spec": "mkdirp@^0.5.0", "_where": "/Users/chengwei/kafka-doc-zh/doc/zh/node_modules/vinyl-fs", "author": { "name": "James Halliday", "email": "[email protected]", "url": "http://substack.net" }, "bin": { "mkdirp": "bin/cmd.js" }, "bugs": { "url": "https://github.com/substack/node-mkdirp/issues" }, "dependencies": { "minimist": "0.0.8" }, "description": "Recursively mkdir, like `mkdir -p`", "devDependencies": { "mock-fs": "2 >=2.7.0", "tap": "1" }, "directories": {}, "dist": { "shasum": "30057438eac6cf7f8c4767f38648d6697d75c903", "tarball": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz" }, "gitHead": "d4eff0f06093aed4f387e88e9fc301cb76beedc7", "homepage": "https://github.com/substack/node-mkdirp#readme", "keywords": [ "mkdir", "directory" ], "license": "MIT", "main": "index.js", "maintainers": [ { "name": "substack", "email": "[email protected]" } ], "name": "mkdirp", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/substack/node-mkdirp.git" }, "scripts": { "test": "tap test/*.js" }, "version": "0.5.1" }
{ "pile_set_name": "Github" }
make_vala_find_vapi_files() { # XDG_DATA_DIRS: required for finding .vapi files if [ -d "$1/share/vala/vapi" -o -d "$1/share/vala-@apiVersion@/vapi" ]; then addToSearchPath XDG_DATA_DIRS $1/share fi } addEnvHooks "$hostOffset" make_vala_find_vapi_files _multioutMoveVapiDirs() { moveToOutput share/vala/vapi "${!outputDev}" moveToOutput share/vala-@apiVersion@/vapi "${!outputDev}" } preFixupHooks+=(_multioutMoveVapiDirs)
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <title>API documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap.min.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/prettify.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap-responsive.min.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/application.css'/> <!-- IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container-fluid"> <div class="row-fluid"> <div id='container'> <ul class='breadcrumb'> <li> <a href='../../../apidoc/v2.en.html'>Foreman v2</a> <span class='divider'>/</span> </li> <li> <a href='../../../apidoc/v2/domains.en.html'> Domains </a> <span class='divider'>/</span> </li> <li class='active'>index</li> <li class='pull-right'> &nbsp;[ <a href="../../../apidoc/v2/domains/index.ca.html">ca</a> | <a href="../../../apidoc/v2/domains/index.cs_CZ.html">cs_CZ</a> | <a href="../../../apidoc/v2/domains/index.de.html">de</a> | <b><a href="../../../apidoc/v2/domains/index.en.html">en</a></b> | <a href="../../../apidoc/v2/domains/index.en_GB.html">en_GB</a> | <a href="../../../apidoc/v2/domains/index.es.html">es</a> | <a href="../../../apidoc/v2/domains/index.fr.html">fr</a> | <a href="../../../apidoc/v2/domains/index.gl.html">gl</a> | <a href="../../../apidoc/v2/domains/index.it.html">it</a> | <a href="../../../apidoc/v2/domains/index.ja.html">ja</a> | <a href="../../../apidoc/v2/domains/index.ko.html">ko</a> | <a href="../../../apidoc/v2/domains/index.nl_NL.html">nl_NL</a> | <a href="../../../apidoc/v2/domains/index.pl.html">pl</a> | <a href="../../../apidoc/v2/domains/index.pt_BR.html">pt_BR</a> | <a href="../../../apidoc/v2/domains/index.ru.html">ru</a> | <a href="../../../apidoc/v2/domains/index.sv_SE.html">sv_SE</a> | <a href="../../../apidoc/v2/domains/index.zh_CN.html">zh_CN</a> | <a href="../../../apidoc/v2/domains/index.zh_TW.html">zh_TW</a> ] </li> </ul> <div class='page-header'> <h1> GET /api/domains <br> <small>List of domains</small> </h1> </div> <div class='page-header'> <h1> GET /api/subnets/:subnet_id/domains <br> <small>List of domains per subnet</small> </h1> </div> <div class='page-header'> <h1> GET /api/locations/:location_id/domains <br> <small>List of domains per location</small> </h1> </div> <div class='page-header'> <h1> GET /api/organizations/:organization_id/domains <br> <small>List of domains per organization</small> </h1> </div> <div> <h2>Params</h2> <table class='table'> <thead> <tr> <th>Param name</th> <th>Description</th> </tr> </thead> <tbody> <tr style='background-color:rgb(255,255,255);'> <td> <strong>subnet_id </strong><br> <small> optional </small> </td> <td> <p>ID of subnet</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a String</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>location_id </strong><br> <small> optional </small> </td> <td> <p>Scope by locations</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a Integer</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>organization_id </strong><br> <small> optional </small> </td> <td> <p>Scope by organizations</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a Integer</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>search </strong><br> <small> optional </small> </td> <td> <p>filter results</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a String</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>order </strong><br> <small> optional </small> </td> <td> <p>Sort field and order, eg. ‘id DESC’</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a String</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>page </strong><br> <small> optional </small> </td> <td> <p>Page number, starting at 1</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a number.</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>per_page </strong><br> <small> optional </small> </td> <td> <p>Number of results per page to return</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a number.</p> </li> </ul> </td> </tr> </tbody> </table> <h2>Search fields</h2> <table class='table'> <thead> <tr> <th width="20%">Field name</th> <th width="20%">Type</th> <th width="60%">Possible values</th> </tr> </thead> <tbody> <tr> <td>fullname</td> <td>string</td> <td></td> </tr> <tr> <td>location</td> <td>string</td> <td></td> </tr> <tr> <td>location_id</td> <td>integer</td> <td></td> </tr> <tr> <td>name</td> <td>string</td> <td></td> </tr> <tr> <td>organization</td> <td>string</td> <td></td> </tr> <tr> <td>organization_id</td> <td>integer</td> <td></td> </tr> <tr> <td>params</td> <td>text</td> <td></td> </tr> </tbody> </table> </div> </div> </div> <hr> <footer></footer> </div> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/jquery.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/bootstrap-collapse.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/prettify.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/apipie.js'></script> </body> </html>
{ "pile_set_name": "Github" }
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ import { TestP, TestRoot } from '../test'; import { itIntegrates } from '../testIntegrationUtils'; describe('threads', () => { itIntegrates('paused', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); p.cdp.Runtime.evaluate({ expression: 'debugger;' }); await p.dap.once('stopped'); p.log(await p.dap.threads({})); p.assertLog(); }); itIntegrates('not paused', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); p.log(await p.dap.threads({})); p.assertLog(); }); describe('stepping', () => { itIntegrates('basic', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); p.evaluate(` function bar() { return 2; } function foo() { debugger; bar(); bar(); } foo(); `); const { threadId } = p.log(await p.dap.once('stopped')); await p.logger.logStackTrace(threadId); p.log('\nstep over'); p.dap.next({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nstep over'); p.dap.next({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nstep in'); p.dap.stepIn({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nstep out'); p.dap.stepOut({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nresume'); p.dap.continue({ threadId }); p.log(await p.dap.once('continued')); p.assertLog(); }); itIntegrates('cross thread', async ({ r }) => { const p = await r.launchUrlAndLoad('worker.html'); p.cdp.Runtime.evaluate({ expression: `debugger;\nwindow.w.postMessage('message')\n//# sourceURL=test.js`, }); const { threadId } = p.log(await p.dap.once('stopped')); await p.logger.logStackTrace(threadId); p.log('\nstep over'); p.dap.next({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nstep in'); p.dap.stepIn({ threadId }); p.log(await p.dap.once('continued')); const worker = await r.worker(); const { threadId: secondThreadId } = p.log(await worker.dap.once('stopped')); await worker.logger.logStackTrace(secondThreadId); p.log('\nresume'); worker.dap.continue({ threadId: secondThreadId }); p.log(await worker.dap.once('continued')); p.assertLog(); }); itIntegrates('cross thread constructor', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); p.cdp.Runtime.evaluate({ expression: ` debugger; window.w = new Worker('worker.js');\n//# sourceURL=test.js`, }); const { threadId } = p.log(await p.dap.once('stopped')); await p.logger.logStackTrace(threadId); p.log('\nstep over'); p.dap.next({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nstep in'); p.dap.stepIn({ threadId }); p.log(await p.dap.once('continued')); const worker = await r.worker(); const { threadId: secondThreadId } = p.log(await worker.dap.once('stopped')); await worker.logger.logStackTrace(secondThreadId); p.log('\nresume'); worker.dap.continue({ threadId: secondThreadId }); p.log(await worker.dap.once('continued')); p.assertLog(); }); itIntegrates('cross thread skip over tasks', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); p.cdp.Runtime.evaluate({ expression: ` window.p = new Promise(f => window.cb = f); debugger; p.then(() => { var a = 1; // should stop here }); window.w = new Worker('worker.js'); window.w.postMessage('hey'); window.w.addEventListener('message', () => window.cb()); \n//# sourceURL=test.js`, }); const { threadId } = p.log(await p.dap.once('stopped')); await p.logger.logStackTrace(threadId); p.log('\nstep over'); p.dap.next({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nstep in'); p.dap.stepIn({ threadId }); p.log(await p.dap.once('continued')); const { threadId: secondThreadId } = p.log(await p.dap.once('stopped')); await p.logger.logStackTrace(secondThreadId); p.log('\nresume'); p.dap.continue({ threadId: secondThreadId }); p.log(await p.dap.once('continued')); p.assertLog(); }); const runCrossThreadTest = async (r: TestRoot, p: TestP) => { p.cdp.Runtime.evaluate({ expression: `debugger;\nwindow.w = new Worker('workerSourceMap.js');\n//# sourceURL=test.js`, }); const { threadId } = p.log(await p.dap.once('stopped')); await p.logger.logStackTrace(threadId); p.log('\nstep over'); p.dap.next({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nstep in'); p.dap.stepIn({ threadId }); p.log(await p.dap.once('continued')); const worker = await r.worker(); const { threadId: secondThreadId } = p.log(await worker.dap.once('stopped')); await worker.logger.logStackTrace(secondThreadId); p.log('\nresume'); worker.dap.continue({ threadId: secondThreadId }); p.log(await worker.dap.once('continued')); p.assertLog(); }; itIntegrates('cross thread constructor source map', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); await runCrossThreadTest(r, p); }); itIntegrates('cross thread constructor source map predicted', async ({ r }) => { // the call path is different when an instrumentation breakpoint is present, // set a breakpoint to ensure with add the instrumentation bp as well. const p = await r.launchUrlAndLoad('index.html'); await p.dap.setBreakpoints({ source: { path: p.workspacePath('web/does-not-exist.html') }, breakpoints: [{ line: 1, column: 1 }], }); await runCrossThreadTest(r, p); }); itIntegrates('cross thread source map', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); p.cdp.Runtime.evaluate({ expression: ` window.w = new Worker('workerSourceMap.js'); debugger; window.w.postMessage('hey');\n//# sourceURL=test.js`, }); const { threadId } = p.log(await p.dap.once('stopped')); await p.logger.logStackTrace(threadId); p.log('\nstep over'); p.dap.next({ threadId }); p.log(await Promise.all([p.dap.once('continued'), p.dap.once('stopped')])); await p.logger.logStackTrace(threadId); p.log('\nstep in'); p.dap.stepIn({ threadId }); p.log(await p.dap.once('continued')); const worker = await r.worker(); const { threadId: secondThreadId } = p.log(await worker.dap.once('stopped')); await worker.logger.logStackTrace(secondThreadId); p.log('\nresume'); worker.dap.continue({ threadId: secondThreadId }); p.log(await worker.dap.once('continued')); p.assertLog(); }); }); describe('pause on exceptions', () => { async function waitForPauseOnException(p: TestP) { const event = p.log(await p.dap.once('stopped')); p.log(await p.dap.exceptionInfo({ threadId: event.threadId })); p.log(await p.dap.continue({ threadId: event.threadId })); } itIntegrates('cases', async ({ r }) => { const p = await r.launchAndLoad('blank'); p.log('Not pausing on exceptions'); await p.dap.setExceptionBreakpoints({ filters: [] }); await p.evaluate(`setTimeout(() => { throw new Error('hello'); })`); await p.evaluate(`setTimeout(() => { try { throw new Error('hello'); } catch (e) {}})`); p.log('Pausing on uncaught exceptions'); await p.dap.setExceptionBreakpoints({ filters: ['uncaught'] }); await p.evaluate(`setTimeout(() => { try { throw new Error('hello'); } catch (e) {}})`); p.evaluate(`setTimeout(() => { throw new Error('hello'); })`); await waitForPauseOnException(p); p.log('Pausing on caught exceptions'); await p.dap.setExceptionBreakpoints({ filters: ['caught'] }); p.evaluate(`setTimeout(() => { throw new Error('hello'); })`); await waitForPauseOnException(p); p.evaluate(`setTimeout(() => { try { throw new Error('hello'); } catch (e) {}})`); await waitForPauseOnException(p); p.assertLog(); }); itIntegrates('configuration', async ({ r }) => { const p = await r.launch(` <script> try { throw new Error('this error is caught'); } catch (e) { } throw new Error('this error is uncaught'); </script> `); await p.dap.setExceptionBreakpoints({ filters: ['uncaught'] }); p.load(); await waitForPauseOnException(p); p.assertLog(); }); }); });
{ "pile_set_name": "Github" }
package org.openintents.filemanager.test; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.provider.DocumentsContract; import android.view.View; import androidx.test.espresso.Espresso; import androidx.test.espresso.assertion.ViewAssertions; import androidx.test.espresso.intent.rule.IntentsTestRule; import androidx.test.espresso.matcher.ViewMatchers; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.openintents.filemanager.FileManagerActivity; import org.openintents.filemanager.view.PathBar; @RunWith(AndroidJUnit4.class) public class TestViewFolderIntent { @Rule public IntentsTestRule<FileManagerActivity> rule = new IntentsTestRule<>(FileManagerActivity.class, true, false); @Test public void testViewDownloadFolder() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setType(DocumentsContract.Document.MIME_TYPE_DIR); String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); intent.putExtra("org.openintents.extra.ABSOLUTE_PATH", path); rule.launchActivity(intent); Espresso.onView(ViewMatchers.withId(org.openintents.filemanager.R.id.pathbar)).check(ViewAssertions.matches(isShowingPath(path))); } @Test public void testNullPath() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setType(DocumentsContract.Document.MIME_TYPE_DIR); intent.putExtra("org.openintents.extra.ABSOLUTE_PATH", (String) null); rule.launchActivity(intent); // assert is showing toast } @Test public void testInvalidPath() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setType(DocumentsContract.Document.MIME_TYPE_DIR); intent.putExtra("org.openintents.extra.ABSOLUTE_PATH", "/xyz"); rule.launchActivity(intent); // assert is showing toast } @Test public void testFileUriPath() { String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(path)); rule.launchActivity(intent); Espresso.onView(ViewMatchers.withId(org.openintents.filemanager.R.id.pathbar)).check(ViewAssertions.matches(isShowingPath(path))); } private Matcher<? super View> isShowingPath(final String path) { return new BaseMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("PathBar shows " + path); } @Override public boolean matches(Object item) { if (item != null && item.getClass() == PathBar.class) { return (((PathBar) item).getCurrentDirectory().getAbsolutePath().equalsIgnoreCase(path)); } else { return false; } } }; } }
{ "pile_set_name": "Github" }
# 1.1.1 (2016-06-22) - add more context to errors if they are not instanceof Error # 1.1.0 (2015-09-29) - add Emitter#listerCount (to match node v4 api) # 1.0.2 (2014-08-28) - remove un-reachable code - update devDeps ## 1.0.1 / 2014-05-11 - check for console.trace before using it ## 1.0.0 / 2013-12-10 - Update to latest events code from node.js 0.10 - copy tests from node.js ## 0.4.0 / 2011-07-03 ## - Switching to [email protected] ## 0.3.0 / 2011-07-03 ## - Switching to URL based module require. ## 0.2.0 / 2011-06-10 ## - Simplified package structure. - Graphquire for dependency management. ## 0.1.1 / 2011-05-16 ## - Unhandled errors are logged via console.error ## 0.1.0 / 2011-04-22 ## - Initial release
{ "pile_set_name": "Github" }
1 ;-------------------------------------------------------- 2 ; File Created by SDCC : FreeWare ANSI-C Compiler 3 ; Version 2.3.1 Wed Sep 04 21:56:20 2019 4 5 ;-------------------------------------------------------- 6 .module strncmp 7 8 ;-------------------------------------------------------- 9 ; Public variables in this module 10 ;-------------------------------------------------------- 11 .globl _strncmp 12 ;-------------------------------------------------------- 13 ; special function registers 14 ;-------------------------------------------------------- 15 ;-------------------------------------------------------- 16 ; special function bits 17 ;-------------------------------------------------------- 18 ;-------------------------------------------------------- 19 ; internal ram data 20 ;-------------------------------------------------------- 21 .area _DATA 22 ;-------------------------------------------------------- 23 ; overlayable items in internal ram 24 ;-------------------------------------------------------- 25 .area _OVERLAY 26 ;-------------------------------------------------------- 27 ; indirectly addressable internal ram data 28 ;-------------------------------------------------------- 29 .area _ISEG 30 ;-------------------------------------------------------- 31 ; bit data 32 ;-------------------------------------------------------- 33 .area _BSEG 34 ;-------------------------------------------------------- 35 ; external ram data 36 ;-------------------------------------------------------- 37 .area _XSEG 38 ;-------------------------------------------------------- 39 ; global & static initialisations 40 ;-------------------------------------------------------- 41 .area _GSINIT 42 .area _GSFINAL 43 .area _GSINIT 44 ;-------------------------------------------------------- 45 ; Home 46 ;-------------------------------------------------------- 47 .area _HOME 48 ; strncmp.c 10 49 ; genLabel 50 ; genFunction 51 ; --------------------------------- 52 ; Function strncmp 53 ; --------------------------------- 0000 54 ___strncmp_start: 0000 55 _strncmp: 0000 E8 FC 56 lda sp,-4(sp) 57 ; strncmp.c 12 58 ; genAssign 59 ; (operands are equal 3) 60 ; genAssign 61 ; (operands are equal 3) 62 ; genAssign 63 ; (operands are equal 3) 64 ; genLabel 0002 65 00104$: 66 ; genCmpGt 67 ; AOP_STK for 0002 1E 80 68 ld e,#0x80 0004 F8 0B 69 lda hl,11(sp) 0006 7E 70 ld a,(hl) 0007 EE 80 71 xor a,#0x80 0009 57 72 ld d,a 000A 3E 00 73 ld a,#0x00 000C 2B 74 dec hl 000D 96 75 sub a,(hl) 000E 7B 76 ld a,e 000F 9A 77 sbc a,d 0010 D2r54s00 78 jp nc,00106$ 79 ; genPointerGet 80 ; AOP_STK for 0013 F8 06 81 lda hl,6(sp) 0015 5E 82 ld e,(hl) 0016 23 83 inc hl 0017 56 84 ld d,(hl) 0018 1A 85 ld a,(de) 0019 4F 86 ld c,a 87 ; genPointerGet 88 ; AOP_STK for 001A 23 89 inc hl 001B 5E 90 ld e,(hl) 001C 23 91 inc hl 001D 56 92 ld d,(hl) 001E 1A 93 ld a,(de) 001F 47 94 ld b,a 95 ; genPlus 96 ; AOP_STK for 97 ; genPlusIncr 0020 2B 98 dec hl 0021 34 99 inc (hl) 0022 20 02 100 jr nz,00116$ 0024 23 101 inc hl 0025 34 102 inc (hl) 0026 103 00116$: 104 ; genAssign 105 ; (operands are equal 4) 106 ; genCmpEq 107 ; genCmpEq: left 1, right 1, result 0 0026 79 108 ld a,c 0027 B8 109 cp b 0028 C2r54s00 110 jp nz,00106$ 002B 18 03 111 jr 00118$ 002D 112 00117$: 002D C3r54s00 113 jp 00106$ 0030 114 00118$: 115 ; strncmp.c 13 116 ; genPlus 117 ; AOP_STK for 118 ; genPlusIncr 0030 F8 06 119 lda hl,6(sp) 0032 34 120 inc (hl) 0033 20 02 121 jr nz,00119$ 0035 23 122 inc hl 0036 34 123 inc (hl) 0037 124 00119$: 125 ; genAssign 126 ; (operands are equal 4) 127 ; genCmpEq 128 ; genCmpEq: left 1, right 1, result 0 0037 79 129 ld a,c 0038 B7 130 or a,a 0039 C2r47s00 131 jp nz,00102$ 003C 18 03 132 jr 00121$ 003E 133 00120$: 003E C3r47s00 134 jp 00102$ 0041 135 00121$: 136 ; strncmp.c 14 137 ; genRet 0041 11 00 00 138 ld de,#0x0000 0044 C3r99s00 139 jp 00107$ 140 ; genLabel 0047 141 00102$: 142 ; strncmp.c 15 143 ; genMinus 144 ; AOP_STK for 0047 F8 0A 145 lda hl,10(sp) 0049 5E 146 ld e,(hl) 004A 23 147 inc hl 004B 56 148 ld d,(hl) 004C 1B 149 dec de 004D 2B 150 dec hl 004E 73 151 ld (hl),e 004F 23 152 inc hl 0050 72 153 ld (hl),d 154 ; genAssign 155 ; (operands are equal 4) 156 ; genGoto 0051 C3r02s00 157 jp 00104$ 158 ; genLabel 0054 159 00106$: 160 ; strncmp.c 17 161 ; genCmpEq 162 ; AOP_STK for 163 ; genCmpEq: left 2, right 2, result 0 0054 F8 0A 164 lda hl,10(sp) 0056 2A 165 ld a,(hl+) 0057 B6 166 or a,(hl) 0058 C2r67s00 167 jp nz,00109$ 005B 18 03 168 jr 00123$ 005D 169 00122$: 005D C3r67s00 170 jp 00109$ 0060 171 00123$: 172 ; genAssign 173 ; AOP_STK for _strncmp_sloc2_1_0 0060 F8 00 174 lda hl,0(sp) 0062 36 00 175 ld (hl),#0x00 176 ; genGoto 0064 C3r90s00 177 jp 00110$ 178 ; genLabel 0067 179 00109$: 180 ; genAssign 181 ; AOP_STK for 182 ; AOP_STK for _strncmp_sloc0_1_0 0067 F8 06 183 lda hl,6(sp) 0069 2A 184 ld a,(hl+) 006A 5E 185 ld e,(hl) 006B F8 02 186 lda hl,2(sp) 006D 22 187 ld (hl+),a 006E 73 188 ld (hl),e 189 ; genPointerGet 190 ; AOP_STK for _strncmp_sloc0_1_0 191 ; AOP_STK for _strncmp_sloc1_1_0 006F 2B 192 dec hl 0070 5E 193 ld e,(hl) 0071 23 194 inc hl 0072 56 195 ld d,(hl) 0073 1A 196 ld a,(de) 0074 2B 197 dec hl 0075 2B 198 dec hl 0076 77 199 ld (hl),a 200 ; genMinus 201 ; AOP_STK for 0077 F8 08 202 lda hl,8(sp) 0079 5E 203 ld e,(hl) 007A 23 204 inc hl 007B 56 205 ld d,(hl) 007C 21 01 00 206 ld hl,#0x0001 007F 7B 207 ld a,e 0080 95 208 sub a,l 0081 5F 209 ld e,a 0082 7A 210 ld a,d 0083 9C 211 sbc a,h 0084 4F 212 ld c,a 0085 43 213 ld b,e 214 ; genPointerGet 0086 58 215 ld e,b 0087 51 216 ld d,c 0088 1A 217 ld a,(de) 0089 47 218 ld b,a 219 ; genMinus 220 ; AOP_STK for _strncmp_sloc1_1_0 221 ; AOP_STK for _strncmp_sloc2_1_0 008A F8 01 222 lda hl,1(sp) 008C 7E 223 ld a,(hl) 008D 90 224 sub a,b 008E 2B 225 dec hl 008F 77 226 ld (hl),a 227 ; genLabel 0090 228 00110$: 229 ; genCast 230 ; AOP_STK for _strncmp_sloc2_1_0 0090 F8 00 231 lda hl,0(sp) 0092 4E 232 ld c,(hl) 0093 7E 233 ld a,(hl) 0094 17 234 rla 0095 9F 235 sbc a,a 0096 47 236 ld b,a 237 ; genRet 0097 59 238 ld e,c 0098 50 239 ld d,b 240 ; genLabel 0099 241 00107$: 242 ; genEndFunction 0099 E8 04 243 lda sp,4(sp) 009B C9 244 ret 009C 245 ___strncmp_end: 246 .area _CODE 247 ;-------------------------------------------------------- 248 ; code 249 ;-------------------------------------------------------- 250 .area _CODE 251 .area _CODE
{ "pile_set_name": "Github" }
# Copyright 2018 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. FROM scratch LABEL maintainer "[email protected]" COPY ca-certificates.crt /etc/ssl/certs/ COPY h2demo / ENTRYPOINT ["/h2demo", "-prod"]
{ "pile_set_name": "Github" }
import { normalize } from '../ts'; import * as vm from 'vm'; function normalizeEquiv(original: string) { let compiled = normalize(original); expect(compiled.trim()).not.toEqual(original.trim()); let originalResult = vm.runInNewContext(original); let normalizedResult = vm.runInNewContext(compiled); // Sanity check: a test that produces undefined is unlikely to be useful. expect(originalResult).not.toBe(undefined); expect(normalizedResult).toEqual(originalResult); return compiled; } test('simple for loop', () => { normalizeEquiv(` let r = 0; for (let i = 0; i < 3; i++) { r = r + i; } r; `); }); test('for loop without block body', () => { normalizeEquiv(` let r = 0; for (let i = 0; i < 3; i++) { r = r + i; } r; `); }); test('ternary short-circuit', () => { let compiled = normalizeEquiv(` function foo() { throw 'This should not be called' } true ? 1 : foo() `); // Sanity check: ? should not be in output. expect(compiled.indexOf('?')).toBe(-1); }); test('ternary left method call short-circuit', () => { normalizeEquiv(` let x = 0; let y = 0; function foo() { x++; return { bar() { y++; } } } let r = true ? foo().bar() : false; ({ x: x, y: y }); `); }); test('conjunction and function call in loop guard', () => { normalizeEquiv(` let i = 0; let j = 6; function f() { return (i++ % 2) === 0; } while (f() && j++) { } ({ i: i, j: j }); `); }); test('and should evaluate its LHS just once', () => { normalizeEquiv(` var count = 0; function f() { count++; return false; } var tmp = f() && true; ({ count: count }); `); }); test('applications in array literal must be evaluated in order', () => { normalizeEquiv(` function foo() { let counter = 0; function bar() { return ++counter; } return [ counter, bar(), bar(), ]; } var r = foo(); r; `); }); test('simple for .. in loop', () => { normalizeEquiv(` const obj = { a: 0, b: 1, c: 2, }; let r = [ ]; for (const prop in obj) { r.push(obj[prop]); } r; `); }); test('using var like let*', () => { normalizeEquiv(` var a = { x: 100 }, y = a.x; y === 100; `); }); test('left-to-right evaluation of +: application on LHS', () => { normalizeEquiv(` let x = 1; function a() { x += 1; return 1; } a() + x; `); }); test.skip('left-to-right evaluation of +: application on RHS', () => { normalizeEquiv(` let x = 1; function a() { x += 1; return 1; } x + a(); `); }); test('left-to-right evaluation of +: application on both sides', () => { normalizeEquiv(` let x = 1; function a() { x += 1; return 1; } function b() { x *= 10; return 2; } a() + b(); `); }); test('and short-circuiting: method call on RHS', () => { normalizeEquiv(` let x = 0; let y = 0; function foo() { x++; return { bar() { y++; } } } false && foo().bar(); ({ x: x, y: y }); `); }); test('and not short-circuiting: method call on RHS', () => { normalizeEquiv(` let x = 0; let y = 0; function foo() { x++; return { bar() { y++; } } } true && foo().bar(); ({ x: x, y: y }); `); }); test('assignments in sequence expression', () => { normalizeEquiv(` function g() { return 1; } function f(x) { var y = x; var dummy = g(), z = y; return z; }; var r = f(100); r; `); }); test('break in for loop', () => { normalizeEquiv(` let sum = 0; for(let i = 0; i < 5; i++) { sum += i; if (i === 3) break; } sum; `); }); test('function declaration hoisting (based on code generated by Dart2js)', () => { // TODO(arjun): This test should produce something. normalizeEquiv(` let r = (function () { function Isolate() { } init(); function init() { Isolate.$isolateProperties = Object.create(null); Isolate.$finishIsolateConstructor = function (oldIsolate) { var isolateProperties = oldIsolate.$isolateProperties; function Isolate() { } Isolate.$isolateProperties = isolateProperties; return Isolate; }; } Isolate = Isolate.$finishIsolateConstructor(Isolate); })(); true; `); }); test('function declaration hoisting (also based on code generated by Dart2js)', () => { normalizeEquiv(` function Isolate() { } var init = function() { Date.now(); Isolate.method = function (oldIsolate) { return 50; }; } init(); Isolate = Isolate.method(Isolate); Isolate; `); }); test('nested ternary expressions', () => { normalizeEquiv(` function Foo() {} function Bar() {} function Baz() {} function foo() { const o = {}; return (o.left instanceof Foo) ? new Baz(o.left.error) : ((o.right instanceof Bar) ? new Baz(o.right.error) : 7); } var r = foo(); r; `); }); test('short-circuiting with && and ||', () => { normalizeEquiv(` const f = false; let x = 0; f && (x++ === 7); f || (x++ === 7); x; `); }); test('left-to-right evaluation: application in second argument assigns to variable referenced in first argument', () => { normalizeEquiv(` function foo() { let counter = 0; function bar(c1, c2) { ++counter; return c1; } return bar(counter, bar(counter)); } let r = foo(); r; `); }); test('computed method call', () => { normalizeEquiv(` function foo() { return 7; } let r = foo['call']({}); r; `); }); test('switch fallthrough test', () => { normalizeEquiv(` let test = 'test'; let test2; switch (test) { case 'baz': test = 'baz'; case 'test': case 'foo': case 'bar': test2 = test; default: test = 'baz'; } ({ test: test, test2: test2 }); `); }); test('local variable with the same name as the enclosing function', () => { normalizeEquiv(` var BAR = function BAR2() { while(false); } var x = function FOO() { var FOO = 100; BAR(); return FOO; } let r = x(); r; `); }); test('pointless: calling increment', () => { normalizeEquiv(` function inc(x) { return x + 1; } const a = (function (x, y) { return inc(x) + inc(y) })(1, 2) a; `); }); test('continue to a label in a for loop', () => { normalizeEquiv(` let i = 0; l: for (let j = 0; j < 10; j++) { if (j % 2 === 0) { i++; do { continue l; } while (0); i++; } } i; `); }); test('continue to a label in a nested loop', () => { normalizeEquiv(` var i = 0; var j = 8; checkiandj: while (i < 4) { i += 1; checkj: while (j > 4) { j -= 1; if ((j % 2) === 0) { i = 5; continue checkj; } } } ({i: i, j: j}); `); }); test('continue to a label in a nested loop', () => { normalizeEquiv(` var i = 0; var j = 8; checkiandj: while (i < 4) { i += 1; checkj: while (j > 4) { j -= 1; if ((j % 2) === 0) { i = 5; continue checkiandj; } } } ({i: i, j: j}); `); }); test('applications in object literal', () => { normalizeEquiv(` function foo() { let counter = 0; function bar() { return ++counter; } return { a: counter, b: bar(), c: bar() }; } const o = foo(); o; `); }); test('|| short-circuiting: method call on RHS with true on LHS', () => { // TODO(arjun): Ensure we don't trivially simplify true || X to true. normalizeEquiv(` function foo() { throw 'bad'; return { bar() { throw 'very bad'; } }; } true || foo().bar(); true; `); }); test('|| short-circuiting: method call on RHS with false on LHS', () => { // TODO(arjun): Ensure we don't trivially simplify false || X to X. normalizeEquiv(` let x = 0; let y = 0; function foo() { x++; return { bar() { y++; } } } false || foo().bar(); ({ x: x, y: y }); `); }); test('sequencing expression in loop guard', () => { normalizeEquiv(` var i = 0; var j = 0; var loop = true; while(i = i + 1, loop) { j = j + 1; loop = j < 2; } i; `); }); test('sequencing with application in loop guard', () => { normalizeEquiv(` var x = 0; var r; function AFUNCTION() { x++; r = x < 2; } while(AFUNCTION(), r) { } x; `); }); test('sequencing: applications occur in order', () => { normalizeEquiv(` var i = 0; let j = 0; let k = 0; function f() { j = i; i = 1; } function g() { k = i; i = 2; } function h() { return f(), g(), i; } h(); ({ i: i, j: j, k: k }); `); }); test('switch in a while loop', () => { normalizeEquiv(` const tst = 'foo'; let x = 0; let i = 0; while (i++ < 10) { switch (tst) { case 'bar': throw 'A'; break; case 'foo': { x++; break; } default: throw 'B'; } if (i !== x) { throw 'C'; } } x; `); }); test('break out of while(true)', () => { normalizeEquiv(` let i = 0; while (true) { i++; if (i === 10) break; } i; `); }); test('return statement in while(true)', () => { normalizeEquiv(` function foo() { let i = 0; while (true) { if (++i > 9) { return i; } } } let r = foo(); r; `); }); test('uninitialized variable', () => { normalizeEquiv(` let t; t = 1; t; `); }); test('compound conditional', () => { normalizeEquiv(` function F(x) { return x; } let i = 0; if(F(true) && F(true) || F(false)) { i++; } `); });
{ "pile_set_name": "Github" }
[advisory] id = "CVE-2018-1000622" package = "rustdoc" date = "2018-07-05" title = "Uncontrolled search path element vulnerability in rustdoc plugins" categories = ["code-execution"] url = "https://groups.google.com/forum/#!topic/rustlang-security-announcements/4ybxYLTtXuM" cvss = "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H" description = """ Rustdoc, if not passed the `--plugin-path` argument, defaults to `/tmp/rustdoc/plugins`. `/tmp` is world-writable on many systems, and so an attacker could craft a malicious plugin, place it in that directory, and the victim would end up executing their code. This only occurs when the `--plugin` argument is also passed. If you're not using that argument, then the loading, and therefore the bug, will not happen. Because this feature is very difficult to use, and has been deprecated for almost a year[2] with no comments on its usage, we don't expect this to affect many users. For more details, read on. ## Background Rustdoc has a "plugins" feature that lets you extend rustdoc. To write a plugin, you create a library with a specific exposed symbol. You instruct rustdoc to use this plugin, and it will load it, and execute the function as a callback to modify rustdoc's AST. This feature is quite hard to use, because the function needs to take as input and return as output Rustdoc's AST type. The Rust project does not ship a copy of `librustdoc` to end users, and so they would have to synthesize this type on their own. Furthermore, Rust's ABI is unstable, and so dynamically loading a plugin is only guaranteed to work if the plugin is compiled with the same compiler revision as the rustdoc that you're using. Beyond that, the feature and how to use it are completely undocumented. Given all of this, we're not aware of any usage of plugins in the wild, though the functionality still exists in the codebase. ## Description of the attack If you pass the `--plugins` parameter, let's say with "foo", and *do not* pass the `--plugin-path` parameter, rustdoc will look for the "foo" plugin in /tmp/rustdoc/plugins. Given that /tmp is world-writable on many systems, an attacker with access to your machine could place a maliciously crafted plugin into /tmp/rustdoc/plugins, and rustdoc would then load the plugin, and execute the attacker's callback, running arbitrary Rust code as your user instead of theirs. ## Affected Versions This functionality was introduced into rustdoc on December 31, 2013, in commit 14f59e890207f3b7a70bcfffaea7ad8865604111 [3]. That change was to rename `/tmp/rustdoc_ng/plugins` to `/tmp/rustdoc/plugins`; The addition of this search path generally came with the first commit to this iteration of rustdoc, on September 22, 2013, in commit 7b24efd6f333620ed2559d70b32da8f6f9957385 [4]. ## Mitigations To prevent this bug from happening on any version of Rust, you can always pass the `--plugin-path` flag to control the path. This only applies if you use the `--plugin` flag in the first place. For Rust 1.27, we'll be releasing a 1.27.1 on Tuesday with the fix, which consists of requiring `--plugin-path` to be passed whenever `--plugin` is passed. We will not be releasing our own fixes for previous versions of Rust, given the low severity and impact of this bug. The patch to fix 1.27 should be trivially applicable to previous versions, as this code has not changed in a very long time. The patch is included at the end of this email. If you need assistance patching an older version of Rust on your own, please reach out to Steve Klabnik, [email protected], and he'll be happy to help. On beta and nightly we will be removing plugins entirely. ## Timeline of events * Tue, Jul 3, 2018 at 11:57 PM UTC - Bug reported to [email protected] * Tue, Jul 3, 2018 at 12:13 PM UTC - Steve responds, confirming the bug * Weds, Jul 4, 2018 - Steve works up an initial patch * Thu, Jul 5, 2018 at 6:00 PM UTC - Rust team decides to not embargo this bug * Fri, Jul 6, 2018 at 12:38 AM - Final patch created after feedback from Red Hat ## Acknowledgements Thanks to Red Hat Product Security, which found this bug. And specifically to Josh Stone, who took their findings and reported it to us in accordance with our security policy https://www.rust-lang.org/security.html, as well as providing feedback on the patch itself. You can find their bug at [5]. [1]: https://cwe.mitre.org/data/definitions/427.html [2]: https://github.com/rust-lang/rust/issues/44136 [3]: https://github.com/rust-lang/rust/commit/14f59e890207f3b7a70bcfffaea7ad8865604111 [4]: https://github.com/rust-lang/rust/commit/7b24efd6f333620ed2559d70b32da8f6f9957385 [5]: https://bugzilla.redhat.com/show_bug.cgi?id=1597063 """ [versions] patched = ["> 1.27.0"]
{ "pile_set_name": "Github" }
import {addAttributeOptions} from "../model/column/attribute-service"; /** * Checks for lowercase */ export function IsLowercase(target: any, propertyName: string): void { addAttributeOptions(target, propertyName, { validate: { isLowercase: true } }); }
{ "pile_set_name": "Github" }
+++ title = "Talk:Quine" description = "" date = 2015-05-13T22:15:00Z aliases = [] [extra] id = 2249 [taxonomies] categories = [] tags = [] +++ == What is a quine? == I did not read up as fully as I should have on this task. The program is to output its own source without accessing files. This makes the examples here incorrect. See [http://en.wikipedia.org/wiki/Quine_%28computing%29 the wiki] for more clarification. --[[User:Mwn3d|Mwn3d]] 20:32, 17 November 2007 (MST) I don't think this task does illustrate the comparative features of different languages very well. As the Wikipedia article explains, one way to solve this task that will work in every language is put the program code into a string, together with some mechanism to replace it at a special location with a copy of itself. For languages which keep a more-or-less one-to-one representation of the code around at runtime (Lisp, Smalltalk, Forth, etc.), it just boils down to accessing this representation. Smaller solutions are in danger of becoming an exercise in obfuscation, or at least become unreadable very quickly. And the examples seen now which mostly access files are obviously missing the point. So I'd propose to delete this task, and replace it with a task that shows how to access (and maybe manipulate) code at runtime for languages that support it. The general solution can be subsumed by task(s) that show how string manipulation works. [[User:DirkT|Dirk Thierbach]] 18 November 2007 The name of the task is '''Quine'''. A Quine is not allowed to open its source file and to copy it to standard output. All implementations which do this should be removed. [[User:194.48.84.1|194.48.84.1]] 05:56, 20 November 2007 (MST) The task states (perhaps not clearly enough) that the program itself should do the printing, not any toplevel read-eval-print loop, or equivalent. Otherwise, all constants in languages that have such a toplevel would be quines. But that is completely missing the point of the original problem, which (as explained for example in the book ''G&ouml;del, Escher, Bach'') is about self-application, and quoting. -- [[User:DirkT|Dirk Thierbach]] 21 November 2007 :I clarified the task. Different scenarios have different requirements for output. The Lisp example satisfied the spirit of the task (produce a usable reproduction of one's own code), so the task itself needed to be adjusted. I won't take that approach in all cases; It's a matter of the spirit of the task. --[[User:Short Circuit|Short Circuit]] 13:06, 21 November 2007 (MST) :: I beg to differ - it's not the "scenarios" which have requirement for output, it's the spirit of the task itself which is not correctly presented if you allow constants (or empty programs) as solutions. I strongly recommend to read at least the [http://en.wikipedia.org/wiki/Quine_%28computing%29 Wikipedia article], or the book mentioned above (your library should have a copy). The philosopher Quine studied '''self-reference''', as exemplified in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." :: And it's this idea that makes up a Quine - A piece of code, applied to itself, once quoted and once unquoted. (BTW, this then again is the same technique used to prove undecidability theorems.) And the extra requirement "should '''print''' it's output" is one way to enforce that the quoting has to be done by the program itself, not by some external read-eval-print loop. :: The task is bad enough as it is (it doesn't really help in comparing programming languages), and it's not improved by allowing "fortunate" border cases which take away the main point. Ok, so what's the procedure to resolve differences in opinion? [[User:Dirkt|Dirkt]] 14:16, 21 November 2007 (MST) ::: To quote the Wikipedia page in question: ```txt In computing, a quine is a program, a form of metaprogram, that produces its complete source code as its only output. For amusement, programmers sometimes attempt to develop the shortest possible quine in any given programming language. Note that programs that take input are not considered quines. This would allow the source code to be fed to the program via keyboard input, opening the source file of the program, and similar mechanisms. Also, a quine that contains no code is ruled out as trivial; in many programming languages executing such a program will output the code (i.e. nothing). Such an empty program once won the "worst abuse of the rules" prize in the Obfuscated C contest. ``` ::: While the question that Quine investigated implies the quote-interpreting solution, the definition of the problem (per Wikipedia, anyway), doesn't require it. Reading it over, I'll agree that the Lisp example doesn't demonstrate anything one wouldn't get from [[Empty Program]], and would be better replaced with the Scheme/Common Lisp example from the Wikipedia page. I'd have no problem modifying the task description to discard empty programs as trivial, or even requiring the program to use a human-readable output method. Still, the task can still serve to compare languages. Some languages make accessing the source simple, like in the Forth example, or the JavaScript example on the Wikipedia page. Even the string-modifying solution allows for differences between languages; Different languages have different best solutions for replacing a substring. ::: It's not a 1:1 technique comparison, but neither is any task with both functional and procedural language examples. Would you be reasonably satisified if the task was changed to require human-readable output and exclude empty programs? --[[User:Short Circuit|Short Circuit]] 21:35, 21 November 2007 (MST) :::: The problem with Wikipedia of course is that it is great to get a rough feeling for some topic, but it's neither precise nor authoritative. So it's dangerous to take some definition there literally and insist it's the "correct" one - using the context to determine the ''ideas'' is much more appropriate for Wikipedia. :::: It's true that this task exposes (a) access to source code and (b) ways to modify strings, but considering the amount of misunderstanding this task generates, I still think it is much better (and more informative) to handle those on pages of their own. Especially (a) could only benefit from greater detail. Languages like Forth, Smalltalk, Lisp and Tcl have interesting ways to access and modify code at runtime, but you need a code example to bring this out. A Quine isn't one. :::: I've expanded the task description with some background to better explain the "spirit", and required the "canonical" version as one of the code examples. I've also ruled out constant expressions, and replaced your Lisp version with the one from Wikipedia. If you've objections or improvements, feel free to modify it. [[User:Dirkt|Dirkt]] 03:43, 22 November 2007 (MST) ==What is the license for the Forth example?== It says it was copied. I could not easily find a licence for the donor site. --[[User:Paddy3118|Paddy3118]] 02:42, 30 March 2009 (UTC) : Wow... could there exist a "restrictive" license for such a code? It's like saying Hello World is copied, and asking about the license for it (if someone did it and laws agree, I hope at least everyone will laugh at him!). Everyone, taking a look at a forth manual, e.g. I use [http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/The-Text-Interpreter.html#index-source-_0040var_007b-_002d_002d-addr-u---_007d--core-1444 this], can produce exactly the same code, without copying it from nowhere. (<code>Source</code> pushes the address of the current input buffer and its length LEN on stack: ADDR LEN; type "prints" LEN bytes starting from ADDR). Rather straightforward. If the ''copied'' is a problem, to me it's enough to strip the link (which anyway shows other more complex quines), and ask to some forth expert to produce in the smallest time the most straightforward quine using the smallest possible number of forth primitives. I bet it would write down "source type". --[[User:ShinTakezou|ShinTakezou]] 10:34, 30 March 2009 (UTC) : Ick. Being on Rosetta Code, it's licensed GFDL whenever distributed by us. But being that it's copied from another site, there's a question of whether the other site's license is violated. As for what license that would be...Under US copyright law, anything without an explicit copyright label is assumed to be under an "all rights reserved" scenario. However, I think that with appropriate citation, it's acceptable. I'm not sure if what's there qualifies as appropriate citation, though; Someone who knows more about published papers would be a better judge of that. --[[User:Short Circuit|Short Circuit]] 22:11, 30 March 2009 (UTC) : After looking at the edit history, I very strongly suspect that Shin created it on his own, and IanOsgood added a link to the list later. So I think we're completely kosher on this one, though the wording should probably be a bit more clear that the code wasn't copied. AFAIK, if Infinite Monkey Corp independently came up with Romeo and Juliet, they'd be every bit as entitled to its copyright as Shakespeare. (Assuming modern times...) --[[User:Short Circuit|Short Circuit]] 22:18, 30 March 2009 (UTC) :: No, I haven't written the code (as far as I remember I have not contributed to any forth code yet; surely not to quine anyway), or I would have said that here. I simply said that noone can claim a copyright on such a small piece of code, except maybe the creator of the forth language. The code simply says "get the buffer where the source text is, and print it"; provided that a language has a primitive to "print" and one to get such information, everyone able to read a manual can, '''without copying''', produce this quine. If it is not stack based, one could say something like "printf("%s", get_source());" (interpreted C?)... Anyway, if it is an issue, one could try to contact Neal Bridges ([http://www.complang.tuwien.ac.at/forth/quine-complex.fs named here]), maybe he wrote it (or know who can have written it), altogether with more complex quine(s) (and these can't be copied without thinking about a lincense, since hardly one can reproduce them only reading the forth manual...); it appears [http://www.nyx.net/~gthompso/self_forth.txt here also] (author unknown! and cheating suspect...). :: Someone wrote it, maybe after forth manual reading, or maybe taking a look on the net... and IanOsgood added just the link to a list of forth quines, among these there's also "ours". I think there are not license violation (I imagine RC must care a lot about these ''details''), but I am not a lawyer (rather in this case I would like to be a lawyer-eater) --[[User:ShinTakezou|ShinTakezou]] 00:12, 31 March 2009 (UTC) ::: Third thought, I think the guy suspecting it's almost cheating, after all, it's right; I've created the following C cheated-quine: ```c #include "cheater.h" int main() { printf("%s", __source__); } ``` :::Which works (with gcc statement expression extension) provided that cheater.h is ```c #include <stdio.h> #define __source__ ({ \ char *s = "#include \"cheater.h\"\n\ int main()\n\ {\n\ printf(\"%s\", __source__);\n\ }\n"; s;\ }) ``` ::: From a "functional" point of view, this works the same way of forth (and maybe others), by accessing the text of the source stored in memory (not by loading it at runtime...); since C is compiled, the binary holds no the source (compiler at least once loaded the source in memory, but compiled binary can't see its past...), and I had to include it manually... (Hm, one could work harder on debug informations and ELF maybe, and write a more forth-like quine accessing at runtime the "segment" where the whole source code, stored by the compiler itself this time, is and print it...)... Is this a honest quine or really cheating? (Interesting question to me:D) --[[User:ShinTakezou|ShinTakezou]] 00:54, 31 March 2009 (UTC) == Second scheme example correct? == I have some doubt about the correctness of the second scheme example. It only works when entered into an interpreter. When compiled there will be no output. The reason for this is that the expression evaluates to a result which is identical to the original expression. However, I realise that this is not the same as simply entering a constant expression like <code>0</code>, which will evaluate to itself. When the given expression is evaluated, the lambda function will be applied to the argument that follows, resulting in an expression that is identical to the original expression. The problem description states that the program must output its own source. The given example doesn't produce any output by itself (generated by <code>display</code> in scheme). How should we handle this? --[[User:Dsnouck|Dsnouck]] 14:16, 26 May 2010 (UTC) : If you feel that this is a significant issue, I think you should document it. In the general case, the concept and implementation of "output" is situational and depends on the character of the host session, and Quines traditionally assume just one mode of output. (And this is more of an issue in some languages than others.) --[[User:Rdm|Rdm]] 14:24, 26 May 2010 (UTC) == nostalgia comments == I added some nostalgia notes at the end of the Fortran example. I had assumed that this [QUINE} being such an old challenge, that it would be pertinent. Almost a half-century ago!! [[User:Gerard Schildberger|Gerard Schildberger]] == Haskell evaluation == If you're going to allow an expression that evaluates to itself, won't "blah" evaluate to "blah"? For that matter \x.x will evaluate to \x.x [[Special:Contributions/71.176.132.192|71.176.132.192]] 20:35, 26 April 2011 (UTC) :This is the same problem as "if you allow programs which print their source, won't 10 LIST be a quine in classic BASIC?". Or, isn't 42 a Lisp quine? Typing 42 into the REPL produces 42! The answer is that a quine must not depend on some trivial self-evaluating properties built into an object, or built in self-reference which pulls out the source code. A quine must be some kind of '''computation''' which produces its own image. Self-evaluating objects do not compute anything: they appeal to the axiom of self-evaluation which is built into the language. Self-regurgitating programs likewise do not compute anything, they appeal to built-in access to the program source. (Many of the programs put up here so far fail these criteria.) [[Special:Contributions/24.85.131.247|24.85.131.247]] 05:59, 2 October 2011 (UTC) :I just added an example for a compilable Haskell Quine. --[[User:Jgriebler|JMG]] ([[User talk:Jgriebler|talk]]) 22:14, 13 May 2015 (UTC) == C quine == I removed some comments about style about the C quine: it's a bit silly to be serious about good coding style for this subject. If you want properly indented, properly typed and properly header'ed C code, here you go: ```c #include <stdio.h> int main(void){ char*p="#include <stdio.h>%cint main(void){%c%cchar*p=%c%s%c;%c%cprintf(p,10,10,9,34,p,34,10,9,10,9,10,10);%c%creturn 0;%c}%c"; printf(p,10,10,9,34,p,34,10,9,10,9,10,10); return 0; } ``` which does require a trailing newline, btw. Being "more correct", It definitely does not help one read or understand the code. --[[User:Ledrug|Ledrug]] 03:53, 1 September 2011 (UTC) == REXX Quine == '''Error?''' The REXX program (below) produces an extra blank line in the output. This extra blank line can't be noticed easily (or not at all) when just viewing the output, but if the output is re-directed to a file, the extra blank line then becomes obvious. The definition of a quine isn't clear in this regard. Is a listing (of a 19-line program) with an extra blank line equal to a 19-line program? '''IEC999I “Probable user error. Correct job input and resubmit.”''' : It doesn't for me. : The original program contains 53 lines of code (there's a new-line after the last end clause), as does the result; passing the original program and its output through both <tt>diff</tt> and <tt>wc</tt> confirm this: ```txt $ wc -lmw RQuine03.rex 53 215 1029 RQuine03.rex $ cat RQuine03.rex | wc -lmw 53 215 1029 $ rexx RQuine03.rex | wc -lmw 53 215 1029 $ regina RQuine03.rex | wc -lmw 53 215 1029 $ rexx RQuine03.rex |diff -s RQuine03.rex - Files RQuine03.rex and - are identical $ regina RQuine03.rex |diff -s RQuine03.rex - Files RQuine03.rex and - are identical ``` :: I found that the original program (well, at least, the current program) has 52 lines of source code, not 53. If there's a new-line after the "End x_", I can't see it. I looked at the Rosetta Code program via "edit", and there is no blank line after the trailing underscore. I used Regina (REGINA Q3.REX &gt; Q3.OUT) and again verified that the version 3 REXX program did indeed write an extra blank line (for a total of 53.) The Rosetta Code view of the program does not show a blank line after the program. However, to ensure a blank line after the original source, I then added a blank line after the Q3 program and ''it still produced the same result!'' (53 lines). So two different REXX programs produced the same (quine) output, but the two REXX programs are different. So the one that produced the output as the same as the source is the quine program, and the other, ... is not. I used the FC (MS DOS), WINDIFF (MS Windows), and KEDIT programs to verify the outputs. -- [[User:Gerard Schildberger|Gerard Schildberger]] 01:51, 28 June 2012 (UTC) : The ''original'' code on my system is 53 lines long. It produces another file that's also 53 lines long as demonstrated above: that's what it's meant to do. I can't be held responsible for any accidental changes that get made to the contents of the wiki (they even post caveats about merciless editing of things you write in many places). I'm pretty sure I didn't delete the last newline and as I normally put the <tt>&lt;/lang&gt;</tt> tag on a line of its own I can't believe I chose this entry to do something different. (I have edited the sample to insert a newline at the end of the source.) : The fact that two programs with varying numbers of blank lines (at the end or otherwise) produce the same output is beside the point. The one that (in this case) starts with 53 lines, produces a file that's 53 lines long and is identical to itself is the quine, the others aren't; regardless of what they produce as output. : Here's a thought though: :# Run the program extracted from the wiki in whatever state it is in. :# Capture the output from 1 and save it as a source program. :# Run the program from 2 and capture its output too. :# Compare the results of the output from 3 with those from 2. : Dollars to doughnuts they'll both be 53 lines long, identical and a quine. (I tried it: they are.) --[[User:Alansam|Alansam]] 06:05, 28 June 2012 (UTC) :: Yes, they are now after the change that was made. I have no doubt that your original program is 53 lines. I wish you would've done the same four steps on the 52-line version as it existed on Rosetta Code, the same program that I used. They didn't agree before the change. I'm not questioning what you meant to do, just what was actually in the sample code (on Rosetta Code). I have no access to any other copy. I'm sorry if the dog ate your homework, no demand for who's reponsible for the changes was made or implied. There's always the history file if want to know who did what. But the original file as it was on Rosetta Code didn't produce an exact copy of itself. The 52-line version didn't produce a quine, the (current) 53 line does. If it old program did produce a quine, you wouldn't have a need to change it. I also don't understand your ad hominem attacks about 'they" posting caveats about merciless editing of things I write in many places. Could you be more specific if you think that would be pertinent here? -- [[User:Gerard Schildberger|Gerard Schildberger]] 08:00, 28 June 2012 (UTC) :: Also, since this discussion is now in the ''talk'' page, I'd like to point out that saying another version is a cheat isn't professional nor appropriate. If it ''is'' a cheat, then flag it as '''incorrect''' and state why. The REXX versions 1 and 2 don't open any external files, as per the task's description/requirements. -- [[User:Gerard Schildberger|Gerard Schildberger]] 02:01, 28 June 2012 (UTC) : I didn't say the other version "is a cheat", I said it was "kind of a cheat", there's a '''huge''' difference in emphasis. Please don't cherry-pick other people's words to score points: that's unprofessional! :: Sorry, a kind of cheat or a cheat is still a cheat. I'm sorry if you think that I thought that name-calling wasn't appropriate. If that is your idea of cherry-picking, then I'll rephrase. Saying another version is a kind of cheat isn't professional ... Saying (just for instance) that something smells or kind of smells sounds like the same thing. It wasn't my intention to provide a "kind of" cheat; the mechanism used is a very simple way to provide what the quine task asked for. I don't even begin to understand what you meant by scoring points. -- [[User:Gerard Schildberger|Gerard Schildberger]] 08:00, 28 June 2012 (UTC) : Now we're here though; if you read the description of what a Quine is supposed to be (see above) with particular reference to the quote from Wikipedia: ```txt Note that programs that take input are not considered quines. This would allow the source code to be fed to the program via keyboard input, opening the source file of the program, and similar mechanisms... ``` : I suspect that using <tt>sourceline()</tt> falls squarely into the category of "opening the source file of the program and similar mechanisms" which disqualifies it as a Quine. --[[User:Alansam|Alansam]] 06:05, 28 June 2012 (UTC) :: I have a slightly different definition of squarely. The REXX program doesn't open the source file of the program. It doesn't read (or take) the source file through any other mechanism. Reading a copy of the file that is on (or in) a virtual device might be considered taking (reading?) a copy of the source. Putting a number of lines in a stack and then "reading" (or pulling) is "taking" some input could qualify as a method disallowed in the Wiki definition of a quine. I hesitate to call a stack (internal or external queue) a device, albetit a virtual one. There isn't much difference between a stack and a virtual device. I don't begrudge your method nor will I call it names, and I certainly wouldn't call it a kind of cheat. I think debating the definition(s) of a quine (as it applies here) would just lead to endless arguments about the wording of a quine (and/or what the words mean), and what specifically should/could be disqualified, and what qualifies as reading a copy of the program from an input. It's just another method that can be used. My only concern was that the (original) program as I observed it didn't produce a quine. I don't question the method. The REXX method for REXX versions 1 and 2 can also be used, for instance, in CMS when using the NUCXLOAD function which further distances a program from its source, which in simple terms, can load a copy of a REXX program (or it could be any kind of file) in virtual memory (and also rename it), and the original source deleted or disconneted (no longer available to the user). The program can be (much) later be invoked (even by another user) and still work as intended. This method lends itself to a persistent program, surviving what most people call a re-boot (or re-IPL, in CMS terminology), even though the source code is longer present in any form. This subject was of much interest when that capability was introduced into CMS and via ''saved systems'', and it made for some interesting programming techniques, the least of which was to hide the REXX code from the user. This is a lot of discourse on a simple error in the original REXX program (as it existed on Rosetta Code), just admitting that the 52-line version didn't reproduce itself due to a missing blank line. -- [[User:Gerard Schildberger|Gerard Schildberger]] 08:00, 28 June 2012 (UTC)
{ "pile_set_name": "Github" }
function module(globals, path, body) { 'use strict'; // Start name lookup in the global object var current = globals; // For each name in the given path path.split('.').forEach(function (name) { // If the current path element does not exist // in the current namespace, create a new sub-namespace if (typeof current[name] === 'undefined') { current[name] = {}; } // Move to the namespace for the current path element current = current[name]; }); // Execute the module body in the last namespace body(current, globals); } /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js */ module(this, 'sozi.events', function (exports) { 'use strict'; var listenerRegistry = {}; /* * Adds a listener for a given event type. * * The event type is provided as a string by the key parameter. * The function to be executed is provided by the handler parameter. */ exports.listen = function (key, handler) { if (!listenerRegistry.hasOwnProperty(key)) { listenerRegistry[key] = []; } listenerRegistry[key].push(handler); }; /* * Fire an event of the given type. * * All event handlers added for the given event type are * executed. * Additional arguments provided to this function are passed * to the event handlers. */ exports.fire = function (key) { var args = Array.prototype.slice.call(arguments, 1); if (listenerRegistry.hasOwnProperty(key)) { listenerRegistry[key].forEach(function (listener) { listener.apply(null, args); }); } }; }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js * @depend events.js */ module(this, 'sozi.framenumber', function (exports, window) { 'use strict'; // An alias to the global document object var document = window.document; // The SVG group containing the frame number var svgGroup; // The SVG text element and its text node containing the frame number var svgText, svgTextNode; // The SVG circle enclosing the frame number var svgCircle; // Constant: the SVG namespace var SVG_NS = 'http://www.w3.org/2000/svg'; function adjust() { var textBBox = svgText.getBBox(), d = Math.max(textBBox.width, textBBox.height) * 0.75, t = d * 1.25; svgCircle.setAttribute('r', d); svgGroup.setAttribute('transform', 'translate(' + t + ',' + t + ')'); } function onDisplayReady() { svgGroup = document.createElementNS(SVG_NS, 'g'); svgText = document.createElementNS(SVG_NS, 'text'); svgCircle = document.createElementNS(SVG_NS, 'circle'); svgGroup.setAttribute('id', 'sozi-framenumber'); svgCircle.setAttribute('cx', 0); svgCircle.setAttribute('cy', 0); svgGroup.appendChild(svgCircle); svgTextNode = document.createTextNode(sozi.location.getFrameIndex() + 1); svgText.setAttribute('text-anchor', 'middle'); svgText.setAttribute('dominant-baseline', 'central'); svgText.setAttribute('x', 0); svgText.setAttribute('y', 0); svgText.appendChild(svgTextNode); svgGroup.appendChild(svgText); document.documentElement.appendChild(svgGroup); adjust(); } function onFrameChange(index) { svgTextNode.nodeValue = index + 1; } sozi.events.listen('displayready', onDisplayReady); sozi.events.listen('framechange', onFrameChange); }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js * @depend events.js */ module(this, 'sozi.framelist', function (exports, window) { 'use strict'; // An alias to the global document object var document = window.document; // Constant: the margin around the text of the frame list var MARGIN = 5; // The SVG group that will contain the frame list var svgTocGroup; // The SVG group that will contain the frame titles var svgTitlesGroup; // The current height of the frame list, // computed during the initialization var tocHeight = 0; // The X coordinate of the frame list in its hidden state var translateXHidden; // The X coordinate of the frame list when it is completely visible var translateXVisible; // The initial X coordinate of the frame list before starting an animation. // This variable is set before showing/hiding the frame list. var translateXStart; // The final X coordinate of the frame list for the starting animation. // This variable is set before showing/hiding the frame list. var translateXEnd; // The current X coordinate of the frame list for the running animation. // This variable is updated on each animation step. var translateX; // The animator object that will manage animations of the frame list var animator; // Constant: the duration of the showing/hiding animation, in milliseconds var ANIMATION_TIME_MS = 300; // Constant: the acceleration profile of the showing/hiding animation var ANIMATION_PROFILE = 'decelerate'; // Constant: the SVG namespace var SVG_NS = 'http://www.w3.org/2000/svg'; function onMouseOut(evt) { var rel = evt.relatedTarget, svgRoot = document.documentElement; while (rel && rel !== svgTocGroup && rel !== svgRoot) { rel = rel.parentNode; } if (rel !== svgTocGroup) { exports.hide(); sozi.player.restart(); evt.stopPropagation(); } } function onClickArrowUp(evt) { var ty = svgTitlesGroup.getCTM().f; if (ty <= -window.innerHeight / 2) { ty += window.innerHeight / 2; } else if (ty < 0) { ty = 0; } svgTitlesGroup.setAttribute('transform', 'translate(0,' + ty + ')'); evt.stopPropagation(); } function onClickArrowDown(evt) { var ty = svgTitlesGroup.getCTM().f; if (ty + tocHeight >= window.innerHeight * 3 / 2) { ty -= window.innerHeight / 2; } else if (ty + tocHeight > window.innerHeight + 2 * MARGIN) { ty = window.innerHeight - tocHeight - 4 * MARGIN; } svgTitlesGroup.setAttribute('transform', 'translate(0,' + ty + ')'); evt.stopPropagation(); } function onAnimationStep(progress) { var profileProgress = sozi.animation.profiles[ANIMATION_PROFILE](progress), remaining = 1 - profileProgress; translateX = translateXEnd * profileProgress + translateXStart * remaining; svgTocGroup.setAttribute('transform', 'translate(' + translateX + ',0)'); } function onAnimationDone() { // Empty } /* * Create a function that responds to clicks on frame list entries. */ function makeClickHandler(index) { return function (evt) { sozi.player.previewFrame(index); evt.stopPropagation(); }; } /* * The default event handler, to prevent event propagation * through the frame list. */ function defaultEventHandler(evt) { evt.stopPropagation(); } /* * Adds a table of contents to the document. * * The table of contents is a rectangular region with the list of frame titles. * Clicking on a title moves the presentation to the corresponding frame. * * The table of contents is hidden by default. */ function onDisplayReady() { svgTocGroup = document.createElementNS(SVG_NS, 'g'); svgTocGroup.setAttribute('id', 'sozi-toc'); document.documentElement.appendChild(svgTocGroup); svgTitlesGroup = document.createElementNS(SVG_NS, 'g'); svgTocGroup.appendChild(svgTitlesGroup); // The background rectangle of the frame list var tocBackground = document.createElementNS(SVG_NS, 'rect'); tocBackground.setAttribute('id', 'sozi-toc-background'); tocBackground.setAttribute('x', MARGIN); tocBackground.setAttribute('y', MARGIN); tocBackground.setAttribute('rx', MARGIN); tocBackground.setAttribute('ry', MARGIN); tocBackground.addEventListener('click', defaultEventHandler, false); tocBackground.addEventListener('mousedown', defaultEventHandler, false); tocBackground.addEventListener('mouseout', onMouseOut, false); svgTitlesGroup.appendChild(tocBackground); var tocWidth = 0; var currentFrameIndex = sozi.location.getFrameIndex(); sozi.document.frames.forEach(function (frame, frameIndex) { var text = document.createElementNS(SVG_NS, 'text'); text.appendChild(document.createTextNode(frame.title)); svgTitlesGroup.appendChild(text); if (frameIndex === currentFrameIndex) { text.setAttribute('class', 'sozi-toc-current'); } var textWidth = text.getBBox().width; tocHeight += text.getBBox().height; if (textWidth > tocWidth) { tocWidth = textWidth; } text.setAttribute('x', 2 * MARGIN); text.setAttribute('y', tocHeight + MARGIN); text.addEventListener('click', makeClickHandler(frameIndex), false); text.addEventListener('mousedown', defaultEventHandler, false); }); // The 'up' button var tocUp = document.createElementNS(SVG_NS, 'path'); tocUp.setAttribute('class', 'sozi-toc-arrow'); tocUp.setAttribute('d', 'M' + (tocWidth + 3 * MARGIN) + ',' + (5 * MARGIN) + ' l' + (4 * MARGIN) + ',0' + ' l-' + (2 * MARGIN) + ',-' + (3 * MARGIN) + ' z'); tocUp.addEventListener('click', onClickArrowUp, false); tocUp.addEventListener('mousedown', defaultEventHandler, false); svgTocGroup.appendChild(tocUp); // The 'down' button var tocDown = document.createElementNS(SVG_NS, 'path'); tocDown.setAttribute('class', 'sozi-toc-arrow'); tocDown.setAttribute('d', 'M' + (tocWidth + 3 * MARGIN) + ',' + (7 * MARGIN) + ' l' + (4 * MARGIN) + ',0' + ' l-' + (2 * MARGIN) + ',' + (3 * MARGIN) + ' z'); tocDown.addEventListener('click', onClickArrowDown, false); tocDown.addEventListener('mousedown', defaultEventHandler, false); svgTocGroup.appendChild(tocDown); tocBackground.setAttribute('width', tocWidth + 7 * MARGIN); tocBackground.setAttribute('height', tocHeight + 2 * MARGIN); translateXHidden = -tocWidth - 9 * MARGIN; translateXVisible = 0; translateX = translateXEnd = translateXHidden; svgTocGroup.setAttribute('transform', 'translate(' + translateXHidden + ',0)'); animator = new sozi.animation.Animator(onAnimationStep, onAnimationDone); } /* * Highlight the current frame title in the frame list. * * This handler is called on each frame change, * even when the frame list is hidden. */ function onFrameChange(index) { var currentElementList = Array.prototype.slice.call(document.getElementsByClassName('sozi-toc-current')); currentElementList.forEach(function (svgElement) { svgElement.removeAttribute('class'); }); var textElements = svgTitlesGroup.getElementsByTagName('text'); textElements[index].setAttribute('class', 'sozi-toc-current'); } /* * Makes the table of contents visible. */ exports.show = function () { translateXStart = translateX; translateXEnd = translateXVisible; animator.start(ANIMATION_TIME_MS); // FIXME depends on current elapsed time }; /* * Makes the table of contents invisible. */ exports.hide = function () { translateXStart = translateX; translateXEnd = translateXHidden; animator.start(ANIMATION_TIME_MS); // FIXME depends on current elapsed time }; /* * Returns true if the table of contents is visible, false otherwise. */ exports.isVisible = function () { return translateXEnd === translateXVisible; }; sozi.events.listen('displayready', onDisplayReady); sozi.events.listen('cleanup', exports.hide); sozi.events.listen('framechange', onFrameChange); }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js */ module(this, 'sozi.animation', function (exports, window) { 'use strict'; // The browser-specific function to request an animation frame var requestAnimationFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame; // Constant: the default time step // for browsers that do not support animation frames var TIME_STEP_MS = 40; // The handle provided by setInterval // for browsers that do not support animation frames var timer; // The list of running animators var animatorList = []; /* * This function is called periodically and triggers the * animation steps in all animators managed by this module. * * If all animators are removed from the list of animators * managed by this module, then the periodic calling is disabled. * * This function can be called either through requestAnimationFrame() * if the browser supports it, or through setInterval(). */ function loop(timestamp) { if (animatorList.length > 0) { // If there is at least one animator, // and if the browser provides animation frames, // schedule this function to be called again in the next frame. if (requestAnimationFrame) { requestAnimationFrame(loop); } // Step all animators animatorList.forEach(function (animator) { animator.step(timestamp); }); } else { // If all animators have been removed, // and if this function is called periodically // through setInterval, disable the periodic calling. if (!requestAnimationFrame) { window.clearInterval(timer); } } } /* * Start the animation loop. * * This function delegates the periodic update of all animators * to the loop() function, either through requestAnimationFrame() * if the browser supports it, or through setInterval(). */ function start() { if (requestAnimationFrame) { requestAnimationFrame(loop); } else { timer = window.setInterval(function () { loop(Date.now()); }, TIME_STEP_MS); } } /* * Add a new animator object to the list of animators managed * by this module. * * If the animator list was empty before calling this function, * then the animation loop is started. */ function addAnimator(animator) { animatorList.push(animator); if (animatorList.length === 1) { start(); } } /* * Remove the given animator from the list of animators * managed by this module. */ function removeAnimator(animator) { animatorList.splice(animatorList.indexOf(animator), 1); } /* * Construct a new animator. * * Parameters: * - onStep: the function to call on each animation step * - onDone: the function to call when the animation time is elapsed * * The onStep() function is expected to have the following parameters: * - progress: a number between 0 and 1 (included) corresponding to * the elapsed fraction of the total duration * - data: an optional object passed to the application-specific animation code * * The new animator is initialized in the 'stopped' state. */ exports.Animator = function (onStep, onDone) { this.onStep = onStep; this.onDone = onDone; this.durationMs = 0; this.data = {}; this.initialTime = 0; this.started = false; }; /* * Start the current animator. * * Parameters: * - durationMs: the animation duration, in milliseconds * - data: an object to pass to the onStep function * * The current animator is added to the list of animators managed * by this module and is put in the 'started' state. * It will be removed from the list automatically when the given duration * has elapsed. * * The onStep() function is called once before starting the animation. */ exports.Animator.prototype.start = function (durationMs, data) { this.durationMs = durationMs; this.data = data; this.initialTime = Date.now(); this.onStep(0, this.data); if (!this.started) { this.started = true; addAnimator(this); } }; /* * Stop the current animator. * * The current animator is removed from the list of animators managed * by this module and is put in the 'stopped' state. */ exports.Animator.prototype.stop = function () { if (this.started) { removeAnimator(this); this.started = false; } }; /* * Perform one animation step. * * This function is called automatically by the loop() function. * It calls the onStep() function of this animator. * If the animation duration has elapsed, the onDone() function of * the animator is called. */ exports.Animator.prototype.step = function (timestamp) { var elapsedTime = timestamp - this.initialTime; if (elapsedTime >= this.durationMs) { this.stop(); this.onStep(1, this.data); this.onDone(); } else { this.onStep(elapsedTime / this.durationMs, this.data); } }; /* * The acceleration profiles. * * Each profile is a function that operates in the interval [0, 1] * and produces a result in the same interval. * * These functions are meant to be called in onStep() functions * to transform the progress indicator according to the desired * acceleration effect. */ exports.profiles = { 'linear': function (x) { return x; }, 'accelerate': function (x) { return Math.pow(x, 3); }, 'strong-accelerate': function (x) { return Math.pow(x, 5); }, 'decelerate': function (x) { return 1 - Math.pow(1 - x, 3); }, 'strong-decelerate': function (x) { return 1 - Math.pow(1 - x, 5); }, 'accelerate-decelerate': function (x) { var xs = x <= 0.5 ? x : 1 - x, y = Math.pow(2 * xs, 3) / 2; return x <= 0.5 ? y : 1 - y; }, 'strong-accelerate-decelerate': function (x) { var xs = x <= 0.5 ? x : 1 - x, y = Math.pow(2 * xs, 5) / 2; return x <= 0.5 ? y : 1 - y; }, 'decelerate-accelerate': function (x) { var xs = x <= 0.5 ? x : 1 - x, y = (1 - Math.pow(1 - 2 * xs, 2)) / 2; return x <= 0.5 ? y : 1 - y; }, 'strong-decelerate-accelerate': function (x) { var xs = x <= 0.5 ? x : 1 - x, y = (1 - Math.pow(1 - 2 * xs, 3)) / 2; return x <= 0.5 ? y : 1 - y; } }; }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js */ module(this, 'sozi.proto', function (exports) { 'use strict'; exports.Object = { installConstructors: function () { var thisObject = this; this.instance = function () { thisObject.construct.apply(this, arguments); this.installConstructors(); this.type = thisObject; this.supertype = exports.Object; }; this.subtype = function (anObject) { this.augment(anObject); this.installConstructors(); this.supertype = thisObject; }; this.instance.prototype = this; this.subtype.prototype = this; }, construct: function () {}, augment: function (anObject) { for (var attr in anObject) { if (anObject.hasOwnProperty(attr)) { this[attr] = anObject[attr]; } } }, isInstanceOf: function (anObject) { return this.type === anObject || exports.Object.isPrototypeOf(this.type) && this.type.isSubtypeOf(anObject); }, isSubtypeOf: function (anObject) { return this.supertype === anObject || exports.Object.isPrototypeOf(this.supertype) && this.supertype.isSubtypeOf(anObject); } }; // Bootstrap the root object exports.Object.installConstructors(); }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js * @depend proto.js * @depend events.js */ module(this, 'sozi.display', function (exports, window) { 'use strict'; // The global document object var document = window.document; // The initial bounding box of the whole document, // assigned in onDocumentReady() var initialBBox; // Constant: the Sozi namespace var SVG_NS = 'http://www.w3.org/2000/svg'; // The geometry of each layer managed by Sozi exports.layers = {}; exports.CameraState = new sozi.proto.Object.subtype({ construct : function () { // Center coordinates this.cx = this.cy = 0; // Dimensions this.width = this.height = 1; // Rotation angle, in degrees this.angle = 0; // Clipping this.clipped = true; }, setCenter: function (cx, cy) { this.cx = cx; this.cy = cy; return this; }, setSize: function (width, height) { this.width = width; this.height = height; return this; }, setClipped: function (clipped) { this.clipped = clipped; return this; }, /* * Set the angle of the current camera state. * The angle of the current state is normalized * in the interval [-180 ; 180] */ setAngle: function (angle) { this.angle = (angle + 180) % 360 - 180; return this; }, setRawAngle: function (angle) { this.angle = angle; }, /* * Set the current camera's properties to the given SVG element. * * If the element is a rectangle, the properties of the frames are based * on the geometrical properties of the rectangle. * Otherwise, the properties of the frame are based on the bounding box * of the given element. * * Parameters: * - svgElement: an element from the SVG DOM */ setAtElement: function (svgElement) { // Read the raw bounding box of the given SVG element var x, y, w, h; if (svgElement.nodeName === 'rect') { x = svgElement.x.baseVal.value; y = svgElement.y.baseVal.value; w = svgElement.width.baseVal.value; h = svgElement.height.baseVal.value; } else { var b = svgElement.getBBox(); x = b.x; y = b.y; w = b.width; h = b.height; } // Compute the raw coordinates of the center // of the given SVG element var c = document.documentElement.createSVGPoint(); c.x = x + w / 2; c.y = y + h / 2; // Compute the coordinates of the center of the given SVG element // after its current transformation var matrix = svgElement.getCTM(); c = c.matrixTransform(matrix); // Compute the scaling factor applied to the given SVG element var scale = Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b); // Update the camera to match the bounding box information of the // given SVG element after its current transformation return this.setCenter(c.x, c.y) .setSize(w * scale, h * scale) .setAngle(Math.atan2(matrix.b, matrix.a) * 180 / Math.PI); }, setAtState: function (other) { return this.setCenter(other.cx, other.cy) .setSize(other.width, other.height) .setAngle(other.angle) .setClipped(other.clipped); }, getScale: function () { return Math.min(window.innerWidth / this.width, window.innerHeight / this.height); } }); exports.Camera = new exports.CameraState.subtype({ construct: function (idLayer) { exports.CameraState.construct.call(this); // Clipping rectangle this.svgClipRect = document.createElementNS(SVG_NS, 'rect'); // Layer element (typically a 'g' element) this.svgLayer = document.getElementById(idLayer); } }); /* * Initializes the current Display. * * This method prepares the DOM representation of the current SVG document. * All the image is embedded into a global 'g' element on which transformations will be applied. * A clipping rectangle is added. * * This method must be called when the document is ready to be manipulated. */ function onDocumentReady() { var svgRoot = document.documentElement; // TODO check SVG tag // Save the initial bounding box of the document // and force its dimensions to the browser window initialBBox = svgRoot.getBBox(); svgRoot.setAttribute('width', window.innerWidth); svgRoot.setAttribute('height', window.innerHeight); // Initialize display geometry for all layers sozi.document.idLayerList.forEach(function (idLayer) { exports.layers[idLayer] = new exports.Camera.instance(idLayer); /* // Add a clipping path var svgClipPath = document.createElementNS(SVG_NS, 'clipPath'); svgClipPath.setAttribute('id', 'sozi-clip-path-' + idLayer); svgClipPath.appendChild(exports.layers[idLayer].svgClipRect); svgRoot.appendChild(svgClipPath); // Create a group that will support the clipping operation // and move the layer group into that new group var svgClippedGroup = document.createElementNS(SVG_NS, 'g'); svgClippedGroup.setAttribute('clip-path', 'url(#sozi-clip-path-' + idLayer + ')'); // Adding the layer group to the clipped group must preserve layer ordering svgRoot.insertBefore(svgClippedGroup, exports.layers[idLayer].svgLayer); svgClippedGroup.appendChild(exports.layers[idLayer].svgLayer);*/ }); sozi.events.fire('displayready'); } /* * Resizes the SVG document to fit the browser window. */ function resize() { var svgRoot = document.documentElement; svgRoot.setAttribute('width', window.innerWidth); svgRoot.setAttribute('height', window.innerHeight); exports.update(); } /* * Returns the geometrical properties of the SVG document * * Returns: * - The default size, translation and rotation for the document's bounding box */ exports.getDocumentGeometry = function () { // This object defines the bounding box of the whole document var camera = new exports.CameraState.instance() .setCenter(initialBBox.x + initialBBox.width / 2, initialBBox.y + initialBBox.height / 2) .setSize(initialBBox.width, initialBBox.height) .setClipped(false); // Copy the document's bounding box to all layers var result = { layers: {} }; for (var idLayer in exports.layers) { if (exports.layers.hasOwnProperty(idLayer)) { result.layers[idLayer] = camera; } } return result; }; /* * Apply geometrical transformations to the image according to the current * geometrical attributes of this Display. * * This method is called automatically when the window is resized. * * TODO move the loop body to CameraState */ exports.update = function () { for (var idLayer in exports.layers) { if (exports.layers.hasOwnProperty(idLayer)) { var lg = exports.layers[idLayer]; var scale = lg.getScale(); // Compute the size and location of the frame on the screen var width = lg.width * scale; var height = lg.height * scale; var x = (window.innerWidth - width) / 2; var y = (window.innerHeight - height) / 2; // Adjust the location and size of the clipping rectangle and the frame rectangle var cr = exports.layers[idLayer].svgClipRect; cr.setAttribute('x', lg.clipped ? x : 0); cr.setAttribute('y', lg.clipped ? y : 0); cr.setAttribute('width', lg.clipped ? width : window.innerWidth); cr.setAttribute('height', lg.clipped ? height : window.innerHeight); // Compute and apply the geometrical transformation to the layer group var translateX = -lg.cx + lg.width / 2 + x / scale; var translateY = -lg.cy + lg.height / 2 + y / scale; exports.layers[idLayer].svgLayer.setAttribute('transform', 'scale(' + scale + ')' + 'translate(' + translateX + ',' + translateY + ')' + 'rotate(' + (-lg.angle) + ',' + lg.cx + ',' + lg.cy + ')' ); } } }; /* * Transform the SVG document to show the given frame. * * Parameters: * - frame: the frame to show */ exports.showFrame = function (frame) { for (var idLayer in frame.layers) { if (frame.layers.hasOwnProperty(idLayer)) { exports.layers[idLayer].setAtState(frame.layers[idLayer]); } } exports.update(); }; /* * Apply an additional translation to the SVG document based on onscreen coordinates. * * Parameters: * - deltaX: the horizontal displacement, in pixels * - deltaY: the vertical displacement, in pixels * * TODO move the loop body to CameraState */ exports.drag = function (deltaX, deltaY) { for (var idLayer in exports.layers) { if (exports.layers.hasOwnProperty(idLayer)) { var lg = exports.layers[idLayer]; var scale = lg.getScale(); var angleRad = lg.angle * Math.PI / 180; lg.cx -= (deltaX * Math.cos(angleRad) - deltaY * Math.sin(angleRad)) / scale; lg.cy -= (deltaX * Math.sin(angleRad) + deltaY * Math.cos(angleRad)) / scale; lg.clipped = false; } } exports.update(); }; /* * Zooms the display with the given factor. * * The zoom is centered around (x, y) with respect to the center of the display area. * * TODO move the loop body to CameraState */ exports.zoom = function (factor, x, y) { for (var idLayer in exports.layers) { if (exports.layers.hasOwnProperty(idLayer)) { exports.layers[idLayer].width /= factor; exports.layers[idLayer].height /= factor; } } exports.drag( (1 - factor) * (x - window.innerWidth / 2), (1 - factor) * (y - window.innerHeight / 2) ); }; /* * Rotate the display with the given angle. * * The rotation is centered around the center of the display area. * * TODO move the loop body to CameraState */ exports.rotate = function (angle) { for (var idLayer in exports.layers) { if (exports.layers.hasOwnProperty(idLayer)) { exports.layers[idLayer].angle += angle; exports.layers[idLayer].angle %= 360; } } exports.update(); }; sozi.events.listen('documentready', onDocumentReady); window.addEventListener('resize', resize, false); }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js * @depend events.js * @depend animation.js * @depend display.js */ module(this, 'sozi.player', function (exports, window) { 'use strict'; // An alias to the Sozi display module var display = sozi.display; // The animator object used to animate transitions var animator; // The handle returned by setTimeout() for frame timeout var nextFrameTimeout; // Constants: default animation properties // for out-of-sequence transitions var DEFAULT_DURATION_MS = 500; var DEFAULT_ZOOM_PERCENT = -10; var DEFAULT_PROFILE = 'linear'; // The source frame index for the current transition var sourceFrameIndex = 0; // The index of the visible frame var currentFrameIndex = 0; // The state of the presentation. // If false, no automatic transition will be fired. var playing = false; // The state of the current frame. // If true, an automatic transition will be fired after the current timeout. var waiting = false; /* * Event handler: animation step. * * This method is called periodically by animator after the animation * has been started, and until the animation time is elapsed. * * Parameter data provides the following information: * - initialState and finalState contain the geometrical properties of the display * at the start and end of the animation. * - profile is a reference to the speed profile function to use. * - zoomWidth and zoomHeight are the parameters of the zooming polynomial if the current * animation has a non-zero zooming effect. * * Parameter progress is a float number between 0 (start of the animation) * and 1 (end of the animation). * * TODO move the interpolation code to display.js */ function onAnimationStep(progress, data) { for (var idLayer in data) { if (data.hasOwnProperty(idLayer)) { var lg = display.layers[idLayer]; var profileProgress = data[idLayer].profile(progress); var profileRemaining = 1 - profileProgress; for (var attr in data[idLayer].initialState) { if (data[idLayer].initialState.hasOwnProperty(attr)) { if (typeof data[idLayer].initialState[attr] === 'number' && typeof data[idLayer].finalState[attr] === 'number') { lg[attr] = data[idLayer].finalState[attr] * profileProgress + data[idLayer].initialState[attr] * profileRemaining; } } } var ps; if (data[idLayer].zoomWidth && data[idLayer].zoomWidth.k !== 0) { ps = progress - data[idLayer].zoomWidth.ts; lg.width = data[idLayer].zoomWidth.k * ps * ps + data[idLayer].zoomWidth.ss; } if (data[idLayer].zoomHeight && data[idLayer].zoomHeight.k !== 0) { ps = progress - data[idLayer].zoomHeight.ts; lg.height = data[idLayer].zoomHeight.k * ps * ps + data[idLayer].zoomHeight.ss; } lg.clipped = data[idLayer].finalState.clipped; } } display.update(); } /* * Starts waiting before moving to the next frame. * * It the current frame has a timeout set, this method * will register a timer to move to the next frame automatically * after the specified time. * * If the current frame is the last, the presentation will * move to the first frame. */ function waitTimeout() { if (sozi.document.frames[currentFrameIndex].timeoutEnable) { waiting = true; var index = (currentFrameIndex + 1) % sozi.document.frames.length; nextFrameTimeout = window.setTimeout(function () { exports.moveToFrame(index); }, sozi.document.frames[currentFrameIndex].timeoutMs ); } } /* * Event handler: animation done. * * This method is called by animator when the current animation is finished. * * If the animation was a transition in the normal course of the presentation, * then we call the waitTimeout method to process the timeout property of the current frame. */ function onAnimationDone() { sourceFrameIndex = currentFrameIndex; if (playing) { waitTimeout(); } } /* * Starts the presentation from the given frame index (0-based). * * This method sets the 'playing' flag, shows the desired frame * and calls waitTimeout. */ exports.startFromIndex = function (index) { playing = true; waiting = false; sourceFrameIndex = index; currentFrameIndex = index; display.showFrame(sozi.document.frames[index]); waitTimeout(); }; exports.restart = function () { exports.startFromIndex(currentFrameIndex); }; /* * Stops the presentation. * * This method clears the 'playing'. * If the presentation was in 'waiting' mode due to a timeout * in the current frame, then it stops waiting. * The current animation is stopped in its current state. */ exports.stop = function () { animator.stop(); if (waiting) { window.clearTimeout(nextFrameTimeout); waiting = false; } playing = false; sourceFrameIndex = currentFrameIndex; }; function getZoomData(zoomPercent, s0, s1) { var result = { ss: ((zoomPercent < 0) ? Math.max(s0, s1) : Math.min(s0, s1)) * (100 - zoomPercent) / 100, ts: 0.5, k: 0 }; if (zoomPercent !== 0) { var a = s0 - s1; var b = s0 - result.ss; var c = s1 - result.ss; if (a !== 0) { var d = Math.sqrt(b * c); var u = (b - d) / a; var v = (b + d) / a; result.ts = (u > 0 && u <= 1) ? u : v; } result.k = b / result.ts / result.ts; } return result; } /* * Jump to a frame with the given index (0-based). * * This method does not animate the transition from the current * state of the display to the desired frame. * * The presentation is stopped: if a timeout has been set for the * target frame, it will be ignored. * * The URL hash is set to the given frame index (1-based). */ exports.jumpToFrame = function (index) { exports.stop(); sozi.events.fire('cleanup'); sourceFrameIndex = index; currentFrameIndex = index; display.showFrame(sozi.document.frames[index]); sozi.events.fire('framechange', index); }; /* * Returns an associative array where keys are layer names * and values are objects in the form { initialState: finalState: profile: zoomWidth: zoomHeight:} */ function getAnimationData(initialState, finalState, zoomPercent, profile) { var data = {}; for (var idLayer in initialState.layers) { if (initialState.layers.hasOwnProperty(idLayer)) { data[idLayer] = { initialState: new sozi.display.CameraState.instance(), finalState: new sozi.display.CameraState.instance() }; data[idLayer].profile = profile || finalState.layers[idLayer].transitionProfile; data[idLayer].initialState.setAtState(initialState.layers[idLayer]); // If the current layer is referenced in final state, copy the final properties // else, copy initial state to final state for the current layer. if (finalState.layers.hasOwnProperty(idLayer)) { data[idLayer].finalState.setAtState(finalState.layers[idLayer]); } else { data[idLayer].finalState.setAtState(initialState.layers[idLayer]); } // Keep the smallest angle difference between initial state and final state // TODO this should be handled in the interpolation function if (data[idLayer].finalState.angle - data[idLayer].initialState.angle > 180) { data[idLayer].finalState.setRawAngle(data[idLayer].finalState.angle - 360); } else if (data[idLayer].finalState.angle - data[idLayer].initialState.angle < -180) { data[idLayer].initialState.setRawAngle(data[idLayer].initialState.angle - 360); } var zp = zoomPercent || finalState.layers[idLayer].transitionZoomPercent; if (zp && finalState.layers.hasOwnProperty(idLayer)) { data[idLayer].zoomWidth = getZoomData(zp, initialState.layers[idLayer].width, finalState.layers[idLayer].width); data[idLayer].zoomHeight = getZoomData(zp, initialState.layers[idLayer].height, finalState.layers[idLayer].height); } } } return data; } exports.previewFrame = function (index) { currentFrameIndex = index; animator.start(DEFAULT_DURATION_MS, getAnimationData(display, sozi.document.frames[index], DEFAULT_ZOOM_PERCENT, sozi.animation.profiles[DEFAULT_PROFILE])); sozi.events.fire('framechange', index); }; /* * Moves to a frame with the given index (0-based). * * This method animates the transition from the current * state of the display to the desired frame. * * If the given frame index corresponds to the next frame in the list, * the transition properties of the next frame are used. * Otherwise, default transition properties are used. * * The URL hash is set to the given frame index (1-based). */ exports.moveToFrame = function (index) { if (waiting) { window.clearTimeout(nextFrameTimeout); waiting = false; } var durationMs, zoomPercent, profile; if (index === (currentFrameIndex + 1) % sozi.document.frames.length) { durationMs = sozi.document.frames[index].transitionDurationMs; zoomPercent = undefined; // Set for each layer profile = undefined; // Set for each layer } else { durationMs = DEFAULT_DURATION_MS; zoomPercent = DEFAULT_ZOOM_PERCENT; profile = sozi.animation.profiles[DEFAULT_PROFILE]; } sozi.events.fire('cleanup'); playing = true; currentFrameIndex = index; animator.start(durationMs, getAnimationData(display, sozi.document.frames[index], zoomPercent, profile)); sozi.events.fire('framechange', index); }; /* * Moves to the first frame of the presentation. */ exports.moveToFirst = function () { exports.moveToFrame(0); }; /* * Jumps to the previous frame */ exports.jumpToPrevious = function () { var index = currentFrameIndex; if (!animator.started || sourceFrameIndex <= currentFrameIndex) { index -= 1; } if (index >= 0) { exports.jumpToFrame(index); } }; /* * Moves to the previous frame. */ exports.moveToPrevious = function () { for (var index = currentFrameIndex - 1; index >= 0; index -= 1) { var frame = sozi.document.frames[index]; if (!frame.timeoutEnable || frame.timeoutMs !== 0) { exports.moveToFrame(index); break; } } }; /* * Jumps to the next frame */ exports.jumpToNext = function () { var index = currentFrameIndex; if (!animator.started || sourceFrameIndex >= currentFrameIndex) { index += 1; } if (index < sozi.document.frames.length) { exports.jumpToFrame(index); } }; /* * Moves to the next frame. */ exports.moveToNext = function () { if (currentFrameIndex < sozi.document.frames.length - 1 || sozi.document.frames[currentFrameIndex].timeoutEnable) { exports.moveToFrame((currentFrameIndex + 1) % sozi.document.frames.length); } }; /* * Moves to the last frame of the presentation. */ exports.moveToLast = function () { exports.moveToFrame(sozi.document.frames.length - 1); }; /* * Restores the current frame. * * This method restores the display to fit the current frame, * e.g. after the display has been zoomed or dragged. */ exports.moveToCurrent = function () { exports.moveToFrame(currentFrameIndex); }; /* * Shows all the document in the browser window. */ exports.showAll = function () { exports.stop(); sozi.events.fire('cleanup'); animator.start(DEFAULT_DURATION_MS, getAnimationData(display, display.getDocumentGeometry(), DEFAULT_ZOOM_PERCENT, sozi.animation.profiles[DEFAULT_PROFILE] ) ); }; /* * Event handler: display ready. */ function onDisplayReady() { exports.startFromIndex(sozi.location.getFrameIndex()); // Hack to fix the blank screen bug in Chrome/Chromium // See https://github.com/senshu/Sozi/issues/109 window.setTimeout(display.update, 1); } animator = new sozi.animation.Animator(onAnimationStep, onAnimationDone); sozi.events.listen('displayready', onDisplayReady); }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js * @depend player.js * @depend display.js */ module(this, 'sozi.actions', function (exports, window) { 'use strict'; // Module aliases var player = sozi.player; var display = sozi.display; // The global document object var document = window.document; // Constants: mouse button numbers var DRAG_BUTTON = 0; // Left button var TOC_BUTTON = 1; // Middle button // Constants: increments for zooming and rotating var SCALE_FACTOR = 1.05; var ROTATE_STEP = 5; // State variables for the drag action var dragButtonIsDown = false; var dragging = false; var dragClientX = 0; var dragClientY = 0; /* * Zooms the display in the given direction. * * Only the sign of direction is used: * - zoom in when direction > 0 * - zoom out when direction <= 0 * * The scaling is centered around point (x, y). */ function zoom(direction, x, y) { player.stop(); display.zoom(direction > 0 ? SCALE_FACTOR : 1 / SCALE_FACTOR, x, y); } /* * Rotate the display in the given direction. * * Only the sign of direction is used: * - rotate anticlockwise when direction > 0 * - rotate clockwise when direction <= 0 */ function rotate(direction) { player.stop(); display.rotate(direction > 0 ? ROTATE_STEP : -ROTATE_STEP); } /* * Show/hide the frame list. * * The presentation stops when the frame list is showed, * and restarts when the frame list is hidden. */ function toggleFrameList() { if (sozi.framelist.isVisible()) { sozi.framelist.hide(); player.restart(); } else { player.stop(); sozi.framelist.show(); } } /* * Event handler: mouse down. * * When the left button is pressed, we register the current coordinates * in case the mouse will be dragged. Flag 'dragButtonIsDown' is set until * the button is released (onMouseUp). This flag is used by onMouseMove. * * When the middle button is pressed, the table of contents is shown or hidden. */ function onMouseDown(evt) { if (evt.button === DRAG_BUTTON) { dragButtonIsDown = true; dragging = false; dragClientX = evt.clientX; dragClientY = evt.clientY; } else if (evt.button === TOC_BUTTON) { toggleFrameList(); } evt.stopPropagation(); evt.preventDefault(); } /* * Event handler: mouse move. * * If the left mouse button is down, then the mouse move is a drag action. * This method computes the displacement since the button was pressed or * since the last move, and updates the reference coordinates for the next move. */ function onMouseMove(evt) { if (dragButtonIsDown) { player.stop(); dragging = true; sozi.events.fire('cleanup'); display.drag(evt.clientX - dragClientX, evt.clientY - dragClientY); dragClientX = evt.clientX; dragClientY = evt.clientY; } evt.stopPropagation(); } /* * Event handler: mouse up. * * Releasing the left button resets the 'dragButtonIsDown' flag. */ function onMouseUp(evt) { if (evt.button === DRAG_BUTTON) { dragButtonIsDown = false; } evt.stopPropagation(); evt.preventDefault(); } /* * Event handler: context menu (i.e. right click). * * Right click goes one frame back. * * There is no 'click' event for the right mouse button and the menu * can't be disabled in 'onMouseDown'. */ function onContextMenu(evt) { player.moveToPrevious(); evt.stopPropagation(); evt.preventDefault(); } /* * Event handler: mouse click. * * Left-click moves the presentation to the next frame. * * No 'click' event is generated for the middle button in Firefox. * See 'onMouseDown' for middle click handling. * * Dragging the mouse produces a 'click' event when the button is released. * If flag 'dragging' was set by 'onMouseMove', then the click event is the result * of a drag action. */ function onClick(evt) { if (!dragging && evt.button !== TOC_BUTTON) { player.moveToNext(); } evt.stopPropagation(); evt.preventDefault(); } /* * Event handler: mouse wheel. * * Rolling the mouse wheel stops the presentation and zooms the current display. * * FIXME shift key does not work in Opera */ function onWheel(evt) { if (!evt) { evt = window.event; } var delta = 0; if (evt.wheelDelta) { // IE and Opera delta = evt.wheelDelta; } else if (evt.detail) { // Mozilla delta = -evt.detail; } if (delta !== 0) { if (evt.shiftKey) { rotate(delta); } else { zoom(delta, evt.clientX, evt.clientY); } } evt.stopPropagation(); evt.preventDefault(); } /* * Event handler: key press. * * Keyboard handling is split into two methods: onKeyPress and onKeyDown * in order to get the same behavior across browsers. * * This method handles character keys '+', '-', '=', 'F' and 'T'. */ function onKeyPress(evt) { // Keys with modifiers are ignored if (evt.altKey || evt.ctrlKey || evt.metaKey) { return; } switch (evt.charCode || evt.keyCode) { case 43: // + zoom(1, window.innerWidth / 2, window.innerHeight / 2); break; case 45: // - zoom(-1, window.innerWidth / 2, window.innerHeight / 2); break; case 61: // = player.moveToCurrent(); break; case 70: // F case 102: // f player.showAll(); break; case 84: // T case 116: // t toggleFrameList(); break; case 82: // R rotate(-1); break; case 114: // r rotate(1); break; } evt.stopPropagation(); evt.preventDefault(); } /* * Event handler: key down. * * Keyboard handling is split into two methods: onKeyPress and onKeyDown * in order to get the same behavior across browsers. * * This method handles navigation keys (arrows, page up/down, home, end) * and the space and enter keys. */ function onKeyDown(evt) { // Keys with modifiers are ignored if (evt.altKey || evt.ctrlKey || evt.metaKey) { return; } switch (evt.keyCode) { case 36: // Home player.moveToFirst(); break; case 35: // End player.moveToLast(); break; case 38: // Arrow up player.jumpToPrevious(); break; case 33: // Page up case 37: // Arrow left player.moveToPrevious(); break; case 40: // Arrow down player.jumpToNext(); break; case 34: // Page down case 39: // Arrow right case 13: // Enter case 32: // Space player.moveToNext(); break; } evt.stopPropagation(); // In Chrome/Chromium, preventDefault() inhibits the 'keypress' event } function onLoad() { var svgRoot = document.documentElement; // TODO also use shift-click as an alternative for middle-click svgRoot.addEventListener('click', onClick, false); svgRoot.addEventListener('mousedown', onMouseDown, false); svgRoot.addEventListener('mouseup', onMouseUp, false); svgRoot.addEventListener('mousemove', onMouseMove, false); svgRoot.addEventListener('keypress', onKeyPress, false); svgRoot.addEventListener('keydown', onKeyDown, false); svgRoot.addEventListener('contextmenu', onContextMenu, false); svgRoot.addEventListener('DOMMouseScroll', onWheel, false); // Mozilla window.onmousewheel = onWheel; } window.addEventListener('load', onLoad, false); }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js * @depend events.js */ module(this, 'sozi.document', function (exports, window) { 'use strict'; // An alias to the global document object var document = window.document; // Constant: the Sozi namespace var SOZI_NS = 'http://sozi.baierouge.fr'; // Constant: the default frame properties, if missing in the SVG document var DEFAULTS = { 'title': 'Untitled', 'sequence': '0', 'hide': 'true', 'clip': 'false', 'timeout-enable': 'false', 'timeout-ms': '5000', 'transition-duration-ms': '1000', 'transition-zoom-percent': '0', 'transition-profile': 'linear' }; // The definitions of all valid frames in the current document exports.frames = []; // The list of layer ids managed by Sozi exports.idLayerList = []; /* * Returns the value of an attribute of a given Sozi SVG element. * * If the attribute is not set, then a default value is returned. * See DEFAULTS. */ function readAttribute(soziElement, attr) { var value = soziElement.getAttributeNS(SOZI_NS, attr); return value === '' ? DEFAULTS[attr] : value; } function readLayerProperties(frame, idLayer, soziElement) { var layer = frame.layers[idLayer] = frame.layers[idLayer] || new sozi.display.CameraState.instance(); if (typeof layer.hide === 'undefined' || soziElement.hasAttributeNS(SOZI_NS, 'hide')) { layer.hide = readAttribute(soziElement, 'hide') === 'true'; } if (typeof layer.transitionZoomPercent === 'undefined' || soziElement.hasAttributeNS(SOZI_NS, 'transition-zoom-percent')) { layer.transitionZoomPercent = parseInt(readAttribute(soziElement, 'transition-zoom-percent'), 10); } if (typeof layer.transitionProfile === 'undefined' || soziElement.hasAttributeNS(SOZI_NS, 'transition-profile')) { layer.transitionProfile = sozi.animation.profiles[readAttribute(soziElement, 'transition-profile') || 'linear']; } if (soziElement.hasAttributeNS(SOZI_NS, 'refid')) { // The previous value of the 'clip' attribute will be preserved // when setting the new geometry object. var svgElement = document.getElementById(soziElement.getAttributeNS(SOZI_NS, 'refid')); if (svgElement) { if (layer.hide) { svgElement.style.visibility = 'hidden'; } layer.setAtElement(svgElement); } } if (soziElement.hasAttributeNS(SOZI_NS, 'clip')) { layer.setClipped(readAttribute(soziElement, 'clip') === 'true'); } } /* * Builds the list of frames from the current document. * * This method collects all elements with tag 'sozi:frame' and * retrieves their geometrical and animation attributes. * SVG elements that should be hidden during the presentation are hidden. * * The resulting list is available in frames, sorted by frame indices. */ function readFrames() { // Collect all group ids of <layer> elements var soziLayerList = Array.prototype.slice.call(document.getElementsByTagNameNS(SOZI_NS, 'layer')); soziLayerList.forEach(function (soziLayer) { var idLayer = soziLayer.getAttributeNS(SOZI_NS, 'group'); if (idLayer && exports.idLayerList.indexOf(idLayer) === -1 && document.getElementById(idLayer)) { exports.idLayerList.push(idLayer); } }); // If at least one <frame> element has a refid attribute, // reorganize the document, grouping objects that do not belong // to a group referenced in <layer> elements var soziFrameList = Array.prototype.slice.call(document.getElementsByTagNameNS(SOZI_NS, 'frame')); if (soziFrameList.some(function (soziFrame) { return soziFrame.hasAttributeNS(SOZI_NS, 'refid'); })) { var svgRoot = document.documentElement; var SVG_NS = 'http://www.w3.org/2000/svg'; // Create the first wrapper group var svgWrapper = document.createElementNS(SVG_NS, 'g'); // For each child of the root SVG element var svgElementList = Array.prototype.slice.call(svgRoot.childNodes); svgElementList.forEach(function (svgElement, index) { if (!svgElement.getAttribute) { // Remove text elements svgRoot.removeChild(svgElement); } else if (exports.idLayerList.indexOf(svgElement.getAttribute('id')) === -1) { // If the current element is not a referenced layer, // move it to the current wrapper element // FIXME move graphic elements only svgRoot.removeChild(svgElement); svgWrapper.appendChild(svgElement); } else if (svgWrapper.firstChild) { // If the current element is a referenced layer, // and if there were other non-referenced elements before it, // insert the wrapper group before the current element svgWrapper.setAttribute('id', 'sozi-wrapper-' + index); exports.idLayerList.push('sozi-wrapper-' + index); svgRoot.insertBefore(svgWrapper, svgElement); // Prepare a new wrapper element svgWrapper = document.createElementNS(SVG_NS, 'g'); } }); // Append last wrapper if needed if (svgWrapper.firstChild) { svgWrapper.setAttribute('id', 'sozi-wrapper-' + svgElementList.length); exports.idLayerList.push('sozi-wrapper-' + svgElementList.length); svgRoot.appendChild(svgWrapper); } } // Analyze <frame> elements soziFrameList.forEach(function (soziFrame, indexFrame) { var newFrame = { id: soziFrame.getAttribute('id'), title: readAttribute(soziFrame, 'title'), sequence: parseInt(readAttribute(soziFrame, 'sequence'), 10), timeoutEnable: readAttribute(soziFrame, 'timeout-enable') === 'true', timeoutMs: parseInt(readAttribute(soziFrame, 'timeout-ms'), 10), transitionDurationMs: parseInt(readAttribute(soziFrame, 'transition-duration-ms'), 10), layers: {} }; // Get the default properties for all layers, either from // the current <frame> element or from the corresponding // layer in the previous frame. // Those properties can later be overriden by <layer> elements exports.idLayerList.forEach(function (idLayer) { if (indexFrame === 0 || idLayer.search('sozi-wrapper-[0-9]+') !== -1) { // In the first frame, or in wrapper layers, // read layer attributes from the <frame> element readLayerProperties(newFrame, idLayer, soziFrame); } else { // After the first frame, in referenced layers, // copy attributes from the corresponding layer in the previous frame var currentLayer = newFrame.layers[idLayer] = {}; var previousLayer = exports.frames[exports.frames.length - 1].layers[idLayer]; for (var attr in previousLayer) { if (previousLayer.hasOwnProperty(attr)) { currentLayer[attr] = previousLayer[attr]; } } } }); // Collect and analyze <layer> elements in the current <frame> element soziLayerList = Array.prototype.slice.call(soziFrame.getElementsByTagNameNS(SOZI_NS, 'layer')); soziLayerList.forEach(function (soziLayer) { var idLayer = soziLayer.getAttributeNS(SOZI_NS, 'group'); if (idLayer && exports.idLayerList.indexOf(idLayer) !== -1) { readLayerProperties(newFrame, idLayer, soziLayer); } }); // If the <frame> element has at least one valid layer, // add it to the frame list for (var idLayer in newFrame.layers) { if (newFrame.layers.hasOwnProperty(idLayer)) { exports.frames.push(newFrame); break; } } }); // Sort frames by sequence index exports.frames.sort( function (a, b) { return a.sequence - b.sequence; } ); } /* * Event handler: document load. * * This function reads the frames from the document. */ function onLoad() { document.documentElement.removeAttribute('viewBox'); readFrames(); sozi.events.fire('documentready'); } window.addEventListener('load', onLoad, false); }); /* * Sozi - A presentation tool using the SVG standard * * Copyright (C) 2010-2012 Guillaume Savaton * * This program is dual licensed under the terms of the MIT license * or the GNU General Public License (GPL) version 3. * A copy of both licenses is provided in the doc/ folder of the * official release of Sozi. * * See http://sozi.baierouge.fr/wiki/en:license for details. * * @depend module.js * @depend events.js */ module(this, 'sozi.location', function (exports, window) { 'use strict'; var changedFromWithin = false; /* * Returns the frame index given in the URL hash. * * In the URL, the frame index starts a 1. * This method converts it into a 0-based index. * * If the URL hash is not a positive integer, then 0 is returned. * It the URL hash is an integer greater than the last frame index, then * the last frame index is returned. */ exports.getFrameIndex = function () { var index = window.location.hash ? parseInt(window.location.hash.slice(1), 10) - 1 : 0; if (isNaN(index) || index < 0) { return 0; } else if (index >= sozi.document.frames.length) { return sozi.document.frames.length - 1; } else { return index; } }; /* * Event handler: hash change. * * This function is called when the URL hash is changed. * If the hash was changed manually in the address bar, and if it corresponds to * a valid frame number, then the presentation moves to that frame. * * The hashchange event can be triggered externally, by the user modifying the URL, * or internally, by the script modifying window.location.hash. */ function onHashChange() { var index = exports.getFrameIndex(); if (!changedFromWithin) { sozi.player.moveToFrame(index); } changedFromWithin = false; } /* * Event handler: frame change. * * This function is called when the presentation has reached a * new frame. * The URL hash is changed based on the provided frame index. */ function onFrameChange(index) { changedFromWithin = true; window.location.hash = '#' + (index + 1); } /* * Event handler: document load. * * This function registers the 'framechange' handler. */ function onLoad() { sozi.events.listen('framechange', onFrameChange); } window.addEventListener('hashchange', onHashChange, false); window.addEventListener('load', onLoad, false); });
{ "pile_set_name": "Github" }
using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using GalaSoft.MvvmLight.Command; using Plugin.Connectivity; using TorneoPredicciones.Interfaces; using TorneoPredicciones.Models; using TorneoPredicciones.Services; using Xamarin.Forms; using Point = TorneoPredicciones.Models.Point; namespace TorneoPredicciones.ViewModels { public class MainViewModel : INotifyPropertyChanged { #region Eventos public event PropertyChangedEventHandler PropertyChanged; #endregion #region Atriutos private readonly ApiService _apiService; private readonly DataService _dataService; private User _currentUser; #endregion #region Singleton private static MainViewModel _instance; public static MainViewModel GetInstance() { return _instance ?? (_instance = new MainViewModel()); } #endregion //notas, siempre se crea una pagina, luego una viewmodel y despues se instancia en la MainViewModel (osea yo) para asi asociar // usando el patron Locator, en la page, el binding principal, el nombre que pongamos aqui es el nombre al cual bindamos la pagina // que a su vez envia a bindar a la viwemodel correspondiente //recordar especificar en el loadmenu el nombre de la pagina y configurar en el MenuItemViewModel hacia donde va a navegar //pues es en el menuitemviewmodel donde se instancian los viewmodel (new) usando este patron //de igual forma en el navigationservice se debe crear en la funcion navigate hacia donde va pinchada la accion #region Properties public ProfileViewModel Profile { get; set; } public LoginViewModel Login { get; set; } public SelectTournamentViewModel SelectTournament { get; set; } public SelectMatchViewModel SelectMatch { get; set; } public EditPredictionViewModel EditPrediction { get; set; } public NewUserViewModel NewUser { get; set; } public SelectGroupViewModel SelectGroup { get; set; } public ChangePasswordViewModel ChangePassword { get; set; } public ForgotPasswordViewModel ForgotPassword { get; set; } public MyResultsViewModel MyResults { get; set; } public ConfigViewModel Config { get; set; } public PositionsViewModel Positions { get; set; } public UsersGroupViewModel UsersGroup { get; set; } public SelectUserGroupViewModel SelectUserGroup { get; set; } public ObservableCollection<MenuItemViewModel> Menu { get; set; } //public User CurrentUser { get; set; } public User CurrentUser { set { if (_currentUser == value) return; _currentUser = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentUser")); } get { return _currentUser; } } #endregion #region Constructores public MainViewModel() { _instance = this; Login = new LoginViewModel(); _apiService= new ApiService(); _dataService= new DataService(); LoadMenu(); } #endregion #region Comandos public ICommand RefreshPointsCommand { get {return new RelayCommand(RefreshPoints);} } private async void RefreshPoints() { if (!CrossConnectivity.Current.IsConnected) { return; } var isReachable = await CrossConnectivity.Current.IsRemoteReachable("notasti.com"); if (!isReachable) { return; } var parameters = _dataService.First<Parameter>(false); var user = _dataService.First<User>(false); var response = await _apiService.GetPoints(parameters.UrlBase, "/api", "/Users/GetPoints", user.TokenType, user.AccessToken,user.UserId); if (!response.IsSuccess) { return; } var point = (Point) response.Result; if (CurrentUser.Points != point.Points) { CurrentUser.Points = point.Points; _dataService.Update(CurrentUser); //actualizamos la base de datos local PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentUser")); } } #endregion #region Metodos public void RegisterDevice() { var register = DependencyService.Get<IRegisterDevice>(); register.RegisterDevice(); } private void LoadMenu() { Menu = new ObservableCollection<MenuItemViewModel>(); Menu.Add(new MenuItemViewModel { Icon = "predictions.png", PageName = "SelectTournamentPage", Title = "Predictions", }); Menu.Add(new MenuItemViewModel { Icon = "groups.png", PageName = "SelectUserGroupPage", Title = "My Groups", }); Menu.Add(new MenuItemViewModel { Icon = "tournaments.png", PageName = "SelectTournamentPage", Title = "Tournaments", }); Menu.Add(new MenuItemViewModel { Icon = "myresults.png", PageName = "SelectTournamentPage", Title = "My Results", }); Menu.Add(new MenuItemViewModel { Icon = "config.png", PageName = "ConfigPage", Title = "Config", }); Menu.Add(new MenuItemViewModel { Icon = "logut.png", PageName = "LoginPage", Title = "Logut", }); Menu.Add(new MenuItemViewModel { Icon = "groups.png", PageName = "SelectGroupPage", Title = "All Groups", }); } public void SetCurrentUser(User user) { CurrentUser = user; } #endregion } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="collation"> <UniqueIdentifier>{68f85997-0019-471f-b155-5eed0137f082}</UniqueIdentifier> </Filter> <Filter Include="formatting"> <UniqueIdentifier>{8152306c-460d-49f3-961a-c500eda24e9d}</UniqueIdentifier> </Filter> <Filter Include="misc"> <UniqueIdentifier>{15349ca9-e31d-4f6b-a4c4-f73892fa5aa6}</UniqueIdentifier> </Filter> <Filter Include="regex"> <UniqueIdentifier>{faac495b-a9d6-47ad-ae47-a56c30c60b3a}</UniqueIdentifier> </Filter> <Filter Include="transforms"> <UniqueIdentifier>{e750fa6c-e471-4db0-92f9-81c84d84b5ba}</UniqueIdentifier> </Filter> <Filter Include="charset detect"> <UniqueIdentifier>{59edb5a3-26d1-4c91-af50-4aa35e6e9730}</UniqueIdentifier> </Filter> <Filter Include="spoof"> <UniqueIdentifier>{7b4a0782-fad3-44cd-b3b4-e75b0356d600}</UniqueIdentifier> </Filter> </ItemGroup> <ItemGroup> <ClCompile Include="coleitr.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="coll.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="search.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="sortkey.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="stsearch.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="ucol.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="ucol_res.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="ucol_sit.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="ucoleitr.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="usearch.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="affixpatternparser.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="dayperiodrules.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="decimfmtimpl.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="digitaffix.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="digitaffixesandpadding.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="digitformatter.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="digitgrouping.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="digitinterval.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="pluralaffix.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="precision.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="smallintformatter.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="valueformatter.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="visibledigits.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="astro.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="basictz.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="buddhcal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="calendar.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="cecal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="chnsecal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="choicfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="coptccal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="curramt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="currfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="currpinf.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="currunit.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="dangical.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="datefmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="dcfmtsym.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="decContext.c"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="decfmtst.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="decimalformatpattern.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="decimfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="decNumber.c"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="digitlst.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="dtfmtsym.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="dtitvfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="dtitvinf.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="dtptngen.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="dtrule.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="ethpccal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="fmtable.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="fmtable_cnv.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="format.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="fphdlimp.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="fpositer.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="gender.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="gregocal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="gregoimp.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="hebrwcal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="indiancal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="islamcal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="japancal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="measfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="measunit.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="measure.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="msgfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="nfrs.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="nfrule.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="nfsubs.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="numfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="numsys.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="olsontz.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="persncal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="plurfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="plurrule.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="quantityformatter.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="rbnf.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="rbtz.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="reldatefmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="reldtfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="scientificnumberformatter.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="selfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="sharedbreakiterator.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="simpletz.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="smpdtfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="smpdtfst.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="standardplural.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="taiwncal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="timezone.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="tmunit.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="tmutamt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="tmutfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="tzrule.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="tztrans.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="ucal.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="udat.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="udateintervalformat.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="udatpg.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="ufieldpositer.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="ulocdata.c"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="umsg.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="unum.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="unumsys.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="upluralrules.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="utmscale.c"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="vtzone.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="vzone.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="windtfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="winnmfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="wintzimpl.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="zonemeta.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="zrule.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="ztrans.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="ucln_in.cpp"> <Filter>misc</Filter> </ClCompile> <ClCompile Include="regexcmp.cpp"> <Filter>regex</Filter> </ClCompile> <ClCompile Include="regeximp.cpp"> <Filter>regex</Filter> </ClCompile> <ClCompile Include="regexst.cpp"> <Filter>regex</Filter> </ClCompile> <ClCompile Include="regextxt.cpp"> <Filter>regex</Filter> </ClCompile> <ClCompile Include="rematch.cpp"> <Filter>regex</Filter> </ClCompile> <ClCompile Include="repattrn.cpp"> <Filter>regex</Filter> </ClCompile> <ClCompile Include="uregex.cpp"> <Filter>regex</Filter> </ClCompile> <ClCompile Include="uregexc.cpp"> <Filter>regex</Filter> </ClCompile> <ClCompile Include="anytrans.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="brktrans.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="casetrn.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="cpdtrans.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="esctrn.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="funcrepl.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="name2uni.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="nortrans.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="nultrans.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="quant.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="rbt.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="rbt_data.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="rbt_pars.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="rbt_rule.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="rbt_set.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="remtrans.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="strmatch.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="strrepl.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="titletrn.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="tolowtrn.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="toupptrn.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="translit.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="transreg.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="tridpars.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="unesctrn.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="uni2name.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="utrans.cpp"> <Filter>transforms</Filter> </ClCompile> <ClCompile Include="csdetect.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="csmatch.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="csr2022.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="csrecog.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="csrmbcs.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="csrsbcs.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="csrucode.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="csrutf8.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="inputext.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="ucsdet.cpp"> <Filter>charset detect</Filter> </ClCompile> <ClCompile Include="identifier_info.cpp"> <Filter>spoof</Filter> </ClCompile> <ClCompile Include="scriptset.cpp"> <Filter>spoof</Filter> </ClCompile> <ClCompile Include="uspoof.cpp"> <Filter>spoof</Filter> </ClCompile> <ClCompile Include="uspoof_build.cpp"> <Filter>spoof</Filter> </ClCompile> <ClCompile Include="uspoof_conf.cpp"> <Filter>spoof</Filter> </ClCompile> <ClCompile Include="uspoof_impl.cpp"> <Filter>spoof</Filter> </ClCompile> <ClCompile Include="uspoof_wsconf.cpp"> <Filter>spoof</Filter> </ClCompile> <ClCompile Include="alphaindex.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="tzfmt.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="tzgnames.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="tznames.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="tznames_impl.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="compactdecimalformat.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="region.cpp"> <Filter>formatting</Filter> </ClCompile> <ClCompile Include="uregion.cpp"> <Filter>formatting</Filter> </ClCompile> </ItemGroup> <ItemGroup> <ClCompile Include="bocsu.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collation.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationbuilder.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationcompare.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationdata.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationdatabuilder.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationdatareader.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationdatawriter.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationfastlatin.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationfastlatinbuilder.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationfcd.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationiterator.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationkeys.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationroot.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationrootelements.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationruleparser.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationsets.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationsettings.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationtailoring.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="collationweights.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="rulebasedcollator.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="uitercollationiterator.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="utf8collationiterator.cpp"> <Filter>collation</Filter> </ClCompile> <ClCompile Include="utf16collationiterator.cpp"> <Filter>collation</Filter> </ClCompile> <ClInclude Include="bocsu.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="ucol_imp.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="usrchimp.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="affixpatternparser.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="decimalformatpatternimpl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="decimfmtimpl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="digitaffix.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="digitaffixesandpadding.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="digitformatter.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="digitgrouping.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="digitinterval.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="pluralaffix.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="precision.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="significantdigitinterval.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="smallintformatter.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="valueformatter.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="visibledigits.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="astro.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="buddhcal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="cecal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="chnsecal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="coptccal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="currfmt.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="dangical.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="dayperiodrules.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="decContext.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="decfmtst.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="decimalformatpattern.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="decNumber.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="decNumberLocal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="digitlst.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="dtitv_impl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="dtptngen_impl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="ethpccal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="fphdlimp.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="gregoimp.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="hebrwcal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="indiancal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="islamcal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="japancal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="msgfmt_impl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="nfrlist.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="nfrs.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="nfrule.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="nfsubs.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="olsontz.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="persncal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="plurrule_impl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="quantityformatter.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="reldtfmt.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="sharedbreakiterator.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="sharedcalendar.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="shareddateformatsymbols.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="sharednumberformat.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="sharedpluralrules.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="smpdtfst.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="standardplural.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="taiwncal.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="umsg_imp.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="vzone.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="windtfmt.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="winnmfmt.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="wintzimpl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="zonemeta.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="zrule.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="ztrans.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="ucln_in.h"> <Filter>misc</Filter> </ClInclude> <ClInclude Include="regexcmp.h"> <Filter>regex</Filter> </ClInclude> <ClInclude Include="regexcst.h"> <Filter>regex</Filter> </ClInclude> <ClInclude Include="regeximp.h"> <Filter>regex</Filter> </ClInclude> <ClInclude Include="regexst.h"> <Filter>regex</Filter> </ClInclude> <ClInclude Include="regextxt.h"> <Filter>regex</Filter> </ClInclude> <ClInclude Include="anytrans.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="brktrans.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="casetrn.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="cpdtrans.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="esctrn.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="funcrepl.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="name2uni.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="nortrans.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="nultrans.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="quant.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="rbt.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="rbt_data.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="rbt_pars.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="rbt_rule.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="rbt_set.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="remtrans.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="strmatch.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="strrepl.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="titletrn.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="tolowtrn.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="toupptrn.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="transreg.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="tridpars.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="unesctrn.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="uni2name.h"> <Filter>transforms</Filter> </ClInclude> <ClInclude Include="csdetect.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="csmatch.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="csr2022.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="csrecog.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="csrmbcs.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="csrsbcs.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="csrucode.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="csrutf8.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="inputext.h"> <Filter>charset detect</Filter> </ClInclude> <ClInclude Include="identifier_info.h"> <Filter>spoof</Filter> </ClInclude> <ClInclude Include="scriptset.h"> <Filter>spoof</Filter> </ClInclude> <ClInclude Include="uspoof_conf.h"> <Filter>spoof</Filter> </ClInclude> <ClInclude Include="uspoof_impl.h"> <Filter>spoof</Filter> </ClInclude> <ClInclude Include="uspoof_wsconf.h"> <Filter>spoof</Filter> </ClInclude> <ClInclude Include="tzgnames.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="tznames_impl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="numsys_impl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="dcfmtimp.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="selfmtimpl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="region_impl.h"> <Filter>formatting</Filter> </ClInclude> <ClInclude Include="collation.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationbuilder.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationcompare.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationdata.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationdatabuilder.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationdatareader.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationdatawriter.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationfastlatin.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationfastlatinbuilder.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationfcd.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationiterator.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationkeys.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationroot.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationrootelements.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationruleparser.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationsets.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationsettings.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationtailoring.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="collationweights.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="utf16collationiterator.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="uitercollationiterator.h"> <Filter>collation</Filter> </ClInclude> <ClInclude Include="utf8collationiterator.h"> <Filter>collation</Filter> </ClInclude> </ItemGroup> <ItemGroup> <ResourceCompile Include="i18n.rc"> <Filter>misc</Filter> </ResourceCompile> </ItemGroup> <ItemGroup> <CustomBuild Include="unicode\coleitr.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\coll.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\search.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\sortkey.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\stsearch.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\tblcoll.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\ucol.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\ucoleitr.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\usearch.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\basictz.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\calendar.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\choicfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\curramt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\currunit.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\datefmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\dcfmtsym.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\decimfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\dtfmtsym.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\dtitvfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\dtitvinf.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\dtptngen.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\dtrule.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\fieldpos.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\fmtable.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\format.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\fpositer.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\gender.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\gregocal.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\measfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\measunit.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\measure.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\msgfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\numfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\numsys.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\plurfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\plurrule.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\rbnf.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\rbtz.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\scientificnumberformatter.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\selfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\simpletz.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\smpdtfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\timezone.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\tmunit.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\tmutamt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\tmutfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\tzrule.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\tztrans.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\ucal.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\udat.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\udateintervalformat.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\udatpg.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\ugender.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\ufieldpositer.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\ulocdata.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\umsg.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\unum.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\unumsys.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\upluralrules.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\ureldatefmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\utmscale.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\vtzone.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\regex.h"> <Filter>regex</Filter> </CustomBuild> <CustomBuild Include="unicode\uregex.h"> <Filter>regex</Filter> </CustomBuild> <CustomBuild Include="unicode\translit.h"> <Filter>transforms</Filter> </CustomBuild> <CustomBuild Include="unicode\unirepl.h"> <Filter>transforms</Filter> </CustomBuild> <CustomBuild Include="unicode\utrans.h"> <Filter>transforms</Filter> </CustomBuild> <CustomBuild Include="unicode\ucsdet.h"> <Filter>charset detect</Filter> </CustomBuild> <CustomBuild Include="unicode\uspoof.h"> <Filter>spoof</Filter> </CustomBuild> <CustomBuild Include="unicode\alphaindex.h"> <Filter>collation</Filter> </CustomBuild> <CustomBuild Include="unicode\tzfmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\tznames.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\compactdecimalformat.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\currpinf.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\region.h"> <Filter>misc</Filter> </CustomBuild> <CustomBuild Include="unicode\uregion.h"> <Filter>misc</Filter> </CustomBuild> <CustomBuild Include="unicode\reldatefmt.h"> <Filter>formatting</Filter> </CustomBuild> <CustomBuild Include="unicode\uformattable.h"> <Filter>formatting</Filter> </CustomBuild> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
package pflag import ( "fmt" "net" "strconv" ) // -- net.IPMask value type ipMaskValue net.IPMask func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue { *p = val return (*ipMaskValue)(p) } func (i *ipMaskValue) String() string { return net.IPMask(*i).String() } func (i *ipMaskValue) Set(s string) error { ip := ParseIPv4Mask(s) if ip == nil { return fmt.Errorf("failed to parse IP mask: %q", s) } *i = ipMaskValue(ip) return nil } func (i *ipMaskValue) Type() string { return "ipMask" } // ParseIPv4Mask written in IP form (e.g. 255.255.255.0). // This function should really belong to the net package. func ParseIPv4Mask(s string) net.IPMask { mask := net.ParseIP(s) if mask == nil { if len(s) != 8 { return nil } // net.IPMask.String() actually outputs things like ffffff00 // so write a horrible parser for that as well :-( m := []int{} for i := 0; i < 4; i++ { b := "0x" + s[2*i:2*i+2] d, err := strconv.ParseInt(b, 0, 0) if err != nil { return nil } m = append(m, int(d)) } s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3]) mask = net.ParseIP(s) if mask == nil { return nil } } return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15]) } func parseIPv4Mask(sval string) (interface{}, error) { mask := ParseIPv4Mask(sval) if mask == nil { return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval) } return mask, nil } // GetIPv4Mask return the net.IPv4Mask value of a flag with the given name func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) { val, err := f.getFlagType(name, "ipMask", parseIPv4Mask) if err != nil { return nil, err } return val.(net.IPMask), nil } // IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. // The argument p points to an net.IPMask variable in which to store the value of the flag. func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { f.VarP(newIPMaskValue(value, p), name, "", usage) } // IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { f.VarP(newIPMaskValue(value, p), name, shorthand, usage) } // IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. // The argument p points to an net.IPMask variable in which to store the value of the flag. func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { CommandLine.VarP(newIPMaskValue(value, p), name, "", usage) } // IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage) } // IPMask defines an net.IPMask flag with specified name, default value, and usage string. // The return value is the address of an net.IPMask variable that stores the value of the flag. func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask { p := new(net.IPMask) f.IPMaskVarP(p, name, "", value, usage) return p } // IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { p := new(net.IPMask) f.IPMaskVarP(p, name, shorthand, value, usage) return p } // IPMask defines an net.IPMask flag with specified name, default value, and usage string. // The return value is the address of an net.IPMask variable that stores the value of the flag. func IPMask(name string, value net.IPMask, usage string) *net.IPMask { return CommandLine.IPMaskP(name, "", value, usage) } // IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash. func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { return CommandLine.IPMaskP(name, shorthand, value, usage) }
{ "pile_set_name": "Github" }
import _plotly_utils.basevalidators class HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="hoverlabel", parent_name="scattergeo", **kwargs): super(HoverlabelValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Hoverlabel"), data_docs=kwargs.pop( "data_docs", """ align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for align . bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for bgcolor . bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for bordercolor . font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for namelength . """, ), **kwargs )
{ "pile_set_name": "Github" }
.modal.fade#interconnect-modal{ tabindex: -1, role: 'dialog', aria: { labelledby: 'interconnect-modal-label', hidden: true } } .modal-dialog.modal-dialog-centered{ role: 'document' } .modal-content = form_for(RemoteProject.new, as: :project, url: interconnects_path) do |f| .modal-header %h5.modal-title#interconnect-modal-label Add custom OBS instance .modal-body .form-group = f.label :name, 'Local Project Name' %abbr.text-danger{ title: 'required' } * = f.text_field :name, class: 'form-control', required: true, placeholder: 'Add a name for your project' .form-group = f.label :remote_url, 'Remote OBS api url' %abbr.text-danger{ title: 'required' } * = f.text_field :remoteurl, class: 'form-control', required: true, placeholder: 'Add an OBS api url' .form-group = f.label :title %abbr.text-danger{ title: 'required' } * = f.text_field :title, class: 'form-control', required: true, placeholder: 'Remote OBS instance' .form-group = f.label :description %abbr.text-danger{ title: 'required' } * = f.text_field :description, class: 'form-control', required: true, placeholder: 'This project is representing a remote build service instance.' .modal-footer = render partial: 'webui/shared/dialog_action_buttons'
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); /** * This file is part of the Yasumi package. * * Copyright (c) 2015 - 2020 AzuyaLabs * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Sacha Telgenhof <[email protected]> */ namespace Yasumi\tests\Spain\Catalonia; use Yasumi\tests\Spain\SpainBaseTestCase; use Yasumi\tests\YasumiBase; /** * Base class for test cases of the Catalonia (Spain) holiday provider. */ abstract class CataloniaBaseTestCase extends SpainBaseTestCase { use YasumiBase; /** * Name of the region (e.g. country / state) to be tested */ public const REGION = 'Spain/Catalonia'; /** * Timezone in which this provider has holidays defined */ public const TIMEZONE = 'Europe/Madrid'; }
{ "pile_set_name": "Github" }
From 514985ae786dcde9842e46899ef5b6218662a119 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Fern=C3=A1ndez=20Rojas?= <[email protected]> Date: Sat, 7 Mar 2015 16:32:51 +0100 Subject: [PATCH 14/14] Add OSX and FreeBSD support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Álvaro Fernández Rojas <[email protected]> --- Makefile | 9 ++++++++- src/boot.c | 1 + src/check.c | 1 + src/endian.h | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/fat.c | 1 + src/fatlabel.c | 1 + src/fsck.fat.h | 3 +-- src/io.h | 2 +- src/lfn.c | 1 + src/mkfs.fat.c | 19 ++++++++++++++++--- src/types.h | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 11 files changed, 145 insertions(+), 7 deletions(-) create mode 100644 src/endian.h create mode 100644 src/types.h diff --git a/Makefile b/Makefile index 1593f3d..7359a79 100644 --- a/Makefile +++ b/Makefile @@ -28,12 +28,19 @@ DOCDIR = $(PREFIX)/share/doc MANDIR = $(PREFIX)/share/man #OPTFLAGS = -O2 -fomit-frame-pointer -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -OPTFLAGS = -O2 -fomit-frame-pointer -D_GNU_SOURCE $(shell getconf LFS_CFLAGS) +OPTFLAGS = -O2 -fomit-frame-pointer -D_GNU_SOURCE #WARNFLAGS = -Wall -pedantic -std=c99 WARNFLAGS = -Wall -Wextra -Wno-sign-compare -Wno-missing-field-initializers -Wmissing-prototypes -Wstrict-prototypes -Wwrite-strings DEBUGFLAGS = -g CFLAGS += $(OPTFLAGS) $(WARNFLAGS) $(DEBUGFLAGS) +UNAME_S := $(shell uname -s) +ifeq ($(UNAME_S),Darwin) + LDLIBS += -liconv +else + OPTFLAGS += $(shell getconf LFS_CFLAGS) +endif + VPATH = src all: build diff --git a/src/boot.c b/src/boot.c index 0c0918f..1da9889 100644 --- a/src/boot.c +++ b/src/boot.c @@ -31,6 +31,7 @@ #include <time.h> #include "common.h" +#include "endian.h" #include "fsck.fat.h" #include "fat.h" #include "io.h" diff --git a/src/check.c b/src/check.c index 488f715..17ff16a 100644 --- a/src/check.c +++ b/src/check.c @@ -31,6 +31,7 @@ #include <time.h> #include "common.h" +#include "endian.h" #include "fsck.fat.h" #include "io.h" #include "fat.h" diff --git a/src/endian.h b/src/endian.h new file mode 100644 index 0000000..6613e65 --- /dev/null +++ b/src/endian.h @@ -0,0 +1,57 @@ +/* endian.h - Endian functions + + Copyright (C) 2015 Álvaro Fernández Rojas <[email protected]> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 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/>. + + The complete text of the GNU General Public License + can be found in /usr/share/common-licenses/GPL-3 file. +*/ + +#ifndef _ENDIAN_H +#define _ENDIAN_H + +#if defined(__linux__) + #include <endian.h> +#elif defined(__APPLE__) + #include <libkern/OSByteOrder.h> + + #define htobe16(x) OSSwapHostToBigInt16(x) + #define htole16(x) OSSwapHostToLittleInt16(x) + #define be16toh(x) OSSwapBigToHostInt16(x) + #define le16toh(x) OSSwapLittleToHostInt16(x) + + #define htobe32(x) OSSwapHostToBigInt32(x) + #define htole32(x) OSSwapHostToLittleInt32(x) + #define be32toh(x) OSSwapBigToHostInt32(x) + #define le32toh(x) OSSwapLittleToHostInt32(x) + + #define htobe64(x) OSSwapHostToBigInt64(x) + #define htole64(x) OSSwapHostToLittleInt64(x) + #define be64toh(x) OSSwapBigToHostInt64(x) + #define le64toh(x) OSSwapLittleToHostInt64(x) +#elif defined(__FreeBSD__) + #include <sys/endian.h> + + #define be16toh(x) betoh16(x) + #define le16toh(x) letoh16(x) + + #define be32toh(x) betoh32(x) + #define le32toh(x) letoh32(x) + + #define be64toh(x) betoh64(x) + #define le64toh(x) letoh64(x) +#endif + +#endif /* _ENDIAN_H */ diff --git a/src/fat.c b/src/fat.c index 5a92f56..481c08a 100644 --- a/src/fat.c +++ b/src/fat.c @@ -30,6 +30,7 @@ #include <unistd.h> #include "common.h" +#include "endian.h" #include "fsck.fat.h" #include "io.h" #include "check.h" diff --git a/src/fatlabel.c b/src/fatlabel.c index 1484ba5..6de831c 100644 --- a/src/fatlabel.c +++ b/src/fatlabel.c @@ -33,6 +33,7 @@ #include <ctype.h> #include "common.h" +#include "types.h" #include "fsck.fat.h" #include "io.h" #include "boot.h" diff --git a/src/fsck.fat.h b/src/fsck.fat.h index e5f6178..8b0ccb9 100644 --- a/src/fsck.fat.h +++ b/src/fsck.fat.h @@ -27,11 +27,10 @@ #ifndef _DOSFSCK_H #define _DOSFSCK_H -#include <fcntl.h> #include <stddef.h> #include <stdint.h> -#include <endian.h> +#include "types.h" #include "msdos_fs.h" #define VFAT_LN_ATTR (ATTR_RO | ATTR_HIDDEN | ATTR_SYS | ATTR_VOLUME) diff --git a/src/io.h b/src/io.h index d23d07e..eecfdc5 100644 --- a/src/io.h +++ b/src/io.h @@ -27,7 +27,7 @@ #ifndef _IO_H #define _IO_H -#include <fcntl.h> /* for loff_t */ +#include "types.h" loff_t llseek(int fd, loff_t offset, int whence); diff --git a/src/lfn.c b/src/lfn.c index 2601172..f679168 100644 --- a/src/lfn.c +++ b/src/lfn.c @@ -28,6 +28,7 @@ #include <time.h> #include "common.h" +#include "endian.h" #include "io.h" #include "fsck.fat.h" #include "lfn.h" diff --git a/src/mkfs.fat.c b/src/mkfs.fat.c index 02e0918..f2cee09 100644 --- a/src/mkfs.fat.c +++ b/src/mkfs.fat.c @@ -48,8 +48,6 @@ #include <fcntl.h> #include <sys/mount.h> -#include <endian.h> -#include <mntent.h> #include <signal.h> #include <string.h> #include <stdio.h> @@ -61,13 +59,14 @@ #include <errno.h> #include <ctype.h> #include <stdint.h> -#include <endian.h> #if defined(__linux__) + #include <mntent.h> #include <linux/hdreg.h> #include <linux/fs.h> #include <linux/fd.h> #elif defined(__FreeBSD__) || defined(__APPLE__) + #include <sys/mount.h> #include <sys/disk.h> #define BLOCK_SIZE_BITS 10 @@ -97,7 +96,9 @@ }; #endif +#include "endian.h" #include "msdos_fs.h" +#include "types.h" /* In earlier versions, an own llseek() was used, but glibc lseek() is * sufficient (or even better :) for 64 bit offsets in the meantime */ @@ -525,6 +526,7 @@ static uint64_t count_blocks(char *filename, int *remainder) static void check_mount(char *device_name) { +#if defined(__linux__) FILE *f; struct mntent *mnt; @@ -534,6 +536,17 @@ static void check_mount(char *device_name) if (strcmp(device_name, mnt->mnt_fsname) == 0) die("%s contains a mounted filesystem."); endmntent(f); +#elif defined(__APPLE__) || defined(__FreeBSD__) + struct statfs* mounts; + int num_mounts = getmntinfo(&mounts, MNT_WAIT); + if (num_mounts < 0) + return; + for ( int i = 0; i < num_mounts; i++ ) + { + if (strcmp(device_name, mounts[i].f_mntfromname) == 0) + die("%s contains a mounted filesystem."); + } +#endif } /* Establish the geometry and media parameters for the device */ diff --git a/src/types.h b/src/types.h new file mode 100644 index 0000000..a3f1a47 --- /dev/null +++ b/src/types.h @@ -0,0 +1,57 @@ +/* types.h - Missing types + + Copyright (C) 2015 Álvaro Fernández Rojas <[email protected]> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 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/>. + + The complete text of the GNU General Public License + can be found in /usr/share/common-licenses/GPL-3 file. +*/ + +#ifndef _TYPES_H +#define _TYPES_H + +#if defined(__linux__) + #include <fcntl.h> +#elif defined(__APPLE__) + #ifndef loff_t + typedef long long loff_t; + #endif /* loff_t */ + + #ifndef lseek64 + #define lseek64 lseek + #endif /* lseek64 */ + + #ifndef off64_t + #ifdef _LP64 + typedef off_t off64_t; + #else + typedef __longlong_t off64_t; + #endif /* _LP64 */ + #endif /* off64_t */ +#elif defined(__FreeBSD__) + #ifndef loff_t + typedef long long loff_t; + #endif /* loff_t */ + + #ifndef lseek64 + #define lseek64 lseek + #endif /* lseek64 */ + + #ifndef off64_t + typedef off_t off64_t; + #endif /* off64_t */ +#endif + +#endif /* _TYPES_H */ -- 1.9.1
{ "pile_set_name": "Github" }
# To learn about Buck see [Docs](https://buckbuild.com/). # To run your application with Buck: # - install Buck # - `npm start` - to start the packager # - `cd android` # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck # - `buck install -r android/app` - compile, install and run application # lib_deps = [] for jarfile in glob(['libs/*.jar']): name = 'jars__' + jarfile[jarfile.rindex('/') + 1: jarfile.rindex('.jar')] lib_deps.append(':' + name) prebuilt_jar( name = name, binary_jar = jarfile, ) for aarfile in glob(['libs/*.aar']): name = 'aars__' + aarfile[aarfile.rindex('/') + 1: aarfile.rindex('.aar')] lib_deps.append(':' + name) android_prebuilt_aar( name = name, aar = aarfile, ) android_library( name = "all-libs", exported_deps = lib_deps, ) android_library( name = "app-code", srcs = glob([ "src/main/java/**/*.java", ]), deps = [ ":all-libs", ":build_config", ":res", ], ) android_build_config( name = "build_config", package = "com.example", ) android_resource( name = "res", package = "com.example", res = "src/main/res", ) android_binary( name = "app", keystore = "//android/keystores:debug", manifest = "src/main/AndroidManifest.xml", package_type = "debug", deps = [ ":app-code", ], )
{ "pile_set_name": "Github" }
/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'sourcearea', 'de-ch', { toolbar: 'Quellcode' } );
{ "pile_set_name": "Github" }
--- title: "Installation in Python virtual environment" description: "How to install Home Assistant in a Python virtual environment." redirect_from: /getting-started/installation-virtualenv/ --- If you already have Python 3.7 or later installed, you can easily give Home Assistant a spin. It's recommended when installing Python packages that you use a [virtual environment](https://docs.python.org/3.7/library/venv.html#module-venv). This will make sure that your Python installation and Home Assistant installation won't impact one another. The following steps will work on most UNIX like systems. <div class='note'> This is a generic guide for running Home Assistant under Python. We recommend to use [our recommended installation guides](/docs/installation/#recommended). The steps below may be shorter but some users find difficulty when applying updates and may run into issues. Before you begin the guide below, ensure that you have a *so-called standard* build environment that includes things like `make`, `gcc`, `python3`, including Python 3 `setuptools` and `pip` modules. Less obvious is the need to install `openssl-dev` (for opensslv.h), `libffi-dev` (for cffi.h) for things to build later on, `libopenjp2-7` and `libtiff5` needed for the frontend. </div> {% comment %} This page describes installation instructions for a pure Python installation. It should not contain any OS specific instructions. {% endcomment %} ### Install 1. Create a virtual environment in your current directory: ```bash python3 -m venv homeassistant ``` 2. Open the virtual environment: ```bash cd homeassistant ``` 3. Activate the virtual environment: ```bash source bin/activate ``` 4. Install Home Assistant: ```bash python3 -m pip install homeassistant ``` 5. Run Home Assistant: ```bash hass --open-ui ``` 6. You can now reach the web interface on `http://ipaddress:8123/` - the first start may take a couple of minutes before the web interface is available. This can take longer if you're using lower-end hardware like a Raspberry Pi Zero. ### Upgrade 1. Stop Home Assistant 2. Open the directory where the virtual environment is located, activate the virtual environment, then upgrade Home Assistant: ```bash cd homeassistant source bin/activate python3 -m pip install --upgrade homeassistant ``` 3. Start Home Assistant 4. You can now reach the web interface on `http://ipaddress:8123/` - the first start may take some time before the web interface is available, depending on how many integrations need to be upgraded. ### Run a specific version In the event that a Home Assistant version doesn't play well with your hardware setup, you can downgrade to a previous release. For example: ```bash cd homeassistant source bin/activate pip3 install homeassistant==0.XX.X ``` #### Run the beta version If you would like to test next release before anyone else, you can install the beta version, for example: ```bash cd homeassistant source bin/activate pip3 install --pre --upgrade homeassistant ``` #### Run the development version If you want to stay on the bleeding-edge Home Assistant development branch, you can upgrade to `dev`. <div class='note warning'> The "dev" branch is likely to be unstable. Potential consequences include loss of data and instance corruption. </div> For example: ```bash cd homeassistant source bin/activate pip3 install --upgrade git+git://github.com/home-assistant/home-assistant.git@dev ``` ### Notes - In the future, if you want to start Home Assistant manually again, follow step 2, 3 and 5. - It's recommended to run Home Assistant as a dedicated user. <div class='info'> Looking for more advanced guides? Check our [Raspberry Pi OS guide](/docs/installation/raspberry-pi/) or the [other installation guides](/docs/installation/). </div> ### After upgrading Python If you've upgraded Python (for example, you were running 3.7.1 and now you've installed 3.7.3) then you'll need to build a new virtual environment. Simply rename your existing virtual environment directory: ```bash mv homeassistant homeassistant.old ``` Then follow the [Install](#install) steps again, being sure to use the newly installed version of Python.
{ "pile_set_name": "Github" }
/* mkfs.fat.c - utility to create FAT/MS-DOS filesystems Copyright (C) 1991 Linus Torvalds <[email protected]> Copyright (C) 1992-1993 Remy Card <[email protected]> Copyright (C) 1993-1994 David Hudson <[email protected]> Copyright (C) 1998 H. Peter Anvin <[email protected]> Copyright (C) 1998-2005 Roman Hodek <[email protected]> Copyright (C) 2008-2014 Daniel Baumann <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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/>. The complete text of the GNU General Public License can be found in /usr/share/common-licenses/GPL-3 file. */ /* Description: Utility to allow an MS-DOS filesystem to be created under Linux. A lot of the basic structure of this program has been borrowed from Remy Card's "mke2fs" code. As far as possible the aim here is to make the "mkfs.fat" command look almost identical to the other Linux filesystem make utilties, eg bad blocks are still specified as blocks, not sectors, but when it comes down to it, DOS is tied to the idea of a sector (512 bytes as a rule), and not the block. For example the boot block does not occupy a full cluster. Fixes/additions May 1998 by Roman Hodek <[email protected]>: - Atari format support - New options -A, -S, -C - Support for filesystems > 2GB - FAT32 support */ /* Include the header files */ #include "version.h" #include <fcntl.h> #include <linux/hdreg.h> #include <sys/mount.h> #include <linux/fs.h> #include <linux/fd.h> #include <endian.h> #include <mntent.h> #include <signal.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/time.h> #include <unistd.h> #include <time.h> #include <errno.h> #include <ctype.h> #include <stdint.h> #include <endian.h> #include <getopt.h> #include "msdos_fs.h" /* In earlier versions, an own llseek() was used, but glibc lseek() is * sufficient (or even better :) for 64 bit offsets in the meantime */ #define llseek lseek64 /* Constant definitions */ #define TRUE 1 /* Boolean constants */ #define FALSE 0 #define TEST_BUFFER_BLOCKS 16 #define HARD_SECTOR_SIZE 512 #define SECTORS_PER_BLOCK ( BLOCK_SIZE / HARD_SECTOR_SIZE ) #define NO_NAME "NO NAME " /* Macro definitions */ /* Report a failure message and return a failure error code */ #define die( str ) fatal_error( "%s: " str "\n" ) /* Mark a cluster in the FAT as bad */ #define mark_sector_bad( sector ) mark_FAT_sector( sector, FAT_BAD ) /* Compute ceil(a/b) */ static inline int cdiv(int a, int b) { return (a + b - 1) / b; } /* FAT values */ #define FAT_EOF (atari_format ? 0x0fffffff : 0x0ffffff8) #define FAT_BAD 0x0ffffff7 #define MSDOS_EXT_SIGN 0x29 /* extended boot sector signature */ #define MSDOS_FAT12_SIGN "FAT12 " /* FAT12 filesystem signature */ #define MSDOS_FAT16_SIGN "FAT16 " /* FAT16 filesystem signature */ #define MSDOS_FAT32_SIGN "FAT32 " /* FAT32 filesystem signature */ #define BOOT_SIGN 0xAA55 /* Boot sector magic number */ #define MAX_CLUST_12 ((1 << 12) - 16) #define MAX_CLUST_16 ((1 << 16) - 16) #define MIN_CLUST_32 65529 /* M$ says the high 4 bits of a FAT32 FAT entry are reserved and don't belong * to the cluster number. So the max. cluster# is based on 2^28 */ #define MAX_CLUST_32 ((1 << 28) - 16) #define FAT12_THRESHOLD 4085 #define OLDGEMDOS_MAX_SECTORS 32765 #define GEMDOS_MAX_SECTORS 65531 #define GEMDOS_MAX_SECTOR_SIZE (16*1024) #define BOOTCODE_SIZE 448 #define BOOTCODE_FAT32_SIZE 420 /* __attribute__ ((packed)) is used on all structures to make gcc ignore any * alignments */ struct msdos_volume_info { uint8_t drive_number; /* BIOS drive number */ uint8_t RESERVED; /* Unused */ uint8_t ext_boot_sign; /* 0x29 if fields below exist (DOS 3.3+) */ uint8_t volume_id[4]; /* Volume ID number */ uint8_t volume_label[11]; /* Volume label */ uint8_t fs_type[8]; /* Typically FAT12 or FAT16 */ } __attribute__ ((packed)); struct msdos_boot_sector { uint8_t boot_jump[3]; /* Boot strap short or near jump */ uint8_t system_id[8]; /* Name - can be used to special case partition manager volumes */ uint8_t sector_size[2]; /* bytes per logical sector */ uint8_t cluster_size; /* sectors/cluster */ uint16_t reserved; /* reserved sectors */ uint8_t fats; /* number of FATs */ uint8_t dir_entries[2]; /* root directory entries */ uint8_t sectors[2]; /* number of sectors */ uint8_t media; /* media code (unused) */ uint16_t fat_length; /* sectors/FAT */ uint16_t secs_track; /* sectors per track */ uint16_t heads; /* number of heads */ uint32_t hidden; /* hidden sectors (unused) */ uint32_t total_sect; /* number of sectors (if sectors == 0) */ union { struct { struct msdos_volume_info vi; uint8_t boot_code[BOOTCODE_SIZE]; } __attribute__ ((packed)) _oldfat; struct { uint32_t fat32_length; /* sectors/FAT */ uint16_t flags; /* bit 8: fat mirroring, low 4: active fat */ uint8_t version[2]; /* major, minor filesystem version */ uint32_t root_cluster; /* first cluster in root directory */ uint16_t info_sector; /* filesystem info sector */ uint16_t backup_boot; /* backup boot sector */ uint16_t reserved2[6]; /* Unused */ struct msdos_volume_info vi; uint8_t boot_code[BOOTCODE_FAT32_SIZE]; } __attribute__ ((packed)) _fat32; } __attribute__ ((packed)) fstype; uint16_t boot_sign; } __attribute__ ((packed)); #define fat32 fstype._fat32 #define oldfat fstype._oldfat struct fat32_fsinfo { uint32_t reserved1; /* Nothing as far as I can tell */ uint32_t signature; /* 0x61417272L */ uint32_t free_clusters; /* Free cluster count. -1 if unknown */ uint32_t next_cluster; /* Most recently allocated cluster. * Unused under Linux. */ uint32_t reserved2[4]; }; /* The "boot code" we put into the filesystem... it writes a message and tells the user to try again */ unsigned char dummy_boot_jump[3] = { 0xeb, 0x3c, 0x90 }; unsigned char dummy_boot_jump_m68k[2] = { 0x60, 0x1c }; #define MSG_OFFSET_OFFSET 3 char dummy_boot_code[BOOTCODE_SIZE] = "\x0e" /* push cs */ "\x1f" /* pop ds */ "\xbe\x5b\x7c" /* mov si, offset message_txt */ /* write_msg: */ "\xac" /* lodsb */ "\x22\xc0" /* and al, al */ "\x74\x0b" /* jz key_press */ "\x56" /* push si */ "\xb4\x0e" /* mov ah, 0eh */ "\xbb\x07\x00" /* mov bx, 0007h */ "\xcd\x10" /* int 10h */ "\x5e" /* pop si */ "\xeb\xf0" /* jmp write_msg */ /* key_press: */ "\x32\xe4" /* xor ah, ah */ "\xcd\x16" /* int 16h */ "\xcd\x19" /* int 19h */ "\xeb\xfe" /* foo: jmp foo */ /* message_txt: */ "This is not a bootable disk. Please insert a bootable floppy and\r\n" "press any key to try again ... \r\n"; #define MESSAGE_OFFSET 29 /* Offset of message in above code */ /* Global variables - the root of all evil :-) - see these and weep! */ static const char *program_name = "mkfs.fat"; /* Name of the program */ static char *device_name = NULL; /* Name of the device on which to create the filesystem */ static int atari_format = 0; /* Use Atari variation of MS-DOS FS format */ static int check = FALSE; /* Default to no readablity checking */ static int verbose = 0; /* Default to verbose mode off */ static long volume_id; /* Volume ID number */ static time_t create_time; /* Creation time */ static char volume_name[] = NO_NAME; /* Volume name */ static uint64_t blocks; /* Number of blocks in filesystem */ static int sector_size = 512; /* Size of a logical sector */ static int sector_size_set = 0; /* User selected sector size */ static int backup_boot = 0; /* Sector# of backup boot sector */ static int reserved_sectors = 0; /* Number of reserved sectors */ static int badblocks = 0; /* Number of bad blocks in the filesystem */ static int nr_fats = 2; /* Default number of FATs to produce */ static int size_fat = 0; /* Size in bits of FAT entries */ static int size_fat_by_user = 0; /* 1 if FAT size user selected */ static int dev = -1; /* FS block device file handle */ static int ignore_full_disk = 0; /* Ignore warning about 'full' disk devices */ static off_t currently_testing = 0; /* Block currently being tested (if autodetect bad blocks) */ static struct msdos_boot_sector bs; /* Boot sector data */ static int start_data_sector; /* Sector number for the start of the data area */ static int start_data_block; /* Block number for the start of the data area */ static unsigned char *fat; /* File allocation table */ static unsigned alloced_fat_length; /* # of FAT sectors we can keep in memory */ static unsigned char *info_sector; /* FAT32 info sector */ static struct msdos_dir_entry *root_dir; /* Root directory */ static int size_root_dir; /* Size of the root directory in bytes */ static int sectors_per_cluster = 0; /* Number of sectors per disk cluster */ static int root_dir_entries = 0; /* Number of root directory entries */ static char *blank_sector; /* Blank sector - all zeros */ static int hidden_sectors = 0; /* Number of hidden sectors */ static int hidden_sectors_by_user = 0; /* -h option invoked */ static int drive_number_option = 0; /* drive number */ static int drive_number_by_user = 0; /* drive number option invoked */ static int fat_media_byte = 0; /* media byte in header and starting FAT */ static int malloc_entire_fat = FALSE; /* Whether we should malloc() the entire FAT or not */ static int align_structures = TRUE; /* Whether to enforce alignment */ static int orphaned_sectors = 0; /* Sectors that exist in the last block of filesystem */ static int invariant = 0; /* Whether to set normally randomized or current time based values to constants */ /* Function prototype definitions */ static void fatal_error(const char *fmt_string) __attribute__ ((noreturn)); static void mark_FAT_cluster(int cluster, unsigned int value); static void mark_FAT_sector(int sector, unsigned int value); static long do_check(char *buffer, int try, off_t current_block); static void alarm_intr(int alnum); static void check_blocks(void); static void get_list_blocks(char *filename); static int valid_offset(int fd, loff_t offset); static uint64_t count_blocks(char *filename, int *remainder); static void check_mount(char *device_name); static void establish_params(int device_num, int size); static void setup_tables(void); static void write_tables(void); /* The function implementations */ /* Handle the reporting of fatal errors. Volatile to let gcc know that this doesn't return */ static void fatal_error(const char *fmt_string) { fprintf(stderr, fmt_string, program_name, device_name); exit(1); /* The error exit code is 1! */ } /* Mark the specified cluster as having a particular value */ static void mark_FAT_cluster(int cluster, unsigned int value) { switch (size_fat) { case 12: value &= 0x0fff; if (((cluster * 3) & 0x1) == 0) { fat[3 * cluster / 2] = (unsigned char)(value & 0x00ff); fat[(3 * cluster / 2) + 1] = (unsigned char)((fat[(3 * cluster / 2) + 1] & 0x00f0) | ((value & 0x0f00) >> 8)); } else { fat[3 * cluster / 2] = (unsigned char)((fat[3 * cluster / 2] & 0x000f) | ((value & 0x000f) << 4)); fat[(3 * cluster / 2) + 1] = (unsigned char)((value & 0x0ff0) >> 4); } break; case 16: value &= 0xffff; fat[2 * cluster] = (unsigned char)(value & 0x00ff); fat[(2 * cluster) + 1] = (unsigned char)(value >> 8); break; case 32: value &= 0xfffffff; fat[4 * cluster] = (unsigned char)(value & 0x000000ff); fat[(4 * cluster) + 1] = (unsigned char)((value & 0x0000ff00) >> 8); fat[(4 * cluster) + 2] = (unsigned char)((value & 0x00ff0000) >> 16); fat[(4 * cluster) + 3] = (unsigned char)((value & 0xff000000) >> 24); break; default: die("Bad FAT size (not 12, 16, or 32)"); } } /* Mark a specified sector as having a particular value in it's FAT entry */ static void mark_FAT_sector(int sector, unsigned int value) { int cluster; cluster = (sector - start_data_sector) / (int)(bs.cluster_size) / (sector_size / HARD_SECTOR_SIZE); if (cluster < 0) die("Invalid cluster number in mark_FAT_sector: probably bug!"); mark_FAT_cluster(cluster, value); } /* Perform a test on a block. Return the number of blocks that could be read successfully */ static long do_check(char *buffer, int try, off_t current_block) { long got; if (llseek(dev, current_block * BLOCK_SIZE, SEEK_SET) /* Seek to the correct location */ !=current_block * BLOCK_SIZE) die("seek failed during testing for blocks"); got = read(dev, buffer, try * BLOCK_SIZE); /* Try reading! */ if (got < 0) got = 0; if (got & (BLOCK_SIZE - 1)) printf("Unexpected values in do_check: probably bugs\n"); got /= BLOCK_SIZE; return got; } /* Alarm clock handler - display the status of the quest for bad blocks! Then retrigger the alarm for five senconds later (so we can come here again) */ static void alarm_intr(int alnum) { (void)alnum; if (currently_testing >= blocks) return; signal(SIGALRM, alarm_intr); alarm(5); if (!currently_testing) return; printf("%lld... ", (unsigned long long)currently_testing); fflush(stdout); } static void check_blocks(void) { int try, got; int i; static char blkbuf[BLOCK_SIZE * TEST_BUFFER_BLOCKS]; if (verbose) { printf("Searching for bad blocks "); fflush(stdout); } currently_testing = 0; if (verbose) { signal(SIGALRM, alarm_intr); alarm(5); } try = TEST_BUFFER_BLOCKS; while (currently_testing < blocks) { if (currently_testing + try > blocks) try = blocks - currently_testing; got = do_check(blkbuf, try, currently_testing); currently_testing += got; if (got == try) { try = TEST_BUFFER_BLOCKS; continue; } else try = 1; if (currently_testing < start_data_block) die("bad blocks before data-area: cannot make fs"); for (i = 0; i < SECTORS_PER_BLOCK; i++) /* Mark all of the sectors in the block as bad */ mark_sector_bad(currently_testing * SECTORS_PER_BLOCK + i); badblocks++; currently_testing++; } if (verbose) printf("\n"); if (badblocks) printf("%d bad block%s\n", badblocks, (badblocks > 1) ? "s" : ""); } static void get_list_blocks(char *filename) { int i; FILE *listfile; long blockno; listfile = fopen(filename, "r"); if (listfile == (FILE *) NULL) die("Can't open file of bad blocks"); while (!feof(listfile)) { fscanf(listfile, "%ld\n", &blockno); for (i = 0; i < SECTORS_PER_BLOCK; i++) /* Mark all of the sectors in the block as bad */ mark_sector_bad(blockno * SECTORS_PER_BLOCK + i); badblocks++; } fclose(listfile); if (badblocks) printf("%d bad block%s\n", badblocks, (badblocks > 1) ? "s" : ""); } /* Given a file descriptor and an offset, check whether the offset is a valid offset for the file - return FALSE if it isn't valid or TRUE if it is */ static int valid_offset(int fd, loff_t offset) { char ch; if (llseek(fd, offset, SEEK_SET) < 0) return FALSE; if (read(fd, &ch, 1) < 1) return FALSE; return TRUE; } /* Given a filename, look to see how many blocks of BLOCK_SIZE are present, returning the answer */ static uint64_t count_blocks(char *filename, int *remainder) { loff_t high, low; int fd; if ((fd = open(filename, O_RDONLY)) < 0) { perror(filename); exit(1); } /* first try SEEK_END, which should work on most devices nowadays */ if ((low = llseek(fd, 0, SEEK_END)) <= 0) { low = 0; for (high = 1; valid_offset(fd, high); high *= 2) low = high; while (low < high - 1) { const loff_t mid = (low + high) / 2; if (valid_offset(fd, mid)) low = mid; else high = mid; } ++low; } close(fd); *remainder = (low % BLOCK_SIZE) / sector_size; return (low / BLOCK_SIZE); } /* Check to see if the specified device is currently mounted - abort if it is */ static void check_mount(char *device_name) { /* older versions of Bionic don't have setmntent (4.x) or an incomplete impl (5.x) */ #ifdef MOUNTED FILE *f; struct mntent *mnt; if ((f = setmntent(MOUNTED, "r")) == NULL) return; while ((mnt = getmntent(f)) != NULL) if (strcmp(device_name, mnt->mnt_fsname) == 0) die("%s contains a mounted filesystem."); endmntent(f); #endif } /* Establish the geometry and media parameters for the device */ static void establish_params(int device_num, int size) { long loop_size; struct hd_geometry geometry; struct floppy_struct param; int def_root_dir_entries = 512; if ((0 == device_num) || ((device_num & 0xff00) == 0x0200)) /* file image or floppy disk */ { if (0 == device_num) { param.size = size / 512; switch (param.size) { case 720: param.sect = 9; param.head = 2; break; case 1440: param.sect = 9; param.head = 2; break; case 2400: param.sect = 15; param.head = 2; break; case 2880: param.sect = 18; param.head = 2; break; case 5760: param.sect = 36; param.head = 2; break; default: /* fake values */ param.sect = 32; param.head = 64; break; } } else { /* is a floppy diskette */ if (ioctl(dev, FDGETPRM, &param)) /* Can we get the diskette geometry? */ die("unable to get diskette geometry for '%s'"); } bs.secs_track = htole16(param.sect); /* Set up the geometry information */ bs.heads = htole16(param.head); switch (param.size) { /* Set up the media descriptor byte */ case 720: /* 5.25", 2, 9, 40 - 360K */ bs.media = (char)0xfd; bs.cluster_size = (char)2; def_root_dir_entries = 112; break; case 1440: /* 3.5", 2, 9, 80 - 720K */ bs.media = (char)0xf9; bs.cluster_size = (char)2; def_root_dir_entries = 112; break; case 2400: /* 5.25", 2, 15, 80 - 1200K */ bs.media = (char)0xf9; bs.cluster_size = (char)(atari_format ? 2 : 1); def_root_dir_entries = 224; break; case 5760: /* 3.5", 2, 36, 80 - 2880K */ bs.media = (char)0xf0; bs.cluster_size = (char)2; def_root_dir_entries = 224; break; case 2880: /* 3.5", 2, 18, 80 - 1440K */ floppy_default: bs.media = (char)0xf0; bs.cluster_size = (char)(atari_format ? 2 : 1); def_root_dir_entries = 224; break; default: /* Anything else */ if (0 == device_num) goto def_hd_params; else goto floppy_default; } } else if ((device_num & 0xff00) == 0x0700) { /* This is a loop device */ if (ioctl(dev, BLKGETSIZE, &loop_size)) die("unable to get loop device size"); switch (loop_size) { /* Assuming the loop device -> floppy later */ case 720: /* 5.25", 2, 9, 40 - 360K */ bs.secs_track = le16toh(9); bs.heads = le16toh(2); bs.media = (char)0xfd; bs.cluster_size = (char)2; def_root_dir_entries = 112; break; case 1440: /* 3.5", 2, 9, 80 - 720K */ bs.secs_track = le16toh(9); bs.heads = le16toh(2); bs.media = (char)0xf9; bs.cluster_size = (char)2; def_root_dir_entries = 112; break; case 2400: /* 5.25", 2, 15, 80 - 1200K */ bs.secs_track = le16toh(15); bs.heads = le16toh(2); bs.media = (char)0xf9; bs.cluster_size = (char)(atari_format ? 2 : 1); def_root_dir_entries = 224; break; case 5760: /* 3.5", 2, 36, 80 - 2880K */ bs.secs_track = le16toh(36); bs.heads = le16toh(2); bs.media = (char)0xf0; bs.cluster_size = (char)2; bs.dir_entries[0] = (char)224; bs.dir_entries[1] = (char)0; break; case 2880: /* 3.5", 2, 18, 80 - 1440K */ bs.secs_track = le16toh(18); bs.heads = le16toh(2); bs.media = (char)0xf0; bs.cluster_size = (char)(atari_format ? 2 : 1); def_root_dir_entries = 224; break; default: /* Anything else: default hd setup */ printf("Loop device does not match a floppy size, using " "default hd params\n"); bs.secs_track = htole16(32); /* these are fake values... */ bs.heads = htole16(64); goto def_hd_params; } } else /* Must be a hard disk then! */ { /* Can we get the drive geometry? (Note I'm not too sure about */ /* whether to use HDIO_GETGEO or HDIO_REQ) */ if (ioctl(dev, HDIO_GETGEO, &geometry) || geometry.sectors == 0 || geometry.heads == 0) { printf("unable to get drive geometry, using default 255/63\n"); bs.secs_track = htole16(63); bs.heads = htole16(255); } else { bs.secs_track = htole16(geometry.sectors); /* Set up the geometry information */ bs.heads = htole16(geometry.heads); if (!hidden_sectors_by_user) hidden_sectors = htole32(geometry.start); } def_hd_params: bs.media = (char)0xf8; /* Set up the media descriptor for a hard drive */ if (!size_fat && blocks * SECTORS_PER_BLOCK > 1064960) { if (verbose) printf("Auto-selecting FAT32 for large filesystem\n"); size_fat = 32; } if (size_fat == 32) { /* For FAT32, try to do the same as M$'s format command * (see http://www.win.tue.nl/~aeb/linux/fs/fat/fatgen103.pdf p. 20): * fs size <= 260M: 0.5k clusters * fs size <= 8G: 4k clusters * fs size <= 16G: 8k clusters * fs size <= 32G: 16k clusters * fs size > 32G: 32k clusters */ uint32_t sz_mb = (blocks + (1 << (20 - BLOCK_SIZE_BITS)) - 1) >> (20 - BLOCK_SIZE_BITS); bs.cluster_size = sz_mb > 32 * 1024 ? 64 : sz_mb > 16 * 1024 ? 32 : sz_mb > 8 * 1024 ? 16 : sz_mb > 260 ? 8 : 1; } else { /* FAT12 and FAT16: start at 4 sectors per cluster */ bs.cluster_size = (char)4; } } if (!root_dir_entries) root_dir_entries = def_root_dir_entries; } /* * If alignment is enabled, round the first argument up to the second; the * latter must be a power of two. */ static unsigned int align_object(unsigned int sectors, unsigned int clustsize) { if (align_structures) return (sectors + clustsize - 1) & ~(clustsize - 1); else return sectors; } /* Create the filesystem data tables */ static void setup_tables(void) { unsigned num_sectors; unsigned cluster_count = 0, fat_length; struct tm *ctime; struct msdos_volume_info *vi = (size_fat == 32 ? &bs.fat32.vi : &bs.oldfat.vi); if (atari_format) { /* On Atari, the first few bytes of the boot sector are assigned * differently: The jump code is only 2 bytes (and m68k machine code * :-), then 6 bytes filler (ignored), then 3 byte serial number. */ bs.boot_jump[2] = 'm'; memcpy((char *)bs.system_id, "kdosf", strlen("kdosf")); } else memcpy((char *)bs.system_id, "mkfs.fat", strlen("mkfs.fat")); if (sectors_per_cluster) bs.cluster_size = (char)sectors_per_cluster; if (fat_media_byte) bs.media = (char) fat_media_byte; if (bs.media == 0xf8) vi->drive_number=0x80; else vi->drive_number=0x00; if (drive_number_by_user) vi->drive_number= (char) drive_number_option; if (size_fat == 32) { /* Under FAT32, the root dir is in a cluster chain, and this is * signalled by bs.dir_entries being 0. */ root_dir_entries = 0; } if (atari_format) { bs.system_id[5] = (unsigned char)(volume_id & 0x000000ff); bs.system_id[6] = (unsigned char)((volume_id & 0x0000ff00) >> 8); bs.system_id[7] = (unsigned char)((volume_id & 0x00ff0000) >> 16); } else { vi->volume_id[0] = (unsigned char)(volume_id & 0x000000ff); vi->volume_id[1] = (unsigned char)((volume_id & 0x0000ff00) >> 8); vi->volume_id[2] = (unsigned char)((volume_id & 0x00ff0000) >> 16); vi->volume_id[3] = (unsigned char)(volume_id >> 24); } if (!atari_format) { memcpy(vi->volume_label, volume_name, 11); memcpy(bs.boot_jump, dummy_boot_jump, 3); /* Patch in the correct offset to the boot code */ bs.boot_jump[1] = ((size_fat == 32 ? (char *)&bs.fat32.boot_code : (char *)&bs.oldfat.boot_code) - (char *)&bs) - 2; if (size_fat == 32) { int offset = (char *)&bs.fat32.boot_code - (char *)&bs + MESSAGE_OFFSET + 0x7c00; if (dummy_boot_code[BOOTCODE_FAT32_SIZE - 1]) printf("Warning: message too long; truncated\n"); dummy_boot_code[BOOTCODE_FAT32_SIZE - 1] = 0; memcpy(bs.fat32.boot_code, dummy_boot_code, BOOTCODE_FAT32_SIZE); bs.fat32.boot_code[MSG_OFFSET_OFFSET] = offset & 0xff; bs.fat32.boot_code[MSG_OFFSET_OFFSET + 1] = offset >> 8; } else { memcpy(bs.oldfat.boot_code, dummy_boot_code, BOOTCODE_SIZE); } bs.boot_sign = htole16(BOOT_SIGN); } else { memcpy(bs.boot_jump, dummy_boot_jump_m68k, 2); } if (verbose >= 2) printf("Boot jump code is %02x %02x\n", bs.boot_jump[0], bs.boot_jump[1]); if (!reserved_sectors) reserved_sectors = (size_fat == 32) ? 32 : 1; else { if (size_fat == 32 && reserved_sectors < 2) die("On FAT32 at least 2 reserved sectors are needed."); } bs.reserved = htole16(reserved_sectors); if (verbose >= 2) printf("Using %d reserved sectors\n", reserved_sectors); bs.fats = (char)nr_fats; if (!atari_format || size_fat == 32) bs.hidden = htole32(hidden_sectors); else { /* In Atari format, hidden is a 16 bit field */ uint16_t hidden = htole16(hidden_sectors); if (hidden_sectors & ~0xffff) die("#hidden doesn't fit in 16bit field of Atari format\n"); memcpy(&bs.hidden, &hidden, 2); } num_sectors = (long long)(blocks * BLOCK_SIZE / sector_size) + orphaned_sectors; if (!atari_format) { unsigned fatdata1216; /* Sectors for FATs + data area (FAT12/16) */ unsigned fatdata32; /* Sectors for FATs + data area (FAT32) */ unsigned fatlength12, fatlength16, fatlength32; unsigned maxclust12, maxclust16, maxclust32; unsigned clust12, clust16, clust32; int maxclustsize; unsigned root_dir_sectors = cdiv(root_dir_entries * 32, sector_size); /* * If the filesystem is 8192 sectors or less (4 MB with 512-byte * sectors, i.e. floppy size), don't align the data structures. */ if (num_sectors <= 8192) { if (align_structures && verbose >= 2) printf("Disabling alignment due to tiny filesystem\n"); align_structures = FALSE; } if (sectors_per_cluster) bs.cluster_size = maxclustsize = sectors_per_cluster; else /* An initial guess for bs.cluster_size should already be set */ maxclustsize = 128; do { fatdata32 = num_sectors - reserved_sectors; fatdata1216 = fatdata32 - align_object(root_dir_sectors, bs.cluster_size); if (verbose >= 2) printf("Trying with %d sectors/cluster:\n", bs.cluster_size); /* The factor 2 below avoids cut-off errors for nr_fats == 1. * The "nr_fats*3" is for the reserved first two FAT entries */ clust12 = 2 * ((long long)fatdata1216 * sector_size + nr_fats * 3) / (2 * (int)bs.cluster_size * sector_size + nr_fats * 3); fatlength12 = cdiv(((clust12 + 2) * 3 + 1) >> 1, sector_size); fatlength12 = align_object(fatlength12, bs.cluster_size); /* Need to recalculate number of clusters, since the unused parts of the * FATS and data area together could make up space for an additional, * not really present cluster. */ clust12 = (fatdata1216 - nr_fats * fatlength12) / bs.cluster_size; maxclust12 = (fatlength12 * 2 * sector_size) / 3; if (maxclust12 > MAX_CLUST_12) maxclust12 = MAX_CLUST_12; if (verbose >= 2) printf("FAT12: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n", clust12, fatlength12, maxclust12, MAX_CLUST_12); if (clust12 > maxclust12 - 2) { clust12 = 0; if (verbose >= 2) printf("FAT12: too much clusters\n"); } clust16 = ((long long)fatdata1216 * sector_size + nr_fats * 4) / ((int)bs.cluster_size * sector_size + nr_fats * 2); fatlength16 = cdiv((clust16 + 2) * 2, sector_size); fatlength16 = align_object(fatlength16, bs.cluster_size); /* Need to recalculate number of clusters, since the unused parts of the * FATS and data area together could make up space for an additional, * not really present cluster. */ clust16 = (fatdata1216 - nr_fats * fatlength16) / bs.cluster_size; maxclust16 = (fatlength16 * sector_size) / 2; if (maxclust16 > MAX_CLUST_16) maxclust16 = MAX_CLUST_16; if (verbose >= 2) printf("FAT16: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n", clust16, fatlength16, maxclust16, MAX_CLUST_16); if (clust16 > maxclust16 - 2) { if (verbose >= 2) printf("FAT16: too much clusters\n"); clust16 = 0; } /* The < 4078 avoids that the filesystem will be misdetected as having a * 12 bit FAT. */ if (clust16 < FAT12_THRESHOLD && !(size_fat_by_user && size_fat == 16)) { if (verbose >= 2) printf(clust16 < FAT12_THRESHOLD ? "FAT16: would be misdetected as FAT12\n" : "FAT16: too much clusters\n"); clust16 = 0; } clust32 = ((long long)fatdata32 * sector_size + nr_fats * 8) / ((int)bs.cluster_size * sector_size + nr_fats * 4); fatlength32 = cdiv((clust32 + 2) * 4, sector_size); /* Need to recalculate number of clusters, since the unused parts of the * FATS and data area together could make up space for an additional, * not really present cluster. */ clust32 = (fatdata32 - nr_fats * fatlength32) / bs.cluster_size; maxclust32 = (fatlength32 * sector_size) / 4; if (maxclust32 > MAX_CLUST_32) maxclust32 = MAX_CLUST_32; if (clust32 && clust32 < MIN_CLUST_32 && !(size_fat_by_user && size_fat == 32)) { clust32 = 0; if (verbose >= 2) printf("FAT32: not enough clusters (%d)\n", MIN_CLUST_32); } if (verbose >= 2) printf("FAT32: #clu=%u, fatlen=%u, maxclu=%u, limit=%u\n", clust32, fatlength32, maxclust32, MAX_CLUST_32); if (clust32 > maxclust32) { clust32 = 0; if (verbose >= 2) printf("FAT32: too much clusters\n"); } if ((clust12 && (size_fat == 0 || size_fat == 12)) || (clust16 && (size_fat == 0 || size_fat == 16)) || (clust32 && size_fat == 32)) break; bs.cluster_size <<= 1; } while (bs.cluster_size && bs.cluster_size <= maxclustsize); /* Use the optimal FAT size if not specified; * FAT32 is (not yet) choosen automatically */ if (!size_fat) { size_fat = (clust16 > clust12) ? 16 : 12; if (verbose >= 2) printf("Choosing %d bits for FAT\n", size_fat); } switch (size_fat) { case 12: cluster_count = clust12; fat_length = fatlength12; bs.fat_length = htole16(fatlength12); memcpy(vi->fs_type, MSDOS_FAT12_SIGN, 8); break; case 16: if (clust16 < FAT12_THRESHOLD) { if (size_fat_by_user) { fprintf(stderr, "WARNING: Not enough clusters for a " "16 bit FAT! The filesystem will be\n" "misinterpreted as having a 12 bit FAT without " "mount option \"fat=16\".\n"); } else { fprintf(stderr, "This filesystem has an unfortunate size. " "A 12 bit FAT cannot provide\n" "enough clusters, but a 16 bit FAT takes up a little " "bit more space so that\n" "the total number of clusters becomes less than the " "threshold value for\n" "distinction between 12 and 16 bit FATs.\n"); die("Make the filesystem a bit smaller manually."); } } cluster_count = clust16; fat_length = fatlength16; bs.fat_length = htole16(fatlength16); memcpy(vi->fs_type, MSDOS_FAT16_SIGN, 8); break; case 32: if (clust32 < MIN_CLUST_32) fprintf(stderr, "WARNING: Not enough clusters for a 32 bit FAT!\n"); cluster_count = clust32; fat_length = fatlength32; bs.fat_length = htole16(0); bs.fat32.fat32_length = htole32(fatlength32); memcpy(vi->fs_type, MSDOS_FAT32_SIGN, 8); root_dir_entries = 0; break; default: die("FAT not 12, 16 or 32 bits"); } /* Adjust the number of root directory entries to help enforce alignment */ if (align_structures) { root_dir_entries = align_object(root_dir_sectors, bs.cluster_size) * (sector_size >> 5); } } else { unsigned clusters, maxclust, fatdata; /* GEMDOS always uses a 12 bit FAT on floppies, and always a 16 bit FAT on * hard disks. So use 12 bit if the size of the filesystem suggests that * this fs is for a floppy disk, if the user hasn't explicitly requested a * size. */ if (!size_fat) size_fat = (num_sectors == 1440 || num_sectors == 2400 || num_sectors == 2880 || num_sectors == 5760) ? 12 : 16; if (verbose >= 2) printf("Choosing %d bits for FAT\n", size_fat); /* Atari format: cluster size should be 2, except explicitly requested by * the user, since GEMDOS doesn't like other cluster sizes very much. * Instead, tune the sector size for the FS to fit. */ bs.cluster_size = sectors_per_cluster ? sectors_per_cluster : 2; if (!sector_size_set) { while (num_sectors > GEMDOS_MAX_SECTORS) { num_sectors >>= 1; sector_size <<= 1; } } if (verbose >= 2) printf("Sector size must be %d to have less than %d log. sectors\n", sector_size, GEMDOS_MAX_SECTORS); /* Check if there are enough FAT indices for how much clusters we have */ do { fatdata = num_sectors - cdiv(root_dir_entries * 32, sector_size) - reserved_sectors; /* The factor 2 below avoids cut-off errors for nr_fats == 1 and * size_fat == 12 * The "2*nr_fats*size_fat/8" is for the reserved first two FAT entries */ clusters = (2 * ((long long)fatdata * sector_size - 2 * nr_fats * size_fat / 8)) / (2 * ((int)bs.cluster_size * sector_size + nr_fats * size_fat / 8)); fat_length = cdiv((clusters + 2) * size_fat / 8, sector_size); /* Need to recalculate number of clusters, since the unused parts of the * FATS and data area together could make up space for an additional, * not really present cluster. */ clusters = (fatdata - nr_fats * fat_length) / bs.cluster_size; maxclust = (fat_length * sector_size * 8) / size_fat; if (verbose >= 2) printf("ss=%d: #clu=%d, fat_len=%d, maxclu=%d\n", sector_size, clusters, fat_length, maxclust); /* last 10 cluster numbers are special (except FAT32: 4 high bits rsvd); * first two numbers are reserved */ if (maxclust <= (size_fat == 32 ? MAX_CLUST_32 : (1 << size_fat) - 0x10) && clusters <= maxclust - 2) break; if (verbose >= 2) printf(clusters > maxclust - 2 ? "Too many clusters\n" : "FAT too big\n"); /* need to increment sector_size once more to */ if (sector_size_set) die("With this sector size, the maximum number of FAT entries " "would be exceeded."); num_sectors >>= 1; sector_size <<= 1; } while (sector_size <= GEMDOS_MAX_SECTOR_SIZE); if (sector_size > GEMDOS_MAX_SECTOR_SIZE) die("Would need a sector size > 16k, which GEMDOS can't work with"); cluster_count = clusters; if (size_fat != 32) bs.fat_length = htole16(fat_length); else { bs.fat_length = 0; bs.fat32.fat32_length = htole32(fat_length); } } bs.sector_size[0] = (char)(sector_size & 0x00ff); bs.sector_size[1] = (char)((sector_size & 0xff00) >> 8); bs.dir_entries[0] = (char)(root_dir_entries & 0x00ff); bs.dir_entries[1] = (char)((root_dir_entries & 0xff00) >> 8); if (size_fat == 32) { /* set up additional FAT32 fields */ bs.fat32.flags = htole16(0); bs.fat32.version[0] = 0; bs.fat32.version[1] = 0; bs.fat32.root_cluster = htole32(2); bs.fat32.info_sector = htole16(1); if (!backup_boot) backup_boot = (reserved_sectors >= 7) ? 6 : (reserved_sectors >= 2) ? reserved_sectors - 1 : 0; else { if (backup_boot == 1) die("Backup boot sector must be after sector 1"); else if (backup_boot >= reserved_sectors) die("Backup boot sector must be a reserved sector"); } if (verbose >= 2) printf("Using sector %d as backup boot sector (0 = none)\n", backup_boot); bs.fat32.backup_boot = htole16(backup_boot); memset(&bs.fat32.reserved2, 0, sizeof(bs.fat32.reserved2)); } if (atari_format) { /* Just some consistency checks */ if (num_sectors >= GEMDOS_MAX_SECTORS) die("GEMDOS can't handle more than 65531 sectors"); else if (num_sectors >= OLDGEMDOS_MAX_SECTORS) printf("Warning: More than 32765 sector need TOS 1.04 " "or higher.\n"); } if (num_sectors >= 65536) { bs.sectors[0] = (char)0; bs.sectors[1] = (char)0; bs.total_sect = htole32(num_sectors); } else { bs.sectors[0] = (char)(num_sectors & 0x00ff); bs.sectors[1] = (char)((num_sectors & 0xff00) >> 8); if (!atari_format) bs.total_sect = htole32(0); } if (!atari_format) vi->ext_boot_sign = MSDOS_EXT_SIGN; if (!cluster_count) { if (sectors_per_cluster) /* If yes, die if we'd spec'd sectors per cluster */ die("Too many clusters for filesystem - try more sectors per cluster"); else die("Attempting to create a too large filesystem"); } /* The two following vars are in hard sectors, i.e. 512 byte sectors! */ start_data_sector = (reserved_sectors + nr_fats * fat_length) * (sector_size / HARD_SECTOR_SIZE); start_data_block = (start_data_sector + SECTORS_PER_BLOCK - 1) / SECTORS_PER_BLOCK; if (blocks < start_data_block + 32) /* Arbitrary undersize filesystem! */ die("Too few blocks for viable filesystem"); if (verbose) { printf("%s has %d head%s and %d sector%s per track,\n", device_name, le16toh(bs.heads), (le16toh(bs.heads) != 1) ? "s" : "", le16toh(bs.secs_track), (le16toh(bs.secs_track) != 1) ? "s" : ""); printf("hidden sectors 0x%04x;\n", hidden_sectors); printf("logical sector size is %d,\n", sector_size); printf("using 0x%02x media descriptor, with %d sectors;\n", (int)(bs.media), num_sectors); printf("drive number 0x%02x;\n", (int) (vi->drive_number)); printf("filesystem has %d %d-bit FAT%s and %d sector%s per cluster.\n", (int)(bs.fats), size_fat, (bs.fats != 1) ? "s" : "", (int)(bs.cluster_size), (bs.cluster_size != 1) ? "s" : ""); printf("FAT size is %d sector%s, and provides %d cluster%s.\n", fat_length, (fat_length != 1) ? "s" : "", cluster_count, (cluster_count != 1) ? "s" : ""); printf("There %s %u reserved sector%s.\n", (reserved_sectors != 1) ? "are" : "is", reserved_sectors, (reserved_sectors != 1) ? "s" : ""); if (size_fat != 32) { unsigned root_dir_entries = bs.dir_entries[0] + ((bs.dir_entries[1]) * 256); unsigned root_dir_sectors = cdiv(root_dir_entries * 32, sector_size); printf("Root directory contains %u slots and uses %u sectors.\n", root_dir_entries, root_dir_sectors); } printf("Volume ID is %08lx, ", volume_id & (atari_format ? 0x00ffffff : 0xffffffff)); if (strcmp(volume_name, NO_NAME)) printf("volume label %s.\n", volume_name); else printf("no volume label.\n"); } /* Make the file allocation tables! */ if (malloc_entire_fat) alloced_fat_length = fat_length; else alloced_fat_length = 1; if ((fat = (unsigned char *)malloc(alloced_fat_length * sector_size)) == NULL) die("unable to allocate space for FAT image in memory"); memset(fat, 0, alloced_fat_length * sector_size); mark_FAT_cluster(0, 0xffffffff); /* Initial fat entries */ mark_FAT_cluster(1, 0xffffffff); fat[0] = (unsigned char)bs.media; /* Put media type in first byte! */ if (size_fat == 32) { /* Mark cluster 2 as EOF (used for root dir) */ mark_FAT_cluster(2, FAT_EOF); } /* Make the root directory entries */ size_root_dir = (size_fat == 32) ? bs.cluster_size * sector_size : (((int)bs.dir_entries[1] * 256 + (int)bs.dir_entries[0]) * sizeof(struct msdos_dir_entry)); if ((root_dir = (struct msdos_dir_entry *)malloc(size_root_dir)) == NULL) { free(fat); /* Tidy up before we die! */ die("unable to allocate space for root directory in memory"); } memset(root_dir, 0, size_root_dir); if (memcmp(volume_name, NO_NAME, 11)) { struct msdos_dir_entry *de = &root_dir[0]; memcpy(de->name, volume_name, 8); memcpy(de->ext, volume_name + 8, 3); de->attr = ATTR_VOLUME; if (!invariant) ctime = localtime(&create_time); else ctime = gmtime(&create_time); de->time = htole16((unsigned short)((ctime->tm_sec >> 1) + (ctime->tm_min << 5) + (ctime->tm_hour << 11))); de->date = htole16((unsigned short)(ctime->tm_mday + ((ctime->tm_mon + 1) << 5) + ((ctime->tm_year - 80) << 9))); de->ctime_cs = 0; de->ctime = de->time; de->cdate = de->date; de->adate = de->date; de->starthi = htole16(0); de->start = htole16(0); de->size = htole32(0); } if (size_fat == 32) { /* For FAT32, create an info sector */ struct fat32_fsinfo *info; if (!(info_sector = malloc(sector_size))) die("Out of memory"); memset(info_sector, 0, sector_size); /* fsinfo structure is at offset 0x1e0 in info sector by observation */ info = (struct fat32_fsinfo *)(info_sector + 0x1e0); /* Info sector magic */ info_sector[0] = 'R'; info_sector[1] = 'R'; info_sector[2] = 'a'; info_sector[3] = 'A'; /* Magic for fsinfo structure */ info->signature = htole32(0x61417272); /* We've allocated cluster 2 for the root dir. */ info->free_clusters = htole32(cluster_count - 1); info->next_cluster = htole32(2); /* Info sector also must have boot sign */ *(uint16_t *) (info_sector + 0x1fe) = htole16(BOOT_SIGN); } if (!(blank_sector = malloc(sector_size))) die("Out of memory"); memset(blank_sector, 0, sector_size); } /* Write the new filesystem's data tables to wherever they're going to end up! */ #define error(str) \ do { \ free (fat); \ if (info_sector) free (info_sector); \ free (root_dir); \ die (str); \ } while(0) #define seekto(pos,errstr) \ do { \ loff_t __pos = (pos); \ if (llseek (dev, __pos, SEEK_SET) != __pos) \ error ("seek to " errstr " failed whilst writing tables"); \ } while(0) #define writebuf(buf,size,errstr) \ do { \ int __size = (size); \ if (write (dev, buf, __size) != __size) \ error ("failed whilst writing " errstr); \ } while(0) static void write_tables(void) { int x; int fat_length; fat_length = (size_fat == 32) ? le32toh(bs.fat32.fat32_length) : le16toh(bs.fat_length); seekto(0, "start of device"); /* clear all reserved sectors */ for (x = 0; x < reserved_sectors; ++x) writebuf(blank_sector, sector_size, "reserved sector"); /* seek back to sector 0 and write the boot sector */ seekto(0, "boot sector"); writebuf((char *)&bs, sizeof(struct msdos_boot_sector), "boot sector"); /* on FAT32, write the info sector and backup boot sector */ if (size_fat == 32) { seekto(le16toh(bs.fat32.info_sector) * sector_size, "info sector"); writebuf(info_sector, 512, "info sector"); if (backup_boot != 0) { seekto(backup_boot * sector_size, "backup boot sector"); writebuf((char *)&bs, sizeof(struct msdos_boot_sector), "backup boot sector"); } } /* seek to start of FATS and write them all */ seekto(reserved_sectors * sector_size, "first FAT"); for (x = 1; x <= nr_fats; x++) { int y; int blank_fat_length = fat_length - alloced_fat_length; writebuf(fat, alloced_fat_length * sector_size, "FAT"); for (y = 0; y < blank_fat_length; y++) writebuf(blank_sector, sector_size, "FAT"); } /* Write the root directory directly after the last FAT. This is the root * dir area on FAT12/16, and the first cluster on FAT32. */ writebuf((char *)root_dir, size_root_dir, "root directory"); if (blank_sector) free(blank_sector); if (info_sector) free(info_sector); free(root_dir); /* Free up the root directory space from setup_tables */ free(fat); /* Free up the fat table space reserved during setup_tables */ } /* Report the command usage and exit with the given error code */ static void usage(int exitval) { fprintf(stderr, "\ Usage: mkfs.fat [-a][-A][-c][-C][-v][-I][-l bad-block-file][-b backup-boot-sector]\n\ [-m boot-msg-file][-n volume-name][-i volume-id]\n\ [-s sectors-per-cluster][-S logical-sector-size][-f number-of-FATs]\n\ [-h hidden-sectors][-F fat-size][-r root-dir-entries][-R reserved-sectors]\n\ [-M FAT-media-byte][-D drive_number]\n\ [--invariant]\n\ [--help]\n\ /dev/name [blocks]\n"); exit(exitval); } /* * ++roman: On m68k, check if this is an Atari; if yes, turn on Atari variant * of MS-DOS filesystem by default. */ static void check_atari(void) { #ifdef __mc68000__ FILE *f; char line[128], *p; if (!(f = fopen("/proc/hardware", "r"))) { perror("/proc/hardware"); return; } while (fgets(line, sizeof(line), f)) { if (strncmp(line, "Model:", 6) == 0) { p = line + 6; p += strspn(p, " \t"); if (strncmp(p, "Atari ", 6) == 0) atari_format = 1; break; } } fclose(f); #endif } /* The "main" entry point into the utility - we pick up the options and attempt to process them in some sort of sensible way. In the event that some/all of the options are invalid we need to tell the user so that something can be done! */ int main(int argc, char **argv) { int c; char *tmp; char *listfile = NULL; FILE *msgfile; struct stat statbuf; int i = 0, pos, ch; int create = 0; uint64_t cblocks = 0; int min_sector_size; int bad_block_count = 0; struct timeval create_timeval; enum {OPT_HELP=1000, OPT_INVARIANT,}; const struct option long_options[] = { {"help", no_argument, NULL, OPT_HELP}, {"invariant", no_argument, NULL, OPT_INVARIANT}, {0,} }; if (argc && *argv) { /* What's the program name? */ char *p; program_name = *argv; if ((p = strrchr(program_name, '/'))) program_name = p + 1; } gettimeofday(&create_timeval, NULL); create_time = create_timeval.tv_sec; volume_id = (uint32_t) ((create_timeval.tv_sec << 20) | create_timeval.tv_usec); /* Default volume ID = creation time, fudged for more uniqueness */ check_atari(); printf("mkfs.fat " VERSION " (" VERSION_DATE ")\n"); while ((c = getopt_long(argc, argv, "aAb:cCf:D:F:Ii:l:m:M:n:r:R:s:S:h:v", long_options, NULL)) != -1) /* Scan the command line for options */ switch (c) { case 'A': /* toggle Atari format */ atari_format = !atari_format; break; case 'a': /* a : skip alignment */ align_structures = FALSE; break; case 'b': /* b : location of backup boot sector */ backup_boot = (int)strtol(optarg, &tmp, 0); if (*tmp || backup_boot < 2 || backup_boot > 0xffff) { printf("Bad location for backup boot sector : %s\n", optarg); usage(1); } break; case 'c': /* c : Check FS as we build it */ check = TRUE; malloc_entire_fat = TRUE; /* Need to be able to mark clusters bad */ break; case 'C': /* C : Create a new file */ create = TRUE; break; case 'D': /* D : Choose Drive Number */ drive_number_option = (int) strtol (optarg, &tmp, 0); if (*tmp || (drive_number_option != 0 && drive_number_option != 0x80)) { printf ("Drive number must be 0 or 0x80: %s\n", optarg); usage(1); } drive_number_by_user=1; break; case 'f': /* f : Choose number of FATs */ nr_fats = (int)strtol(optarg, &tmp, 0); if (*tmp || nr_fats < 1 || nr_fats > 4) { printf("Bad number of FATs : %s\n", optarg); usage(1); } break; case 'F': /* F : Choose FAT size */ size_fat = (int)strtol(optarg, &tmp, 0); if (*tmp || (size_fat != 12 && size_fat != 16 && size_fat != 32)) { printf("Bad FAT type : %s\n", optarg); usage(1); } size_fat_by_user = 1; break; case 'h': /* h : number of hidden sectors */ hidden_sectors = (int)strtol(optarg, &tmp, 0); if (*tmp || hidden_sectors < 0) { printf("Bad number of hidden sectors : %s\n", optarg); usage(1); } hidden_sectors_by_user = 1; break; case 'I': ignore_full_disk = 1; break; case 'i': /* i : specify volume ID */ volume_id = strtoul(optarg, &tmp, 16); if (*tmp) { printf("Volume ID must be a hexadecimal number\n"); usage(1); } break; case 'l': /* l : Bad block filename */ listfile = optarg; malloc_entire_fat = TRUE; /* Need to be able to mark clusters bad */ break; case 'm': /* m : Set boot message */ if (strcmp(optarg, "-")) { msgfile = fopen(optarg, "r"); if (!msgfile) perror(optarg); } else msgfile = stdin; if (msgfile) { /* The boot code ends at offset 448 and needs a null terminator */ i = MESSAGE_OFFSET; pos = 0; /* We are at beginning of line */ do { ch = getc(msgfile); switch (ch) { case '\r': /* Ignore CRs */ case '\0': /* and nulls */ break; case '\n': /* LF -> CR+LF if necessary */ if (pos) { /* If not at beginning of line */ dummy_boot_code[i++] = '\r'; pos = 0; } dummy_boot_code[i++] = '\n'; break; case '\t': /* Expand tabs */ do { dummy_boot_code[i++] = ' '; pos++; } while (pos % 8 && i < BOOTCODE_SIZE - 1); break; case EOF: dummy_boot_code[i++] = '\0'; /* Null terminator */ break; default: dummy_boot_code[i++] = ch; /* Store character */ pos++; /* Advance position */ break; } } while (ch != EOF && i < BOOTCODE_SIZE - 1); /* Fill up with zeros */ while (i < BOOTCODE_SIZE - 1) dummy_boot_code[i++] = '\0'; dummy_boot_code[BOOTCODE_SIZE - 1] = '\0'; /* Just in case */ if (ch != EOF) printf("Warning: message too long; truncated\n"); if (msgfile != stdin) fclose(msgfile); } break; case 'M': /* M : FAT Media byte */ fat_media_byte = (int)strtol(optarg, &tmp, 0); if (*tmp) { printf("Bad number for media descriptor : %s\n", optarg); usage(1); } if (fat_media_byte != 0xf0 && (fat_media_byte < 0xf8 || fat_media_byte > 0xff)) { printf("FAT Media byte must either be between 0xF8 and 0xFF or be 0xF0 : %s\n", optarg); usage(1); } break; case 'n': /* n : Volume name */ sprintf(volume_name, "%-11.11s", optarg); for (i = 0; volume_name[i] && i < 11; i++) /* don't know if here should be more strict !uppercase(label[i]) */ if (islower(volume_name[i])) { fprintf(stderr, "mkfs.fat: warning - lowercase labels might not work properly with DOS or Windows\n"); break; } break; case 'r': /* r : Root directory entries */ root_dir_entries = (int)strtol(optarg, &tmp, 0); if (*tmp || root_dir_entries < 16 || root_dir_entries > 32768) { printf("Bad number of root directory entries : %s\n", optarg); usage(1); } break; case 'R': /* R : number of reserved sectors */ reserved_sectors = (int)strtol(optarg, &tmp, 0); if (*tmp || reserved_sectors < 1 || reserved_sectors > 0xffff) { printf("Bad number of reserved sectors : %s\n", optarg); usage(1); } break; case 's': /* s : Sectors per cluster */ sectors_per_cluster = (int)strtol(optarg, &tmp, 0); if (*tmp || (sectors_per_cluster != 1 && sectors_per_cluster != 2 && sectors_per_cluster != 4 && sectors_per_cluster != 8 && sectors_per_cluster != 16 && sectors_per_cluster != 32 && sectors_per_cluster != 64 && sectors_per_cluster != 128)) { printf("Bad number of sectors per cluster : %s\n", optarg); usage(1); } break; case 'S': /* S : Sector size */ sector_size = (int)strtol(optarg, &tmp, 0); if (*tmp || (sector_size != 512 && sector_size != 1024 && sector_size != 2048 && sector_size != 4096 && sector_size != 8192 && sector_size != 16384 && sector_size != 32768)) { printf("Bad logical sector size : %s\n", optarg); usage(1); } sector_size_set = 1; break; case 'v': /* v : Verbose execution */ ++verbose; break; case OPT_HELP: usage(0); break; case OPT_INVARIANT: invariant = 1; volume_id = 0x1234abcd; create_time = 1426325213; break; default: printf("Unknown option: %c\n", c); usage(1); } if (optind < argc) { device_name = argv[optind]; /* Determine the number of blocks in the FS */ if (!device_name) { printf("No device specified.\n"); usage(1); } if (!create) cblocks = count_blocks(device_name, &orphaned_sectors); /* Have a look and see! */ } if (optind == argc - 2) { /* Either check the user specified number */ blocks = strtoull(argv[optind + 1], &tmp, 0); if (!create && blocks != cblocks) { fprintf(stderr, "Warning: block count mismatch: "); fprintf(stderr, "found %llu but assuming %llu.\n", (unsigned long long)cblocks, (unsigned long long)blocks); } if (*tmp) bad_block_count = 1; } else if (optind == argc - 1) { /* Or use value found */ if (create) die("Need intended size with -C."); blocks = cblocks; } else { fprintf(stderr, "No device specified!\n"); usage(1); } if (bad_block_count) { printf("Bad block count : %s\n", argv[optind + 1]); usage(1); } if (check && listfile) /* Auto and specified bad block handling are mutually */ die("-c and -l are incompatible"); /* exclusive of each other! */ if (!create) { check_mount(device_name); /* Is the device already mounted? */ dev = open(device_name, O_EXCL | O_RDWR); /* Is it a suitable device to build the FS on? */ if (dev < 0) { fprintf(stderr, "%s: unable to open %s: %s\n", program_name, device_name, strerror(errno)); exit(1); /* The error exit code is 1! */ } } else { /* create the file */ dev = open(device_name, O_EXCL | O_RDWR | O_CREAT, 0666); if (dev < 0) { if (errno == EEXIST) die("file %s already exists"); else die("unable to create %s"); } /* expand to desired size */ if (ftruncate(dev, blocks * BLOCK_SIZE)) die("unable to resize %s"); } if (fstat(dev, &statbuf) < 0) die("unable to stat %s"); if (!S_ISBLK(statbuf.st_mode)) { statbuf.st_rdev = 0; check = 0; } else /* * Ignore any 'full' fixed disk devices, if -I is not given. * On a MO-disk one doesn't need partitions. The filesytem can go * directly to the whole disk. Under other OSes this is known as * the 'superfloppy' format. As I don't know how to find out if * this is a MO disk I introduce a -I (ignore) switch. -Joey */ if (!ignore_full_disk && ((statbuf.st_rdev & 0xffffff3f) == 0x0300 || /* hda, hdb */ (statbuf.st_rdev & 0xffffff0f) == 0x0800 || /* sd */ (statbuf.st_rdev & 0xffffff3f) == 0x0d00 || /* xd */ (statbuf.st_rdev & 0xffffff3f) == 0x1600) /* hdc, hdd */ ) die("Device partition expected, not making filesystem on entire device '%s' (use -I to override)"); if (sector_size_set) { if (ioctl(dev, BLKSSZGET, &min_sector_size) >= 0) if (sector_size < min_sector_size) { sector_size = min_sector_size; fprintf(stderr, "Warning: sector size was set to %d (minimal for this device)\n", sector_size); } } else { if (ioctl(dev, BLKSSZGET, &min_sector_size) >= 0) { sector_size = min_sector_size; sector_size_set = 1; } } if (sector_size > 4096) fprintf(stderr, "Warning: sector size is set to %d > 4096, such filesystem will not propably mount\n", sector_size); establish_params(statbuf.st_rdev, statbuf.st_size); /* Establish the media parameters */ setup_tables(); /* Establish the filesystem tables */ if (check) /* Determine any bad block locations and mark them */ check_blocks(); else if (listfile) get_list_blocks(listfile); write_tables(); /* Write the filesystem tables away! */ exit(0); /* Terminate with no errors! */ }
{ "pile_set_name": "Github" }
pragma solidity ^0.4.2; // ---------------------------------------------------------------------------------------------- // Basic ERC20 Token Contract For **TESTING ONLY** on Testnet or Dev blockchain. // // Enjoy. (c) Bok Consulting Pty Ltd 2016. The MIT Licence. // ---------------------------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 contract ERC20Interface { // Get the total token supply function totalSupply() constant returns (uint256 totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) returns (bool success); // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address _from, address _to, uint256 _value) returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract TestERC20Token is ERC20Interface { // Owner of this contract address public owner; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // Total supply uint256 _totalSupply; // Functions with this modifier can only be executed by the bank modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } // Constructor function TestERC20Token() { owner = msg.sender; } function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } // What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0) { balances[_to] += _amount; balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function () payable { if (msg.value > 0) { _totalSupply += msg.value; balances[msg.sender] += msg.value; } } function withdrawEthers(uint256 ethers) onlyOwner returns (bool ok) { if (this.balance >= ethers) { return owner.send(ethers); } } // Triggered when fiat currency is converted to tokens event TokensCreated(address indexed _owner, uint256 _amount); }
{ "pile_set_name": "Github" }
{ "name": "vue-bus", "version": "1.2.1", "description": "A event bus for Vue.js", "main": "dist/vue-bus.common.js", "module": "dist/vue-bus.esm.js", "unpkg": "dist/vue-bus.js", "jsdelivr": "dist/vue-bus.js", "typings": "types/index.d.ts", "files": [ "src", "dist/*.js", "types/*.d.ts" ], "scripts": { "lint": "eslint src __tests__", "build": "rimraf dist && rollup -c && uglifyjs dist/vue-bus.js -c -m --comments -o dist/vue-bus.min.js", "test": "jest && codecov" }, "repository": { "type": "git", "url": "git+https://github.com/yangmingshan/vue-bus.git" }, "keywords": [ "vue", "events", "bus" ], "author": "Yang Mingshan <[email protected]>", "license": "MIT", "bugs": { "url": "https://github.com/yangmingshan/vue-bus/issues" }, "homepage": "https://github.com/yangmingshan/vue-bus#readme", "devDependencies": { "@rollup/plugin-buble": "^0.21.3", "buble": "^0.20.0", "codecov": "^3.2.0", "eslint": "^7.4.0", "eslint-config-standard": "^14.1.0", "eslint-plugin-import": "^2.16.0", "eslint-plugin-node": "^11.0.0", "eslint-plugin-promise": "^4.0.1", "eslint-plugin-standard": "^4.0.0", "jest": "^26.1.0", "rimraf": "^3.0.0", "rollup": "^2.0.6", "uglify-js": "^3.5.1", "vue": "^2.6.10" }, "jest": { "coverageDirectory": "./coverage/", "collectCoverage": true } }
{ "pile_set_name": "Github" }
<p> Shame page will be offline until entries are updated. </p> <!-- <p> This is a list of projects or companies violating FFmpeg's license. The list is part of an effort to get them to comply with the licensing terms by shaming them in public. </p> <p> A good way to help us is to link to this page, thereby boosting its pagerank, possibly near or past the homepage of the offender. We discourage you from using or buying the software listed here, unless you do so to pester its producers and demand that they comply with the license of FFmpeg. </p> <p> Our issue tracker also contains a list of <a href="https://trac.ffmpeg.org/report/1">license violations</a>. If you become aware of license infringements, please notify us on the <a href="contact.html">ffmpeg-devel mailing list</a> and/or add it to our <a href="https://trac.ffmpeg.org">issue tracker</a>. </p> <p> (in alphabetical order) </p> <ul> <li><a href="http://www.alivemedia.net" rel="nofollow">alive</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1160">issue tracker entry</a></li> <li><a href="http://www.alloksoft.com" rel="nofollow">Alloksoft</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue438">issue tracker entry</a></li> <li><a href="http://www.amrplayer.com" rel="nofollow">AMR Player</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1070">issue tracker entry</a></li> <li><a href="http://anvsoft.com" rel="nofollow">AnvSoft</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1246">issue tracker entry</a>, reproduced 2009-11-03</li> <li><a href="http://www.any-video-converter.com" rel="nofollow">Any DVD/Video Converter</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue922">issue tracker entry</a>, reproduced 2009-11-03</li> <li><a href="http://www.aone-media.com" rel="nofollow">Aone</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1308">issue tracker entry</a>, reproduced 2009-11-14</li> <li><a href="http://www.tomp4.com/html/videoconverter.html" rel="nofollow">Aplus Video Converter</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1213">issue tracker entry</a></li> <li><a href="http://applian.com/replay-converter/index.php" rel="nofollow">Applian Replay Converter</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue110">issue tracker entry</a></li> <li><a href="http://www.avcware.com" rel="nofollow">AVCWare</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue932">issue tracker entry</a></li> <li><a href="http://www.avs4you.com/AVS-Video-Converter.aspx" rel="nofollow">AVS Video Converter</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue733">issue tracker entry</a></li> <li><a href="http://www.alltoaudio.com" rel="nofollow">Aya Media Techologies</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue930">issue tracker entry</a></li> <li><a href="http://www.baofeng.com" rel="nofollow">Baofeng Storm</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue866">issue tracker entry</a>, reproduced 2009-11-03</li> <li><a href="http://www.cinemaforge.com">CinemaForge</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue933">issue tracker entry</a></li> <li><a href="http://potplayer.daum.net" rel="nofollow">Daum tv PotPlayer</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue2112">issue tracker entry</a>, reproduced 2010-11-03</li> <li><a href="http://www.doremilabs.com/v1control.html" rel="nofollow">Doremi Asset Manager</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue727">issue tracker entry</a></li> <li><a href="http://www.downloadhelper.net/install-converter.php" rel="nofollow">DownloadHelper ConvertHelper</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1096">issue tracker entry</a>, reproduced 2009-11-04</li> <li><a href="http://www.dvdfab.com" rel="nofollow">DVDFab</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue382">issue tracker entry</a></li> <li><a href="http://www.dvdxdv.com" rel="nofollow">DVDxDV</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1105">issue tracker entry</a></li> <li><a href="http://www.eatcam.com" rel="nofollow">EatCam</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1513">issue tracker entry</a>, reproduced 2009-11-03</li> <li><a href="http://www.effectmatrix.com" rel="nofollow">EffectMatrix Software</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue456">issue tracker entry</a></li> <li><a href="http://www.eztoosoft.com" rel="nofollow">Eztoo</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue828">issue tracker entry</a></li> <li><a href="http://www.formatoz.com" rel="nofollow">Format Factory</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1214">issue tracker entry</a></li> <li><a href="http://www.winxdvd.com/" rel="nofollow">FreeTime Soft</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue722">issue tracker entry</a></li> <li><a href="http://www.sourcemac.com/?page=fstream&amp;lang=en" rel="nofollow">FStream</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1471">issue tracker entry</a>, reproduced 2009-11-03</li> <li><a href="http://www.geovid.com" rel="nofollow">GeoVid</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue918">issue tracker entry</a></li> <li><a href="http://www.getflv.net/index.html" rel="nofollow">GetFLV</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1085">issue tracker entry</a></li> <li><a href="http://www.gomlab.com/" rel="nofollow">GOM Player</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue112">issue tracker entry</a></li> <li><a href="http://www.h264encoder.com/" rel="nofollow">H264Encoder.com</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue787">issue tracker entry</a></li> <li><a href="http://www.imtoo.com" rel="nofollow">ImTOO</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1311">issue tracker entry</a>, reproduced 2009-11-14</li> <li><a href="http://www.iskysoft.net" rel="nofollow">iSkysoft</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue927">issue tracker entry</a></li> <li><a href="http://www.kmplayer.com/forums/" rel="nofollow">The KMPlayer</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue820">issue tracker entry</a></li> <li><a href="http://www.koyotesoft.com" rel="nofollow">Koyote Software</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue931">issue tracker entry</a></li> <li><a href="www.livestation.com" rel="nofollow">Livestation</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue920">issue tracker entry</a></li> <li><a href="http://www.alldj.com" rel="nofollow">MasterSoft Inc.</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue723">issue tracker entry</a></li> <li><a href="http://mediacoderhq.com" rel="nofollow">MediaCoder</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1162">issue tracker entry</a></li> <li><a href="http://www.moyea.com" rel="nofollow">Moyea</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue926">issue tracker entry</a></li> <li><a href="http://www.mp4converter.net/dvd-to-appletv-converter-mac.html" rel="nofollow">MP4Converter</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue111">issue tracker entry</a></li> <li><a href="http://www.netgem.com/" rel="nofollow">Netgem</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue678">issue tracker entry</a></li> <li><a href="http://www.opellsoft.com/" rel="nofollow">Opell Video Converter Pro</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue493">issue tracker entry</a></li> <li><a href="http://liveradio.orange.fr/" rel="nofollow">Orange Liveradio</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1502">issue tracker entry</a></li> <li><a href="http://www.themediamall.com/playon/" rel="nofollow">PlayOn</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1403">issue tracker entry</a></li> <li><a href="http://www.powerpoint-dvd-converter.com" rel="nofollow">PowerPoint DVD Converter</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue924">issue tracker entry</a></li> <li><a href="http://www.presentersoft.com" rel="nofollow">PresenterSoft</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue925">issue tracker entry</a></li> <li><a href="http://player.qzone.qq.com" rel="nofollow">QQPlayer</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1519">issue tracker entry</a>, reproduced 2009-11-04</li> <li><a href="http://www.redkawa.com" rel="nofollow">Red Kawa</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue923">issue tracker entry</a></li> <li><a href="http://www.riptiger.com" rel="nofollow">RipTiger</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1450">issue tracker entry</a>, reproduced 2009-11-03</li> <li><a href="http://www.rhozet.com/carbon_coder.html" rel="nofollow">Rhozet Carbon Coder</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue484">issue tracker entry</a>, reproduced 2009-09-18</li> <li><a href="http://sagetv.com" rel="nofollow">SageTV</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue2375">issue tracker entry</a>, reproduced 2011-01-03</li> <li><a href="http://www.cctvhw.com/english/" rel="nofollow">ShenZhen Hawell</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue513">issue tracker entry</a></li> <li><a href="http://www.skypecap.com" rel="nofollow">SkypeCap</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue321">issue tracker entry</a></li> <li><a href="http://www.softservice.org/products_flashcam.html" rel="nofollow">Soft Service, Ltd. FlashCam</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue559">issue tracker entry</a></li> <li><a href="http://www.sothinkmedia.com" rel="nofollow">SourceTec Software</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1158">issue tracker entry</a>, reproduced 2009-11-04</li> <li><a href="http://www.video-convert-master.com/index.htm" rel="nofollow">Video Convert Master</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue413">issue tracker entry</a></li> <li><a href="http://vio.thepiratebay.org/" rel="nofollow">ViO mobile video converter</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue763">issue tracker entry</a></li> <li><a href="http://www.virtualdj.com" rel="nofollow">VirtualDJ</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1412">issue tracker entry</a>, reproduced 2009-11-04</li> <li><a href="http://www.mzys.cn" rel="nofollow">WisMencoder</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1133">issue tracker entry</a></li> <li><a href="http://www.wondershare.com" rel="nofollow">Wondershare</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue928">issue tracker entry</a>, reproduced 2009-11-14</li> <li><a href="http://www.xilisoft.com" rel="nofollow">Xilisoft Video Converter</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue929">issue tracker entry</a>, reproduced 2010-03-08</li> <li><a href="http://www.xlinksoft.com" rel="nofollow">XlinkSoft</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1509">issue tracker entry</a>, reproduced 2009-11-03</li> <li><a href="http://www.xmedia-recode.de" rel="nofollow">XMedia Recode</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1144">issue tracker entry</a></li> <li><a href="http://www.zoiper.com/" rel="nofollow">ZoIPer</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue1045">issue tracker entry</a></li> </ul> <p> The companies below are not yet in full compliance, but we are in negotiations with them and making good progress towards compliance. </p> <ul> <li><a href="http://chromaplayer.com/" rel="nofollow">Chroma</a>, <a href="http://roundup.ffmpeg.org/roundup/ffmpeg/issue726">issue tracker entry</a></li> </ul> -->
{ "pile_set_name": "Github" }
/* * This file is part of ELKI: * Environment for Developing KDD-Applications Supported by Index-Structures * * Copyright (C) 2019 * ELKI Development Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package elki.index.tree.spatial.rstarvariants.strategies.reinsert; import elki.data.spatial.SpatialComparable; import elki.utilities.datastructures.arraylike.ArrayAdapter; /** * Reinsertion strategy to resolve overflows in the RStarTree. * * @author Erich Schubert * @since 0.5.0 */ public interface ReinsertStrategy { /** * Perform reinsertions. * * @param entries Entries in overflowing node * @param getter Adapter for the entries array * @param page Spatial extend of the page * @return index of pages to reinsert. */ <A> int[] computeReinserts(A entries, ArrayAdapter<? extends SpatialComparable, ? super A> getter, SpatialComparable page); }
{ "pile_set_name": "Github" }
export default function p2a(a: any): string[]
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2010, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.kernel.feature.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.eclipse.equinox.region.Region; import org.eclipse.equinox.region.RegionDigraph; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleListener; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.framework.startlevel.FrameworkStartLevel; import org.osgi.framework.wiring.FrameworkWiring; import org.osgi.service.component.ComponentConstants; import org.osgi.service.component.ComponentContext; import com.ibm.ws.kernel.boot.internal.BootstrapConstants; import com.ibm.ws.kernel.feature.ServerStarted; import com.ibm.ws.kernel.feature.internal.BundleList.FeatureResourceHandler; import com.ibm.ws.kernel.feature.internal.FeatureManager.FeatureChange; import com.ibm.ws.kernel.feature.internal.FeatureManager.ProvisioningMode; import com.ibm.ws.kernel.feature.internal.subsystem.FeatureRepository; import com.ibm.ws.kernel.feature.internal.subsystem.FeatureResourceImpl; import com.ibm.ws.kernel.feature.internal.subsystem.SubsystemFeatureDefinitionImpl; import com.ibm.ws.kernel.feature.provisioning.ActivationType; import com.ibm.ws.kernel.feature.provisioning.FeatureResource; import com.ibm.ws.kernel.feature.provisioning.ProvisioningFeatureDefinition; import com.ibm.ws.kernel.feature.resolver.FeatureResolver.Result; import com.ibm.ws.kernel.provisioning.BundleRepositoryRegistry; import com.ibm.ws.kernel.provisioning.BundleRepositoryRegistry.BundleRepositoryHolder; import com.ibm.ws.kernel.provisioning.ContentBasedLocalBundleRepository; import com.ibm.ws.kernel.service.location.internal.SymbolRegistry; import com.ibm.ws.runtime.update.RuntimeUpdateManager; import com.ibm.ws.runtime.update.RuntimeUpdateNotification; import com.ibm.wsspi.kernel.service.location.VariableRegistry; import com.ibm.wsspi.kernel.service.location.WsLocationAdmin; import com.ibm.wsspi.kernel.service.location.WsResource; import com.ibm.wsspi.kernel.service.utils.OnErrorUtil; import com.ibm.wsspi.kernel.service.utils.OnErrorUtil.OnError; import junit.framework.AssertionFailedError; import test.common.SharedLocationManager; import test.common.SharedOutputManager; import test.utils.SharedConstants; import test.utils.TestUtils; import test.utils.TestUtils.TestBundleRevision; import test.utils.TestUtils.TestBundleStartLevel; import test.utils.TestUtils.TestFrameworkStartLevel; import test.utils.TestUtils.TestFrameworkWiring; /** * */ @RunWith(JMock.class) public class FeatureManagerTest { static final SharedOutputManager outputMgr = SharedOutputManager.getInstance().trace("*=audit=enabled:featureManager=all=enabled"); static final String serverName = "FeatureManagerTest"; static final Collection<ProvisioningFeatureDefinition> noKernelFeatures = Collections.<ProvisioningFeatureDefinition> emptySet(); static WsLocationAdmin locSvc; static Field bListResources; /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { outputMgr.captureStreams(); bListResources = BundleList.class.getDeclaredField("resources"); bListResources.setAccessible(true); File root = SharedConstants.TEST_DATA_FILE.getCanonicalFile(); File lib = new File(root, "lib"); TestUtils.setUtilsInstallDir(root); TestUtils.setKernelUtilsBootstrapLibDir(lib); TestUtils.clearBundleRepositoryRegistry(); locSvc = (WsLocationAdmin) SharedLocationManager.createLocations(SharedConstants.TEST_DATA_DIR, serverName); TestUtils.recursiveClean(locSvc.getServerResource(null)); BundleRepositoryRegistry.initializeDefaults(serverName, true); SymbolRegistry.getRegistry().addStringSymbol("websphere.kernel", "kernelCore-1.0.mf"); SymbolRegistry.getRegistry().addStringSymbol("websphere.log.provider", "defaultLogging-1.0.mf"); } @AfterClass public static void tearDownAfterClass() throws Exception { outputMgr.restoreStreams(); TestUtils.setUtilsInstallDir(null); TestUtils.setKernelUtilsBootstrapLibDir(null); TestUtils.clearBundleRepositoryRegistry(); } Mockery context = new JUnit4Mockery(); final Bundle mockBundle = context.mock(Bundle.class); final BundleContext mockBundleContext = context.mock(BundleContext.class); final ComponentContext mockComponentContext = context.mock(ComponentContext.class); final ExecutorService executorService = context.mock(ExecutorService.class); final VariableRegistry variableRegistry = context.mock(VariableRegistry.class); final MockServiceReference<WsLocationAdmin> mockLocationService = new MockServiceReference<WsLocationAdmin>(locSvc); final MockServiceReference<ScheduledExecutorService> mockScheduledExecutorService = new MockServiceReference<ScheduledExecutorService>(context.mock(ScheduledExecutorService.class)); final RegionDigraph mockDigraph = context.mock(RegionDigraph.class); final RuntimeUpdateManager runtimeUpdateManager = context.mock(RuntimeUpdateManager.class); final RuntimeUpdateNotification appForceRestart = context.mock(RuntimeUpdateNotification.class, "appForceRestart"); final RuntimeUpdateNotification featureBundlesResolved = context.mock(RuntimeUpdateNotification.class, "featureBundlesResolved"); final RuntimeUpdateNotification featureBundlesProcessed = context.mock(RuntimeUpdateNotification.class, "featureBundlesProcessed"); final RuntimeUpdateNotification featureUpdatesCompleted = context.mock(RuntimeUpdateNotification.class, "featureUpdatesCompleted"); final Region mockKernelRegion = context.mock(Region.class); final TestBundleRevision mockBundleRevision = context.mock(TestBundleRevision.class); final TestBundleStartLevel mockBundleStartLevel = context.mock(TestBundleStartLevel.class); final TestFrameworkStartLevel testFrameworkStartLevel = new TestFrameworkStartLevel(); final TestFrameworkWiring testFrameworkWiring = new TestFrameworkWiring(); FeatureManager fm; Provisioner provisioner; @Before public void setUp() throws Exception { fm = new FeatureManager(); fm.featureChanges.clear(); fm.onError = OnError.WARN; fm.bundleContext = mockBundleContext; fm.fwStartLevel = testFrameworkStartLevel; fm.setExecutorService(executorService); fm.setLocationService(locSvc); fm.setVariableRegistry(variableRegistry); fm.setDigraph(mockDigraph); fm.setRuntimeUpdateManager(runtimeUpdateManager); // We have to activate the FeatureManager here so that the component context will be // propagated to the AtomicServiceReferences for the locationService and executorService try { context.checking(new Expectations() { { allowing(mockComponentContext).getBundleContext(); will(returnValue(mockBundleContext)); allowing(mockBundleContext).getBundle(Constants.SYSTEM_BUNDLE_LOCATION); will(returnValue(mockBundle)); allowing(mockBundle).getBundleContext(); will(returnValue(mockBundleContext)); allowing(mockBundleContext).getBundles(); will(returnValue(new Bundle[0])); //allow mock calls from the BundleInstallOriginBundleListener <init> allowing(mockBundleContext).getBundle(); will(returnValue(mockBundle)); one(mockBundleContext).getDataFile("bundle.origin.cache"); allowing(mockBundleContext).addBundleListener(with(any(BundleListener.class))); allowing(mockBundleContext).getProperty("websphere.os.extension"); will(returnValue(null)); allowing(mockBundleContext).removeBundleListener(with(any(BundleListener.class))); one(mockBundle).adapt(FrameworkStartLevel.class); will(returnValue(testFrameworkStartLevel)); one(mockBundle).adapt(FrameworkWiring.class); will(returnValue(testFrameworkWiring)); allowing(mockBundleContext).getProperty(with("com.ibm.ws.liberty.content.request")); will(returnValue(null)); allowing(mockBundleContext).getProperty(with("com.ibm.ws.liberty.feature.request")); will(returnValue(null)); allowing(mockBundleContext).getProperty(with("com.ibm.ws.kernel.classloading.apiPackagesToHide")); will(returnValue(null)); allowing(mockBundleContext).getProperty(with("wlp.process.type")); will(returnValue(BootstrapConstants.LOC_PROCESS_TYPE_SERVER)); allowing(mockComponentContext).locateService(with("locationService"), with(any(ServiceReference.class))); will(returnValue(locSvc)); allowing(mockComponentContext).locateService(with("executorService"), with(any(ServiceReference.class))); will(returnValue(executorService)); allowing(mockComponentContext).locateService(with("variableRegistry"), with(any(ServiceReference.class))); will(returnValue(variableRegistry)); allowing(executorService).execute(with(any(Runnable.class))); one(variableRegistry).addVariable(with("feature:usr"), with("${usr.extension.dir}/lib/features/")); allowing(mockBundleContext).getBundles(); allowing(mockBundleContext).registerService(with(any(Class.class)), with(any(ServerStarted.class)), with(any(Dictionary.class))); allowing(mockBundleContext).registerService(with(any(String[].class)), with(any(PackageInspectorImpl.class)), with(any(Dictionary.class))); // allow calls to digraph by Provisioner allowing(mockDigraph).getRegion(mockBundle); will(returnValue(mockKernelRegion)); allowing(mockKernelRegion).getName(); will(returnValue("kernel.region")); allowing(mockDigraph).copy(); will(returnValue(mockDigraph)); allowing(runtimeUpdateManager).createNotification(RuntimeUpdateNotification.FEATURE_UPDATES_COMPLETED); will(returnValue(featureUpdatesCompleted)); allowing(runtimeUpdateManager).createNotification(RuntimeUpdateNotification.APP_FORCE_RESTART); will(returnValue(appForceRestart)); allowing(runtimeUpdateManager).createNotification(RuntimeUpdateNotification.FEATURE_BUNDLES_RESOLVED); will(returnValue(featureBundlesResolved)); allowing(appForceRestart).setResult(with(any(Boolean.class))); allowing(featureBundlesResolved).setResult(with(any(Boolean.class))); allowing(runtimeUpdateManager).getNotification(RuntimeUpdateNotification.FEATURE_BUNDLES_PROCESSED); will(returnValue(featureBundlesProcessed)); allowing(featureBundlesProcessed).waitForCompletion(); allowing(featureUpdatesCompleted).setResult(with(any(Boolean.class))); allowing(mockBundleContext).getProperty("wlp.liberty.boot"); will(returnValue(null)); allowing(mockBundleContext).getDataFile("feature.fix.cache"); will(returnValue(File.createTempFile("feature.fix.cache", null))); allowing(featureBundlesResolved).setProperties(with(any(Map.class))); } }); fm.activate(mockComponentContext, new HashMap<String, Object>()); } catch (Throwable t) { outputMgr.failWithThrowable("setUp", t); } fm.featureRepository = new FeatureRepository(); fm.bundleCache = new BundleList(fm); fm.featureRepository.init(); fm.bundleCache.init(); provisioner = new Provisioner(fm, null); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { // Clear the output generated after each method invocation, this keeps // things sane outputMgr.resetStreams(); TestUtils.recursiveClean(locSvc.getServerResource(null)); } @Test(expected = NullPointerException.class) public void testUnitializedProvisioner() { // No provisioner, should blow up with NPE FeatureChange featureChange = new FeatureChange(runtimeUpdateManager, ProvisioningMode.INITIAL_PROVISIONING, new String[] { "notexist" }); featureChange.createNotifications(); fm.updateFeatures(locSvc, null, null, featureChange, 1L); } @Test(expected = IllegalStateException.class) public void testUnitializedProvisionerWithFailOnError() { final String m = "testUnitializedProvisionerWithFailOnError"; try { fm.onError = OnError.FAIL; context.checking(new Expectations() { { one(mockBundle).stop(); } }); // onError is FAIL which means we expect an // IllegalStateException FeatureChange featureChange = new FeatureChange(runtimeUpdateManager, ProvisioningMode.INITIAL_PROVISIONING, new String[] { "notexist" }); featureChange.createNotifications(); fm.updateFeatures(locSvc, null, null, featureChange, 1L); } catch (IllegalStateException e) { throw e; } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testUpdateFeaturesNotExistFeature() { final String m = "testUpdateFeaturesNotExistFeature"; try { // This shouldn't do anything: no return to test-- make sure it doesn't // blow up w/ NPE! fm.onError = OnError.WARN; String missingFeature = "CWWKF0001E"; FeatureChange featureChange = new FeatureChange(runtimeUpdateManager, ProvisioningMode.INITIAL_PROVISIONING, new String[] { "notexist", "NotExist" }); featureChange.createNotifications(); fm.updateFeatures(locSvc, provisioner, null, featureChange, 1L); assertTrue("An error should have been issued about the missing feature", outputMgr.checkForMessages(missingFeature)); assertTrue("The error message should contain notexist", outputMgr.checkForMessages("notexist")); assertFalse("The error message should not contain NotExist", outputMgr.checkForMessages("NotExist")); // We put notexist on there twice -- this should condense to ONE error message // for only one missing feature String err = outputMgr.getCapturedErr(); int pos = err.indexOf(missingFeature); assertTrue("Error output should contain the error message: " + pos, pos > -1); pos = err.indexOf(missingFeature, pos + missingFeature.length()); assertFalse("Error output should not contain a second error message: " + pos + ": " + err, pos > -1); } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test(expected = IllegalStateException.class) public void testUpdateFeaturesNotExistFeatureWithFailOnError() { final String m = "testUpdateFeaturesNotExistFeatureWithFailOnError"; try { fm.onError = OnError.FAIL; context.checking(new Expectations() { { one(mockBundle).stop(); } }); // continueOnError=false means that we expect an IllegalStateException due // to the non-existant feature 'notexist' FeatureChange featureChange = new FeatureChange(runtimeUpdateManager, ProvisioningMode.INITIAL_PROVISIONING, new String[] { "notexist" }); featureChange.createNotifications(); fm.updateFeatures(locSvc, provisioner, null, featureChange, 1L); } catch (IllegalStateException e) { throw e; } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test(expected = IllegalStateException.class) public void testUpdateFeaturesMixedWithFailOnError() { final String m = "testUpdateFeaturesMixedWithFailOnError"; try { fm.onError = OnError.FAIL; final AtomicBoolean installBundlesCalled = new AtomicBoolean(false); Provisioner provisioner = new Provisioner(fm, null) { /** Override installBundles to verify that it is not called in this scenario */ @Override public void installBundles(BundleContext bContext, BundleList bundleList, BundleInstallStatus installStatus, int minStartLevel, int defaultStartLevel, int defaultInitialStartLevel, WsLocationAdmin locSvc) { installBundlesCalled.set(true); } }; context.checking(new Expectations() { { one(mockBundle).stop(); } }); // continueOnError=false means that we expect an IllegalStateException due // to the non-existant feature 'notexist'; installBundles should not be called // even though there is one existing feature 'good' in the list FeatureChange featureChange = new FeatureChange(runtimeUpdateManager, ProvisioningMode.INITIAL_PROVISIONING, new String[] { "good", "notexist" }); featureChange.createNotifications(); fm.updateFeatures(locSvc, provisioner, null, featureChange, 1L); assertFalse("installBundles should not have been called", installBundlesCalled.get()); } catch (IllegalStateException e) { throw e; } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } /** * @param bundleList * @return */ @SuppressWarnings("unchecked") protected List<FeatureResource> getResources(BundleList bundleList) { try { return (List<FeatureResource>) bListResources.get(bundleList); } catch (Exception e) { Error err = new AssertionFailedError("Could not obtain the value of FeatureCache.resources"); err.initCause(e); throw err; } } /** * Test method */ @Test public void testNoEnabledFeatures() { final String m = "testNoEnabledFeatures"; try { fm.onError = OnError.WARN; FeatureChange featureChange = new FeatureChange(runtimeUpdateManager, ProvisioningMode.INITIAL_PROVISIONING, new String[0]); featureChange.createNotifications(); fm.updateFeatures(locSvc, new Provisioner(fm, null), null, featureChange, 1L); // SharedOutputMgr routing trace to standard out assertTrue("Assert 'no enabled features' warning", outputMgr.checkForStandardOut("CWWKF0009W")); } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testActivate() { final String m = "testActivate"; try { context.checking(new Expectations() { { allowing(mockComponentContext).getBundleContext(); will(returnValue(mockBundleContext)); allowing(mockBundleContext).getBundle(Constants.SYSTEM_BUNDLE_LOCATION); will(returnValue(mockBundle)); allowing(mockBundle).getBundleContext(); will(returnValue(mockBundleContext)); allowing(mockBundleContext).getBundles(); will(returnValue(new Bundle[0])); one(mockBundle).adapt(FrameworkStartLevel.class); will(returnValue(testFrameworkStartLevel)); one(mockBundle).adapt(FrameworkWiring.class); will(returnValue(testFrameworkWiring)); allowing(executorService).execute(with(any(Runnable.class))); one(variableRegistry).addVariable(with("feature:usr"), with("${usr.extension.dir}/lib/features/")); //allow mock calls from the BundleInstallOriginBundleListener <init> allowing(mockBundleContext).getBundle(); will(returnValue(mockBundle)); one(mockBundleContext).getDataFile("bundle.origin.cache"); } }); Map<String, Object> componentProps = new HashMap<String, Object>(); fm.activate(mockComponentContext, componentProps); } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testUpdated() { final String m = "testUpdated"; try { // Immediate return: no NPE fm.updated(null); context.checking(new Expectations() { { allowing(executorService).execute(with(any(Runnable.class))); } }); Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(OnErrorUtil.CFG_KEY_ON_ERROR, OnError.FAIL); fm.updated(props); } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testLoadFeatureInclude() { final String m = "testLoadFeatureInclude"; try { BundleInstallStatus installStatus = new BundleInstallStatus(); Result result = FeatureManager.featureResolver.resolveFeatures(fm.featureRepository, noKernelFeatures, Collections.singleton("include"), Collections.<String> emptySet(), false); fm.reportErrors(result, Collections.<String> emptyList(), Collections.singleton("include"), installStatus); assertTrue("CWWKF0001E error message", outputMgr.checkForStandardErr("CWWKF0001E:")); } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testUpdate() { final String m = "testUpdate"; try { // Add list of empty features fm.featureChanges.add(new FeatureChange(runtimeUpdateManager, ProvisioningMode.UPDATE, new String[0])); fm.onError = OnError.WARN; fm.processFeatureChanges(); assertTrue("CWWKF0007I start audit should be in output", outputMgr.checkForMessages("CWWKF0007I")); assertTrue("CWWKF0008I complete audit", outputMgr.checkForMessages("CWWKF0008I")); fm.deactivate(ComponentConstants.DEACTIVATION_REASON_BUNDLE_STOPPED); // no-op } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testFeaturesRequest() { final String m = "testFeaturesRequest"; try { // Add list of empty features fm.featureChanges.add(new FeatureChange(runtimeUpdateManager, ProvisioningMode.FEATURES_REQUEST, new String[0])); fm.onError = OnError.WARN; fm.processFeatureChanges(); assertTrue("CWWKF0007I start audit should be in output", outputMgr.checkForMessages("CWWKF0007I")); assertTrue("CWWKF0036I finished gathering a list of required features should be in output", outputMgr.checkForMessages("CWWKF0036I")); assertTrue("CWWKF0008I complete audit", outputMgr.checkForMessages("CWWKF0008I")); fm.deactivate(ComponentConstants.DEACTIVATION_REASON_BUNDLE_STOPPED); // no-op } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testInstallStatusNull() { final String m = "testUpdate"; try { fm.onError = OnError.FAIL; fm.checkInstallStatus(null); } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test(expected = IllegalStateException.class) public void testInstallStatusOtherException() { final String m = "testInstallStatusOtherException"; try { fm.onError = OnError.FAIL; context.checking(new Expectations() { { one(mockBundle).stop(); } }); final BundleInstallStatus iStatus = new BundleInstallStatus(); iStatus.addOtherException(new Throwable("some other exception")); fm.checkInstallStatus(iStatus); throw new Throwable("stopFramework not called"); } catch (IllegalStateException e) { assertTrue("CWWKF0004E -- other exception in stderr", outputMgr.checkForStandardErr("CWWKF0004E")); throw e; } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testMissingBundleException() { final String m = "testMissingBundleException"; try { fm.onError = OnError.FAIL; context.checking(new Expectations() { { one(mockBundle).stop(); } }); final BundleInstallStatus iStatus = new BundleInstallStatus(); iStatus.addMissingBundle(new FeatureResourceImpl("missing", Collections.<String, String> emptyMap(), null, null, ActivationType.SEQUENTIAL)); try { fm.checkInstallStatus(iStatus); throw new Throwable("stopFramework not called"); } catch (IllegalStateException e) { } } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testInstallStatusInstallException() { final String m = "testInstallStatusInstallException"; try { fm.onError = OnError.FAIL; context.checking(new Expectations() { { one(mockBundle).stop(); } }); final BundleInstallStatus iStatus = new BundleInstallStatus(); iStatus.addInstallException("bundle", new Throwable("exception-b1")); iStatus.addInstallException("bundle2", new Throwable("exception-b2")); try { fm.checkInstallStatus(iStatus); throw new Throwable("stopFramework not called"); } catch (IllegalStateException e) { assertTrue("CWWKF0003E -- install exception in stderr", outputMgr.checkForStandardErr("CWWKF0003E")); // message should be issued once for each bundle install exception assertTrue("exception-b1 -- install exception in stderr", outputMgr.checkForStandardErr("exception-b1")); assertTrue("exception-b2 -- install exception in stderr", outputMgr.checkForStandardErr("exception-b2")); } } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testBundleStatusException() { final String m = "testBundleStatusException"; try { fm.onError = OnError.FAIL; context.checking(new Expectations() { { one(mockBundle).stop(); } }); final Bundle mockBundle2 = context.mock(Bundle.class, "bundle2"); final BundleLifecycleStatus bStatus = new BundleLifecycleStatus(); bStatus.addStartException(mockBundle, new Throwable("terrible thing")); bStatus.addStartException(mockBundle2, new Throwable("horrible other thing")); try { fm.checkBundleStatus(bStatus); throw new Throwable("stopFramework not called"); } catch (IllegalStateException e) { assertTrue("CWWKF0005E -- exception in stderr", outputMgr.checkForStandardErr("CWWKF0005E")); // message should be issued once for each bundle exception assertTrue("terrible thing -- exception in stderr", outputMgr.checkForStandardErr("terrible thing")); assertTrue("horrible other thing -- exception in stderr", outputMgr.checkForStandardErr("horrible other thing")); } } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testLoadFeatureDefinition() { final String m = "testLoadFeatureDefinition"; try { BundleInstallStatus installStatus = new BundleInstallStatus(); // make sure handles just a : Result result = FeatureManager.featureResolver.resolveFeatures(fm.featureRepository, noKernelFeatures, Collections.singleton(":"), Collections.<String> emptySet(), false); fm.reportErrors(result, Collections.<String> emptyList(), Collections.singleton(":"), installStatus); assertTrue("CWWKF0001E error message", outputMgr.checkForStandardErr("CWWKF0001E:")); assertTrue("There should be missing features", installStatus.featuresMissing()); assertTrue("installStatus should contain : as missing feature", installStatus.getMissingFeatures().contains(":")); outputMgr.resetStreams(); installStatus.getMissingFeatures().clear(); // make sure handles nothing after : // CWWKF0001E: A feature definition could not be found for usr: result = FeatureManager.featureResolver.resolveFeatures(fm.featureRepository, noKernelFeatures, Collections.singleton("usr:"), Collections.<String> emptySet(), false); fm.reportErrors(result, Collections.<String> emptyList(), Collections.singleton("usr:"), installStatus); assertTrue("CWWKF0001E error message", outputMgr.checkForStandardErr("CWWKF0001E:")); assertTrue("specification of usr:", outputMgr.checkForStandardErr("usr:")); assertTrue("installStatus shuold contain : as missing feature", installStatus.getMissingFeatures().contains("usr:")); outputMgr.resetStreams(); installStatus.getMissingFeatures().clear(); // give it one it should not find // CWWKF0001E: A feature definition could not be found for usr:bad result = FeatureManager.featureResolver.resolveFeatures(fm.featureRepository, noKernelFeatures, Collections.singleton("usr:bad"), Collections.<String> emptySet(), false); fm.reportErrors(result, Collections.<String> emptyList(), Collections.singleton("usr:bad"), installStatus); assertTrue("CWWKF0001E error message", outputMgr.checkForStandardErr("CWWKF0001E:")); assertTrue("specification of usr:bad", outputMgr.checkForStandardErr("usr:bad")); assertTrue("installStatus should contain : as missing feature", installStatus.getMissingFeatures().contains("usr:bad")); // now test with a 'core' feature with no ':' result = FeatureManager.featureResolver.resolveFeatures(fm.featureRepository, noKernelFeatures, Collections.singleton("coreMissing-1.0"), Collections.<String> emptySet(), false); fm.reportErrors(result, Collections.<String> emptyList(), Collections.singleton("coreMissing-1.0"), installStatus); assertTrue("CWWKF0001E error message", outputMgr.checkForStandardErr("CWWKF0001E:")); assertTrue("specification of coreMissing-1.0", outputMgr.checkForStandardErr("coreMissing-1.0")); assertTrue("installStatus should contain : as missing feature", installStatus.getMissingFeatures().contains("coreMissing-1.0")); } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } @Test public void testReadWriteCache() throws IOException { final String m = "testReadWriteCache"; WsResource cacheFile = locSvc.getServerWorkareaResource(m); final AtomicLong id = new AtomicLong(); try { context.checking(new Expectations() { { exactly(2).of(mockBundle).getBundleId(); will(returnValue(id.incrementAndGet())); } }); if (cacheFile.exists()) cacheFile.delete(); assertFalse("Cache file should be a unique temp file (should not exist)", cacheFile.exists()); InputStream is = TestUtils.createValidFeatureManifestStream("simple.feature-1.0", "simple;version=\"[0.1,0.2)\", simpleTwo;version=\"[2.0, 2.0.100)\""); SubsystemFeatureDefinitionImpl definitionImpl = new SubsystemFeatureDefinitionImpl("", is); assertEquals("Subsystem should be for core repository (empty string)", "", definitionImpl.getBundleRepositoryType()); final BundleList list = new BundleList(cacheFile, fm); list.addAll(definitionImpl, fm); assertEquals("List should have 2 elements", 2, getResources(list).size()); list.foreach(new FeatureResourceHandler() { @Override public boolean handle(FeatureResource fr) { String bundleRepositoryType = fr.getBundleRepositoryType(); BundleRepositoryHolder bundleRepositoryHolder = fm.getBundleRepositoryHolder(bundleRepositoryType); ContentBasedLocalBundleRepository lbr = bundleRepositoryHolder.getBundleRepository(); File f = lbr.selectBundle(null, fr.getSymbolicName(), fr.getVersionRange()); WsResource resource = locSvc.asResource(f, f.isFile()); list.createAssociation(fr, mockBundle, resource, fr.getStartLevel()); return true; } }); list.store(); assertTrue("Cache file should exist after cache is stored", cacheFile.exists()); BundleList list2 = new BundleList(cacheFile, fm); list2.init(); assertEquals("List should have two elements", 2, getResources(list2).size()); List<?> res1 = getResources(list); List<?> res2 = getResources(list2); for (Object o1 : res1) { boolean found = false; for (Object o2 : res2) { if (match((FeatureResource) o1, (FeatureResource) o2)) { found = true; break; } } assertTrue("List read from cache should contain element from original list: " + o1, found); } } catch (Throwable t) { outputMgr.failWithThrowable(m, t); } } private boolean match(FeatureResource o1, FeatureResource o2) { System.out.println("o1: " + o1.toString() + " , " + o1.getMatchString() + " , " + o1.getLocation()); System.out.println("o2: " + o2.toString() + " , " + o2.getMatchString() + " , " + o2.getLocation()); if (!o1.getMatchString().equals(o2.getMatchString())) return false; return true; } }
{ "pile_set_name": "Github" }
plaidml-keras==0.6.2 mplfinance
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* ftlcdfil.h */ /* */ /* FreeType API for color filtering of subpixel bitmap glyphs */ /* (specification). */ /* */ /* Copyright 2006-2008, 2010, 2013, 2014 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FT_LCD_FILTER_H__ #define __FT_LCD_FILTER_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************** * * @section: * lcd_filtering * * @title: * LCD Filtering * * @abstract: * Reduce color fringes of LCD-optimized bitmaps. * * @description: * The @FT_Library_SetLcdFilter API can be used to specify a low-pass * filter, which is then applied to LCD-optimized bitmaps generated * through @FT_Render_Glyph. This is useful to reduce color fringes * that would occur with unfiltered rendering. * * Note that no filter is active by default, and that this function is * *not* implemented in default builds of the library. You need to * #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING in your `ftoption.h' file * in order to activate it. * * FreeType generates alpha coverage maps, which are linear by nature. * For instance, the value 0x80 in bitmap representation means that * (within numerical precision) 0x80/0xFF fraction of that pixel is * covered by the glyph's outline. The blending function for placing * text over a background is * * { * dst = alpha * src + (1 - alpha) * dst , * } * * which is known as OVER. However, when calculating the output of the * OVER operator, the source colors should first be transformed to a * linear color space, then alpha blended in that space, and transformed * back to the output color space. * * When linear light blending is used, the default FIR5 filtering * weights (as given by FT_LCD_FILTER_DEFAULT) are no longer optimal, as * they have been designed for black on white rendering while lacking * gamma correction. To preserve color neutrality, weights for a FIR5 * filter should be chosen according to two free parameters `a' and `c', * and the FIR weights should be * * { * [a - c, a + c, 2 * a, a + c, a - c] . * } * * This formula generates equal weights for all the color primaries * across the filter kernel, which makes it colorless. One suggested * set of weights is * * { * [0x10, 0x50, 0x60, 0x50, 0x10] , * } * * where `a' has value 0x30 and `b' value 0x20. The weights in filter * may have a sum larger than 0x100, which increases coloration slightly * but also improves contrast. */ /**************************************************************************** * * @enum: * FT_LcdFilter * * @description: * A list of values to identify various types of LCD filters. * * @values: * FT_LCD_FILTER_NONE :: * Do not perform filtering. When used with subpixel rendering, this * results in sometimes severe color fringes. * * FT_LCD_FILTER_DEFAULT :: * The default filter reduces color fringes considerably, at the cost * of a slight blurriness in the output. * * FT_LCD_FILTER_LIGHT :: * The light filter is a variant that produces less blurriness at the * cost of slightly more color fringes than the default one. It might * be better, depending on taste, your monitor, or your personal vision. * * FT_LCD_FILTER_LEGACY :: * This filter corresponds to the original libXft color filter. It * provides high contrast output but can exhibit really bad color * fringes if glyphs are not extremely well hinted to the pixel grid. * In other words, it only works well if the TrueType bytecode * interpreter is enabled *and* high-quality hinted fonts are used. * * This filter is only provided for comparison purposes, and might be * disabled or stay unsupported in the future. * * @since: * 2.3.0 */ typedef enum FT_LcdFilter_ { FT_LCD_FILTER_NONE = 0, FT_LCD_FILTER_DEFAULT = 1, FT_LCD_FILTER_LIGHT = 2, FT_LCD_FILTER_LEGACY = 16, FT_LCD_FILTER_MAX /* do not remove */ } FT_LcdFilter; /************************************************************************** * * @func: * FT_Library_SetLcdFilter * * @description: * This function is used to apply color filtering to LCD decimated * bitmaps, like the ones used when calling @FT_Render_Glyph with * @FT_RENDER_MODE_LCD or @FT_RENDER_MODE_LCD_V. * * @input: * library :: * A handle to the target library instance. * * filter :: * The filter type. * * You can use @FT_LCD_FILTER_NONE here to disable this feature, or * @FT_LCD_FILTER_DEFAULT to use a default filter that should work * well on most LCD screens. * * @return: * FreeType error code. 0~means success. * * @note: * This feature is always disabled by default. Clients must make an * explicit call to this function with a `filter' value other than * @FT_LCD_FILTER_NONE in order to enable it. * * Due to *PATENTS* covering subpixel rendering, this function doesn't * do anything except returning `FT_Err_Unimplemented_Feature' if the * configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not * defined in your build of the library, which should correspond to all * default builds of FreeType. * * The filter affects glyph bitmaps rendered through @FT_Render_Glyph, * @FT_Outline_Get_Bitmap, @FT_Load_Glyph, and @FT_Load_Char. * * It does _not_ affect the output of @FT_Outline_Render and * @FT_Outline_Get_Bitmap. * * If this feature is activated, the dimensions of LCD glyph bitmaps are * either larger or taller than the dimensions of the corresponding * outline with regards to the pixel grid. For example, for * @FT_RENDER_MODE_LCD, the filter adds up to 3~pixels to the left, and * up to 3~pixels to the right. * * The bitmap offset values are adjusted correctly, so clients shouldn't * need to modify their layout and glyph positioning code when enabling * the filter. * * @since: * 2.3.0 */ FT_EXPORT( FT_Error ) FT_Library_SetLcdFilter( FT_Library library, FT_LcdFilter filter ); /************************************************************************** * * @func: * FT_Library_SetLcdFilterWeights * * @description: * Use this function to override the filter weights selected by * @FT_Library_SetLcdFilter. By default, FreeType uses the quintuple * (0x00, 0x55, 0x56, 0x55, 0x00) for FT_LCD_FILTER_LIGHT, and (0x10, * 0x40, 0x70, 0x40, 0x10) for FT_LCD_FILTER_DEFAULT and * FT_LCD_FILTER_LEGACY. * * @input: * library :: * A handle to the target library instance. * * weights :: * A pointer to an array; the function copies the first five bytes and * uses them to specify the filter weights. * * @return: * FreeType error code. 0~means success. * * @note: * Due to *PATENTS* covering subpixel rendering, this function doesn't * do anything except returning `FT_Err_Unimplemented_Feature' if the * configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not * defined in your build of the library, which should correspond to all * default builds of FreeType. * * This function must be called after @FT_Library_SetLcdFilter to have * any effect. * * @since: * 2.4.0 */ FT_EXPORT( FT_Error ) FT_Library_SetLcdFilterWeights( FT_Library library, unsigned char *weights ); /* */ FT_END_HEADER #endif /* __FT_LCD_FILTER_H__ */ /* END */
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Working with text corpora\n", "\n", "Your text data usually comes in the form of (long) plain text strings that are stored in one or several files on disk. The [Corpus](api.rst#tmtoolkit-corpus) class is for loading and managing *plain text* corpora, i.e. a set of documents with a label and their content as text strings. It resembles a [Python dictionary](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) with additional functionality.\n", "\n", "Let's import the `Corpus` class first:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/html": [ "<style type='text/css'>\n", ".datatable table.frame { margin-bottom: 0; }\n", ".datatable table.frame thead { border-bottom: none; }\n", ".datatable table.frame tr.coltypes td { color: #FFFFFF; line-height: 6px; padding: 0 0.5em;}\n", ".datatable .boolean { background: #DDDD99; }\n", ".datatable .object { background: #565656; }\n", ".datatable .integer { background: #5D9E5D; }\n", ".datatable .float { background: #4040CC; }\n", ".datatable .string { background: #CC4040; }\n", ".datatable .row_index { background: var(--jp-border-color3); border-right: 1px solid var(--jp-border-color0); color: var(--jp-ui-font-color3); font-size: 9px;}\n", ".datatable .frame tr.coltypes .row_index { background: var(--jp-border-color0);}\n", ".datatable th:nth-child(2) { padding-left: 12px; }\n", ".datatable .hellipsis { color: var(--jp-cell-editor-border-color);}\n", ".datatable .vellipsis { background: var(--jp-layout-color0); color: var(--jp-cell-editor-border-color);}\n", ".datatable .na { color: var(--jp-cell-editor-border-color); font-size: 80%;}\n", ".datatable .footer { font-size: 9px; }\n", ".datatable .frame_dimensions { background: var(--jp-border-color3); border-top: 1px solid var(--jp-border-color0); color: var(--jp-ui-font-color3); display: inline-block; opacity: 0.6; padding: 1px 10px 1px 5px;}\n", "</style>\n" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from tmtoolkit.corpus import Corpus" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "## Loading text data\n", "\n", "Several methods are implemented to load text data from different sources:\n", "\n", "- load built-in datasets\n", "- load plain text files (\".txt files\")\n", "- load folder(s) with plain text files\n", "- load a tabular (i.e. CSV or Excel) file containing document IDs and texts\n", "- load a ZIP file containing plain text or tabular files\n", "\n", "We can create a `Corpus` object directly by immediately loading a dataset using one of the `Corpus.from_...` methods. This is what we've done when we used `corpus = Corpus.from_builtin_corpus('en-NewsArticles')` in the [previous chapter](getting_started.ipynb). Let's load a folder with example documents. Make sure that the path is relative to the current working directory. The data for these examples can be downloaded from [GitHub](https://github.com/WZBSocialScienceCenter/tmtoolkit/tree/master/doc/source/data). \n", "\n", "\n", "<div class=\"alert alert-info\">\n", "\n", "Note\n", "\n", "If you want to work with \"rich text documents\", i.e. formatted, non-plain text sources such as PDFs, Word documents, HTML files, etc. you must convert them to one of the supported formats first. For example you can use the [pdftotext](https://www.mankier.com/1/pdftotext) command from the Linux package `poppler-utils` to convert from PDF to plain text files or [pandoc](https://pandoc.org/) to convert from Word or HTML to plain text.\n", "\n", "</div>" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "<Corpus [3 documents]>" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus = Corpus.from_folder('data/corpus_example')\n", "corpus" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "Again, we can have a look which document labels were created and print one sample document:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "['sample1', 'sample2', 'sample3']" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.doc_labels" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "'This is the first example file. ☺'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus['sample1']" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "Now let's look at *all* documents' text. Since we have a very small corpus, printing all text out shouldn't be a problem. We can iterate through all documents by using the `items()` method because a `Corpus` object behaves like a `dict`. We will write a small function for this because we'll reuse this later and one of the most important principles when writing code is [DRY – don't repeat yourself](https://en.wikipedia.org/wiki/Don't_repeat_yourself)." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sample1 :\n", "This is the first example file. ☺\n", "---\n", "\n", "sample2 :\n", "Here comes the second example.\n", "\n", "This one contains three lines of plain text which means two paragraphs.\n", "---\n", "\n", "sample3 :\n", "And here we go with the third and final example file.\n", "Another line of text.\n", "\n", "§2.\n", "This is the second paragraph.\n", "\n", "The third and final paragraph.\n", "---\n", "\n" ] } ], "source": [ "def print_corpus(c):\n", " \"\"\"Print all documents and their text in corpus `c`\"\"\"\n", " \n", " for doc_label, doc_text in c.items():\n", " print(doc_label, ':')\n", " print(doc_text)\n", " print('---\\n')\n", "\n", "print_corpus(corpus)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another option is to create a `Corpus` object by passing a dictionary of already obtained data and optionally add further documents using the `Corpus.add_...` methods. We can also create an empty `Corpus` and then add documents:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "<Corpus [0 documents]>" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus = Corpus()\n", "corpus" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "['data_corpus_example-sample1']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.add_files('data/corpus_example/sample1.txt')\n", "corpus.doc_labels" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "See how we created an empty corpus first and then added a single document. Also note that this time the document label is different. Its prefixed by a normalized version of the path to the document. We can alter the `doc_label_fmt` argument of [Corpus.add_files()](api.rst#tmtoolkit.corpus.Corpus.add_files) in order to control how document labels are generated. But at first, let's remove the previously loaded document from the corpus. Since a `Corpus` instance behaves like a Python `dict`, we can use `del`:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "<Corpus [0 documents]>" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "del corpus['data_corpus_example-sample1']\n", "corpus" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "Now we use a modified `doc_label_fmt` paramater value to generate document labels only from the file name and not from the full path to the document. We also load three files now:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "['sample1', 'sample2', 'sample3']" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.add_files(['data/corpus_example/sample1.txt',\n", " 'data/corpus_example/sample2.txt',\n", " 'data/corpus_example/sample3.txt'],\n", " doc_label_fmt='{basename}')\n", "corpus.doc_labels\n" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "As noted in the beginning, there are more `add_...` and `from_...` methods to load text data from different sources. See the [Corpus API](api.rst#tmtoolkit-corpus) for details.\n", "\n", "<div class=\"alert alert-info\">\n", "\n", "Note\n", "\n", "Please be aware of the difference of the `add_...` and `from_...` methods: The former *modifies* a given Corpus instance, whereas the latter *creates* a new Corpus instance.\n", "\n", "</div>\n", "\n", "## Corpus properties and methods\n", "\n", "A `Corpus` object provides several helpful properties that summarize the plain text data and several methods to manage the documents.\n", " \n", "### Number of documents and characters\n", " \n", "Let's start with the number of documents in the corpus. There are two ways to obtain this value: " ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(corpus)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.n_docs" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "is_executing": false, "name": "#%% md\n" } }, "source": [ "Another important property is the number of characters per document: " ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "{'sample1': 33, 'sample2': 103, 'sample3': 142}" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.doc_lengths" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "### Characters used in the corpus \n", "\n", "The `unique_characters` property returns the set of characters that occur at least once in the document." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "{'\\n',\n", " ' ',\n", " '.',\n", " '2',\n", " 'A',\n", " 'H',\n", " 'T',\n", " 'a',\n", " 'c',\n", " 'd',\n", " 'e',\n", " 'f',\n", " 'g',\n", " 'h',\n", " 'i',\n", " 'l',\n", " 'm',\n", " 'n',\n", " 'o',\n", " 'p',\n", " 'r',\n", " 's',\n", " 't',\n", " 'w',\n", " 'x',\n", " '§',\n", " '☺'}" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.unique_characters" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "is_executing": false, "name": "#%% md\n" } }, "source": [ "This is helpful if you want to check if there are strange characters in your documents that you may want to replace or remove. For example, I included a Unicode smiley ☺ in the first document (which may not be rendered correctly in your browser) that we can remove using [Corpus.remove_characters()](api.rst#tmtoolkit.corpus.Corpus.remove_characters). " ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "'This is the first example file. ☺'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus['sample1']" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "'This is the first example file. '" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.remove_characters('☺')\n", "corpus['sample1']" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "is_executing": false, "name": "#%% md\n" } }, "source": [ "[Corpus.filter_characters()](api.rst#tmtoolkit.corpus.Corpus.filter_characters) behaves similar to the above used method but by default removes *all* characters that are not in a whitelist of allowed characters.\n", "\n", "[Corpus.replace_characters()](api.rst#tmtoolkit.corpus.Corpus.replace_characters) also allows to replace certain characters with others. With [Corpus.apply()](api.rst#tmtoolkit.corpus.Corpus.apply) you can perform any custom text transformation on each document.\n", "\n", "There are more filtering methods: [Corpus.filter_by_min_length()](api.rst#tmtoolkit.corpus.Corpus.filter_by_min_length) / [Corpus.filter_by_max_length()](api.rst#tmtoolkit.corpus.Corpus.filter_by_max_length) allow to remove documents that are too short or too long.\n", "\n", "<div class=\"alert alert-info\">\n", "\n", "Note\n", "\n", "These methods already go in the direction of \"text preprocessing\", which is the topic of the next chapter and is implemented in the [tmtoolkit.preprocess](api.rst#tmtoolkit-preprocess) module. However, the methods in `Corpus` differ substantially from the `preprocess` module, as the `Corpus` methods work on untokenized plain text strings whereas the `preprocess` functions and methods work on document *tokens* (e.g. individual words) and therefore provide a much richer set of tools. However, sometimes it is necessary to do things like removing certain characters *before* tokenization, e.g. when such characters confuse the tokenizer.\n", "\n", "</div>\n", "\n", "### Splitting by paragraphs\n", "\n", "Another helpful method is [Corpus.split_by_paragraphs()](api.rst#tmtoolkit.corpus.Corpus.split_by_paragraphs). This allows splitting each document of the corpus by paragraph.\n", "\n", "Again, let's have a look at our current corpus' documents:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sample1 :\n", "This is the first example file. \n", "---\n", "\n", "sample2 :\n", "Here comes the second example.\n", "\n", "This one contains three lines of plain text which means two paragraphs.\n", "---\n", "\n", "sample3 :\n", "And here we go with the third and final example file.\n", "Another line of text.\n", "\n", "§2.\n", "This is the second paragraph.\n", "\n", "The third and final paragraph.\n", "---\n", "\n" ] } ], "source": [ "print_corpus(corpus)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "As we can see, `sample1` contains one paragraph, `sample2` two and `sample3` three paragraphs. Now we can split those and get the expected number of documents (each paragraph is then an individual document):" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "<Corpus [6 documents]>" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.split_by_paragraphs()\n", "corpus" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "Our newly created six documents:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sample1-1 :\n", "This is the first example file. \n", "---\n", "\n", "sample2-1 :\n", "Here comes the second example.\n", "---\n", "\n", "sample2-2 :\n", "This one contains three lines of plain text which means two paragraphs.\n", "---\n", "\n", "sample3-1 :\n", "And here we go with the third and final example file. Another line of text.\n", "---\n", "\n", "sample3-2 :\n", "§2. This is the second paragraph.\n", "---\n", "\n", "sample3-3 :\n", "The third and final paragraph.\n", "---\n", "\n" ] } ], "source": [ "print_corpus(corpus)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "is_executing": false, "name": "#%% md\n" } }, "source": [ "You can further customize the splitting process by tweaking the parameters, e.g. the minimum number of line breaks used to detect paragraphs (default is two line breaks).\n", "\n", "### Sampling a corpus \n", "\n", "Finally you can sample the documents in a corpus using [Corpus.sample()](api.rst#tmtoolkit.corpus.Corpus.sample). To get a random sample of three documents from our corpus:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "data": { "text/plain": [ "<Corpus [3 documents]>" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.sample(3)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['sample1-1', 'sample2-1', 'sample2-2', 'sample3-1', 'sample3-2', 'sample3-3']" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "corpus.doc_labels" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "is_executing": false, "name": "#%% md\n" } }, "source": [ "Note that this returns a new `Corpus` instance by default. You can pass `as_corpus=False` if you only need a Python dict." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The [next chapter](preprocessing.ipynb) will show how to apply several text preprocessing functions to a corpus." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" }, "pycharm": { "stem_cell": { "cell_type": "raw", "metadata": { "collapsed": false }, "source": [] } } }, "nbformat": 4, "nbformat_minor": 2 }
{ "pile_set_name": "Github" }
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __gnu_javax_crypto_key_srp6_SRP6Host__ #define __gnu_javax_crypto_key_srp6_SRP6Host__ #pragma interface #include <gnu/javax/crypto/key/srp6/SRP6KeyAgreement.h> extern "Java" { namespace gnu { namespace javax { namespace crypto { namespace key { class IncomingMessage; class OutgoingMessage; namespace srp6 { class SRP6Host; } } namespace sasl { namespace srp { class SRPAuthInfoProvider; } } } } } namespace java { namespace security { class KeyPair; } } } class gnu::javax::crypto::key::srp6::SRP6Host : public ::gnu::javax::crypto::key::srp6::SRP6KeyAgreement { public: SRP6Host(); public: // actually protected virtual void engineInit(::java::util::Map *); virtual ::gnu::javax::crypto::key::OutgoingMessage * engineProcessMessage(::gnu::javax::crypto::key::IncomingMessage *); virtual void engineReset(); private: ::gnu::javax::crypto::key::OutgoingMessage * computeSharedSecret(::gnu::javax::crypto::key::IncomingMessage *); ::java::security::KeyPair * __attribute__((aligned(__alignof__( ::gnu::javax::crypto::key::srp6::SRP6KeyAgreement)))) hostKeyPair; ::gnu::javax::crypto::sasl::srp::SRPAuthInfoProvider * passwordDB; public: static ::java::lang::Class class$; }; #endif // __gnu_javax_crypto_key_srp6_SRP6Host__
{ "pile_set_name": "Github" }
package com.shensiyuan.zerocopy; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.net.Socket; public class OldIOClient { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 8899); String fileName = "/Users/zhanglong/Desktop/spark-2.2.0-bin-hadoop2.7.tgz"; InputStream inputStream = new FileInputStream(fileName); DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); byte[] buffer = new byte[4096]; long readCount; long total = 0; long startTime = System.currentTimeMillis(); while ((readCount = inputStream.read(buffer)) >= 0) { total += readCount; dataOutputStream.write(buffer); } System.out.println("发送总字节数: " + total + ", 耗时: " + (System.currentTimeMillis() - startTime)); dataOutputStream.close(); socket.close(); inputStream.close(); } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 6336869efe01e3f4e91371605b8b008e MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
// from: https://www.shadertoy.com/view/XdVXW3 // from: https://www.shadertoy.com/view/MsyXD3 #ifdef GL_ES precision mediump float; precision mediump int; #endif #define PROCESSING_TEXTURE_SHADER uniform sampler2D texture; varying vec4 vertColor; varying vec4 vertTexCoord; uniform vec2 texOffset; void main() { /* vec2 uv = vertTexCoord.xy; vec2 z = texOffset.xy * 1.5 / vertTexCoord.xy; vec2 c = vertTexCoord.xy; c.xy = 0.75-abs(z-0.75); gl_FragColor = texture2D(texture,fract(z*exp2(ceil(-log2(min(c.y,c.x)))))); */ // vec2 uv = texOffset.xy * 1.5; vec2 z = vertTexCoord.xy;// / vertTexCoord.xy; // vec2 p = vertTexCoord.xy - 0.5; // vec4 color = texture2D(texture, p); gl_FragColor = texture2D(texture,fract(z*exp2(ceil(-log2(.5-abs(z.y-.5)))))); } /* void mainImage(out vec4 c,vec2 z) { z *= 1.5/iResolution.xy; c.xy = .75-abs(z-.75); c = texture2D(iChannel0,fract(z*exp2(ceil(-log2(min(c.y,c.x)))))); } */ /* void mainImage(out vec4 c,vec2 z) { z /= iResolution.xy; c = texture2D(iChannel0,fract(z*exp2(ceil(-log2(.5-abs(z.y-.5)))))); } */
{ "pile_set_name": "Github" }
/* ** ClanLib SDK ** Copyright (c) 1997-2016 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Mark Page */ #pragma once namespace clan { /// \addtogroup clanCore_Math clanCore Math /// \{ template<typename Type> class Line2x; template<typename Type> class Line3x; template<typename Type> class Rectx; template<typename Type> class Vec2; class Angle; /// \brief 3D line /// /// These line templates are defined for: int (Line3), float (Line3f), double (Line3d) template<typename Type> class Line3x { public: Vec3<Type> p; Vec3<Type> q; Line3x() : p(), q() {} Line3x(const Line3x<Type> &copy) : p(copy.p), q(copy.q) {} Line3x(const Vec3<Type> &point_p, const Vec3<Type> &point_q) : p(point_p), q(point_q) {} /// \brief Return the intersection of this and other line /// /// \param second = The second line to use /// \param intersect = On Return: true if the lines intersect, false if the lines are parallel /// \param range = Rounding error delta, to use to judge whether of not the lines intersect /// \return The point Vec3<Type> get_intersection(const Line3x<Type> &second, bool &intersect, Type range = (Type) 0.5) const; /// \brief = operator. Line3x<Type> &operator = (const Line3x<Type>& copy) { p = copy.p; q = copy.q; return *this; } /// \brief == operator. bool operator == (const Line3x<Type>& line) const { return ((p == line.p) && (q == line.q)); } /// \brief != operator. bool operator != (const Line3x<Type>& line) const { return ((p != line.p) || (q != line.q)); } }; /// \brief 2D line /// /// These line templates are defined for: int (Line2i), float (Line2f), double (Line2d) template<typename Type> class Line2x { public: /// \brief First point on the line Vec2<Type> p; // \brief Another point on the line Vec2<Type> q; Line2x() : p(), q() { } Line2x(const Line2x<Type> &copy) : p(copy.p), q(copy.q) {} Line2x(const Vec2<Type> &point_p, const Vec2<Type> &point_q) : p(point_p), q(point_q) {} Line2x(const Vec2<Type> &point_p, Type gradient) : p(point_p), q(static_cast<Type> (1), gradient) {} /// \brief Return the intersection of this and other line /// /// \param second = The second line to use /// \param intersect = On Return: true if the lines intersect, false if the lines are parallel /// \return The point Vec2<Type> get_intersection(const Line2x<Type> &second, bool &intersect) const; /// \brief Return [<0, 0, >0] if the Point P is right, on or left of the line trough A,B /// /// \param point = The point /// \return Value representing - left (>0), centre (=0), or right (<0) Type point_right_of_line(Vec2<Type> point) const { return (q.x - p.x) * (point.y - p.y) - (point.x - p.x) * (q.y - p.y); } /// \brief = operator. Line2x<Type> &operator = (const Line2x<Type>& copy) { p = copy.p; q = copy.q; return *this; } /// \brief == operator. bool operator == (const Line2x<Type>& line) const { return ((p == line.p) && (q == line.q)); } /// \brief != operator. bool operator != (const Line2x<Type>& line) const { return ((p != line.p) || (q != line.q)); } }; /// \brief 2D line - Integer class Line2 : public Line2x<int> { public: Line2() : Line2x<int>() { } Line2(const Line2x<int> &copy) : Line2x<int>(copy) { } Line2(const Vec2<int> &point_p, const Vec2<int> &point_q) : Line2x<int>(point_p, point_q) { } Line2(const Vec2<int> &point_p, int gradient) : Line2x<int>(point_p, gradient) { } }; /// \brief 2D line - Float class Line2f : public Line2x<float> { public: Line2f() : Line2x<float>() { } Line2f(const Line2x<float> &copy) : Line2x<float>(copy) { } Line2f(const Vec2<float> &point_p, const Vec2<float> &point_q) : Line2x<float>(point_p, point_q) { } Line2f(const Vec2<float> &point_p, float gradient) : Line2x<float>(point_p, gradient) { } }; /// \brief 2D line - Double class Line2d : public Line2x<double> { public: Line2d() : Line2x<double>() { } Line2d(const Line2x<double> &copy) : Line2x<double>(copy) { } Line2d(const Vec2<double> &point_p, const Vec2<double> &point_q) : Line2x<double>(point_p, point_q) { } Line2d(const Vec2<double> &point_p, double gradient) : Line2x<double>(point_p, gradient) { } }; /// \brief 3D line - Integer class Line3 : public Line3x<int> { public: Line3() : Line3x<int>() { } Line3(const Line3x<int> &copy) : Line3x<int>(copy) { } Line3(const Vec3<int> &point_p, const Vec3<int> &point_q) : Line3x<int>(point_p, point_q) { } }; /// \brief 3D line - Float class Line3f : public Line3x<float> { public: Line3f() : Line3x<float>() { } Line3f(const Line3x<float> &copy) : Line3x<float>(copy) { } Line3f(const Vec3<float> &point_p, const Vec3<float> &point_q) : Line3x<float>(point_p, point_q) { } }; /// \brief 3D line - Double class Line3d : public Line3x<double> { public: Line3d() : Line3x<double>() { } Line3d(const Line3x<double> &copy) : Line3x<double>(copy) { } Line3d(const Vec3<double> &podouble_p, const Vec3<double> &podouble_q) : Line3x<double>(podouble_p, podouble_q) { } }; /// \} }
{ "pile_set_name": "Github" }
The SSH BMC provider provides a limited level of BMC functionality by running commands over an SSH connection to the host using a trusted SSH key. It has the following configuration options for authentication, for the remote SSH user and private SSH key: :bmc_ssh_user: root :bmc_ssh_key: /usr/share/foreman/.ssh/id_rsa The following configuration options control the commands executed by the provider on the remote host: :bmc_ssh_powerstatus: "true" :bmc_ssh_powercycle: "shutdown -r +1" :bmc_ssh_poweroff: "shutdown +1" :bmc_ssh_poweron: "false" No power on support is possible with this provider.
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="file.ext"> <body> <trans-unit id="1"> <source>This value is not a valid captcha.</source> <target>El valor del captcha no es válido.</target> </trans-unit> </body> </file> </xliff>
{ "pile_set_name": "Github" }
# BEGIN BPS TAGGED BLOCK {{{ # # COPYRIGHT: # # This software is Copyright (c) 1996-2020 Best Practical Solutions, LLC # <[email protected]> # # (Except where explicitly superseded by other copyright notices) # # # LICENSE: # # This work is made available to you under the terms of Version 2 of # the GNU General Public License. A copy of that license should have # been provided with this software, but in any event can be snarfed # from www.gnu.org. # # This work is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 or visit their web page on the internet at # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html. # # # CONTRIBUTION SUBMISSION POLICY: # # (The following paragraph is not intended to limit the rights granted # to you to modify and distribute this software under the terms of # the GNU General Public License and is only of importance to you if # you choose to contribute your changes and enhancements to the # community by submitting them to Best Practical Solutions, LLC.) # # By intentionally submitting any modifications, corrections or # derivatives to this work, or any other work intended for use with # Request Tracker, to Best Practical Solutions, LLC, you confirm that # you are the copyright holder for those contributions and you grant # Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable, # royalty-free, perpetual, license to use, copy, create derivative # works based on those contributions, and sublicense and distribute # those contributions and any derivatives thereof. # # END BPS TAGGED BLOCK }}} package RT::REST2::Resource::Articles; use strict; use warnings; use Moose; use namespace::autoclean; extends 'RT::REST2::Resource::Collection'; with 'RT::REST2::Resource::Collection::QueryByJSON'; sub dispatch_rules { Path::Dispatcher::Rule::Regex->new( regex => qr{^/articles/?$}, block => sub { { collection_class => 'RT::Articles' } }, ) } __PACKAGE__->meta->make_immutable; 1;
{ "pile_set_name": "Github" }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import com.adobe.test.Assert; var gTestfile = 'regress-178389.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 178389; var summary = 'Function.prototype.toSource should not override Function.prototype.toString'; var actual = ''; var expect = ''; //printBugNumber(BUGNUMBER); //printStatus (summary); function f() { var g = function (){}; } expect = f.toString(); Function.prototype.toSource = function () { return ''; }; actual = f.toString(); Assert.expectEq(summary, expect, actual);
{ "pile_set_name": "Github" }
================== HR Attendance RFID ================== .. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! This file is generated by oca-gen-addon-readme !! !! changes will be overwritten. !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! .. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png :target: https://odoo-community.org/page/development-status :alt: Beta .. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html :alt: License: AGPL-3 .. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fhr-lightgray.png?logo=github :target: https://github.com/OCA/hr/tree/12.0/hr_attendance_rfid :alt: OCA/hr .. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png :target: https://translation.odoo-community.org/projects/hr-12-0/hr-12-0-hr_attendance_rfid :alt: Translate me on Weblate .. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png :target: https://runbot.odoo-community.org/runbot/116/12.0 :alt: Try me on Runbot |badge1| |badge2| |badge3| |badge4| |badge5| This module extends the functionality of HR Attendance in order to allow the logging of employee attendances using an RFID based employee attendance system. **Table of contents** .. contents:: :local: Configuration ============= To use this module, you need to use an external system that calls the method 'register_attendance' of the model 'hr.employee' passing as parameter the code of the RFID card. Developers of a compatible RFID based employee attendance system should be familiar with the outputs of this method and implement proper calls and management of responses. It is advisory to create an exclusive user to perform this task. As user doesn't need several access, it is just essential to perform the check in/out, a group has been created. Add your attendance device user to RFID Attendance group. Usage ===== #. The HR employee responsible to set up new employees should go to 'Attendances -> Manage Attendances -> Employees' and register the RFID card code of each of your employees. You can use an USB plugged RFID reader connected to your computer for this purpose. #. The employee should put his/her card to the RFID based employee attendance system. It is expected that the system will provide some form of output of the registration event. Bug Tracker =========== Bugs are tracked on `GitHub Issues <https://github.com/OCA/hr/issues>`_. In case of trouble, please check there if your issue has already been reported. If you spotted it first, help us smashing it by providing a detailed and welcomed `feedback <https://github.com/OCA/hr/issues/new?body=module:%20hr_attendance_rfid%0Aversion:%2012.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_. Do not contact contributors directly about support or help with technical issues. Credits ======= Authors ~~~~~~~ * Comunitea * Eficent Contributors ~~~~~~~~~~~~ * Omar Catiñeira Saavedra <[email protected]> * Héctor Villarreal Ortega <[email protected]> * Jordi Ballester Alomar <[email protected]> Maintainers ~~~~~~~~~~~ This module is maintained by the OCA. .. image:: https://odoo-community.org/logo.png :alt: Odoo Community Association :target: https://odoo-community.org OCA, or the Odoo Community Association, is a nonprofit organization whose mission is to support the collaborative development of Odoo features and promote its widespread use. This module is part of the `OCA/hr <https://github.com/OCA/hr/tree/12.0/hr_attendance_rfid>`_ project on GitHub. You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
{ "pile_set_name": "Github" }
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace archive_ff1_dpk.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("FF1 DPK")] public string PluginName { get { return ((string)(this["PluginName"])); } } } }
{ "pile_set_name": "Github" }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package acmpca const ( // ErrCodeCertificateMismatchException for service response error code // "CertificateMismatchException". // // The certificate authority certificate you are importing does not comply with // conditions specified in the certificate that signed it. ErrCodeCertificateMismatchException = "CertificateMismatchException" // ErrCodeConcurrentModificationException for service response error code // "ConcurrentModificationException". // // A previous update to your private CA is still ongoing. ErrCodeConcurrentModificationException = "ConcurrentModificationException" // ErrCodeInvalidArgsException for service response error code // "InvalidArgsException". // // One or more of the specified arguments was not valid. ErrCodeInvalidArgsException = "InvalidArgsException" // ErrCodeInvalidArnException for service response error code // "InvalidArnException". // // The requested Amazon Resource Name (ARN) does not refer to an existing resource. ErrCodeInvalidArnException = "InvalidArnException" // ErrCodeInvalidNextTokenException for service response error code // "InvalidNextTokenException". // // The token specified in the NextToken argument is not valid. Use the token // returned from your previous call to ListCertificateAuthorities. ErrCodeInvalidNextTokenException = "InvalidNextTokenException" // ErrCodeInvalidPolicyException for service response error code // "InvalidPolicyException". // // The S3 bucket policy is not valid. The policy must give ACM Private CA rights // to read from and write to the bucket and find the bucket location. ErrCodeInvalidPolicyException = "InvalidPolicyException" // ErrCodeInvalidRequestException for service response error code // "InvalidRequestException". // // The request action cannot be performed or is prohibited. ErrCodeInvalidRequestException = "InvalidRequestException" // ErrCodeInvalidStateException for service response error code // "InvalidStateException". // // The private CA is in a state during which a report or certificate cannot // be generated. ErrCodeInvalidStateException = "InvalidStateException" // ErrCodeInvalidTagException for service response error code // "InvalidTagException". // // The tag associated with the CA is not valid. The invalid argument is contained // in the message field. ErrCodeInvalidTagException = "InvalidTagException" // ErrCodeLimitExceededException for service response error code // "LimitExceededException". // // An ACM Private CA limit has been exceeded. See the exception message returned // to determine the limit that was exceeded. ErrCodeLimitExceededException = "LimitExceededException" // ErrCodeMalformedCSRException for service response error code // "MalformedCSRException". // // The certificate signing request is invalid. ErrCodeMalformedCSRException = "MalformedCSRException" // ErrCodeMalformedCertificateException for service response error code // "MalformedCertificateException". // // One or more fields in the certificate are invalid. ErrCodeMalformedCertificateException = "MalformedCertificateException" // ErrCodePermissionAlreadyExistsException for service response error code // "PermissionAlreadyExistsException". // // The designated permission has already been given to the user. ErrCodePermissionAlreadyExistsException = "PermissionAlreadyExistsException" // ErrCodeRequestAlreadyProcessedException for service response error code // "RequestAlreadyProcessedException". // // Your request has already been completed. ErrCodeRequestAlreadyProcessedException = "RequestAlreadyProcessedException" // ErrCodeRequestFailedException for service response error code // "RequestFailedException". // // The request has failed for an unspecified reason. ErrCodeRequestFailedException = "RequestFailedException" // ErrCodeRequestInProgressException for service response error code // "RequestInProgressException". // // Your request is already in progress. ErrCodeRequestInProgressException = "RequestInProgressException" // ErrCodeResourceNotFoundException for service response error code // "ResourceNotFoundException". // // A resource such as a private CA, S3 bucket, certificate, or audit report // cannot be found. ErrCodeResourceNotFoundException = "ResourceNotFoundException" // ErrCodeTooManyTagsException for service response error code // "TooManyTagsException". // // You can associate up to 50 tags with a private CA. Exception information // is contained in the exception message field. ErrCodeTooManyTagsException = "TooManyTagsException" )
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1beta1 import ( v1beta1 "k8s.io/api/policy/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" ) // PodDisruptionBudgetsGetter has a method to return a PodDisruptionBudgetInterface. // A group's client should implement this interface. type PodDisruptionBudgetsGetter interface { PodDisruptionBudgets(namespace string) PodDisruptionBudgetInterface } // PodDisruptionBudgetInterface has methods to work with PodDisruptionBudget resources. type PodDisruptionBudgetInterface interface { Create(*v1beta1.PodDisruptionBudget) (*v1beta1.PodDisruptionBudget, error) Update(*v1beta1.PodDisruptionBudget) (*v1beta1.PodDisruptionBudget, error) UpdateStatus(*v1beta1.PodDisruptionBudget) (*v1beta1.PodDisruptionBudget, error) Delete(name string, options *v1.DeleteOptions) error DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error Get(name string, options v1.GetOptions) (*v1beta1.PodDisruptionBudget, error) List(opts v1.ListOptions) (*v1beta1.PodDisruptionBudgetList, error) Watch(opts v1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.PodDisruptionBudget, err error) PodDisruptionBudgetExpansion } // podDisruptionBudgets implements PodDisruptionBudgetInterface type podDisruptionBudgets struct { client rest.Interface ns string } // newPodDisruptionBudgets returns a PodDisruptionBudgets func newPodDisruptionBudgets(c *PolicyV1beta1Client, namespace string) *podDisruptionBudgets { return &podDisruptionBudgets{ client: c.RESTClient(), ns: namespace, } } // Get takes name of the podDisruptionBudget, and returns the corresponding podDisruptionBudget object, and an error if there is any. func (c *podDisruptionBudgets) Get(name string, options v1.GetOptions) (result *v1beta1.PodDisruptionBudget, err error) { result = &v1beta1.PodDisruptionBudget{} err = c.client.Get(). Namespace(c.ns). Resource("poddisruptionbudgets"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(). Into(result) return } // List takes label and field selectors, and returns the list of PodDisruptionBudgets that match those selectors. func (c *podDisruptionBudgets) List(opts v1.ListOptions) (result *v1beta1.PodDisruptionBudgetList, err error) { result = &v1beta1.PodDisruptionBudgetList{} err = c.client.Get(). Namespace(c.ns). Resource("poddisruptionbudgets"). VersionedParams(&opts, scheme.ParameterCodec). Do(). Into(result) return } // Watch returns a watch.Interface that watches the requested podDisruptionBudgets. func (c *podDisruptionBudgets) Watch(opts v1.ListOptions) (watch.Interface, error) { opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("poddisruptionbudgets"). VersionedParams(&opts, scheme.ParameterCodec). Watch() } // Create takes the representation of a podDisruptionBudget and creates it. Returns the server's representation of the podDisruptionBudget, and an error, if there is any. func (c *podDisruptionBudgets) Create(podDisruptionBudget *v1beta1.PodDisruptionBudget) (result *v1beta1.PodDisruptionBudget, err error) { result = &v1beta1.PodDisruptionBudget{} err = c.client.Post(). Namespace(c.ns). Resource("poddisruptionbudgets"). Body(podDisruptionBudget). Do(). Into(result) return } // Update takes the representation of a podDisruptionBudget and updates it. Returns the server's representation of the podDisruptionBudget, and an error, if there is any. func (c *podDisruptionBudgets) Update(podDisruptionBudget *v1beta1.PodDisruptionBudget) (result *v1beta1.PodDisruptionBudget, err error) { result = &v1beta1.PodDisruptionBudget{} err = c.client.Put(). Namespace(c.ns). Resource("poddisruptionbudgets"). Name(podDisruptionBudget.Name). Body(podDisruptionBudget). Do(). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *podDisruptionBudgets) UpdateStatus(podDisruptionBudget *v1beta1.PodDisruptionBudget) (result *v1beta1.PodDisruptionBudget, err error) { result = &v1beta1.PodDisruptionBudget{} err = c.client.Put(). Namespace(c.ns). Resource("poddisruptionbudgets"). Name(podDisruptionBudget.Name). SubResource("status"). Body(podDisruptionBudget). Do(). Into(result) return } // Delete takes name of the podDisruptionBudget and deletes it. Returns an error if one occurs. func (c *podDisruptionBudgets) Delete(name string, options *v1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("poddisruptionbudgets"). Name(name). Body(options). Do(). Error() } // DeleteCollection deletes a collection of objects. func (c *podDisruptionBudgets) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("poddisruptionbudgets"). VersionedParams(&listOptions, scheme.ParameterCodec). Body(options). Do(). Error() } // Patch applies the patch and returns the patched podDisruptionBudget. func (c *podDisruptionBudgets) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.PodDisruptionBudget, err error) { result = &v1beta1.PodDisruptionBudget{} err = c.client.Patch(pt). Namespace(c.ns). Resource("poddisruptionbudgets"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }
{ "pile_set_name": "Github" }
import { getFriendlyTitle } from '../title' import { VideoInfo, DanmakuInfo } from '../video-info' import { VideoDownloaderFragment } from './video-downloader-fragment' import { DownloadVideoPackage } from './download-video-package' import { BatchTitleParameter, BatchExtractor } from './batch-download' /** * ☢警告☢ ☢CAUTION☢ * 可读性/可维护性极差, 祖传代码/重复逻辑 * 谨 慎 阅 读 */ interface PageData { entity: Video aid: string cid: string } class Video { async getApiGenerator(dash = false) { function api(aid: number | string, cid: number | string, quality?: number) { if (dash) { if (quality) { return `https://api.bilibili.com/x/player/playurl?avid=${aid}&cid=${cid}&qn=${quality}&otype=json&fourk=1&fnver=0&fnval=16` } else { return `https://api.bilibili.com/x/player/playurl?avid=${aid}&cid=${cid}&otype=json&fourk=1&fnver=0&fnval=16` } } else { if (quality) { return `https://api.bilibili.com/x/player/playurl?avid=${aid}&cid=${cid}&qn=${quality}&otype=json` } else { return `https://api.bilibili.com/x/player/playurl?avid=${aid}&cid=${cid}&otype=json` } } } return api.bind(this) as typeof api } async getDashUrl(quality?: number) { return (await this.getApiGenerator(true))(pageData.aid, pageData.cid, quality) } async getUrl(quality?: number) { return (await this.getApiGenerator())(pageData.aid, pageData.cid, quality) } } class Bangumi extends Video { async getApiGenerator(dash = false) { function api(aid: number | string, cid: number | string, quality?: number) { if (dash) { if (quality) { return `https://api.bilibili.com/pgc/player/web/playurl?avid=${aid}&cid=${cid}&qn=${quality}&otype=json&fourk=1&fnval=16` } else { return `https://api.bilibili.com/pgc/player/web/playurl?avid=${aid}&cid=${cid}&otype=json&fourk=1&fnval=16` } } else { if (quality) { return `https://api.bilibili.com/pgc/player/web/playurl?avid=${aid}&cid=${cid}&qn=${quality}&otype=json` } else { return `https://api.bilibili.com/pgc/player/web/playurl?avid=${aid}&cid=${cid}&qn=&otype=json` } } } return api.bind(this) as typeof api } } // 课程, 不知道为什么b站给它起名cheese, 芝士就是力量? class Cheese extends Video { constructor(public ep: number | string) { super() } async getApiGenerator(dash = false) { function api(aid: number | string, cid: number | string, quality?: number) { if (dash) { if (quality) { return `https://api.bilibili.com/pugv/player/web/playurl?avid=${aid}&cid=${cid}&qn=${quality}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16` } else { return `https://api.bilibili.com/pugv/player/web/playurl?avid=${aid}&cid=${cid}&otype=json&ep_id=${this.ep}&fnver=0&fnval=16` } } else { if (quality) { return `https://api.bilibili.com/pugv/player/web/playurl?avid=${aid}&cid=${cid}&qn=${quality}&otype=json&ep_id=${this.ep}` } else { return `https://api.bilibili.com/pugv/player/web/playurl?avid=${aid}&cid=${cid}&otype=json&ep_id=${this.ep}` } } } return api.bind(this) as typeof api } } const pageData: PageData = { entity: new Video(), aid: '', cid: '' } let formats: VideoFormat[] = [] let selectedFormat: VideoFormat | null = null // let userInfo: { // isLogin: boolean // vipStatus: number // } | null = null class VideoFormat { quality: number internalName: string displayName: string constructor(quality: number, internalName: string, displayName: string) { this.quality = quality this.internalName = internalName this.displayName = displayName } async downloadInfo(dash = false) { const videoInfo = new VideoDownloader(this) await videoInfo.fetchVideoInfo(dash) return videoInfo } static parseFormats(data: any): VideoFormat[] { const qualities = data.accept_quality const internalNames = data.accept_format.split(',') const displayNames = data.accept_description const formats = qualities.map((q: number, index: number) => { return new VideoFormat( q, internalNames[index], displayNames[index] ) }) // while (qualities.length > 0) { // const format = new VideoFormat( // qualities.pop(), // internalNames.pop(), // displayNames.pop() // ) // formats.push(format) // } return formats } static async filterFormats(formats: VideoFormat[]) { return formats // if (userInfo === null) { // userInfo = (await Ajax.getJsonWithCredentials('https://api.bilibili.com/x/web-interface/nav')).data // } // _.remove(formats, f => { // const q = f.quality // if (userInfo!.isLogin === false) { // return q >= 64 // } // if (userInfo!.vipStatus !== 1) { // return q === 116 || q === 112 || q === 74 // } // return false // }) // return formats } static async getAvailableDashFormats(): Promise<VideoFormat[]> { const url = await pageData.entity.getDashUrl() const json = await Ajax.getJsonWithCredentials(url) if (json.code !== 0) { throw new Error('获取清晰度信息失败.') } const data = json.data || json.result || json return await VideoFormat.filterFormats(VideoFormat.parseFormats(data)) } static async getAvailableFormats(): Promise<VideoFormat[]> { const { BannedResponse, throwBannedError } = await import('./batch-warning') try { const url = await pageData.entity.getUrl() const json = await Ajax.getJsonWithCredentials(url) if (json.code !== 0) { throw new Error('获取清晰度信息失败.') } const data = json.data || json.result || json return await VideoFormat.filterFormats(VideoFormat.parseFormats(data)) } catch (error) { if ((error as Error).message.includes(BannedResponse.toString())) { throwBannedError() } throw error } } } const allFormats: VideoFormat[] = [ new VideoFormat(120, '4K', '超清 4K'), new VideoFormat(116, '1080P60', '高清 1080P60'), new VideoFormat(112, '1080P+', '高清 1080P+'), new VideoFormat(80, '1080P', '高清 1080P'), new VideoFormat(74, '720P60', '高清 720P60'), new VideoFormat(64, '720P', '高清 720P'), new VideoFormat(32, '480P', '清晰 480P'), new VideoFormat(16, '360P', '流畅 360P'), ] class VideoDownloader { format: VideoFormat subtitle = false fragments: VideoDownloaderFragment[] fragmentSplitFactor = 6 * 2 workingXhr: XMLHttpRequest[] | null = null progress: (progress: number) => void progressMap: Map<XMLHttpRequest, number> = new Map() videoSpeed: VideoSpeed constructor(format: VideoFormat, fragments?: VideoDownloaderFragment[]) { this.format = format this.fragments = fragments || [] this.videoSpeed = new VideoSpeed(this) } get danmakuOption() { return settings.downloadVideoDefaultDanmaku } get subtitleOption() { return settings.downloadVideoDefaultSubtitle } get isDash() { return this.fragments.some(it => it.url.includes('.m4s')) } get totalSize() { return this.fragments.map(it => it.size).reduce((acc, it) => acc + it) } async fetchVideoInfo(dash = false): Promise<VideoDownloaderFragment[]> { if (!dash) { const url = await pageData.entity.getUrl(this.format.quality) const text = await Ajax.getTextWithCredentials(url) const json = JSON.parse(text.replace(/http:/g, 'https:')) const data = json.data || json.result || json const q = this.format.quality if (data.quality !== q) { const { throwQualityError } = await import('./quality-errors') throwQualityError(q) } const urls = data.durl this.fragments = urls.map((it: any) => { return { length: it.length, size: it.size, url: it.url, backupUrls: it.backup_url } as VideoDownloaderFragment }) } else { const { dashToFragments, getDashInfo } = await import('./video-dash') const dashes = await getDashInfo( await pageData.entity.getDashUrl(this.format.quality), this.format.quality ) this.fragments = dashToFragments(dashes) } return this.fragments } updateProgress() { const progress = this.progressMap ? [...this.progressMap.values()].reduce((a, b) => a + b, 0) / this.totalSize : 0 if (progress > 1 || progress < 0) { console.error(`[下载视频] 进度异常: ${progress}`, this.progressMap.values()) } this.progress && this.progress(progress) } cancelDownload() { this.videoSpeed.stopMeasure() if (this.workingXhr !== null) { this.workingXhr.forEach(it => it.abort()) } else { logError('Cancel Download Failed: forEach in this.workingXhr not found.') } } downloadFragment(fragment: VideoDownloaderFragment) { const promises: Promise<ArrayBuffer>[] = [] /** * 按一定大小分段或许对大视频更好 * * DASH: * - 小于等于24MB时, 均分为12段 (`this.fragmentSplitFactor = 12`) * - 大于24MB时, 每4MB为一段 * * FLV: * - 小于等于96MB时, 均分为12段 * - 大于96MB时, 每16MB为一段 */ const minimalLength = this.isDash ? 4 * 1024 * 1024 : 16 * 1024 * 1024 let partialLength: number if (fragment.size <= minimalLength * 6) { partialLength = fragment.size / this.fragmentSplitFactor } else { partialLength = minimalLength } let startByte = 0 const getPartNumber = (xhr: XMLHttpRequest) => [...this.progressMap.keys()].indexOf(xhr) + 1 while (startByte < fragment.size) { const endByte = Math.min(fragment.size - 1, Math.round(startByte + partialLength)) const range = `bytes=${startByte}-${endByte}` const rangeLength = endByte - startByte + 1 promises.push(new Promise((resolve, reject) => { const xhr = new XMLHttpRequest() xhr.open('GET', fragment.url) xhr.responseType = 'arraybuffer' xhr.withCredentials = false xhr.addEventListener('progress', (e) => { console.log(`[下载视频] 视频片段${getPartNumber(xhr)}下载进度: ${e.loaded}/${rangeLength} bytes loaded, ${range}`) this.progressMap.set(xhr, e.loaded) this.updateProgress() }) xhr.addEventListener('load', () => { if (('' + xhr.status)[0] === '2') { console.log(`[下载视频] 视频片段${getPartNumber(xhr)}下载完成`) resolve(xhr.response) } else { reject(`视频片段${getPartNumber(xhr)}请求失败, response = ${xhr.status}`) } }) xhr.addEventListener('abort', () => reject('canceled')) xhr.addEventListener('error', () => { console.error(`[下载视频] 视频片段${getPartNumber(xhr)}下载失败: ${range}`) this.progressMap.set(xhr, 0) this.updateProgress() xhr.open('GET', fragment.url) xhr.setRequestHeader('Range', range) xhr.send() }) xhr.setRequestHeader('Range', range) this.progressMap.set(xhr, 0) xhr.send() this.workingXhr!.push(xhr) })) startByte = Math.round(startByte + partialLength) + 1 } return Promise.all(promises) } async copyUrl() { const urls = this.fragments.map(it => it.url).reduce((acc, it) => acc + '\r\n' + it) GM.setClipboard(urls, 'text') } async showUrl() { const message = this.fragments.map(it => /*html*/` <a class="download-link" href="${it.url}">${it.url}</a> `).reduce((acc, it) => acc + '\r\n' + it) Toast.success(message + /*html*/`<a class="link" id="copy-link" style="cursor: pointer;margin: 8px 0 0 0;">复制全部</a>`, '显示链接') const copyLinkButton = await SpinQuery.select('#copy-link') as HTMLElement copyLinkButton.addEventListener('click', async () => { await this.copyUrl() }) } async exportIdm() { const { toIdmFormat } = await import('./idm-support') const idm = toIdmFormat([this]) const danmaku = await this.downloadDanmaku() const subtitle = await this.downloadSubtitle() const pack = new DownloadVideoPackage() pack.add( `${getFriendlyTitle()}.${this.danmakuOption === 'ASS' ? 'ass' : 'xml'}`, danmaku ) pack.add( `${getFriendlyTitle()}.${this.subtitleOption === 'ASS' ? 'ass' : 'json'}`, subtitle ) pack.add( `${getFriendlyTitle()}.ef2`, idm ) await pack.emit(`${getFriendlyTitle()}.zip`) } async exportData(copy = false) { const data = JSON.stringify([{ fragments: this.fragments, title: getFriendlyTitle(), totalSize: this.fragments.map(it => it.size).reduce((acc, it) => acc + it), referer: document.URL.replace(window.location.search, '') }]) if (copy) { GM.setClipboard(data, 'text') } else { const blob = new Blob([data], { type: 'text/json' }) const danmaku = await this.downloadDanmaku() const pack = new DownloadVideoPackage() pack.add(`${getFriendlyTitle()}.json`, blob) pack.add(getFriendlyTitle() + '.' + this.danmakuOption.toLowerCase(), danmaku) await pack.emit(`${getFriendlyTitle()}.zip`) } } async exportAria2(rpc = false) { const { getNumber } = await import('./get-number') if (rpc) { // https://aria2.github.io/manual/en/html/aria2c.html#json-rpc-using-http-get const danmaku = await this.downloadDanmaku() const subtitle = await this.downloadSubtitle() const pack = new DownloadVideoPackage() pack.add( `${getFriendlyTitle()}.${this.danmakuOption === 'ASS' ? 'ass' : 'xml'}`, danmaku ) pack.add( `${getFriendlyTitle()}.${this.subtitleOption === 'ASS' ? 'ass' : 'json'}`, subtitle ) await pack.emit() const option = settings.aria2RpcOption const params = this.fragments.map((fragment, index) => { let indexNumber = '' if (this.fragments.length > 1 && !this.isDash) { indexNumber = ' - ' + getNumber(index + 1, this.fragments.length) } const params = [] if (option.secretKey !== '') { params.push(`token:${option.secretKey}`) } params.push([fragment.url]) params.push({ referer: document.URL.replace(window.location.search, ''), 'user-agent': UserAgent, out: `${getFriendlyTitle()}${indexNumber}${this.extension(fragment)}`, split: this.fragmentSplitFactor, dir: (option.baseDir + option.dir) || undefined, 'max-download-limit': option.maxDownloadLimit || undefined, }) const id = encodeURIComponent(`${getFriendlyTitle()}${indexNumber}`) return { params, id, } }) const { sendRpc } = await import('./aria2-rpc') await sendRpc(params) } else { // https://aria2.github.io/manual/en/html/aria2c.html#input-file const input = ` # Generated by Bilibili Evolved Video Export # https://github.com/the1812/Bilibili-Evolved/ ${this.fragments.map((it, index) => { let indexNumber = '' if (this.fragments.length > 1 && !this.isDash) { indexNumber = ' - ' + getNumber(index + 1, this.fragments.length) } return ` ${it.url} referer=${document.URL.replace(window.location.search, '')} user-agent=${UserAgent} out=${getFriendlyTitle()}${indexNumber}${this.extension(it)} split=${this.fragmentSplitFactor} `.trim() }).join('\n')} `.trim() const blob = new Blob([input], { type: 'text/plain' }) const danmaku = await this.downloadDanmaku() const subtitle = await this.downloadSubtitle() const pack = new DownloadVideoPackage() pack.add(`${getFriendlyTitle()}.txt`, blob) pack.add(getFriendlyTitle() + '.' + this.danmakuOption.toLowerCase(), danmaku) pack.add(getFriendlyTitle() + '.' + this.subtitleOption.toLowerCase(), subtitle) await pack.emit(`${getFriendlyTitle()}.zip`) } } extension(fragment?: VideoDownloaderFragment) { const f = (fragment || this.fragments[0]) const match = [ '.flv', '.mp4', ].find(it => f.url.includes(it)) if (match) { return match } else if (f.url.includes('.m4s')) { return this.fragments.indexOf(f) === 0 ? '.mp4' : '.m4a' } else { console.warn('No extension detected.') return '.flv' } } async downloadDanmaku() { if (this.danmakuOption !== '无') { const danmakuInfo = new DanmakuInfo(pageData.cid) await danmakuInfo.fetchInfo() if (this.danmakuOption === 'XML') { return danmakuInfo.rawXML } else { const { convertToAss } = await import('../download-danmaku') return convertToAss(danmakuInfo.rawXML) } } else { return null } } async downloadSubtitle() { if (this.subtitle && this.subtitleOption !== '无') { const { getSubtitleConfig, getSubtitleList } = await import('../download-subtitle/download-subtitle') const [config, language] = await getSubtitleConfig() const subtitles = await getSubtitleList(pageData.aid, pageData.cid) const subtitle = subtitles.find(s => s.language === language) || subtitles[0] const json = await Ajax.getJson(subtitle.url) const rawData = json.body if (this.subtitleOption === 'JSON') { return rawData } else { const { SubtitleConverter } = await import('../download-subtitle/subtitle-converter') const converter = new SubtitleConverter(config) const ass = await converter.convertToAss(rawData) return ass } } return null } async download() { this.workingXhr = [] this.progressMap = new Map() this.updateProgress() const downloadedData: ArrayBuffer[][] = [] this.videoSpeed.startMeasure() for (const fragment of this.fragments) { const data = await this.downloadFragment(fragment) downloadedData.push(data) } if (downloadedData.length < 1) { throw new Error('下载失败.') } const title = getFriendlyTitle() const pack = new DownloadVideoPackage() const { getNumber } = await import('./get-number') downloadedData.forEach((data, index) => { let filename: string const fragment = this.fragments[index] if (downloadedData.length > 1 && !this.isDash) { filename = `${title} - ${getNumber(index + 1, downloadedData.length)}${this.extension(fragment)}` } else { filename = `${title}${this.extension(fragment)}` } pack.add(filename, new Blob(Array.isArray(data) ? data : [data])) }) const danmaku = await this.downloadDanmaku() pack.add( `${getFriendlyTitle()}.${this.danmakuOption === 'ASS' ? 'ass' : 'xml'}`, danmaku ) const subtitle = await this.downloadSubtitle() pack.add( `${getFriendlyTitle()}.${this.subtitleOption === 'ASS' ? 'ass' : 'json'}`, subtitle ) await pack.emit(title + '.zip') this.progress && this.progress(0) this.videoSpeed.stopMeasure() } } class VideoSpeed { workingDownloader: VideoDownloader lastProgress = 0 measureInterval = 1000 intervalTimer: number speedUpdate: (speed: string) => void constructor(downloader: VideoDownloader) { this.workingDownloader = downloader } startMeasure() { this.intervalTimer = setInterval(() => { const progress = this.workingDownloader.progressMap ? [...this.workingDownloader.progressMap.values()].reduce((a, b) => a + b, 0) : 0 const loadedBytes = progress - this.lastProgress if (this.speedUpdate !== undefined) { this.speedUpdate(formatFileSize(loadedBytes) + '/s') } this.lastProgress = progress }, this.measureInterval) } stopMeasure() { clearInterval(this.intervalTimer) } } async function loadPageData() { const aid = await SpinQuery.select(() => (unsafeWindow || window).aid) const cid = await SpinQuery.select(() => (unsafeWindow || window).cid) if (!(aid && cid)) { return false } pageData.aid = aid pageData.cid = cid if (document.URL.includes('bangumi')) { pageData.entity = new Bangumi() } else if (document.URL.includes('cheese')) { const match = document.URL.match(/cheese\/play\/ep([\d]+)/)! pageData.entity = new Cheese(match[1]) } else { pageData.entity = new Video() } try { formats = await VideoFormat.getAvailableFormats() } catch (error) { return false } return true } const getDefaultFormat = (formats: VideoFormat[]) => { const defaultQuality = settings.downloadVideoQuality const format = formats.find(f => f.quality === defaultQuality) if (format) { return format } const nextFormat = formats.filter(f => f.quality < defaultQuality).shift() if (nextFormat) { return nextFormat } return formats.shift()!! } async function loadWidget() { selectedFormat = getDefaultFormat(formats) resources.applyStyle('downloadVideoStyle') const button = dq('#download-video') as HTMLElement button.addEventListener('click', () => { const panel = dq('.download-video') as HTMLElement panel.classList.toggle('opened') window.scroll(0, 0); (dq('.gui-settings-mask') as HTMLDivElement).click() }) // document.body.insertAdjacentHTML('beforeend', resources.import('downloadVideoHtml')) // loadPanel() button.addEventListener('mouseover', () => { // document.body.insertAdjacentHTML('beforeend', resources.import('downloadVideoHtml')) loadPanel() }, { once: true }) } async function loadPanel() { // const start = performance.now() let workingDownloader: VideoDownloader // const sizeCache = new Map<VideoFormat, number>() type ExportType = 'copyLink' | 'showLink' | 'aria2' | 'aria2RPC' | 'copyVLD' | 'exportVLD' | 'ffmpegEpisodes' | 'ffmpegFragments' | 'idm' interface EpisodeItem { title: string titleParameters?: BatchTitleParameter checked: boolean index: number cid: string aid: string } const panelTabs = [ { name: 'single', displayName: '单个视频', }, { name: 'batch', displayName: '批量导出', }, { name: 'manual', displayName: '手动输入', }, ] const panel = new Vue({ // el: '.download-video', template: resources.import('downloadVideoHtml'), components: { VDropdown: () => import('./v-dropdown.vue'), VCheckbox: () => import('./v-checkbox.vue'), RpcProfiles: () => import('./aria2-rpc-profiles.vue'), }, data: { /** 当前页面是否支持批量导出 */ batch: false, /** 当前页面是否含有CC字幕 */ subtitle: false, selectedTab: panelTabs[0], coverUrl: EmptyImageUrl, aid: pageData.aid, cid: pageData.cid, dashModel: { value: settings.downloadVideoFormat, items: ['flv', 'dash'], }, qualityModel: { value: selectedFormat!.displayName, items: formats.map(f => f.displayName) }, manualQualityModel: { value: allFormats[1].displayName, items: allFormats.map(f => f.displayName), }, danmakuModel: { value: settings.downloadVideoDefaultDanmaku as DanmakuOption, items: ['无', 'XML', 'ASS'] as DanmakuOption[] }, subtitleModel: { value: settings.downloadVideoDefaultSubtitle as SubtitleOption, items: ['无', 'JSON', 'ASS'] as SubtitleOption[] }, codecModel: { value: settings.downloadVideoDashCodec, items: ['AVC/H.264', 'HEVC/H.265'] }, // ffmpegModel: { // value: settings.downloadVideoFfmpegSupport, // items: ['无', '文件列表'] // // items: ['无', '文件列表', '文件列表+脚本'] // }, progressPercent: 0, size: '获取大小中' as number | string, blobUrl: '', lastCheckedEpisodeIndex: -1, episodeList: [] as EpisodeItem[], downloading: false, speed: '', rpcSettings: settings.aria2RpcOption, showRpcSettings: false, busy: false, saveRpcSettingsText: '保存配置', enableDash: settings.enableDashDownload, lastDirectDownloadLink: '', manualInputText: '', }, computed: { tabs() { if (this.batch) { return panelTabs } const clone = [...panelTabs] _.remove(clone, it => it.name === 'batch') return clone }, manualInputItems() { const itemTexts: string[] = (this.manualInputText as string).split(/\s/g) const items = itemTexts.map(it => it.match(/av(\d+)/i) || it.match(/^(\d+)$/)) return _.uniq(items.filter(it => it !== null).map(it => it![1])) }, downloadSingle() { return this.selectedTab.name === 'single' }, displaySize() { if (typeof this.size === 'string') { return this.size } return formatFileSize(this.size) }, sizeWarning() { if (typeof this.size === 'string') { return false } return this.size > 1073741824 // 1GB }, selectedEpisodeCount() { return (this.episodeList as EpisodeItem[]).filter(item => item.checked).length }, dash() { return this.dashModel.value === 'dash' }, }, methods: { close() { this.$el.classList.remove('opened') }, danmakuOptionChange() { settings.downloadVideoDefaultDanmaku = this.danmakuModel.value }, subtitleOptionChange() { settings.downloadVideoDefaultSubtitle = this.subtitleModel.value }, // ffmpegChange() { // settings.downloadVideoFfmpegSupport = this.ffmpegModel.value // }, async codecChange() { settings.downloadVideoDashCodec = this.codecModel.value await this.formatChange() }, async dashChange() { // console.log('dash change') const format = settings.downloadVideoFormat = this.dashModel.value as typeof settings.downloadVideoFormat let updatedFormats = [] if (format === 'flv') { updatedFormats = await VideoFormat.getAvailableFormats() } else { updatedFormats = await VideoFormat.getAvailableDashFormats() } formats = updatedFormats selectedFormat = getDefaultFormat(formats) this.qualityModel.items = updatedFormats.map(f => f.displayName) this.qualityModel.value = this.qualityModel.items[formats.indexOf(selectedFormat)] await this.formatChange() }, // userSelect 用于区分用户操作和自动更新, 只有用户操作才应更新默认选择的画质 async formatChange(userSelect = false) { // console.log('format change') const format = this.getFormat() as VideoFormat if (userSelect) { settings.downloadVideoQuality = format.quality } try { this.size = '获取大小中' const videoDownloader = await format.downloadInfo(this.dash) this.size = videoDownloader.totalSize // sizeCache.set(format, this.size) } catch (error) { this.size = '获取大小失败' throw error } }, getManualFormat() { let format: VideoFormat | undefined format = allFormats.find(f => f.displayName === this.manualQualityModel.value) if (!format) { console.error(`No format found. model value = ${this.manualQualityModel.value}`) return null } return format }, getFormat() { let format: VideoFormat | undefined format = formats.find(f => f.displayName === this.qualityModel.value) if (!format) { console.error(`No format found. model value = ${this.qualityModel.value}`) return null } return format }, async exportData(type: ExportType) { if (this.busy === true) { return } try { this.busy = true if (this.selectedTab.name === 'batch') { await this.exportBatchData(type) return } if (this.selectedTab.name === 'manual') { await this.exportManualData(type) return } const format = this.getFormat() as VideoFormat const videoDownloader = await format.downloadInfo(this.dash) videoDownloader.subtitle = this.subtitle switch (type) { case 'copyLink': await videoDownloader.copyUrl() Toast.success('已复制链接到剪贴板.', '下载视频', 3000) break case 'showLink': await videoDownloader.showUrl() break case 'aria2': await videoDownloader.exportAria2(false) break case 'aria2RPC': await videoDownloader.exportAria2(true) break case 'copyVLD': await videoDownloader.exportData(true) Toast.success('已复制VLD数据到剪贴板.', '下载视频', 3000) break case 'exportVLD': await videoDownloader.exportData(false) break case 'ffmpegFragments': if (videoDownloader.fragments.length < 2) { Toast.info('当前视频没有分段.', '分段合并', 3000) } else { const { getFragmentsList } = await import('./ffmpeg-support') // const { getFragmentsMergeScript } = await import('./ffmpeg-support') const pack = new DownloadVideoPackage() pack.add('ffmpeg-files.txt', getFragmentsList(videoDownloader.fragments.length, getFriendlyTitle(), videoDownloader.fragments.map(f => videoDownloader.extension(f)))) // const isWindows = window.navigator.appVersion.includes('Win') // const extension = isWindows ? 'bat' : 'sh' // const script = getFragmentsMergeScript({ // fragments: videoDownloader.fragments, // title: getFriendlyTitle(), // totalSize: videoDownloader.totalSize, // cid: pageData.cid, // referer: document.URL.replace(window.location.search, ''), // }, this.dash || videoDownloader.extension()) // if (isWindows) { // const { GBK } = await import('./gbk') // const data = new Blob([new Uint8Array(GBK.encode(script))]) // pack.add(`${getFriendlyTitle()}.${extension}`, data) // } else { // pack.add(`${getFriendlyTitle()}.${extension}`, script) // } await pack.emit() } break case 'idm': await videoDownloader.exportIdm() break default: break } } catch (error) { logError(error) } finally { this.busy = false } }, async exportBatchData(type: ExportType) { const episodeList = this.episodeList as EpisodeItem[] const { MaxBatchSize, showBatchWarning } = await import('./batch-warning') if (episodeList.every(item => !item.checked)) { Toast.info('请至少选择1集或以上的数量!', '批量导出', 3000) return } if (episodeList.filter(item => item.checked).length > MaxBatchSize) { showBatchWarning('批量导出') return } const episodeFilter = (item: EpisodeItem) => { const match = episodeList.find((it: EpisodeItem) => it.cid === item.cid) as EpisodeItem | undefined if (match === undefined) { return false } return match.checked } const batchExtractor = this.batchExtractor as BatchExtractor const format: VideoFormat = this.getFormat() if (this.danmakuModel.value !== '无') { const danmakuToast = Toast.info('下载弹幕中...', '批量导出') const pack = new DownloadVideoPackage() try { if (this.danmakuModel.value === 'XML') { for (const item of episodeList.filter(episodeFilter)) { const danmakuInfo = new DanmakuInfo(item.cid) await danmakuInfo.fetchInfo() pack.add(batchExtractor.formatTitle(item.titleParameters) + '.xml', danmakuInfo.rawXML) } } else { const { convertToAss } = await import('../download-danmaku') for (const item of episodeList.filter(episodeFilter)) { const danmakuInfo = new DanmakuInfo(item.cid) await danmakuInfo.fetchInfo() pack.add(batchExtractor.formatTitle(item.titleParameters) + '.ass', await convertToAss(danmakuInfo.rawXML)) } } await pack.emit(this.cid + '.danmakus.zip') } catch (error) { logError(`弹幕下载失败`) throw error } finally { danmakuToast.dismiss() } } if (this.subtitleModel.value !== '无') { const subtitleToast = Toast.info('下载字幕中...', '批量导出') const pack = new DownloadVideoPackage() try { const { getSubtitleConfig, getSubtitleList } = await import('../download-subtitle/download-subtitle') const [config, language] = await getSubtitleConfig() for (const item of episodeList.filter(episodeFilter)) { const subtitles = await getSubtitleList(item.aid, item.cid) const subtitle = subtitles.find(s => s.language === language) || subtitles[0] if (subtitle === undefined) { continue } const json = await Ajax.getJson(subtitle.url) const rawData = json.body if (this.subtitleModel.value === 'JSON') { pack.add(batchExtractor.formatTitle(item.titleParameters) + '.json', rawData) } else { const { SubtitleConverter } = await import('../download-subtitle/subtitle-converter') const converter = new SubtitleConverter(config) const ass = await converter.convertToAss(rawData) pack.add(batchExtractor.formatTitle(item.titleParameters) + '.ass', ass) } } await pack.emit(this.cid + '.subtitles.zip') } catch (error) { logError(`字幕下载失败`) throw error } finally { subtitleToast.dismiss() } } const toast = Toast.info('获取链接中...', '批量导出') batchExtractor.config.itemFilter = episodeFilter batchExtractor.config.api = await pageData.entity.getApiGenerator(this.dash) let result: string try { switch (type) { case 'idm': const items = await batchExtractor.getRawItems(format) const { toIdmFormat } = await import('./idm-support') result = toIdmFormat(items) await DownloadVideoPackage.single( getFriendlyTitle(false) + '.ef2', new Blob([result], { type: 'text/plain' }), ) return case 'aria2': result = await batchExtractor.collectAria2(format, toast, false) await DownloadVideoPackage.single( getFriendlyTitle(false) + '.txt', new Blob([result], { type: 'text/plain' }), { ffmpeg: this.ffmpegOption } ) return case 'aria2RPC': await batchExtractor.collectAria2(format, toast, true) Toast.success(`成功发送了批量请求.`, 'aria2 RPC', 3000) return case 'copyVLD': GM.setClipboard(await batchExtractor.collectData(format, toast), { mimetype: 'text/plain' }) Toast.success('已复制批量vld数据到剪贴板.', '批量导出', 3000) return case 'exportVLD': result = await batchExtractor.collectData(format, toast) await DownloadVideoPackage.single( getFriendlyTitle(false) + '.json', new Blob([result], { type: 'text/json' }), { ffmpeg: this.ffmpegOption } ) return case 'ffmpegFragments': { const items = await batchExtractor.getRawItems(format) if (items.every(it => it.fragments.length < 2)) { Toast.info('所有选择的分P都没有分段.', '分段列表', 3000) return } const videoDownloader = new VideoDownloader(format, items[0].fragments) const { getBatchFragmentsList } = await import('./ffmpeg-support') // const pack = new DownloadVideoPackage() // const isWindows = window.navigator.appVersion.includes('Win') // const extension = isWindows ? 'bat' : 'sh' // const script = getBatchMergeScript(items, videoDownloader.extension()) // if (isWindows) { // const { GBK } = await import('./gbk') // const data = new Blob([new Uint8Array(GBK.encode(script))]) // pack.add(`${getFriendlyTitle()}.${extension}`, data) // } else { // pack.add(`${getFriendlyTitle()}.${extension}`, script) // } // await pack.emit() const map = getBatchFragmentsList(items, this.dash || videoDownloader.extension()) if (!map) { Toast.info('所有选择的分P都没有分段.', '分段列表', 3000) return } const pack = new DownloadVideoPackage() for (const [filename, content] of map.entries()) { pack.add(filename, content) } await pack.emit(escapeFilename(`${getFriendlyTitle(false)}.zip`)) // } } break case 'ffmpegEpisodes': { const items = await batchExtractor.getRawItems(format) const videoDownloader = new VideoDownloader(format, items[0].fragments) const { getBatchEpisodesList } = await import('./ffmpeg-support') const content = getBatchEpisodesList(items, this.dash || videoDownloader.extension()) const pack = new DownloadVideoPackage() pack.add('ffmpeg-files.txt', content) await pack.emit() } break default: return } } catch (error) { logError(error) } finally { toast.dismiss() } }, async exportManualData(type: ExportType) { const { MaxBatchSize, showBatchWarning } = await import('./batch-warning') if (this.manualInputItems.length === 0) { Toast.info('请至少输入一个有效的视频链接!', '手动输入', 3000) return } if (this.manualInputItems.length > MaxBatchSize) { showBatchWarning('手动输入') return } const { ManualInputBatch } = await import('./batch-download') const batch = new ManualInputBatch({ api: await (new Video().getApiGenerator(this.dash)), itemFilter: () => true, }) batch.items = this.manualInputItems if (this.danmakuModel.value !== '无') { const danmakuToast = Toast.info('下载弹幕中...', '手动输入') const pack = new DownloadVideoPackage() try { if (this.danmakuModel.value === 'XML') { for (const item of (await batch.getItemList())) { const danmakuInfo = new DanmakuInfo(item.cid) await danmakuInfo.fetchInfo() pack.add(ManualInputBatch.formatTitle(item.titleParameters) + '.xml', danmakuInfo.rawXML) } } else { const { convertToAss } = await import('../download-danmaku') for (const item of (await batch.getItemList())) { const danmakuInfo = new DanmakuInfo(item.cid) await danmakuInfo.fetchInfo() pack.add(ManualInputBatch.formatTitle(item.titleParameters) + '.ass', await convertToAss(danmakuInfo.rawXML)) } } await pack.emit('manual-exports.danmakus.zip') } catch (error) { logError(`弹幕下载失败`) throw error } finally { danmakuToast.dismiss() } } if (this.subtitleModel.value !== '无') { const subtitleToast = Toast.info('下载字幕中...', '批量导出') const pack = new DownloadVideoPackage() try { const { getSubtitleConfig, getSubtitleList } = await import('../download-subtitle/download-subtitle') const [config, language] = await getSubtitleConfig() for (const item of (await batch.getItemList())) { const subtitles = await getSubtitleList(item.aid, item.cid) const subtitle = subtitles.find(s => s.language === language) || subtitles[0] const json = await Ajax.getJson(subtitle.url) const rawData = json.body if (this.subtitleModel.value === 'JSON') { pack.add(ManualInputBatch.formatTitle(item.titleParameters) + '.json', rawData) } else { const { SubtitleConverter } = await import('../download-subtitle/subtitle-converter') const converter = new SubtitleConverter(config) const ass = await converter.convertToAss(rawData) pack.add(ManualInputBatch.formatTitle(item.titleParameters) + '.ass', ass) } } await pack.emit('manual-exports.subtitles.zip') } catch (error) { logError(`字幕下载失败`) throw error } finally { subtitleToast.dismiss() } } const toast = Toast.info('获取链接中...', '手动输入') try { switch (type) { default: case 'aria2': { const result = await batch.collectAria2(this.getManualFormat().quality, false) as string await DownloadVideoPackage.single( 'manual-exports.txt', new Blob([result], { type: 'text/plain' }), { ffmpeg: this.ffmpegOption } ) break } case 'aria2RPC': { await batch.collectAria2(this.getManualFormat().quality, true) Toast.success(`成功发送了批量请求.`, 'aria2 RPC', 3000) break } case 'idm': { const items = await batch.getRawItems(this.getManualFormat().quality) const { toIdmFormat } = await import('./idm-support') const result = toIdmFormat(items) await DownloadVideoPackage.single( 'manual-exports.ef2', new Blob([result], { type: 'text/plain' }), ) break } } } catch (error) { logError(error) } finally { toast.dismiss() } }, async checkBatch() { const urls = [ '//www.bilibili.com/bangumi', '//www.bilibili.com/video', '//www.bilibili.com/blackboard/bnj2020.html' ] if (!urls.some(url => document.URL.includes(url))) { this.batch = false this.episodeList = [] return } const { BatchExtractor } = await import('batch-download') const { MaxBatchSize } = await import('./batch-warning') if (await BatchExtractor.test() !== true) { this.batch = false this.episodeList = [] return } const batchExtractor = this.batchExtractor = new BatchExtractor() this.batch = true this.episodeList = (await batchExtractor.getItemList()).map((item, index) => { return { aid: item.aid, cid: item.cid, title: item.title, titleParameters: item.titleParameters, index, checked: index < MaxBatchSize, } as EpisodeItem }) }, async checkSubtitle() { const { getSubtitleList } = await import('../download-subtitle/download-subtitle') const subtitles = await getSubtitleList(pageData.aid, pageData.cid) this.subtitle = subtitles.length > 0 }, cancelDownload() { if (workingDownloader) { workingDownloader.cancelDownload() } }, async startDownload() { const format = this.getFormat() as VideoFormat if (format.quality === 120) { Toast.info('4K视频不支持直接下载, 请使用下方的导出选项.', '下载视频', 5000) return } try { this.downloading = true const videoDownloader = await format.downloadInfo(this.dash) videoDownloader.subtitle = this.subtitle videoDownloader.videoSpeed.speedUpdate = speed => this.speed = speed videoDownloader.progress = percent => { this.progressPercent = Math.trunc(percent * 100) } workingDownloader = videoDownloader await videoDownloader.download() this.lastDirectDownloadLink = DownloadVideoPackage.lastPackageUrl } catch (error) { if (error !== 'canceled') { logError(error) } this.progressPercent = 0 } finally { this.downloading = false this.speed = '' } }, selectAllEpisodes() { this.episodeList.forEach((item: EpisodeItem) => item.checked = true) }, unselectAllEpisodes() { this.episodeList.forEach((item: EpisodeItem) => item.checked = false) }, inverseAllEpisodes() { this.episodeList.forEach((item: EpisodeItem) => item.checked = !item.checked) }, shiftToggleEpisodes(e: MouseEvent, index: number) { if (!e.shiftKey || this.lastCheckedEpisodeIndex === -1) { console.log('set lastCheckedEpisodeIndex', index) this.lastCheckedEpisodeIndex = index return } if (e.shiftKey && this.lastCheckedEpisodeIndex !== -1) { (this.episodeList as EpisodeItem[]) .slice( Math.min(this.lastCheckedEpisodeIndex, index) + 1, Math.max(this.lastCheckedEpisodeIndex, index), ) .forEach(it => { it.checked = !it.checked }) console.log('shift toggle', Math.min(this.lastCheckedEpisodeIndex, index) + 1, Math.max(this.lastCheckedEpisodeIndex, index), ) this.lastCheckedEpisodeIndex = index e.preventDefault() } }, toggleRpcSettings() { this.showRpcSettings = !this.showRpcSettings }, saveRpcSettings() { if (this.rpcSettings.host === '') { this.rpcSettings.host = '127.0.0.1' } if (this.rpcSettings.port === '') { this.rpcSettings.port = '6800' } settings.aria2RpcOption = this.rpcSettings const profile = settings.aria2RpcOptionProfiles.find(p => p.name === settings.aria2RpcOptionSelectedProfile) if (profile) { Object.assign(profile, this.rpcSettings) settings.aria2RpcOptionProfiles = settings.aria2RpcOptionProfiles } this.saveRpcSettingsText = '已保存' setTimeout(() => this.saveRpcSettingsText = '保存配置', 2000) }, updateProfile(profile: RpcOptionProfile) { settings.aria2RpcOption = this.rpcSettings = _.omit(profile, 'name') as RpcOption } }, async mounted() { // if (settings.downloadVideoFormat === 'dash') { // console.log('init set dash') // this.dashModel.value = 'dash' // await this.dashChange() // } } }) // const vueCreated = performance.now() const el = panel.$mount().$el document.body.insertAdjacentElement('beforeend', el) // const vueMounted = performance.now() // el.classList.add('loaded') // const repainted = performance.now() // console.log(vueCreated - start, vueMounted - vueCreated, repainted - vueMounted) Observer.videoChange(async () => { panel.close() panel.batch = false panel.selectedTab = panelTabs[0] const button = dq('#download-video') as HTMLElement const canDownload = await loadPageData() button.style.display = canDownload ? 'flex' : 'none' if (!canDownload) { return } panel.aid = pageData.aid panel.cid = pageData.cid try { const videoInfo = new VideoInfo(pageData.aid) await videoInfo.fetchInfo() panel.coverUrl = videoInfo.coverUrl.replace('http:', 'https:') } catch (error) { panel.coverUrl = EmptyImageUrl } panel.dashChange() panel.checkSubtitle() await panel.checkBatch() }) } export default { widget: { content: /*html*/` <button class="gui-settings-flat-button" style="position: relative; z-index: 100;" id="download-video"> <i class="icon-download"></i> <span>下载视频</span> </button>`, condition: loadPageData, success: loadWidget, }, }
{ "pile_set_name": "Github" }
#ifndef __gl3_h_ #define __gl3_h_ 1 #ifdef __cplusplus extern "C" { #endif /* ** Copyright (c) 2013-2015 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the ** "Materials"), to deal in the Materials without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Materials, and to ** permit persons to whom the Materials are 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 Materials. ** ** THE MATERIALS ARE 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 ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ /* ** This header is generated from the Khronos OpenGL / OpenGL ES XML ** API Registry. The current version of the Registry, generator scripts ** used to make the header, and the header can be found at ** http://www.opengl.org/registry/ ** ** Khronos $Revision: 31811 $ on $Date: 2015-08-10 00:01:11 -0700 (Mon, 10 Aug 2015) $ */ #include <GLES3/gl3platform.h> #ifndef GL_APIENTRYP #define GL_APIENTRYP GL_APIENTRY* #endif /* Generated on date 20150809 */ /* Generated C header for: * API: gles2 * Profile: common * Versions considered: 2\.[0-9]|3\.0 * Versions emitted: .* * Default extensions included: None * Additional extensions included: _nomatch_^ * Extensions removed: _nomatch_^ */ #ifndef GL_ES_VERSION_2_0 #define GL_ES_VERSION_2_0 1 #include <KHR/khrplatform.h> typedef khronos_int8_t GLbyte; typedef khronos_float_t GLclampf; typedef khronos_int32_t GLfixed; typedef short GLshort; typedef unsigned short GLushort; typedef void GLvoid; typedef struct __GLsync *GLsync; typedef khronos_int64_t GLint64; typedef khronos_uint64_t GLuint64; typedef unsigned int GLenum; typedef unsigned int GLuint; typedef char GLchar; typedef khronos_float_t GLfloat; typedef khronos_ssize_t GLsizeiptr; typedef khronos_intptr_t GLintptr; typedef unsigned int GLbitfield; typedef int GLint; typedef unsigned char GLboolean; typedef int GLsizei; typedef khronos_uint8_t GLubyte; #define GL_DEPTH_BUFFER_BIT 0x00000100 #define GL_STENCIL_BUFFER_BIT 0x00000400 #define GL_COLOR_BUFFER_BIT 0x00004000 #define GL_FALSE 0 #define GL_TRUE 1 #define GL_POINTS 0x0000 #define GL_LINES 0x0001 #define GL_LINE_LOOP 0x0002 #define GL_LINE_STRIP 0x0003 #define GL_TRIANGLES 0x0004 #define GL_TRIANGLE_STRIP 0x0005 #define GL_TRIANGLE_FAN 0x0006 #define GL_ZERO 0 #define GL_ONE 1 #define GL_SRC_COLOR 0x0300 #define GL_ONE_MINUS_SRC_COLOR 0x0301 #define GL_SRC_ALPHA 0x0302 #define GL_ONE_MINUS_SRC_ALPHA 0x0303 #define GL_DST_ALPHA 0x0304 #define GL_ONE_MINUS_DST_ALPHA 0x0305 #define GL_DST_COLOR 0x0306 #define GL_ONE_MINUS_DST_COLOR 0x0307 #define GL_SRC_ALPHA_SATURATE 0x0308 #define GL_FUNC_ADD 0x8006 #define GL_BLEND_EQUATION 0x8009 #define GL_BLEND_EQUATION_RGB 0x8009 #define GL_BLEND_EQUATION_ALPHA 0x883D #define GL_FUNC_SUBTRACT 0x800A #define GL_FUNC_REVERSE_SUBTRACT 0x800B #define GL_BLEND_DST_RGB 0x80C8 #define GL_BLEND_SRC_RGB 0x80C9 #define GL_BLEND_DST_ALPHA 0x80CA #define GL_BLEND_SRC_ALPHA 0x80CB #define GL_CONSTANT_COLOR 0x8001 #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 #define GL_CONSTANT_ALPHA 0x8003 #define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 #define GL_BLEND_COLOR 0x8005 #define GL_ARRAY_BUFFER 0x8892 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 #define GL_STREAM_DRAW 0x88E0 #define GL_STATIC_DRAW 0x88E4 #define GL_DYNAMIC_DRAW 0x88E8 #define GL_BUFFER_SIZE 0x8764 #define GL_BUFFER_USAGE 0x8765 #define GL_CURRENT_VERTEX_ATTRIB 0x8626 #define GL_FRONT 0x0404 #define GL_BACK 0x0405 #define GL_FRONT_AND_BACK 0x0408 #define GL_TEXTURE_2D 0x0DE1 #define GL_CULL_FACE 0x0B44 #define GL_BLEND 0x0BE2 #define GL_DITHER 0x0BD0 #define GL_STENCIL_TEST 0x0B90 #define GL_DEPTH_TEST 0x0B71 #define GL_SCISSOR_TEST 0x0C11 #define GL_POLYGON_OFFSET_FILL 0x8037 #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E #define GL_SAMPLE_COVERAGE 0x80A0 #define GL_NO_ERROR 0 #define GL_INVALID_ENUM 0x0500 #define GL_INVALID_VALUE 0x0501 #define GL_INVALID_OPERATION 0x0502 #define GL_OUT_OF_MEMORY 0x0505 #define GL_CW 0x0900 #define GL_CCW 0x0901 #define GL_LINE_WIDTH 0x0B21 #define GL_ALIASED_POINT_SIZE_RANGE 0x846D #define GL_ALIASED_LINE_WIDTH_RANGE 0x846E #define GL_CULL_FACE_MODE 0x0B45 #define GL_FRONT_FACE 0x0B46 #define GL_DEPTH_RANGE 0x0B70 #define GL_DEPTH_WRITEMASK 0x0B72 #define GL_DEPTH_CLEAR_VALUE 0x0B73 #define GL_DEPTH_FUNC 0x0B74 #define GL_STENCIL_CLEAR_VALUE 0x0B91 #define GL_STENCIL_FUNC 0x0B92 #define GL_STENCIL_FAIL 0x0B94 #define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 #define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 #define GL_STENCIL_REF 0x0B97 #define GL_STENCIL_VALUE_MASK 0x0B93 #define GL_STENCIL_WRITEMASK 0x0B98 #define GL_STENCIL_BACK_FUNC 0x8800 #define GL_STENCIL_BACK_FAIL 0x8801 #define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 #define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 #define GL_STENCIL_BACK_REF 0x8CA3 #define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 #define GL_STENCIL_BACK_WRITEMASK 0x8CA5 #define GL_VIEWPORT 0x0BA2 #define GL_SCISSOR_BOX 0x0C10 #define GL_COLOR_CLEAR_VALUE 0x0C22 #define GL_COLOR_WRITEMASK 0x0C23 #define GL_UNPACK_ALIGNMENT 0x0CF5 #define GL_PACK_ALIGNMENT 0x0D05 #define GL_MAX_TEXTURE_SIZE 0x0D33 #define GL_MAX_VIEWPORT_DIMS 0x0D3A #define GL_SUBPIXEL_BITS 0x0D50 #define GL_RED_BITS 0x0D52 #define GL_GREEN_BITS 0x0D53 #define GL_BLUE_BITS 0x0D54 #define GL_ALPHA_BITS 0x0D55 #define GL_DEPTH_BITS 0x0D56 #define GL_STENCIL_BITS 0x0D57 #define GL_POLYGON_OFFSET_UNITS 0x2A00 #define GL_POLYGON_OFFSET_FACTOR 0x8038 #define GL_TEXTURE_BINDING_2D 0x8069 #define GL_SAMPLE_BUFFERS 0x80A8 #define GL_SAMPLES 0x80A9 #define GL_SAMPLE_COVERAGE_VALUE 0x80AA #define GL_SAMPLE_COVERAGE_INVERT 0x80AB #define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 #define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 #define GL_DONT_CARE 0x1100 #define GL_FASTEST 0x1101 #define GL_NICEST 0x1102 #define GL_GENERATE_MIPMAP_HINT 0x8192 #define GL_BYTE 0x1400 #define GL_UNSIGNED_BYTE 0x1401 #define GL_SHORT 0x1402 #define GL_UNSIGNED_SHORT 0x1403 #define GL_INT 0x1404 #define GL_UNSIGNED_INT 0x1405 #define GL_FLOAT 0x1406 #define GL_FIXED 0x140C #define GL_DEPTH_COMPONENT 0x1902 #define GL_ALPHA 0x1906 #define GL_RGB 0x1907 #define GL_RGBA 0x1908 #define GL_LUMINANCE 0x1909 #define GL_LUMINANCE_ALPHA 0x190A #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 #define GL_UNSIGNED_SHORT_5_6_5 0x8363 #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_MAX_VERTEX_ATTRIBS 0x8869 #define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB #define GL_MAX_VARYING_VECTORS 0x8DFC #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D #define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C #define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 #define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD #define GL_SHADER_TYPE 0x8B4F #define GL_DELETE_STATUS 0x8B80 #define GL_LINK_STATUS 0x8B82 #define GL_VALIDATE_STATUS 0x8B83 #define GL_ATTACHED_SHADERS 0x8B85 #define GL_ACTIVE_UNIFORMS 0x8B86 #define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 #define GL_ACTIVE_ATTRIBUTES 0x8B89 #define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A #define GL_SHADING_LANGUAGE_VERSION 0x8B8C #define GL_CURRENT_PROGRAM 0x8B8D #define GL_NEVER 0x0200 #define GL_LESS 0x0201 #define GL_EQUAL 0x0202 #define GL_LEQUAL 0x0203 #define GL_GREATER 0x0204 #define GL_NOTEQUAL 0x0205 #define GL_GEQUAL 0x0206 #define GL_ALWAYS 0x0207 #define GL_KEEP 0x1E00 #define GL_REPLACE 0x1E01 #define GL_INCR 0x1E02 #define GL_DECR 0x1E03 #define GL_INVERT 0x150A #define GL_INCR_WRAP 0x8507 #define GL_DECR_WRAP 0x8508 #define GL_VENDOR 0x1F00 #define GL_RENDERER 0x1F01 #define GL_VERSION 0x1F02 #define GL_EXTENSIONS 0x1F03 #define GL_NEAREST 0x2600 #define GL_LINEAR 0x2601 #define GL_NEAREST_MIPMAP_NEAREST 0x2700 #define GL_LINEAR_MIPMAP_NEAREST 0x2701 #define GL_NEAREST_MIPMAP_LINEAR 0x2702 #define GL_LINEAR_MIPMAP_LINEAR 0x2703 #define GL_TEXTURE_MAG_FILTER 0x2800 #define GL_TEXTURE_MIN_FILTER 0x2801 #define GL_TEXTURE_WRAP_S 0x2802 #define GL_TEXTURE_WRAP_T 0x2803 #define GL_TEXTURE 0x1702 #define GL_TEXTURE_CUBE_MAP 0x8513 #define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C #define GL_TEXTURE0 0x84C0 #define GL_TEXTURE1 0x84C1 #define GL_TEXTURE2 0x84C2 #define GL_TEXTURE3 0x84C3 #define GL_TEXTURE4 0x84C4 #define GL_TEXTURE5 0x84C5 #define GL_TEXTURE6 0x84C6 #define GL_TEXTURE7 0x84C7 #define GL_TEXTURE8 0x84C8 #define GL_TEXTURE9 0x84C9 #define GL_TEXTURE10 0x84CA #define GL_TEXTURE11 0x84CB #define GL_TEXTURE12 0x84CC #define GL_TEXTURE13 0x84CD #define GL_TEXTURE14 0x84CE #define GL_TEXTURE15 0x84CF #define GL_TEXTURE16 0x84D0 #define GL_TEXTURE17 0x84D1 #define GL_TEXTURE18 0x84D2 #define GL_TEXTURE19 0x84D3 #define GL_TEXTURE20 0x84D4 #define GL_TEXTURE21 0x84D5 #define GL_TEXTURE22 0x84D6 #define GL_TEXTURE23 0x84D7 #define GL_TEXTURE24 0x84D8 #define GL_TEXTURE25 0x84D9 #define GL_TEXTURE26 0x84DA #define GL_TEXTURE27 0x84DB #define GL_TEXTURE28 0x84DC #define GL_TEXTURE29 0x84DD #define GL_TEXTURE30 0x84DE #define GL_TEXTURE31 0x84DF #define GL_ACTIVE_TEXTURE 0x84E0 #define GL_REPEAT 0x2901 #define GL_CLAMP_TO_EDGE 0x812F #define GL_MIRRORED_REPEAT 0x8370 #define GL_FLOAT_VEC2 0x8B50 #define GL_FLOAT_VEC3 0x8B51 #define GL_FLOAT_VEC4 0x8B52 #define GL_INT_VEC2 0x8B53 #define GL_INT_VEC3 0x8B54 #define GL_INT_VEC4 0x8B55 #define GL_BOOL 0x8B56 #define GL_BOOL_VEC2 0x8B57 #define GL_BOOL_VEC3 0x8B58 #define GL_BOOL_VEC4 0x8B59 #define GL_FLOAT_MAT2 0x8B5A #define GL_FLOAT_MAT3 0x8B5B #define GL_FLOAT_MAT4 0x8B5C #define GL_SAMPLER_2D 0x8B5E #define GL_SAMPLER_CUBE 0x8B60 #define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 #define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 #define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 #define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A #define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F #define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A #define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B #define GL_COMPILE_STATUS 0x8B81 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_SHADER_SOURCE_LENGTH 0x8B88 #define GL_SHADER_COMPILER 0x8DFA #define GL_SHADER_BINARY_FORMATS 0x8DF8 #define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 #define GL_LOW_FLOAT 0x8DF0 #define GL_MEDIUM_FLOAT 0x8DF1 #define GL_HIGH_FLOAT 0x8DF2 #define GL_LOW_INT 0x8DF3 #define GL_MEDIUM_INT 0x8DF4 #define GL_HIGH_INT 0x8DF5 #define GL_FRAMEBUFFER 0x8D40 #define GL_RENDERBUFFER 0x8D41 #define GL_RGBA4 0x8056 #define GL_RGB5_A1 0x8057 #define GL_RGB565 0x8D62 #define GL_DEPTH_COMPONENT16 0x81A5 #define GL_STENCIL_INDEX8 0x8D48 #define GL_RENDERBUFFER_WIDTH 0x8D42 #define GL_RENDERBUFFER_HEIGHT 0x8D43 #define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 #define GL_RENDERBUFFER_RED_SIZE 0x8D50 #define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 #define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 #define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 #define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 #define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 #define GL_COLOR_ATTACHMENT0 0x8CE0 #define GL_DEPTH_ATTACHMENT 0x8D00 #define GL_STENCIL_ATTACHMENT 0x8D20 #define GL_NONE 0 #define GL_FRAMEBUFFER_COMPLETE 0x8CD5 #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 #define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD #define GL_FRAMEBUFFER_BINDING 0x8CA6 #define GL_RENDERBUFFER_BINDING 0x8CA7 #define GL_MAX_RENDERBUFFER_SIZE 0x84E8 #define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 typedef void (GL_APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); typedef void (GL_APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); typedef void (GL_APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); typedef void (GL_APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); typedef void (GL_APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer); typedef void (GL_APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer); typedef void (GL_APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture); typedef void (GL_APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); typedef void (GL_APIENTRYP PFNGLBLENDFUNCPROC) (GLenum sfactor, GLenum dfactor); typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); typedef void (GL_APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); typedef void (GL_APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); typedef GLenum (GL_APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target); typedef void (GL_APIENTRYP PFNGLCLEARPROC) (GLbitfield mask); typedef void (GL_APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); typedef void (GL_APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d); typedef void (GL_APIENTRYP PFNGLCLEARSTENCILPROC) (GLint s); typedef void (GL_APIENTRYP PFNGLCOLORMASKPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); typedef void (GL_APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); typedef void (GL_APIENTRYP PFNGLCOPYTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); typedef GLuint (GL_APIENTRYP PFNGLCREATEPROGRAMPROC) (void); typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); typedef void (GL_APIENTRYP PFNGLCULLFACEPROC) (GLenum mode); typedef void (GL_APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); typedef void (GL_APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers); typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); typedef void (GL_APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers); typedef void (GL_APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); typedef void (GL_APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures); typedef void (GL_APIENTRYP PFNGLDEPTHFUNCPROC) (GLenum func); typedef void (GL_APIENTRYP PFNGLDEPTHMASKPROC) (GLboolean flag); typedef void (GL_APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f); typedef void (GL_APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); typedef void (GL_APIENTRYP PFNGLDISABLEPROC) (GLenum cap); typedef void (GL_APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (GL_APIENTRYP PFNGLDRAWARRAYSPROC) (GLenum mode, GLint first, GLsizei count); typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices); typedef void (GL_APIENTRYP PFNGLENABLEPROC) (GLenum cap); typedef void (GL_APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (GL_APIENTRYP PFNGLFINISHPROC) (void); typedef void (GL_APIENTRYP PFNGLFLUSHPROC) (void); typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); typedef void (GL_APIENTRYP PFNGLFRONTFACEPROC) (GLenum mode); typedef void (GL_APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); typedef void (GL_APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target); typedef void (GL_APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); typedef void (GL_APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); typedef void (GL_APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures); typedef void (GL_APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); typedef void (GL_APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); typedef GLint (GL_APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); typedef void (GL_APIENTRYP PFNGLGETBOOLEANVPROC) (GLenum pname, GLboolean *data); typedef void (GL_APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); typedef GLenum (GL_APIENTRYP PFNGLGETERRORPROC) (void); typedef void (GL_APIENTRYP PFNGLGETFLOATVPROC) (GLenum pname, GLfloat *data); typedef void (GL_APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data); typedef void (GL_APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef void (GL_APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef void (GL_APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); typedef void (GL_APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); typedef const GLubyte *(GL_APIENTRYP PFNGLGETSTRINGPROC) (GLenum name); typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); typedef void (GL_APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); typedef GLint (GL_APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); typedef void (GL_APIENTRYP PFNGLHINTPROC) (GLenum target, GLenum mode); typedef GLboolean (GL_APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDPROC) (GLenum cap); typedef GLboolean (GL_APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer); typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); typedef GLboolean (GL_APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer); typedef GLboolean (GL_APIENTRYP PFNGLISSHADERPROC) (GLuint shader); typedef GLboolean (GL_APIENTRYP PFNGLISTEXTUREPROC) (GLuint texture); typedef void (GL_APIENTRYP PFNGLLINEWIDTHPROC) (GLfloat width); typedef void (GL_APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); typedef void (GL_APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param); typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETPROC) (GLfloat factor, GLfloat units); typedef void (GL_APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); typedef void (GL_APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void); typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); typedef void (GL_APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert); typedef void (GL_APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height); typedef void (GL_APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); typedef void (GL_APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); typedef void (GL_APIENTRYP PFNGLSTENCILFUNCPROC) (GLenum func, GLint ref, GLuint mask); typedef void (GL_APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask); typedef void (GL_APIENTRYP PFNGLSTENCILMASKPROC) (GLuint mask); typedef void (GL_APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); typedef void (GL_APIENTRYP PFNGLSTENCILOPPROC) (GLenum fail, GLenum zfail, GLenum zpass); typedef void (GL_APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); typedef void (GL_APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); typedef void (GL_APIENTRYP PFNGLTEXPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat param); typedef void (GL_APIENTRYP PFNGLTEXPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); typedef void (GL_APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); typedef void (GL_APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); typedef void (GL_APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); typedef void (GL_APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); typedef void (GL_APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); typedef void (GL_APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); typedef void (GL_APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); typedef void (GL_APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); typedef void (GL_APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); typedef void (GL_APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); typedef void (GL_APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); typedef void (GL_APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); typedef void (GL_APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height); #ifdef GL_GLEXT_PROTOTYPES GL_APICALL void GL_APIENTRY glActiveTexture (GLenum texture); GL_APICALL void GL_APIENTRY glAttachShader (GLuint program, GLuint shader); GL_APICALL void GL_APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name); GL_APICALL void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer); GL_APICALL void GL_APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer); GL_APICALL void GL_APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer); GL_APICALL void GL_APIENTRY glBindTexture (GLenum target, GLuint texture); GL_APICALL void GL_APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GL_APICALL void GL_APIENTRY glBlendEquation (GLenum mode); GL_APICALL void GL_APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); GL_APICALL void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor); GL_APICALL void GL_APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); GL_APICALL void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); GL_APICALL void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); GL_APICALL GLenum GL_APIENTRY glCheckFramebufferStatus (GLenum target); GL_APICALL void GL_APIENTRY glClear (GLbitfield mask); GL_APICALL void GL_APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GL_APICALL void GL_APIENTRY glClearDepthf (GLfloat d); GL_APICALL void GL_APIENTRY glClearStencil (GLint s); GL_APICALL void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); GL_APICALL void GL_APIENTRY glCompileShader (GLuint shader); GL_APICALL void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); GL_APICALL void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); GL_APICALL void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); GL_APICALL void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); GL_APICALL GLuint GL_APIENTRY glCreateProgram (void); GL_APICALL GLuint GL_APIENTRY glCreateShader (GLenum type); GL_APICALL void GL_APIENTRY glCullFace (GLenum mode); GL_APICALL void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); GL_APICALL void GL_APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers); GL_APICALL void GL_APIENTRY glDeleteProgram (GLuint program); GL_APICALL void GL_APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers); GL_APICALL void GL_APIENTRY glDeleteShader (GLuint shader); GL_APICALL void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures); GL_APICALL void GL_APIENTRY glDepthFunc (GLenum func); GL_APICALL void GL_APIENTRY glDepthMask (GLboolean flag); GL_APICALL void GL_APIENTRY glDepthRangef (GLfloat n, GLfloat f); GL_APICALL void GL_APIENTRY glDetachShader (GLuint program, GLuint shader); GL_APICALL void GL_APIENTRY glDisable (GLenum cap); GL_APICALL void GL_APIENTRY glDisableVertexAttribArray (GLuint index); GL_APICALL void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count); GL_APICALL void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices); GL_APICALL void GL_APIENTRY glEnable (GLenum cap); GL_APICALL void GL_APIENTRY glEnableVertexAttribArray (GLuint index); GL_APICALL void GL_APIENTRY glFinish (void); GL_APICALL void GL_APIENTRY glFlush (void); GL_APICALL void GL_APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); GL_APICALL void GL_APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GL_APICALL void GL_APIENTRY glFrontFace (GLenum mode); GL_APICALL void GL_APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); GL_APICALL void GL_APIENTRY glGenerateMipmap (GLenum target); GL_APICALL void GL_APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers); GL_APICALL void GL_APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers); GL_APICALL void GL_APIENTRY glGenTextures (GLsizei n, GLuint *textures); GL_APICALL void GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); GL_APICALL void GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); GL_APICALL void GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); GL_APICALL GLint GL_APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); GL_APICALL void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean *data); GL_APICALL void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); GL_APICALL GLenum GL_APIENTRY glGetError (void); GL_APICALL void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat *data); GL_APICALL void GL_APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetIntegerv (GLenum pname, GLint *data); GL_APICALL void GL_APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GL_APICALL void GL_APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GL_APICALL void GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); GL_APICALL void GL_APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); GL_APICALL const GLubyte *GL_APIENTRY glGetString (GLenum name); GL_APICALL void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params); GL_APICALL void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params); GL_APICALL void GL_APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params); GL_APICALL GLint GL_APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); GL_APICALL void GL_APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params); GL_APICALL void GL_APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); GL_APICALL void GL_APIENTRY glHint (GLenum target, GLenum mode); GL_APICALL GLboolean GL_APIENTRY glIsBuffer (GLuint buffer); GL_APICALL GLboolean GL_APIENTRY glIsEnabled (GLenum cap); GL_APICALL GLboolean GL_APIENTRY glIsFramebuffer (GLuint framebuffer); GL_APICALL GLboolean GL_APIENTRY glIsProgram (GLuint program); GL_APICALL GLboolean GL_APIENTRY glIsRenderbuffer (GLuint renderbuffer); GL_APICALL GLboolean GL_APIENTRY glIsShader (GLuint shader); GL_APICALL GLboolean GL_APIENTRY glIsTexture (GLuint texture); GL_APICALL void GL_APIENTRY glLineWidth (GLfloat width); GL_APICALL void GL_APIENTRY glLinkProgram (GLuint program); GL_APICALL void GL_APIENTRY glPixelStorei (GLenum pname, GLint param); GL_APICALL void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units); GL_APICALL void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); GL_APICALL void GL_APIENTRY glReleaseShaderCompiler (void); GL_APICALL void GL_APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); GL_APICALL void GL_APIENTRY glSampleCoverage (GLfloat value, GLboolean invert); GL_APICALL void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height); GL_APICALL void GL_APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); GL_APICALL void GL_APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); GL_APICALL void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask); GL_APICALL void GL_APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask); GL_APICALL void GL_APIENTRY glStencilMask (GLuint mask); GL_APICALL void GL_APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask); GL_APICALL void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass); GL_APICALL void GL_APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); GL_APICALL void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); GL_APICALL void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param); GL_APICALL void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params); GL_APICALL void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param); GL_APICALL void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params); GL_APICALL void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GL_APICALL void GL_APIENTRY glUniform1f (GLint location, GLfloat v0); GL_APICALL void GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniform1i (GLint location, GLint v0); GL_APICALL void GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value); GL_APICALL void GL_APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1); GL_APICALL void GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniform2i (GLint location, GLint v0, GLint v1); GL_APICALL void GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value); GL_APICALL void GL_APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); GL_APICALL void GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2); GL_APICALL void GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value); GL_APICALL void GL_APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); GL_APICALL void GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); GL_APICALL void GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value); GL_APICALL void GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glUseProgram (GLuint program); GL_APICALL void GL_APIENTRY glValidateProgram (GLuint program); GL_APICALL void GL_APIENTRY glVertexAttrib1f (GLuint index, GLfloat x); GL_APICALL void GL_APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v); GL_APICALL void GL_APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y); GL_APICALL void GL_APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v); GL_APICALL void GL_APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z); GL_APICALL void GL_APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v); GL_APICALL void GL_APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); GL_APICALL void GL_APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v); GL_APICALL void GL_APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); GL_APICALL void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height); #endif #endif /* GL_ES_VERSION_2_0 */ #ifndef GL_ES_VERSION_3_0 #define GL_ES_VERSION_3_0 1 typedef unsigned short GLhalf; #define GL_READ_BUFFER 0x0C02 #define GL_UNPACK_ROW_LENGTH 0x0CF2 #define GL_UNPACK_SKIP_ROWS 0x0CF3 #define GL_UNPACK_SKIP_PIXELS 0x0CF4 #define GL_PACK_ROW_LENGTH 0x0D02 #define GL_PACK_SKIP_ROWS 0x0D03 #define GL_PACK_SKIP_PIXELS 0x0D04 #define GL_COLOR 0x1800 #define GL_DEPTH 0x1801 #define GL_STENCIL 0x1802 #define GL_RED 0x1903 #define GL_RGB8 0x8051 #define GL_RGBA8 0x8058 #define GL_RGB10_A2 0x8059 #define GL_TEXTURE_BINDING_3D 0x806A #define GL_UNPACK_SKIP_IMAGES 0x806D #define GL_UNPACK_IMAGE_HEIGHT 0x806E #define GL_TEXTURE_3D 0x806F #define GL_TEXTURE_WRAP_R 0x8072 #define GL_MAX_3D_TEXTURE_SIZE 0x8073 #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 #define GL_MAX_ELEMENTS_VERTICES 0x80E8 #define GL_MAX_ELEMENTS_INDICES 0x80E9 #define GL_TEXTURE_MIN_LOD 0x813A #define GL_TEXTURE_MAX_LOD 0x813B #define GL_TEXTURE_BASE_LEVEL 0x813C #define GL_TEXTURE_MAX_LEVEL 0x813D #define GL_MIN 0x8007 #define GL_MAX 0x8008 #define GL_DEPTH_COMPONENT24 0x81A6 #define GL_MAX_TEXTURE_LOD_BIAS 0x84FD #define GL_TEXTURE_COMPARE_MODE 0x884C #define GL_TEXTURE_COMPARE_FUNC 0x884D #define GL_CURRENT_QUERY 0x8865 #define GL_QUERY_RESULT 0x8866 #define GL_QUERY_RESULT_AVAILABLE 0x8867 #define GL_BUFFER_MAPPED 0x88BC #define GL_BUFFER_MAP_POINTER 0x88BD #define GL_STREAM_READ 0x88E1 #define GL_STREAM_COPY 0x88E2 #define GL_STATIC_READ 0x88E5 #define GL_STATIC_COPY 0x88E6 #define GL_DYNAMIC_READ 0x88E9 #define GL_DYNAMIC_COPY 0x88EA #define GL_MAX_DRAW_BUFFERS 0x8824 #define GL_DRAW_BUFFER0 0x8825 #define GL_DRAW_BUFFER1 0x8826 #define GL_DRAW_BUFFER2 0x8827 #define GL_DRAW_BUFFER3 0x8828 #define GL_DRAW_BUFFER4 0x8829 #define GL_DRAW_BUFFER5 0x882A #define GL_DRAW_BUFFER6 0x882B #define GL_DRAW_BUFFER7 0x882C #define GL_DRAW_BUFFER8 0x882D #define GL_DRAW_BUFFER9 0x882E #define GL_DRAW_BUFFER10 0x882F #define GL_DRAW_BUFFER11 0x8830 #define GL_DRAW_BUFFER12 0x8831 #define GL_DRAW_BUFFER13 0x8832 #define GL_DRAW_BUFFER14 0x8833 #define GL_DRAW_BUFFER15 0x8834 #define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A #define GL_SAMPLER_3D 0x8B5F #define GL_SAMPLER_2D_SHADOW 0x8B62 #define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B #define GL_PIXEL_PACK_BUFFER 0x88EB #define GL_PIXEL_UNPACK_BUFFER 0x88EC #define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED #define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF #define GL_FLOAT_MAT2x3 0x8B65 #define GL_FLOAT_MAT2x4 0x8B66 #define GL_FLOAT_MAT3x2 0x8B67 #define GL_FLOAT_MAT3x4 0x8B68 #define GL_FLOAT_MAT4x2 0x8B69 #define GL_FLOAT_MAT4x3 0x8B6A #define GL_SRGB 0x8C40 #define GL_SRGB8 0x8C41 #define GL_SRGB8_ALPHA8 0x8C43 #define GL_COMPARE_REF_TO_TEXTURE 0x884E #define GL_MAJOR_VERSION 0x821B #define GL_MINOR_VERSION 0x821C #define GL_NUM_EXTENSIONS 0x821D #define GL_RGBA32F 0x8814 #define GL_RGB32F 0x8815 #define GL_RGBA16F 0x881A #define GL_RGB16F 0x881B #define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD #define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF #define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 #define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 #define GL_MAX_VARYING_COMPONENTS 0x8B4B #define GL_TEXTURE_2D_ARRAY 0x8C1A #define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D #define GL_R11F_G11F_B10F 0x8C3A #define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B #define GL_RGB9_E5 0x8C3D #define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E #define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 #define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 #define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 #define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 #define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 #define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 #define GL_RASTERIZER_DISCARD 0x8C89 #define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B #define GL_INTERLEAVED_ATTRIBS 0x8C8C #define GL_SEPARATE_ATTRIBS 0x8C8D #define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E #define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F #define GL_RGBA32UI 0x8D70 #define GL_RGB32UI 0x8D71 #define GL_RGBA16UI 0x8D76 #define GL_RGB16UI 0x8D77 #define GL_RGBA8UI 0x8D7C #define GL_RGB8UI 0x8D7D #define GL_RGBA32I 0x8D82 #define GL_RGB32I 0x8D83 #define GL_RGBA16I 0x8D88 #define GL_RGB16I 0x8D89 #define GL_RGBA8I 0x8D8E #define GL_RGB8I 0x8D8F #define GL_RED_INTEGER 0x8D94 #define GL_RGB_INTEGER 0x8D98 #define GL_RGBA_INTEGER 0x8D99 #define GL_SAMPLER_2D_ARRAY 0x8DC1 #define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 #define GL_SAMPLER_CUBE_SHADOW 0x8DC5 #define GL_UNSIGNED_INT_VEC2 0x8DC6 #define GL_UNSIGNED_INT_VEC3 0x8DC7 #define GL_UNSIGNED_INT_VEC4 0x8DC8 #define GL_INT_SAMPLER_2D 0x8DCA #define GL_INT_SAMPLER_3D 0x8DCB #define GL_INT_SAMPLER_CUBE 0x8DCC #define GL_INT_SAMPLER_2D_ARRAY 0x8DCF #define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 #define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 #define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 #define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 #define GL_BUFFER_ACCESS_FLAGS 0x911F #define GL_BUFFER_MAP_LENGTH 0x9120 #define GL_BUFFER_MAP_OFFSET 0x9121 #define GL_DEPTH_COMPONENT32F 0x8CAC #define GL_DEPTH32F_STENCIL8 0x8CAD #define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD #define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 #define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 #define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 #define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 #define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 #define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 #define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 #define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 #define GL_FRAMEBUFFER_DEFAULT 0x8218 #define GL_FRAMEBUFFER_UNDEFINED 0x8219 #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A #define GL_DEPTH_STENCIL 0x84F9 #define GL_UNSIGNED_INT_24_8 0x84FA #define GL_DEPTH24_STENCIL8 0x88F0 #define GL_UNSIGNED_NORMALIZED 0x8C17 #define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 #define GL_READ_FRAMEBUFFER 0x8CA8 #define GL_DRAW_FRAMEBUFFER 0x8CA9 #define GL_READ_FRAMEBUFFER_BINDING 0x8CAA #define GL_RENDERBUFFER_SAMPLES 0x8CAB #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 #define GL_MAX_COLOR_ATTACHMENTS 0x8CDF #define GL_COLOR_ATTACHMENT1 0x8CE1 #define GL_COLOR_ATTACHMENT2 0x8CE2 #define GL_COLOR_ATTACHMENT3 0x8CE3 #define GL_COLOR_ATTACHMENT4 0x8CE4 #define GL_COLOR_ATTACHMENT5 0x8CE5 #define GL_COLOR_ATTACHMENT6 0x8CE6 #define GL_COLOR_ATTACHMENT7 0x8CE7 #define GL_COLOR_ATTACHMENT8 0x8CE8 #define GL_COLOR_ATTACHMENT9 0x8CE9 #define GL_COLOR_ATTACHMENT10 0x8CEA #define GL_COLOR_ATTACHMENT11 0x8CEB #define GL_COLOR_ATTACHMENT12 0x8CEC #define GL_COLOR_ATTACHMENT13 0x8CED #define GL_COLOR_ATTACHMENT14 0x8CEE #define GL_COLOR_ATTACHMENT15 0x8CEF #define GL_COLOR_ATTACHMENT16 0x8CF0 #define GL_COLOR_ATTACHMENT17 0x8CF1 #define GL_COLOR_ATTACHMENT18 0x8CF2 #define GL_COLOR_ATTACHMENT19 0x8CF3 #define GL_COLOR_ATTACHMENT20 0x8CF4 #define GL_COLOR_ATTACHMENT21 0x8CF5 #define GL_COLOR_ATTACHMENT22 0x8CF6 #define GL_COLOR_ATTACHMENT23 0x8CF7 #define GL_COLOR_ATTACHMENT24 0x8CF8 #define GL_COLOR_ATTACHMENT25 0x8CF9 #define GL_COLOR_ATTACHMENT26 0x8CFA #define GL_COLOR_ATTACHMENT27 0x8CFB #define GL_COLOR_ATTACHMENT28 0x8CFC #define GL_COLOR_ATTACHMENT29 0x8CFD #define GL_COLOR_ATTACHMENT30 0x8CFE #define GL_COLOR_ATTACHMENT31 0x8CFF #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 #define GL_MAX_SAMPLES 0x8D57 #define GL_HALF_FLOAT 0x140B #define GL_MAP_READ_BIT 0x0001 #define GL_MAP_WRITE_BIT 0x0002 #define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 #define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 #define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 #define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 #define GL_RG 0x8227 #define GL_RG_INTEGER 0x8228 #define GL_R8 0x8229 #define GL_RG8 0x822B #define GL_R16F 0x822D #define GL_R32F 0x822E #define GL_RG16F 0x822F #define GL_RG32F 0x8230 #define GL_R8I 0x8231 #define GL_R8UI 0x8232 #define GL_R16I 0x8233 #define GL_R16UI 0x8234 #define GL_R32I 0x8235 #define GL_R32UI 0x8236 #define GL_RG8I 0x8237 #define GL_RG8UI 0x8238 #define GL_RG16I 0x8239 #define GL_RG16UI 0x823A #define GL_RG32I 0x823B #define GL_RG32UI 0x823C #define GL_VERTEX_ARRAY_BINDING 0x85B5 #define GL_R8_SNORM 0x8F94 #define GL_RG8_SNORM 0x8F95 #define GL_RGB8_SNORM 0x8F96 #define GL_RGBA8_SNORM 0x8F97 #define GL_SIGNED_NORMALIZED 0x8F9C #define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 #define GL_COPY_READ_BUFFER 0x8F36 #define GL_COPY_WRITE_BUFFER 0x8F37 #define GL_COPY_READ_BUFFER_BINDING 0x8F36 #define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 #define GL_UNIFORM_BUFFER 0x8A11 #define GL_UNIFORM_BUFFER_BINDING 0x8A28 #define GL_UNIFORM_BUFFER_START 0x8A29 #define GL_UNIFORM_BUFFER_SIZE 0x8A2A #define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B #define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D #define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E #define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F #define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 #define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 #define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 #define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 #define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 #define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 #define GL_UNIFORM_TYPE 0x8A37 #define GL_UNIFORM_SIZE 0x8A38 #define GL_UNIFORM_NAME_LENGTH 0x8A39 #define GL_UNIFORM_BLOCK_INDEX 0x8A3A #define GL_UNIFORM_OFFSET 0x8A3B #define GL_UNIFORM_ARRAY_STRIDE 0x8A3C #define GL_UNIFORM_MATRIX_STRIDE 0x8A3D #define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E #define GL_UNIFORM_BLOCK_BINDING 0x8A3F #define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 #define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 #define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 #define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 #define GL_INVALID_INDEX 0xFFFFFFFFu #define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 #define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 #define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 #define GL_OBJECT_TYPE 0x9112 #define GL_SYNC_CONDITION 0x9113 #define GL_SYNC_STATUS 0x9114 #define GL_SYNC_FLAGS 0x9115 #define GL_SYNC_FENCE 0x9116 #define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 #define GL_UNSIGNALED 0x9118 #define GL_SIGNALED 0x9119 #define GL_ALREADY_SIGNALED 0x911A #define GL_TIMEOUT_EXPIRED 0x911B #define GL_CONDITION_SATISFIED 0x911C #define GL_WAIT_FAILED 0x911D #define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 #define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull #define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE #define GL_ANY_SAMPLES_PASSED 0x8C2F #define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A #define GL_SAMPLER_BINDING 0x8919 #define GL_RGB10_A2UI 0x906F #define GL_TEXTURE_SWIZZLE_R 0x8E42 #define GL_TEXTURE_SWIZZLE_G 0x8E43 #define GL_TEXTURE_SWIZZLE_B 0x8E44 #define GL_TEXTURE_SWIZZLE_A 0x8E45 #define GL_GREEN 0x1904 #define GL_BLUE 0x1905 #define GL_INT_2_10_10_10_REV 0x8D9F #define GL_TRANSFORM_FEEDBACK 0x8E22 #define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 #define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 #define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 #define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 #define GL_PROGRAM_BINARY_LENGTH 0x8741 #define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE #define GL_PROGRAM_BINARY_FORMATS 0x87FF #define GL_COMPRESSED_R11_EAC 0x9270 #define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 #define GL_COMPRESSED_RG11_EAC 0x9272 #define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 #define GL_COMPRESSED_RGB8_ETC2 0x9274 #define GL_COMPRESSED_SRGB8_ETC2 0x9275 #define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 #define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 #define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 #define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F #define GL_MAX_ELEMENT_INDEX 0x8D6B #define GL_NUM_SAMPLE_COUNTS 0x9380 #define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF typedef void (GL_APIENTRYP PFNGLREADBUFFERPROC) (GLenum src); typedef void (GL_APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); typedef void (GL_APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); typedef void (GL_APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); typedef void (GL_APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); typedef GLboolean (GL_APIENTRYP PFNGLISQUERYPROC) (GLuint id); typedef void (GL_APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); typedef void (GL_APIENTRYP PFNGLENDQUERYPROC) (GLenum target); typedef void (GL_APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, void **params); typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); typedef void *(GL_APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); typedef void (GL_APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length); typedef void (GL_APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); typedef void (GL_APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); typedef void (GL_APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); typedef GLboolean (GL_APIENTRYP PFNGLISVERTEXARRAYPROC) (GLuint array); typedef void (GL_APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data); typedef void (GL_APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum primitiveMode); typedef void (GL_APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC) (void); typedef void (GL_APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); typedef void (GL_APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); typedef void (GL_APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); typedef void (GL_APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC) (GLuint index, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint index, GLenum pname, GLuint *params); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBI4IPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBI4UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBI4IVPROC) (GLuint index, const GLint *v); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC) (GLuint index, const GLuint *v); typedef void (GL_APIENTRYP PFNGLGETUNIFORMUIVPROC) (GLuint program, GLint location, GLuint *params); typedef GLint (GL_APIENTRYP PFNGLGETFRAGDATALOCATIONPROC) (GLuint program, const GLchar *name); typedef void (GL_APIENTRYP PFNGLUNIFORM1UIPROC) (GLint location, GLuint v0); typedef void (GL_APIENTRYP PFNGLUNIFORM2UIPROC) (GLint location, GLuint v0, GLuint v1); typedef void (GL_APIENTRYP PFNGLUNIFORM3UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); typedef void (GL_APIENTRYP PFNGLUNIFORM4UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); typedef void (GL_APIENTRYP PFNGLUNIFORM1UIVPROC) (GLint location, GLsizei count, const GLuint *value); typedef void (GL_APIENTRYP PFNGLUNIFORM2UIVPROC) (GLint location, GLsizei count, const GLuint *value); typedef void (GL_APIENTRYP PFNGLUNIFORM3UIVPROC) (GLint location, GLsizei count, const GLuint *value); typedef void (GL_APIENTRYP PFNGLUNIFORM4UIVPROC) (GLint location, GLsizei count, const GLuint *value); typedef void (GL_APIENTRYP PFNGLCLEARBUFFERIVPROC) (GLenum buffer, GLint drawbuffer, const GLint *value); typedef void (GL_APIENTRYP PFNGLCLEARBUFFERUIVPROC) (GLenum buffer, GLint drawbuffer, const GLuint *value); typedef void (GL_APIENTRYP PFNGLCLEARBUFFERFVPROC) (GLenum buffer, GLint drawbuffer, const GLfloat *value); typedef void (GL_APIENTRYP PFNGLCLEARBUFFERFIPROC) (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); typedef const GLubyte *(GL_APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index); typedef void (GL_APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); typedef void (GL_APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); typedef GLuint (GL_APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); typedef void (GL_APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); typedef GLsync (GL_APIENTRYP PFNGLFENCESYNCPROC) (GLenum condition, GLbitfield flags); typedef GLboolean (GL_APIENTRYP PFNGLISSYNCPROC) (GLsync sync); typedef void (GL_APIENTRYP PFNGLDELETESYNCPROC) (GLsync sync); typedef GLenum (GL_APIENTRYP PFNGLCLIENTWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); typedef void (GL_APIENTRYP PFNGLWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); typedef void (GL_APIENTRYP PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64 *data); typedef void (GL_APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); typedef void (GL_APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); typedef void (GL_APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum target, GLenum pname, GLint64 *params); typedef void (GL_APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers); typedef void (GL_APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers); typedef GLboolean (GL_APIENTRYP PFNGLISSAMPLERPROC) (GLuint sampler); typedef void (GL_APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param); typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint *param); typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param); typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat *param); typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint *params); typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat *params); typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor); typedef void (GL_APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id); typedef void (GL_APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint *ids); typedef void (GL_APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); typedef GLboolean (GL_APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id); typedef void (GL_APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC) (void); typedef void (GL_APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC) (void); typedef void (GL_APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); typedef void (GL_APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); typedef void (GL_APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value); typedef void (GL_APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments); typedef void (GL_APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); typedef void (GL_APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); #ifdef GL_GLEXT_PROTOTYPES GL_APICALL void GL_APIENTRY glReadBuffer (GLenum src); GL_APICALL void GL_APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); GL_APICALL void GL_APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); GL_APICALL void GL_APIENTRY glTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); GL_APICALL void GL_APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); GL_APICALL void GL_APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); GL_APICALL void GL_APIENTRY glCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); GL_APICALL void GL_APIENTRY glGenQueries (GLsizei n, GLuint *ids); GL_APICALL void GL_APIENTRY glDeleteQueries (GLsizei n, const GLuint *ids); GL_APICALL GLboolean GL_APIENTRY glIsQuery (GLuint id); GL_APICALL void GL_APIENTRY glBeginQuery (GLenum target, GLuint id); GL_APICALL void GL_APIENTRY glEndQuery (GLenum target); GL_APICALL void GL_APIENTRY glGetQueryiv (GLenum target, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params); GL_APICALL GLboolean GL_APIENTRY glUnmapBuffer (GLenum target); GL_APICALL void GL_APIENTRY glGetBufferPointerv (GLenum target, GLenum pname, void **params); GL_APICALL void GL_APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs); GL_APICALL void GL_APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GL_APICALL void GL_APIENTRY glBlitFramebuffer (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); GL_APICALL void GL_APIENTRY glFramebufferTextureLayer (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); GL_APICALL void *GL_APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); GL_APICALL void GL_APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length); GL_APICALL void GL_APIENTRY glBindVertexArray (GLuint array); GL_APICALL void GL_APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays); GL_APICALL void GL_APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); GL_APICALL GLboolean GL_APIENTRY glIsVertexArray (GLuint array); GL_APICALL void GL_APIENTRY glGetIntegeri_v (GLenum target, GLuint index, GLint *data); GL_APICALL void GL_APIENTRY glBeginTransformFeedback (GLenum primitiveMode); GL_APICALL void GL_APIENTRY glEndTransformFeedback (void); GL_APICALL void GL_APIENTRY glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); GL_APICALL void GL_APIENTRY glBindBufferBase (GLenum target, GLuint index, GLuint buffer); GL_APICALL void GL_APIENTRY glTransformFeedbackVaryings (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); GL_APICALL void GL_APIENTRY glGetTransformFeedbackVarying (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); GL_APICALL void GL_APIENTRY glVertexAttribIPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); GL_APICALL void GL_APIENTRY glGetVertexAttribIiv (GLuint index, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetVertexAttribIuiv (GLuint index, GLenum pname, GLuint *params); GL_APICALL void GL_APIENTRY glVertexAttribI4i (GLuint index, GLint x, GLint y, GLint z, GLint w); GL_APICALL void GL_APIENTRY glVertexAttribI4ui (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); GL_APICALL void GL_APIENTRY glVertexAttribI4iv (GLuint index, const GLint *v); GL_APICALL void GL_APIENTRY glVertexAttribI4uiv (GLuint index, const GLuint *v); GL_APICALL void GL_APIENTRY glGetUniformuiv (GLuint program, GLint location, GLuint *params); GL_APICALL GLint GL_APIENTRY glGetFragDataLocation (GLuint program, const GLchar *name); GL_APICALL void GL_APIENTRY glUniform1ui (GLint location, GLuint v0); GL_APICALL void GL_APIENTRY glUniform2ui (GLint location, GLuint v0, GLuint v1); GL_APICALL void GL_APIENTRY glUniform3ui (GLint location, GLuint v0, GLuint v1, GLuint v2); GL_APICALL void GL_APIENTRY glUniform4ui (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); GL_APICALL void GL_APIENTRY glUniform1uiv (GLint location, GLsizei count, const GLuint *value); GL_APICALL void GL_APIENTRY glUniform2uiv (GLint location, GLsizei count, const GLuint *value); GL_APICALL void GL_APIENTRY glUniform3uiv (GLint location, GLsizei count, const GLuint *value); GL_APICALL void GL_APIENTRY glUniform4uiv (GLint location, GLsizei count, const GLuint *value); GL_APICALL void GL_APIENTRY glClearBufferiv (GLenum buffer, GLint drawbuffer, const GLint *value); GL_APICALL void GL_APIENTRY glClearBufferuiv (GLenum buffer, GLint drawbuffer, const GLuint *value); GL_APICALL void GL_APIENTRY glClearBufferfv (GLenum buffer, GLint drawbuffer, const GLfloat *value); GL_APICALL void GL_APIENTRY glClearBufferfi (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); GL_APICALL const GLubyte *GL_APIENTRY glGetStringi (GLenum name, GLuint index); GL_APICALL void GL_APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); GL_APICALL void GL_APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); GL_APICALL void GL_APIENTRY glGetActiveUniformsiv (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); GL_APICALL GLuint GL_APIENTRY glGetUniformBlockIndex (GLuint program, const GLchar *uniformBlockName); GL_APICALL void GL_APIENTRY glGetActiveUniformBlockiv (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetActiveUniformBlockName (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); GL_APICALL void GL_APIENTRY glUniformBlockBinding (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); GL_APICALL void GL_APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); GL_APICALL void GL_APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); GL_APICALL GLsync GL_APIENTRY glFenceSync (GLenum condition, GLbitfield flags); GL_APICALL GLboolean GL_APIENTRY glIsSync (GLsync sync); GL_APICALL void GL_APIENTRY glDeleteSync (GLsync sync); GL_APICALL GLenum GL_APIENTRY glClientWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); GL_APICALL void GL_APIENTRY glWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); GL_APICALL void GL_APIENTRY glGetInteger64v (GLenum pname, GLint64 *data); GL_APICALL void GL_APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); GL_APICALL void GL_APIENTRY glGetInteger64i_v (GLenum target, GLuint index, GLint64 *data); GL_APICALL void GL_APIENTRY glGetBufferParameteri64v (GLenum target, GLenum pname, GLint64 *params); GL_APICALL void GL_APIENTRY glGenSamplers (GLsizei count, GLuint *samplers); GL_APICALL void GL_APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers); GL_APICALL GLboolean GL_APIENTRY glIsSampler (GLuint sampler); GL_APICALL void GL_APIENTRY glBindSampler (GLuint unit, GLuint sampler); GL_APICALL void GL_APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param); GL_APICALL void GL_APIENTRY glSamplerParameteriv (GLuint sampler, GLenum pname, const GLint *param); GL_APICALL void GL_APIENTRY glSamplerParameterf (GLuint sampler, GLenum pname, GLfloat param); GL_APICALL void GL_APIENTRY glSamplerParameterfv (GLuint sampler, GLenum pname, const GLfloat *param); GL_APICALL void GL_APIENTRY glGetSamplerParameteriv (GLuint sampler, GLenum pname, GLint *params); GL_APICALL void GL_APIENTRY glGetSamplerParameterfv (GLuint sampler, GLenum pname, GLfloat *params); GL_APICALL void GL_APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor); GL_APICALL void GL_APIENTRY glBindTransformFeedback (GLenum target, GLuint id); GL_APICALL void GL_APIENTRY glDeleteTransformFeedbacks (GLsizei n, const GLuint *ids); GL_APICALL void GL_APIENTRY glGenTransformFeedbacks (GLsizei n, GLuint *ids); GL_APICALL GLboolean GL_APIENTRY glIsTransformFeedback (GLuint id); GL_APICALL void GL_APIENTRY glPauseTransformFeedback (void); GL_APICALL void GL_APIENTRY glResumeTransformFeedback (void); GL_APICALL void GL_APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); GL_APICALL void GL_APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); GL_APICALL void GL_APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value); GL_APICALL void GL_APIENTRY glInvalidateFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments); GL_APICALL void GL_APIENTRY glInvalidateSubFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); GL_APICALL void GL_APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); GL_APICALL void GL_APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); GL_APICALL void GL_APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); #endif #endif /* GL_ES_VERSION_3_0 */ #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
/****************************************************************************** * * Copyright(c) 2007 - 2014 Intel Corporation. All rights reserved. * * Portions of this file are derived from the ipw3945 project, as well * as portions of the ieee80211 subsystem header files. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * Intel Linux Wireless <[email protected]> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 *****************************************************************************/ #ifndef __iwl_tt_setting_h__ #define __iwl_tt_setting_h__ #include "commands.h" #define IWL_ABSOLUTE_ZERO 0 #define IWL_ABSOLUTE_MAX 0xFFFFFFFF #define IWL_TT_INCREASE_MARGIN 5 #define IWL_TT_CT_KILL_MARGIN 3 enum iwl_antenna_ok { IWL_ANT_OK_NONE, IWL_ANT_OK_SINGLE, IWL_ANT_OK_MULTI, }; /* Thermal Throttling State Machine states */ enum iwl_tt_state { IWL_TI_0, /* normal temperature, system power state */ IWL_TI_1, /* high temperature detect, low power state */ IWL_TI_2, /* higher temperature detected, lower power state */ IWL_TI_CT_KILL, /* critical temperature detected, lowest power state */ IWL_TI_STATE_MAX }; /** * struct iwl_tt_restriction - Thermal Throttling restriction table * @tx_stream: number of tx stream allowed * @is_ht: ht enable/disable * @rx_stream: number of rx stream allowed * * This table is used by advance thermal throttling management * based on the current thermal throttling state, and determines * the number of tx/rx streams and the status of HT operation. */ struct iwl_tt_restriction { enum iwl_antenna_ok tx_stream; enum iwl_antenna_ok rx_stream; bool is_ht; }; /** * struct iwl_tt_trans - Thermal Throttling transaction table * @next_state: next thermal throttling mode * @tt_low: low temperature threshold to change state * @tt_high: high temperature threshold to change state * * This is used by the advanced thermal throttling algorithm * to determine the next thermal state to go based on the * current temperature. */ struct iwl_tt_trans { enum iwl_tt_state next_state; u32 tt_low; u32 tt_high; }; /** * struct iwl_tt_mgnt - Thermal Throttling Management structure * @advanced_tt: advanced thermal throttle required * @state: current Thermal Throttling state * @tt_power_mode: Thermal Throttling power mode index * being used to set power level when * when thermal throttling state != IWL_TI_0 * the tt_power_mode should set to different * power mode based on the current tt state * @tt_previous_temperature: last measured temperature * @iwl_tt_restriction: ptr to restriction tbl, used by advance * thermal throttling to determine how many tx/rx streams * should be used in tt state; and can HT be enabled or not * @iwl_tt_trans: ptr to adv trans table, used by advance thermal throttling * state transaction * @ct_kill_toggle: used to toggle the CSR bit when checking uCode temperature * @ct_kill_exit_tm: timer to exit thermal kill */ struct iwl_tt_mgmt { enum iwl_tt_state state; bool advanced_tt; u8 tt_power_mode; bool ct_kill_toggle; #ifdef CONFIG_IWLWIFI_DEBUG s32 tt_previous_temp; #endif struct iwl_tt_restriction *restriction; struct iwl_tt_trans *transaction; struct timer_list ct_kill_exit_tm; struct timer_list ct_kill_waiting_tm; }; u8 iwl_tt_current_power_mode(struct iwl_priv *priv); bool iwl_tt_is_low_power_state(struct iwl_priv *priv); bool iwl_ht_enabled(struct iwl_priv *priv); enum iwl_antenna_ok iwl_tx_ant_restriction(struct iwl_priv *priv); enum iwl_antenna_ok iwl_rx_ant_restriction(struct iwl_priv *priv); void iwl_tt_enter_ct_kill(struct iwl_priv *priv); void iwl_tt_exit_ct_kill(struct iwl_priv *priv); void iwl_tt_handler(struct iwl_priv *priv); void iwl_tt_initialize(struct iwl_priv *priv); void iwl_tt_exit(struct iwl_priv *priv); #endif /* __iwl_tt_setting_h__ */
{ "pile_set_name": "Github" }
{ "FLAVOUR_0_INTRO": { "description": "", "message": "Avoid the inconvenience of a broken-down hyperspace engine. Get yours serviced today, by the officially endorsed {name} Engine Servicing Company.\n" }, "FLAVOUR_0_PRICE": { "description": "", "message": "\nEngine: {drive}\nService: {price}\nGuarantee: 18 months\n{lasttime}" }, "FLAVOUR_0_RESPONSE": { "description": "", "message": "Foi feita a manutenção ao seu motor." }, "FLAVOUR_0_TITLE": { "description": "", "message": "Engine Servicing Company {name}" }, "FLAVOUR_0_YESPLEASE": { "description": "", "message": "Reparação do motor de hyperspace" }, "FLAVOUR_1_INTRO": { "description": "", "message": "I'm {proprietor}. I can service your hyperdrive, guaranteeing at least a year of trouble-free performance. " }, "FLAVOUR_1_PRICE": { "description": "", "message": "The cost for servicing your {drive} will be {price}\n{lasttime}" }, "FLAVOUR_1_RESPONSE": { "description": "", "message": "Fiz a manutenção do hyperdrive." }, "FLAVOUR_1_TITLE": { "description": "", "message": "{proprietor}: especialista na manutenção de Hyperdrive" }, "FLAVOUR_1_YESPLEASE": { "description": "", "message": "Repare a minha drive" }, "FLAVOUR_2_INTRO": { "description": "", "message": "Hi there. We at {proprietor} & Co stake our reputation on our work.\nWe can tune your ship's hyperdrive, ensuring 12 months of trouble-free operation. " }, "FLAVOUR_2_PRICE": { "description": "", "message": "\n\n{lasttime}\nFor your {drive}, I'll be supervising the work myself, so you can be sure that a good job will be done, for the sum of {price}." }, "FLAVOUR_2_RESPONSE": { "description": "", "message": "Service complete. Thanks for your custom." }, "FLAVOUR_2_TITLE": { "description": "", "message": "{proprietor} & Co HyperMechanics" }, "FLAVOUR_2_YESPLEASE": { "description": "", "message": "Please tune my hyperdrive at the quoted price" }, "FLAVOUR_3_INTRO": { "description": "", "message": "Welcome SuperFix Maintenance. Time for your biannual maintenance? Let us SuperFix your hyperdrive!" }, "FLAVOUR_3_PRICE": { "description": "", "message": "\n\n{lasttime}\nWe can tune your {drive} for just {price}. There's nobody cheaper!" }, "FLAVOUR_3_RESPONSE": { "description": "", "message": "O serviço SuperFix está terminado, com garantia SuperFix!" }, "FLAVOUR_3_TITLE": { "description": "", "message": "Serviço SuperFix (filial {name})" }, "FLAVOUR_3_YESPLEASE": { "description": "", "message": "SuperFix-me!" }, "FLAVOUR_4_INTRO": { "description": "", "message": "Welcome to Time and Space.\n\nWe specialise in interstellar engines. All maintenance work guaranteed for two years." }, "FLAVOUR_4_PRICE": { "description": "", "message": "\n{lasttime}\nServicing your {drive} will cost {price}. Would you like to proceed?" }, "FLAVOUR_4_RESPONSE": { "description": "", "message": "Terminamos o trabalho no seu hyperdrive." }, "FLAVOUR_4_TITLE": { "description": "", "message": "Time and Space Engines, Inc." }, "FLAVOUR_4_YESPLEASE": { "description": "", "message": "Sim, continue por favor" }, "FLAVOUR_5_INTRO": { "description": "", "message": "Avoid the inconvenience of a broken-down hyperspace engine. Get yours serviced today.\n" }, "FLAVOUR_5_PRICE": { "description": "", "message": "\nEngine: {drive}\nService: {price}\n{lasttime}" }, "FLAVOUR_5_RESPONSE": { "description": "", "message": "Foi feita a manutenção ao seu motor." }, "FLAVOUR_5_TITLE": { "description": "", "message": "{proprietor} Engine Servicing Company" }, "FLAVOUR_5_YESPLEASE": { "description": "", "message": "Efetuar a manutenção do motor de hiperespaço" }, "I_DONT_HAVE_ENOUGH_MONEY": { "description": "", "message": "Não tenho créditos suficientes" }, "I_FIXED_THE_HYPERDRIVE_BEFORE_IT_BROKE_DOWN": { "description": "", "message": "Reparei a hyperdrive antes de avariar." }, "THE_SHIPS_HYPERDRIVE_HAS_BEEN_DESTROYED_BY_A_MALFUNCTION": { "description": "", "message": "O hyperdrive da nave foi destruída por uma avaria" }, "YOUR_DRIVE_HAS_NOT_BEEN_SERVICED": { "description": "", "message": "A sua drive ainda não teve manutenção desde que foi instalada em {date}" }, "YOUR_DRIVE_WAS_LAST_SERVICED_ON": { "description": "", "message": "A ultima manutenção da sua drive foi em {date} por {company}" }, "YOU_DO_NOT_HAVE_A_DRIVE_TO_SERVICE": { "description": "", "message": "Não tem uma drive para reparar!" }, "YOU_FIXED_THE_HYPERDRIVE_BEFORE_IT_BROKE_DOWN": { "description": "", "message": "Reparou o hyperdrive antes deste ter avariado." } }
{ "pile_set_name": "Github" }
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.github.mmin18.layoutcast.library"> <application android:allowBackup="true" android:label="@string/app_name" > </application> </manifest>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|ARM"> <Configuration>Debug</Configuration> <Platform>ARM</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|ARM"> <Configuration>Release</Configuration> <Platform>ARM</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{C5B886A7-8300-46FF-B533-9613DE2AF637}</ProjectGuid> <RootNamespace>WRLOutOfProcessWinRTComponent</RootNamespace> <DefaultLanguage>en-US</DefaultLanguage> <VCTargetsPath Condition="'$(VCTargetsPath11)' != '' and '$(VSVersion)' == '' and '$(VisualStudioVersion)' == ''">$(VCTargetsPath11)</VCTargetsPath> <MinimumVisualStudioVersion>11.0</MinimumVisualStudioVersion> <AppContainerApplication>true</AppContainerApplication> <ProjectName>WRLOutOfProcessWinRTComponent_client_cpp</ProjectName> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v110</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v110</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v110</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>true</WholeProgramOptimization> <PlatformToolset>v110</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>true</WholeProgramOptimization> <PlatformToolset>v110</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>true</WholeProgramOptimization> <PlatformToolset>v110</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <ItemDefinitionGroup> <ClCompile> <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile> </ClCompile> </ItemDefinitionGroup> <ItemGroup> <Reference Include="windows"> <IsWinMDFile>true</IsWinMDFile> </Reference> </ItemGroup> <ItemGroup> <ClInclude Include="Constants.h" /> <ClInclude Include="CustomException.xaml.h"> <DependentUpon>CustomException.xaml</DependentUpon> <SubType>Code</SubType> </ClInclude> <ClInclude Include="CustomExceptionWRL.xaml.h"> <DependentUpon>CustomExceptionWRL.xaml</DependentUpon> <SubType>Code</SubType> </ClInclude> <ClInclude Include="OvenClient.xaml.h"> <DependentUpon>OvenClient.xaml</DependentUpon> <SubType>Code</SubType> </ClInclude> <ClInclude Include="OvenClientWRL.xaml.h"> <DependentUpon>OvenClientWRL.xaml</DependentUpon> <SubType>Code</SubType> </ClInclude> <ClInclude Include="MainPage.xaml.h"> <DependentUpon>MainPage.xaml</DependentUpon> </ClInclude> <ClInclude Include="pch.h" /> <ClInclude Include="Common\LayoutAwarePage.h" /> <ClInclude Include="App.xaml.h"> <DependentUpon>App.xaml</DependentUpon> </ClInclude> <ClInclude Include="Sample-Utils\CppSamplesUtils.h" /> <ClInclude Include="Microsoft.SDKSamples.Kitchen.h"> <DependentUpon>Microsoft.SDKSamples.Kitchen.idl</DependentUpon> </ClInclude> </ItemGroup> <ItemGroup> <ApplicationDefinition Include="App.xaml"> <SubType>Designer</SubType> </ApplicationDefinition> <Page Include="Common\StandardStyles.xaml"> <SubType>Designer</SubType> </Page> <Page Include="CustomException.xaml"> <SubType>Designer</SubType> </Page> <Page Include="CustomExceptionWRL.xaml"> <SubType>Designer</SubType> </Page> <Page Include="OvenClient.xaml"> <SubType>Designer</SubType> </Page> <Page Include="OvenClientWRL.xaml"> <SubType>Designer</SubType> </Page> <Page Include="MainPage.xaml"> <SubType>Designer</SubType> </Page> <Page Include="Sample-Utils\SampleTemplateStyles.xaml"> <SubType>Designer</SubType> </Page> </ItemGroup> <ItemGroup> <AppxManifest Include="Package.appxmanifest"> <SubType>Designer</SubType> </AppxManifest> </ItemGroup> <ItemGroup> <ClCompile Include="App.xaml.cpp"> <DependentUpon>App.xaml</DependentUpon> </ClCompile> <ClCompile Include="Common\LayoutAwarePage.cpp" /> <ClCompile Include="Constants.cpp" /> <ClCompile Include="CustomException.xaml.cpp"> <DependentUpon>CustomException.xaml</DependentUpon> <SubType>Code</SubType> </ClCompile> <ClCompile Include="CustomExceptionWRL.xaml.cpp"> <DependentUpon>CustomExceptionWRL.xaml</DependentUpon> <SubType>Code</SubType> </ClCompile> <ClCompile Include="OvenClient.xaml.cpp"> <DependentUpon>OvenClient.xaml</DependentUpon> <SubType>Code</SubType> </ClCompile> <ClCompile Include="OvenClientWRL.xaml.cpp"> <DependentUpon>OvenClientWRL.xaml</DependentUpon> <SubType>Code</SubType> </ClCompile> <ClComplie Include="Sample-Utils\CppSamplesUtils.h" /> <ClCompile Include="MainPage.xaml.cpp"> <DependentUpon>MainPage.xaml</DependentUpon> </ClCompile> <ClCompile Include="pch.cpp"> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader> </ClCompile> </ItemGroup> <ItemGroup> <Image Include="Assets\microsoft-sdk.png" /> <Image Include="Assets\placeholder-sdk.png" /> <Image Include="Assets\smallTile-sdk.png" /> <Image Include="Assets\splash-sdk.png" /> <Image Include="Assets\squareTile-sdk.png" /> <Image Include="Assets\storeLogo-sdk.png" /> <Image Include="Assets\tile-sdk.png" /> <Image Include="Assets\windows-sdk.png" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Server\WRLOutOfProcessWinRTComponent_server.vcxproj" /> <ProjectReference Include="..\Server\WRLOutOfProcessWinRTComponentPS.vcxproj" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ItemDefinitionGroup Condition="('$(Configuration)'=='Debug' or '$(Configuration)'=='Release') and ('$(Platform)'=='Win32' or '$(Platform)'=='x64' or '$(Platform)'=='ARM')"> <ClCompile> <AdditionalIncludeDirectories> %(AdditionalIncludeDirectories); ..\Server\; </AdditionalIncludeDirectories> </ClCompile> </ItemDefinitionGroup> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
{ "pile_set_name": "Github" }
/* Copyright (c) 2011-2013 Gerhard Reitmayr, TU Graz 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. */ #include "kfusion.h" #undef isnan #undef isfinite #include <iostream> #include <TooN/TooN.h> #include <TooN/se3.h> #include <TooN/GR_SVD.h> #define INVALID -2 // this is used to mark invalid entries in normal or vertex maps using namespace std; __global__ void initVolume( Volume volume, const float2 val ){ uint3 pos = make_uint3(thr2pos2()); for(pos.z = 0; pos.z < volume.size.z; ++pos.z) volume.set(pos, val); } __global__ void raycast( Image<float3> pos3D, Image<float3> normal, const Volume volume, const Matrix4 view, const float nearPlane, const float farPlane, const float step, const float largestep){ const uint2 pos = thr2pos2(); const float4 hit = raycast( volume, pos, view, nearPlane, farPlane, step, largestep ); if(hit.w > 0){ pos3D[pos] = make_float3(hit); float3 surfNorm = volume.grad(make_float3(hit)); if(length(surfNorm) == 0){ normal[pos].x = INVALID; } else { normal[pos] = normalize(surfNorm); } } else { pos3D[pos] = make_float3(0); normal[pos] = make_float3(INVALID, 0, 0); } } __forceinline__ __device__ float sq( const float x ){ return x*x; } __global__ void integrate( Volume vol, const Image<float> depth, const Matrix4 invTrack, const Matrix4 K, const float mu, const float maxweight){ uint3 pix = make_uint3(thr2pos2()); float3 pos = invTrack * vol.pos(pix); float3 cameraX = K * pos; const float3 delta = rotate(invTrack, make_float3(0,0, vol.dim.z / vol.size.z)); const float3 cameraDelta = rotate(K, delta); for(pix.z = 0; pix.z < vol.size.z; ++pix.z, pos += delta, cameraX += cameraDelta){ if(pos.z < 0.0001f) // some near plane constraint continue; const float2 pixel = make_float2(cameraX.x/cameraX.z + 0.5f, cameraX.y/cameraX.z + 0.5f); if(pixel.x < 0 || pixel.x > depth.size.x-1 || pixel.y < 0 || pixel.y > depth.size.y-1) continue; const uint2 px = make_uint2(pixel.x, pixel.y); if(depth[px] == 0) continue; const float diff = (depth[px] - cameraX.z) * sqrt(1+sq(pos.x/pos.z) + sq(pos.y/pos.z)); if(diff > -mu){ const float sdf = fminf(1.f, diff/mu); float2 data = vol[pix]; data.x = clamp((data.y*data.x + sdf)/(data.y + 1), -1.f, 1.f); data.y = fminf(data.y+1, maxweight); vol.set(pix, data); } } } __global__ void depth2vertex( Image<float3> vertex, const Image<float> depth, const Matrix4 invK ){ const uint2 pixel = thr2pos2(); if(pixel.x >= depth.size.x || pixel.y >= depth.size.y ) return; if(depth[pixel] > 0){ vertex[pixel] = depth[pixel] * (rotate(invK, make_float3(pixel.x, pixel.y, 1.f))); } else { vertex[pixel] = make_float3(0); } } __global__ void vertex2normal( Image<float3> normal, const Image<float3> vertex ){ const uint2 pixel = thr2pos2(); if(pixel.x >= vertex.size.x || pixel.y >= vertex.size.y ) return; const float3 left = vertex[make_uint2(max(int(pixel.x)-1,0), pixel.y)]; const float3 right = vertex[make_uint2(min(pixel.x+1,vertex.size.x-1), pixel.y)]; const float3 up = vertex[make_uint2(pixel.x, max(int(pixel.y)-1,0))]; const float3 down = vertex[make_uint2(pixel.x, min(pixel.y+1,vertex.size.y-1))]; if(left.z == 0 || right.z == 0 || up.z == 0 || down.z == 0) { normal[pixel].x = INVALID; return; } const float3 dxv = right - left; const float3 dyv = down - up; normal[pixel] = normalize(cross(dyv, dxv)); // switched dx and dy to get factor -1 } template <int HALFSAMPLE> __global__ void mm2meters( Image<float> depth, const Image<ushort> in ){ const uint2 pixel = thr2pos2(); depth[pixel] = in[pixel * (HALFSAMPLE+1)] / 1000.0f; } //column pass using coalesced global memory reads __global__ void bilateral_filter(Image<float> out, const Image<float> in, const Image<float> gaussian, const float e_d, const int r) { const uint2 pos = thr2pos2(); if(in[pos] == 0){ out[pos] = 0; return; } float sum = 0.0f; float t = 0.0f; const float center = in[pos]; for(int i = -r; i <= r; ++i) { for(int j = -r; j <= r; ++j) { const float curPix = in[make_uint2(clamp(pos.x + i, 0u, in.size.x-1), clamp(pos.y + j, 0u, in.size.y-1))]; if(curPix > 0){ const float mod = sq(curPix - center); const float factor = gaussian[make_uint2(i + r, 0)] * gaussian[make_uint2(j + r, 0)] * __expf(-mod / (2 * e_d * e_d)); t += factor * curPix; sum += factor; } } } out[pos] = t / sum; } // filter and halfsample __global__ void halfSampleRobust( Image<float> out, const Image<float> in, const float e_d, const int r){ const uint2 pixel = thr2pos2(); const uint2 centerPixel = 2 * pixel; if(pixel.x >= out.size.x || pixel.y >= out.size.y ) return; float sum = 0.0f; float t = 0.0f; const float center = in[centerPixel]; for(int i = -r + 1; i <= r; ++i){ for(int j = -r + 1; j <= r; ++j){ float current = in[make_uint2(clamp(make_int2(centerPixel.x + j, centerPixel.y + i), make_int2(0), make_int2(in.size.x - 1, in.size.y - 1)))]; // TODO simplify this! if(fabsf(current - center) < e_d){ sum += 1.0f; t += current; } } } out[pixel] = t / sum; } __global__ void generate_gaussian(Image<float> out, float delta, int radius) { int x = threadIdx.x - radius; out[make_uint2(threadIdx.x,0)] = __expf(-(x * x) / (2 * delta * delta)); } __global__ void track( Image<TrackData> output, const Image<float3> inVertex, const Image<float3> inNormal , const Image<float3> refVertex, const Image<float3> refNormal, const Matrix4 Ttrack, const Matrix4 view, const float dist_threshold, const float normal_threshold ) { const uint2 pixel = thr2pos2(); if(pixel.x >= inVertex.size.x || pixel.y >= inVertex.size.y ) return; TrackData & row = output[pixel]; if(inNormal[pixel].x == INVALID ){ row.result = -1; return; } const float3 projectedVertex = Ttrack * inVertex[pixel]; const float3 projectedPos = view * projectedVertex; const float2 projPixel = make_float2( projectedPos.x / projectedPos.z + 0.5f, projectedPos.y / projectedPos.z + 0.5f); if(projPixel.x < 0 || projPixel.x > refVertex.size.x-1 || projPixel.y < 0 || projPixel.y > refVertex.size.y-1 ){ row.result = -2; return; } const uint2 refPixel = make_uint2(projPixel.x, projPixel.y); const float3 referenceNormal = refNormal[refPixel]; if(referenceNormal.x == INVALID){ row.result = -3; return; } const float3 diff = refVertex[refPixel] - projectedVertex; const float3 projectedNormal = rotate(Ttrack, inNormal[pixel]); if(length(diff) > dist_threshold ){ row.result = -4; return; } if(dot(projectedNormal, referenceNormal) < normal_threshold){ row.result = -5; return; } row.result = 1; row.error = dot(referenceNormal, diff); ((float3 *)row.J)[0] = referenceNormal; ((float3 *)row.J)[1] = cross(projectedVertex, referenceNormal); } __global__ void reduce( float * out, const Image<TrackData> J, const uint2 size){ __shared__ float S[112][32]; // this is for the final accumulation const uint sline = threadIdx.x; float sums[32]; float * jtj = sums + 7; float * info = sums + 28; for(uint i = 0; i < 32; ++i) sums[i] = 0; for(uint y = blockIdx.x; y < size.y; y += gridDim.x){ for(uint x = sline; x < size.x; x += blockDim.x ){ const TrackData & row = J[make_uint2(x, y)]; if(row.result < 1){ info[1] += row.result == -4 ? 1 : 0; info[2] += row.result == -5 ? 1 : 0; info[3] += row.result > -4 ? 1 : 0; continue; } // Error part sums[0] += row.error * row.error; // JTe part for(int i = 0; i < 6; ++i) sums[i+1] += row.error * row.J[i]; // JTJ part, unfortunatly the double loop is not unrolled well... jtj[0] += row.J[0] * row.J[0]; jtj[1] += row.J[0] * row.J[1]; jtj[2] += row.J[0] * row.J[2]; jtj[3] += row.J[0] * row.J[3]; jtj[4] += row.J[0] * row.J[4]; jtj[5] += row.J[0] * row.J[5]; jtj[6] += row.J[1] * row.J[1]; jtj[7] += row.J[1] * row.J[2]; jtj[8] += row.J[1] * row.J[3]; jtj[9] += row.J[1] * row.J[4]; jtj[10] += row.J[1] * row.J[5]; jtj[11] += row.J[2] * row.J[2]; jtj[12] += row.J[2] * row.J[3]; jtj[13] += row.J[2] * row.J[4]; jtj[14] += row.J[2] * row.J[5]; jtj[15] += row.J[3] * row.J[3]; jtj[16] += row.J[3] * row.J[4]; jtj[17] += row.J[3] * row.J[5]; jtj[18] += row.J[4] * row.J[4]; jtj[19] += row.J[4] * row.J[5]; jtj[20] += row.J[5] * row.J[5]; // extra info here info[0] += 1; } } for(int i = 0; i < 32; ++i) // copy over to shared memory S[sline][i] = sums[i]; __syncthreads(); // wait for everyone to finish if(sline < 32){ // sum up columns and copy to global memory in the final 32 threads for(unsigned i = 1; i < blockDim.x; ++i) S[0][sline] += S[i][sline]; out[sline+blockIdx.x*32] = S[0][sline]; } } __global__ void trackAndReduce( float * out, const Image<float3> inVertex, const Image<float3> inNormal , const Image<float3> refVertex, const Image<float3> refNormal, const Matrix4 Ttrack, const Matrix4 view, const float dist_threshold, const float normal_threshold ){ __shared__ float S[112][32]; // this is for the final accumulation const uint sline = threadIdx.x; float sums[32]; float * jtj = sums + 7; float * info = sums + 28; for(uint i = 0; i < 32; ++i) sums[i] = 0; float J[6]; for(uint y = blockIdx.x; y < inVertex.size.y; y += gridDim.x){ for(uint x = sline; x < inVertex.size.x; x += blockDim.x ){ const uint2 pixel = make_uint2(x,y); if(inNormal[pixel].x == INVALID){ continue; } const float3 projectedVertex = Ttrack * inVertex[pixel]; const float3 projectedPos = view * projectedVertex; const float2 projPixel = make_float2( projectedPos.x / projectedPos.z + 0.5f, projectedPos.y / projectedPos.z + 0.5f); if(projPixel.x < 0 || projPixel.x > refVertex.size.x-1 || projPixel.y < 0 || projPixel.y > refVertex.size.y-1 ){ info[3] += 1; continue; } const uint2 refPixel = make_uint2(projPixel.x, projPixel.y); if(refNormal[refPixel].x == INVALID){ info[3] += 1; continue; } const float3 referenceNormal = refNormal[refPixel]; const float3 diff = refVertex[refPixel] - projectedVertex; const float3 projectedNormal = rotate(Ttrack, inNormal[pixel]); if(length(diff) > dist_threshold ){ info[1] += 1; continue; } if(dot(projectedNormal, referenceNormal) < normal_threshold){ info[2] += 1; continue; } const float error = dot(referenceNormal, diff); ((float3 *)J)[0] = referenceNormal; ((float3 *)J)[1] = cross(projectedVertex, referenceNormal); // Error part sums[0] += error * error; // JTe part for(int i = 0; i < 6; ++i) sums[i+1] += error * J[i]; // JTJ part jtj[0] += J[0] * J[0]; jtj[1] += J[0] * J[1]; jtj[2] += J[0] * J[2]; jtj[3] += J[0] * J[3]; jtj[4] += J[0] * J[4]; jtj[5] += J[0] * J[5]; jtj[6] += J[1] * J[1]; jtj[7] += J[1] * J[2]; jtj[8] += J[1] * J[3]; jtj[9] += J[1] * J[4]; jtj[10] += J[1] * J[5]; jtj[11] += J[2] * J[2]; jtj[12] += J[2] * J[3]; jtj[13] += J[2] * J[4]; jtj[14] += J[2] * J[5]; jtj[15] += J[3] * J[3]; jtj[16] += J[3] * J[4]; jtj[17] += J[3] * J[5]; jtj[18] += J[4] * J[4]; jtj[19] += J[4] * J[5]; jtj[20] += J[5] * J[5]; // extra info here info[0] += 1; } } for(int i = 0; i < 32; ++i) // copy over to shared memory S[sline][i] = sums[i]; __syncthreads(); // wait for everyone to finish if(sline < 32){ // sum up columns and copy to global memory in the final 32 threads for(unsigned i = 1; i < blockDim.x; ++i) S[0][sline] += S[i][sline]; out[sline+blockIdx.x*32] = S[0][sline]; } } void KFusion::Init( const KFusionConfig & config ) { configuration = config; cudaSetDeviceFlags(cudaDeviceMapHost); integration.init(config.volumeSize, config.volumeDimensions); reduction.alloc(config.inputSize); vertex.alloc(config.inputSize); normal.alloc(config.inputSize); rawDepth.alloc(config.inputSize); inputDepth.resize(config.iterations.size()); inputVertex.resize(config.iterations.size()); inputNormal.resize(config.iterations.size()); for(int i = 0; i < config.iterations.size(); ++i){ inputDepth[i].alloc(config.inputSize >> i); inputVertex[i].alloc(config.inputSize >> i); inputNormal[i].alloc(config.inputSize >> i); } gaussian.alloc(make_uint2(config.radius * 2 + 1, 1)); output.alloc(make_uint2(32,8)); //generate gaussian array generate_gaussian<<< 1, gaussian.size.x>>>(gaussian, config.delta, config.radius); Reset(); } void KFusion::Reset(){ dim3 block(32,16); dim3 grid = divup(dim3(integration.size.x, integration.size.y), block); initVolume<<<grid, block>>>(integration, make_float2(1.0f, 0.0f)); } void KFusion::Clear(){ integration.release(); } void KFusion::setPose( const Matrix4 & p ){ pose = p; } void KFusion::setKinectDeviceDepth( const Image<uint16_t> & in){ if(configuration.inputSize.x == in.size.x) mm2meters<0><<<divup(rawDepth.size, configuration.imageBlock), configuration.imageBlock>>>(rawDepth, in); else if(configuration.inputSize.x == in.size.x / 2 ) mm2meters<1><<<divup(rawDepth.size, configuration.imageBlock), configuration.imageBlock>>>(rawDepth, in); else assert(false); } Matrix4 operator*( const Matrix4 & A, const Matrix4 & B){ Matrix4 R; TooN::wrapMatrix<4,4>(&R.data[0].x) = TooN::wrapMatrix<4,4>(&A.data[0].x) * TooN::wrapMatrix<4,4>(&B.data[0].x); return R; } template<typename P> inline Matrix4 toMatrix4( const TooN::SE3<P> & p){ const TooN::Matrix<4, 4, float> I = TooN::Identity; Matrix4 R; TooN::wrapMatrix<4,4>(&R.data[0].x) = p * I; return R; } Matrix4 inverse( const Matrix4 & A ){ static TooN::Matrix<4, 4, float> I = TooN::Identity; TooN::Matrix<4,4,float> temp = TooN::wrapMatrix<4,4>(&A.data[0].x); Matrix4 R; TooN::wrapMatrix<4,4>(&R.data[0].x) = TooN::gaussian_elimination(temp , I ); return R; } std::ostream & operator<<( std::ostream & out, const Matrix4 & m ){ for(unsigned i = 0; i < 4; ++i) out << m.data[i].x << " " << m.data[i].y << " " << m.data[i].z << " " << m.data[i].w << "\n"; return out; } template <typename P, typename A> TooN::Matrix<6> makeJTJ( const TooN::Vector<21, P, A> & v ){ TooN::Matrix<6> C = TooN::Zeros; C[0] = v.template slice<0,6>(); C[1].template slice<1,5>() = v.template slice<6,5>(); C[2].template slice<2,4>() = v.template slice<11,4>(); C[3].template slice<3,3>() = v.template slice<15,3>(); C[4].template slice<4,2>() = v.template slice<18,2>(); C[5][5] = v[20]; for(int r = 1; r < 6; ++r) for(int c = 0; c < r; ++c) C[r][c] = C[c][r]; return C; } template <typename T, typename A> TooN::Vector<6> solve( const TooN::Vector<27, T, A> & vals ){ const TooN::Vector<6> b = vals.template slice<0,6>(); const TooN::Matrix<6> C = makeJTJ(vals.template slice<6,21>()); TooN::GR_SVD<6,6> svd(C); return svd.backsub(b, 1e6); } void KFusion::Raycast(){ // raycast integration volume into the depth, vertex, normal buffers raycastPose = pose; raycast<<<divup(configuration.inputSize, configuration.raycastBlock), configuration.raycastBlock>>>(vertex, normal, integration, raycastPose * getInverseCameraMatrix(configuration.camera), configuration.nearPlane, configuration.farPlane, configuration.stepSize(), 0.75f * configuration.mu); } bool KFusion::Track() { const Matrix4 invK = getInverseCameraMatrix(configuration.camera); vector<dim3> grids; for(int i = 0; i < configuration.iterations.size(); ++i) grids.push_back(divup(configuration.inputSize >> i, configuration.imageBlock)); // filter the input depth map bilateral_filter<<<grids[0], configuration.imageBlock>>>(inputDepth[0], rawDepth, gaussian, configuration.e_delta, configuration.radius); // half sample the input depth maps into the pyramid levels for(int i = 1; i < configuration.iterations.size(); ++i) halfSampleRobust<<<grids[i], configuration.imageBlock>>>(inputDepth[i], inputDepth[i-1], configuration.e_delta * 3, 1); // prepare the 3D information from the input depth maps for(int i = 0; i < configuration.iterations.size(); ++i){ depth2vertex<<<grids[i], configuration.imageBlock>>>( inputVertex[i], inputDepth[i], getInverseCameraMatrix(configuration.camera / float(1 << i))); // inverse camera matrix depends on level vertex2normal<<<grids[i], configuration.imageBlock>>>( inputNormal[i], inputVertex[i] ); } const Matrix4 oldPose = pose; const Matrix4 projectReference = getCameraMatrix(configuration.camera) * inverse(raycastPose); TooN::Matrix<8, 32, float, TooN::Reference::RowMajor> values(output.data()); for(int level = configuration.iterations.size()-1; level >= 0; --level){ for(int i = 0; i < configuration.iterations[level]; ++i){ if(configuration.combinedTrackAndReduce){ trackAndReduce<<<8, 112>>>( output.getDeviceImage().data(), inputVertex[level], inputNormal[level], vertex, normal, pose, projectReference, configuration.dist_threshold, configuration.normal_threshold ); } else { track<<<grids[level], configuration.imageBlock>>>( reduction, inputVertex[level], inputNormal[level], vertex, normal, pose, projectReference, configuration.dist_threshold, configuration.normal_threshold); reduce<<<8, 112>>>( output.getDeviceImage().data(), reduction, inputVertex[level].size ); // compute the linear system to solve } cudaDeviceSynchronize(); // important due to async nature of kernel call for(int j = 1; j < 8; ++j) values[0] += values[j]; TooN::Vector<6> x = solve(values[0].slice<1,27>()); TooN::SE3<> delta(x); pose = toMatrix4( delta ) * pose; if(norm(x) < 1e-5) break; } } // test on both RSME per pixel and percent of pixels tracked if((sqrt(values(0,0) / values(0,28)) > 2e-2) || (values(0,28) / (rawDepth.size.x * rawDepth.size.y) < configuration.track_threshold) ){ pose = oldPose; return false; } return true; } void KFusion::Integrate() { integrate<<<divup(dim3(integration.size.x, integration.size.y), configuration.imageBlock), configuration.imageBlock>>>( integration, rawDepth, inverse(pose), getCameraMatrix(configuration.camera), configuration.mu, configuration.maxweight ); } int printCUDAError() { cudaError_t error = cudaGetLastError(); if(error) std::cout << cudaGetErrorString(error) << std::endl; return error; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Bucket type = "1" version = "2.0"> <Breakpoints> <BreakpointProxy BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> <BreakpointContent shouldBeEnabled = "Yes" ignoreCount = "0" continueAfterRunningActions = "No" filePath = "PustTest/ViewController.m" timestampString = "516942536.340725" startingColumnNumber = "9223372036854775807" endingColumnNumber = "9223372036854775807" startingLineNumber = "31" endingLineNumber = "31" landmarkName = "-clickFire:" landmarkType = "7"> </BreakpointContent> </BreakpointProxy> <BreakpointProxy BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint"> <BreakpointContent shouldBeEnabled = "Yes" ignoreCount = "0" continueAfterRunningActions = "No" filePath = "PustTest/ViewController.m" timestampString = "516942599.33064" startingColumnNumber = "9223372036854775807" endingColumnNumber = "9223372036854775807" startingLineNumber = "40" endingLineNumber = "40" landmarkName = "-clickFire:" landmarkType = "7"> </BreakpointContent> </BreakpointProxy> </Breakpoints> </Bucket>
{ "pile_set_name": "Github" }
#ifndef BOOST_MPL_AUX_JOINT_ITER_HPP_INCLUDED #define BOOST_MPL_AUX_JOINT_ITER_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: joint_iter.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/next_prior.hpp> #include <boost/mpl/deref.hpp> #include <boost/mpl/iterator_tags.hpp> #include <boost/mpl/aux_/lambda_spec.hpp> #include <boost/mpl/aux_/config/ctps.hpp> #if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) # include <boost/type_traits/is_same.hpp> #endif namespace boost { namespace mpl { #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template< typename Iterator1 , typename LastIterator1 , typename Iterator2 > struct joint_iter { typedef Iterator1 base; typedef forward_iterator_tag category; }; template< typename LastIterator1 , typename Iterator2 > struct joint_iter<LastIterator1,LastIterator1,Iterator2> { typedef Iterator2 base; typedef forward_iterator_tag category; }; template< typename I1, typename L1, typename I2 > struct deref< joint_iter<I1,L1,I2> > { typedef typename joint_iter<I1,L1,I2>::base base_; typedef typename deref<base_>::type type; }; template< typename I1, typename L1, typename I2 > struct next< joint_iter<I1,L1,I2> > { typedef joint_iter< typename mpl::next<I1>::type,L1,I2 > type; }; template< typename L1, typename I2 > struct next< joint_iter<L1,L1,I2> > { typedef joint_iter< L1,L1,typename mpl::next<I2>::type > type; }; #else // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template< typename Iterator1 , typename LastIterator1 , typename Iterator2 > struct joint_iter; template< bool > struct joint_iter_impl { template< typename I1, typename L1, typename I2 > struct result_ { typedef I1 base; typedef forward_iterator_tag category; typedef joint_iter< typename mpl::next<I1>::type,L1,I2 > next; typedef typename deref<I1>::type type; }; }; template<> struct joint_iter_impl<true> { template< typename I1, typename L1, typename I2 > struct result_ { typedef I2 base; typedef forward_iterator_tag category; typedef joint_iter< L1,L1,typename mpl::next<I2>::type > next; typedef typename deref<I2>::type type; }; }; template< typename Iterator1 , typename LastIterator1 , typename Iterator2 > struct joint_iter : joint_iter_impl< is_same<Iterator1,LastIterator1>::value > ::template result_<Iterator1,LastIterator1,Iterator2> { }; #endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION BOOST_MPL_AUX_PASS_THROUGH_LAMBDA_SPEC(3, joint_iter) }} #endif // BOOST_MPL_AUX_JOINT_ITER_HPP_INCLUDED
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: b18c7ae976868a4499e2dbd7f60e92a4 folderAsset: yes timeCreated: 1467313717 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
# sonic centec one image installer SONIC_ONE_IMAGE = sonic-centec.bin $(SONIC_ONE_IMAGE)_MACHINE = centec $(SONIC_ONE_IMAGE)_IMAGE_TYPE = onie $(SONIC_ONE_IMAGE)_INSTALLS = $(SYSTEMD_SONIC_GENERATOR) $(SONIC_ONE_IMAGE)_LAZY_INSTALLS += $(CENTEC_E582_48X6Q_PLATFORM_MODULE) \ $(CENTEC_E582_48X2Q4Z_PLATFORM_MODULE) \ $(EMBEDWAY_ES6220_PLATFORM_MODULE) ifeq ($(INSTALL_DEBUG_TOOLS),y) $(SONIC_ONE_IMAGE)_DOCKERS += $(SONIC_INSTALL_DOCKER_DBG_IMAGES) $(SONIC_ONE_IMAGE)_DOCKERS += $(filter-out $(patsubst %-$(DBG_IMAGE_MARK).gz,%.gz, $(SONIC_INSTALL_DOCKER_DBG_IMAGES)), $(SONIC_INSTALL_DOCKER_IMAGES)) else $(SONIC_ONE_IMAGE)_DOCKERS = $(SONIC_INSTALL_DOCKER_IMAGES) endif SONIC_INSTALLERS += $(SONIC_ONE_IMAGE)
{ "pile_set_name": "Github" }
#include <windows.h> #include <stdio.h> LRESULT WINAPI MainWndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { WNDCLASS wc; MSG msg; HWND hWnd; wc.lpszClassName = "ClipClass"; wc.lpfnWndProc = MainWndProc; wc.style = CS_VREDRAW | CS_HREDRAW; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, (LPCTSTR)IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, (LPCTSTR)IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH); wc.lpszMenuName = NULL; wc.cbClsExtra = 0; wc.cbWndExtra = 0; if (RegisterClass(&wc) == 0) { fprintf(stderr, "RegisterClass failed (last error 0x%lX)\n", GetLastError()); return(1); } hWnd = CreateWindow("ClipClass", "Line clipping test", WS_OVERLAPPEDWINDOW|WS_HSCROLL|WS_VSCROLL, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); if (hWnd == NULL) { fprintf(stderr, "CreateWindow failed (last error 0x%lX)\n", GetLastError()); return(1); } ShowWindow(hWnd, nCmdShow); while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } static void DrawLines(HDC hDC) { static struct { int fromx; int fromy; int tox; int toy; } points[ ] = { { 50, 99, 125, 99 }, { 160, 99, 190, 99 }, { 300, 99, 225, 99 }, { 50, 100, 125, 100 }, { 160, 100, 190, 100 }, { 300, 100, 225, 100 }, { 50, 125, 300, 125 }, { 50, 149, 125, 149 }, { 160, 149, 190, 149 }, { 300, 149, 225, 149 }, { 50, 150, 125, 150 }, { 160, 150, 190, 150 }, { 300, 150, 225, 150 }, { 160, 249, 190, 249 }, { 160, 250, 190, 250 }, { 149, 50, 149, 125 }, { 149, 160, 149, 190 }, { 149, 300, 149, 225 }, { 150, 50, 150, 125 }, { 150, 160, 150, 190 }, { 150, 300, 150, 225 }, { 199, 50, 199, 125 }, { 199, 160, 199, 190 }, { 199, 300, 199, 225 }, { 200, 50, 200, 125 }, { 200, 160, 200, 190 }, { 200, 300, 200, 225 }, { 175, 50, 175, 300 }, { 50, 55, 300, 290 }, { 300, 295, 50, 60 }, { 50, 290, 300, 55 }, { 300, 60, 50, 295 }, { 55, 50, 290, 300 }, { 295, 300, 60, 50 }, { 55, 300, 290, 50 }, { 295, 50, 60, 300 } }; int i; for (i = 0; i < sizeof(points) / sizeof(points[0]); i++) { MoveToEx(hDC, points[i].fromx, points[i].fromy, NULL); LineTo(hDC, points[i].tox, points[i].toy); } } LRESULT CALLBACK MainWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hDC; RECT clr; HRGN ClipRgn, ExcludeRgn; RECT Rect; switch(msg) { case WM_PAINT: GetClientRect(hWnd, &clr); ClipRgn = CreateRectRgnIndirect(&clr); hDC = BeginPaint(hWnd, &ps); Rect.left = 100; Rect.top = 100; Rect.right = 250; Rect.bottom = 150; FillRect(hDC, &Rect, CreateSolidBrush(RGB(0xFF, 0x00, 0x00))); ExcludeRgn = CreateRectRgnIndirect(&Rect); CombineRgn(ClipRgn, ClipRgn, ExcludeRgn, RGN_DIFF); DeleteObject(ExcludeRgn); Rect.left = 150; Rect.top = 150; Rect.right = 200; Rect.bottom = 250; FillRect(hDC, &Rect, CreateSolidBrush(RGB(0xFF, 0x00, 0x00))); SelectObject(hDC, CreatePen(PS_SOLID, 0, RGB(0xFF, 0xFF, 0x00))); DrawLines(hDC); SelectObject(hDC, CreatePen(PS_SOLID, 0, RGB(0x00, 0x00, 0xFF))); ExcludeRgn = CreateRectRgnIndirect(&Rect); CombineRgn(ClipRgn, ClipRgn, ExcludeRgn, RGN_DIFF); DeleteObject(ExcludeRgn); SelectClipRgn(hDC, ClipRgn); DrawLines(hDC); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; }
{ "pile_set_name": "Github" }
// included by json_value.cpp // everything is within Json namespace // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class ValueInternalArray // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// ValueArrayAllocator::~ValueArrayAllocator() { } // ////////////////////////////////////////////////////////////////// // class DefaultValueArrayAllocator // ////////////////////////////////////////////////////////////////// #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR class DefaultValueArrayAllocator : public ValueArrayAllocator { public: // overridden from ValueArrayAllocator virtual ~DefaultValueArrayAllocator() { } virtual ValueInternalArray *newArray() { return new ValueInternalArray(); } virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) { return new ValueInternalArray( other ); } virtual void destructArray( ValueInternalArray *array ) { delete array; } virtual void reallocateArrayPageIndex( Value **&indexes, ValueInternalArray::PageIndex &indexCount, ValueInternalArray::PageIndex minNewIndexCount ) { ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1; if ( minNewIndexCount > newIndexCount ) newIndexCount = minNewIndexCount; void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount ); if ( !newIndexes ) throw std::bad_alloc(); indexCount = newIndexCount; indexes = static_cast<Value **>( newIndexes ); } virtual void releaseArrayPageIndex( Value **indexes, ValueInternalArray::PageIndex indexCount ) { if ( indexes ) free( indexes ); } virtual Value *allocateArrayPage() { return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) ); } virtual void releaseArrayPage( Value *value ) { if ( value ) free( value ); } }; #else // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR /// @todo make this thread-safe (lock when accessign batch allocator) class DefaultValueArrayAllocator : public ValueArrayAllocator { public: // overridden from ValueArrayAllocator virtual ~DefaultValueArrayAllocator() { } virtual ValueInternalArray *newArray() { ValueInternalArray *array = arraysAllocator_.allocate(); new (array) ValueInternalArray(); // placement new return array; } virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) { ValueInternalArray *array = arraysAllocator_.allocate(); new (array) ValueInternalArray( other ); // placement new return array; } virtual void destructArray( ValueInternalArray *array ) { if ( array ) { array->~ValueInternalArray(); arraysAllocator_.release( array ); } } virtual void reallocateArrayPageIndex( Value **&indexes, ValueInternalArray::PageIndex &indexCount, ValueInternalArray::PageIndex minNewIndexCount ) { ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1; if ( minNewIndexCount > newIndexCount ) newIndexCount = minNewIndexCount; void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount ); if ( !newIndexes ) throw std::bad_alloc(); indexCount = newIndexCount; indexes = static_cast<Value **>( newIndexes ); } virtual void releaseArrayPageIndex( Value **indexes, ValueInternalArray::PageIndex indexCount ) { if ( indexes ) free( indexes ); } virtual Value *allocateArrayPage() { return static_cast<Value *>( pagesAllocator_.allocate() ); } virtual void releaseArrayPage( Value *value ) { if ( value ) pagesAllocator_.release( value ); } private: BatchAllocator<ValueInternalArray,1> arraysAllocator_; BatchAllocator<Value,ValueInternalArray::itemsPerPage> pagesAllocator_; }; #endif // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR static ValueArrayAllocator *&arrayAllocator() { static DefaultValueArrayAllocator defaultAllocator; static ValueArrayAllocator *arrayAllocator = &defaultAllocator; return arrayAllocator; } static struct DummyArrayAllocatorInitializer { DummyArrayAllocatorInitializer() { arrayAllocator(); // ensure arrayAllocator() statics are initialized before main(). } } dummyArrayAllocatorInitializer; // ////////////////////////////////////////////////////////////////// // class ValueInternalArray // ////////////////////////////////////////////////////////////////// bool ValueInternalArray::equals( const IteratorState &x, const IteratorState &other ) { return x.array_ == other.array_ && x.currentItemIndex_ == other.currentItemIndex_ && x.currentPageIndex_ == other.currentPageIndex_; } void ValueInternalArray::increment( IteratorState &it ) { JSON_ASSERT_MESSAGE( it.array_ && (it.currentPageIndex_ - it.array_->pages_)*itemsPerPage + it.currentItemIndex_ != it.array_->size_, "ValueInternalArray::increment(): moving iterator beyond end" ); ++(it.currentItemIndex_); if ( it.currentItemIndex_ == itemsPerPage ) { it.currentItemIndex_ = 0; ++(it.currentPageIndex_); } } void ValueInternalArray::decrement( IteratorState &it ) { JSON_ASSERT_MESSAGE( it.array_ && it.currentPageIndex_ == it.array_->pages_ && it.currentItemIndex_ == 0, "ValueInternalArray::decrement(): moving iterator beyond end" ); if ( it.currentItemIndex_ == 0 ) { it.currentItemIndex_ = itemsPerPage-1; --(it.currentPageIndex_); } else { --(it.currentItemIndex_); } } Value & ValueInternalArray::unsafeDereference( const IteratorState &it ) { return (*(it.currentPageIndex_))[it.currentItemIndex_]; } Value & ValueInternalArray::dereference( const IteratorState &it ) { JSON_ASSERT_MESSAGE( it.array_ && (it.currentPageIndex_ - it.array_->pages_)*itemsPerPage + it.currentItemIndex_ < it.array_->size_, "ValueInternalArray::dereference(): dereferencing invalid iterator" ); return unsafeDereference( it ); } void ValueInternalArray::makeBeginIterator( IteratorState &it ) const { it.array_ = const_cast<ValueInternalArray *>( this ); it.currentItemIndex_ = 0; it.currentPageIndex_ = pages_; } void ValueInternalArray::makeIterator( IteratorState &it, ArrayIndex index ) const { it.array_ = const_cast<ValueInternalArray *>( this ); it.currentItemIndex_ = index % itemsPerPage; it.currentPageIndex_ = pages_ + index / itemsPerPage; } void ValueInternalArray::makeEndIterator( IteratorState &it ) const { makeIterator( it, size_ ); } ValueInternalArray::ValueInternalArray() : pages_( 0 ) , size_( 0 ) , pageCount_( 0 ) { } ValueInternalArray::ValueInternalArray( const ValueInternalArray &other ) : pages_( 0 ) , pageCount_( 0 ) , size_( other.size_ ) { PageIndex minNewPages = other.size_ / itemsPerPage; arrayAllocator()->reallocateArrayPageIndex( pages_, pageCount_, minNewPages ); JSON_ASSERT_MESSAGE( pageCount_ >= minNewPages, "ValueInternalArray::reserve(): bad reallocation" ); IteratorState itOther; other.makeBeginIterator( itOther ); Value *value; for ( ArrayIndex index = 0; index < size_; ++index, increment(itOther) ) { if ( index % itemsPerPage == 0 ) { PageIndex pageIndex = index / itemsPerPage; value = arrayAllocator()->allocateArrayPage(); pages_[pageIndex] = value; } new (value) Value( dereference( itOther ) ); } } ValueInternalArray & ValueInternalArray::operator =( const ValueInternalArray &other ) { ValueInternalArray temp( other ); swap( temp ); return *this; } ValueInternalArray::~ValueInternalArray() { // destroy all constructed items IteratorState it; IteratorState itEnd; makeBeginIterator( it); makeEndIterator( itEnd ); for ( ; !equals(it,itEnd); increment(it) ) { Value *value = &dereference(it); value->~Value(); } // release all pages PageIndex lastPageIndex = size_ / itemsPerPage; for ( PageIndex pageIndex = 0; pageIndex < lastPageIndex; ++pageIndex ) arrayAllocator()->releaseArrayPage( pages_[pageIndex] ); // release pages index arrayAllocator()->releaseArrayPageIndex( pages_, pageCount_ ); } void ValueInternalArray::swap( ValueInternalArray &other ) { Value **tempPages = pages_; pages_ = other.pages_; other.pages_ = tempPages; ArrayIndex tempSize = size_; size_ = other.size_; other.size_ = tempSize; PageIndex tempPageCount = pageCount_; pageCount_ = other.pageCount_; other.pageCount_ = tempPageCount; } void ValueInternalArray::clear() { ValueInternalArray dummy; swap( dummy ); } void ValueInternalArray::resize( ArrayIndex newSize ) { if ( newSize == 0 ) clear(); else if ( newSize < size_ ) { IteratorState it; IteratorState itEnd; makeIterator( it, newSize ); makeIterator( itEnd, size_ ); for ( ; !equals(it,itEnd); increment(it) ) { Value *value = &dereference(it); value->~Value(); } PageIndex pageIndex = (newSize + itemsPerPage - 1) / itemsPerPage; PageIndex lastPageIndex = size_ / itemsPerPage; for ( ; pageIndex < lastPageIndex; ++pageIndex ) arrayAllocator()->releaseArrayPage( pages_[pageIndex] ); size_ = newSize; } else if ( newSize > size_ ) resolveReference( newSize ); } void ValueInternalArray::makeIndexValid( ArrayIndex index ) { // Need to enlarge page index ? if ( index >= pageCount_ * itemsPerPage ) { PageIndex minNewPages = (index + 1) / itemsPerPage; arrayAllocator()->reallocateArrayPageIndex( pages_, pageCount_, minNewPages ); JSON_ASSERT_MESSAGE( pageCount_ >= minNewPages, "ValueInternalArray::reserve(): bad reallocation" ); } // Need to allocate new pages ? ArrayIndex nextPageIndex = (size_ % itemsPerPage) != 0 ? size_ - (size_%itemsPerPage) + itemsPerPage : size_; if ( nextPageIndex <= index ) { PageIndex pageIndex = nextPageIndex / itemsPerPage; PageIndex pageToAllocate = (index - nextPageIndex) / itemsPerPage + 1; for ( ; pageToAllocate-- > 0; ++pageIndex ) pages_[pageIndex] = arrayAllocator()->allocateArrayPage(); } // Initialize all new entries IteratorState it; IteratorState itEnd; makeIterator( it, size_ ); size_ = index + 1; makeIterator( itEnd, size_ ); for ( ; !equals(it,itEnd); increment(it) ) { Value *value = &dereference(it); new (value) Value(); // Construct a default value using placement new } } Value & ValueInternalArray::resolveReference( ArrayIndex index ) { if ( index >= size_ ) makeIndexValid( index ); return pages_[index/itemsPerPage][index%itemsPerPage]; } Value * ValueInternalArray::find( ArrayIndex index ) const { if ( index >= size_ ) return 0; return &(pages_[index/itemsPerPage][index%itemsPerPage]); } ValueInternalArray::ArrayIndex ValueInternalArray::size() const { return size_; } int ValueInternalArray::distance( const IteratorState &x, const IteratorState &y ) { return indexOf(y) - indexOf(x); } ValueInternalArray::ArrayIndex ValueInternalArray::indexOf( const IteratorState &iterator ) { if ( !iterator.array_ ) return ArrayIndex(-1); return ArrayIndex( (iterator.currentPageIndex_ - iterator.array_->pages_) * itemsPerPage + iterator.currentItemIndex_ ); } int ValueInternalArray::compare( const ValueInternalArray &other ) const { int sizeDiff( size_ - other.size_ ); if ( sizeDiff != 0 ) return sizeDiff; for ( ArrayIndex index =0; index < size_; ++index ) { int diff = pages_[index/itemsPerPage][index%itemsPerPage].compare( other.pages_[index/itemsPerPage][index%itemsPerPage] ); if ( diff != 0 ) return diff; } return 0; }
{ "pile_set_name": "Github" }
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_SIMD__QUATERNION_H_ #define BT_SIMD__QUATERNION_H_ #include "btVector3.h" #include "btQuadWord.h" #ifdef BT_USE_DOUBLE_PRECISION #define btQuaternionData btQuaternionDoubleData #define btQuaternionDataName "btQuaternionDoubleData" #else #define btQuaternionData btQuaternionFloatData #define btQuaternionDataName "btQuaternionFloatData" #endif //BT_USE_DOUBLE_PRECISION #ifdef BT_USE_SSE //const __m128 ATTRIBUTE_ALIGNED16(vOnes) = {1.0f, 1.0f, 1.0f, 1.0f}; #define vOnes (_mm_set_ps(1.0f, 1.0f, 1.0f, 1.0f)) #endif #if defined(BT_USE_SSE) #define vQInv (_mm_set_ps(+0.0f, -0.0f, -0.0f, -0.0f)) #define vPPPM (_mm_set_ps(-0.0f, +0.0f, +0.0f, +0.0f)) #elif defined(BT_USE_NEON) const btSimdFloat4 ATTRIBUTE_ALIGNED16(vQInv) = {-0.0f, -0.0f, -0.0f, +0.0f}; const btSimdFloat4 ATTRIBUTE_ALIGNED16(vPPPM) = {+0.0f, +0.0f, +0.0f, -0.0f}; #endif /**@brief The btQuaternion implements quaternion to perform linear algebra rotations in combination with btMatrix3x3, btVector3 and btTransform. */ class btQuaternion : public btQuadWord { public: /**@brief No initialization constructor */ btQuaternion() {} #if (defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE)) || defined(BT_USE_NEON) // Set Vector SIMD_FORCE_INLINE btQuaternion(const btSimdFloat4 vec) { mVec128 = vec; } // Copy constructor SIMD_FORCE_INLINE btQuaternion(const btQuaternion& rhs) { mVec128 = rhs.mVec128; } // Assignment Operator SIMD_FORCE_INLINE btQuaternion& operator=(const btQuaternion& v) { mVec128 = v.mVec128; return *this; } #endif // template <typename btScalar> // explicit Quaternion(const btScalar *v) : Tuple4<btScalar>(v) {} /**@brief Constructor from scalars */ btQuaternion(const btScalar& _x, const btScalar& _y, const btScalar& _z, const btScalar& _w) : btQuadWord(_x, _y, _z, _w) { } /**@brief Axis angle Constructor * @param axis The axis which the rotation is around * @param angle The magnitude of the rotation around the angle (Radians) */ btQuaternion(const btVector3& _axis, const btScalar& _angle) { setRotation(_axis, _angle); } /**@brief Constructor from Euler angles * @param yaw Angle around Y unless BT_EULER_DEFAULT_ZYX defined then Z * @param pitch Angle around X unless BT_EULER_DEFAULT_ZYX defined then Y * @param roll Angle around Z unless BT_EULER_DEFAULT_ZYX defined then X */ btQuaternion(const btScalar& yaw, const btScalar& pitch, const btScalar& roll) { #ifndef BT_EULER_DEFAULT_ZYX setEuler(yaw, pitch, roll); #else setEulerZYX(yaw, pitch, roll); #endif } /**@brief Set the rotation using axis angle notation * @param axis The axis around which to rotate * @param angle The magnitude of the rotation in Radians */ void setRotation(const btVector3& axis, const btScalar& _angle) { btScalar d = axis.length(); btAssert(d != btScalar(0.0)); btScalar s = btSin(_angle * btScalar(0.5)) / d; setValue(axis.x() * s, axis.y() * s, axis.z() * s, btCos(_angle * btScalar(0.5))); } /**@brief Set the quaternion using Euler angles * @param yaw Angle around Y * @param pitch Angle around X * @param roll Angle around Z */ void setEuler(const btScalar& yaw, const btScalar& pitch, const btScalar& roll) { btScalar halfYaw = btScalar(yaw) * btScalar(0.5); btScalar halfPitch = btScalar(pitch) * btScalar(0.5); btScalar halfRoll = btScalar(roll) * btScalar(0.5); btScalar cosYaw = btCos(halfYaw); btScalar sinYaw = btSin(halfYaw); btScalar cosPitch = btCos(halfPitch); btScalar sinPitch = btSin(halfPitch); btScalar cosRoll = btCos(halfRoll); btScalar sinRoll = btSin(halfRoll); setValue(cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw, cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw, sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw, cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw); } /**@brief Set the quaternion using euler angles * @param yaw Angle around Z * @param pitch Angle around Y * @param roll Angle around X */ void setEulerZYX(const btScalar& yawZ, const btScalar& pitchY, const btScalar& rollX) { btScalar halfYaw = btScalar(yawZ) * btScalar(0.5); btScalar halfPitch = btScalar(pitchY) * btScalar(0.5); btScalar halfRoll = btScalar(rollX) * btScalar(0.5); btScalar cosYaw = btCos(halfYaw); btScalar sinYaw = btSin(halfYaw); btScalar cosPitch = btCos(halfPitch); btScalar sinPitch = btSin(halfPitch); btScalar cosRoll = btCos(halfRoll); btScalar sinRoll = btSin(halfRoll); setValue(sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw, //x cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw, //y cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw, //z cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw); //formerly yzx } /**@brief Get the euler angles from this quaternion * @param yaw Angle around Z * @param pitch Angle around Y * @param roll Angle around X */ void getEulerZYX(btScalar& yawZ, btScalar& pitchY, btScalar& rollX) const { btScalar squ; btScalar sqx; btScalar sqy; btScalar sqz; btScalar sarg; sqx = m_floats[0] * m_floats[0]; sqy = m_floats[1] * m_floats[1]; sqz = m_floats[2] * m_floats[2]; squ = m_floats[3] * m_floats[3]; sarg = btScalar(-2.) * (m_floats[0] * m_floats[2] - m_floats[3] * m_floats[1]); // If the pitch angle is PI/2 or -PI/2, we can only compute // the sum roll + yaw. However, any combination that gives // the right sum will produce the correct orientation, so we // set rollX = 0 and compute yawZ. if (sarg <= -btScalar(0.99999)) { pitchY = btScalar(-0.5) * SIMD_PI; rollX = 0; yawZ = btScalar(2) * btAtan2(m_floats[0], -m_floats[1]); } else if (sarg >= btScalar(0.99999)) { pitchY = btScalar(0.5) * SIMD_PI; rollX = 0; yawZ = btScalar(2) * btAtan2(-m_floats[0], m_floats[1]); } else { pitchY = btAsin(sarg); rollX = btAtan2(2 * (m_floats[1] * m_floats[2] + m_floats[3] * m_floats[0]), squ - sqx - sqy + sqz); yawZ = btAtan2(2 * (m_floats[0] * m_floats[1] + m_floats[3] * m_floats[2]), squ + sqx - sqy - sqz); } } /**@brief Add two quaternions * @param q The quaternion to add to this one */ SIMD_FORCE_INLINE btQuaternion& operator+=(const btQuaternion& q) { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) mVec128 = _mm_add_ps(mVec128, q.mVec128); #elif defined(BT_USE_NEON) mVec128 = vaddq_f32(mVec128, q.mVec128); #else m_floats[0] += q.x(); m_floats[1] += q.y(); m_floats[2] += q.z(); m_floats[3] += q.m_floats[3]; #endif return *this; } /**@brief Subtract out a quaternion * @param q The quaternion to subtract from this one */ btQuaternion& operator-=(const btQuaternion& q) { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) mVec128 = _mm_sub_ps(mVec128, q.mVec128); #elif defined(BT_USE_NEON) mVec128 = vsubq_f32(mVec128, q.mVec128); #else m_floats[0] -= q.x(); m_floats[1] -= q.y(); m_floats[2] -= q.z(); m_floats[3] -= q.m_floats[3]; #endif return *this; } /**@brief Scale this quaternion * @param s The scalar to scale by */ btQuaternion& operator*=(const btScalar& s) { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) __m128 vs = _mm_load_ss(&s); // (S 0 0 0) vs = bt_pshufd_ps(vs, 0); // (S S S S) mVec128 = _mm_mul_ps(mVec128, vs); #elif defined(BT_USE_NEON) mVec128 = vmulq_n_f32(mVec128, s); #else m_floats[0] *= s; m_floats[1] *= s; m_floats[2] *= s; m_floats[3] *= s; #endif return *this; } /**@brief Multiply this quaternion by q on the right * @param q The other quaternion * Equivilant to this = this * q */ btQuaternion& operator*=(const btQuaternion& q) { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) __m128 vQ2 = q.get128(); __m128 A1 = bt_pshufd_ps(mVec128, BT_SHUFFLE(0, 1, 2, 0)); __m128 B1 = bt_pshufd_ps(vQ2, BT_SHUFFLE(3, 3, 3, 0)); A1 = A1 * B1; __m128 A2 = bt_pshufd_ps(mVec128, BT_SHUFFLE(1, 2, 0, 1)); __m128 B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(2, 0, 1, 1)); A2 = A2 * B2; B1 = bt_pshufd_ps(mVec128, BT_SHUFFLE(2, 0, 1, 2)); B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(1, 2, 0, 2)); B1 = B1 * B2; // A3 *= B3 mVec128 = bt_splat_ps(mVec128, 3); // A0 mVec128 = mVec128 * vQ2; // A0 * B0 A1 = A1 + A2; // AB12 mVec128 = mVec128 - B1; // AB03 = AB0 - AB3 A1 = _mm_xor_ps(A1, vPPPM); // change sign of the last element mVec128 = mVec128 + A1; // AB03 + AB12 #elif defined(BT_USE_NEON) float32x4_t vQ1 = mVec128; float32x4_t vQ2 = q.get128(); float32x4_t A0, A1, B1, A2, B2, A3, B3; float32x2_t vQ1zx, vQ2wx, vQ1yz, vQ2zx, vQ2yz, vQ2xz; { float32x2x2_t tmp; tmp = vtrn_f32(vget_high_f32(vQ1), vget_low_f32(vQ1)); // {z x}, {w y} vQ1zx = tmp.val[0]; tmp = vtrn_f32(vget_high_f32(vQ2), vget_low_f32(vQ2)); // {z x}, {w y} vQ2zx = tmp.val[0]; } vQ2wx = vext_f32(vget_high_f32(vQ2), vget_low_f32(vQ2), 1); vQ1yz = vext_f32(vget_low_f32(vQ1), vget_high_f32(vQ1), 1); vQ2yz = vext_f32(vget_low_f32(vQ2), vget_high_f32(vQ2), 1); vQ2xz = vext_f32(vQ2zx, vQ2zx, 1); A1 = vcombine_f32(vget_low_f32(vQ1), vQ1zx); // X Y z x B1 = vcombine_f32(vdup_lane_f32(vget_high_f32(vQ2), 1), vQ2wx); // W W W X A2 = vcombine_f32(vQ1yz, vget_low_f32(vQ1)); B2 = vcombine_f32(vQ2zx, vdup_lane_f32(vget_low_f32(vQ2), 1)); A3 = vcombine_f32(vQ1zx, vQ1yz); // Z X Y Z B3 = vcombine_f32(vQ2yz, vQ2xz); // Y Z x z A1 = vmulq_f32(A1, B1); A2 = vmulq_f32(A2, B2); A3 = vmulq_f32(A3, B3); // A3 *= B3 A0 = vmulq_lane_f32(vQ2, vget_high_f32(vQ1), 1); // A0 * B0 A1 = vaddq_f32(A1, A2); // AB12 = AB1 + AB2 A0 = vsubq_f32(A0, A3); // AB03 = AB0 - AB3 // change the sign of the last element A1 = (btSimdFloat4)veorq_s32((int32x4_t)A1, (int32x4_t)vPPPM); A0 = vaddq_f32(A0, A1); // AB03 + AB12 mVec128 = A0; #else setValue( m_floats[3] * q.x() + m_floats[0] * q.m_floats[3] + m_floats[1] * q.z() - m_floats[2] * q.y(), m_floats[3] * q.y() + m_floats[1] * q.m_floats[3] + m_floats[2] * q.x() - m_floats[0] * q.z(), m_floats[3] * q.z() + m_floats[2] * q.m_floats[3] + m_floats[0] * q.y() - m_floats[1] * q.x(), m_floats[3] * q.m_floats[3] - m_floats[0] * q.x() - m_floats[1] * q.y() - m_floats[2] * q.z()); #endif return *this; } /**@brief Return the dot product between this quaternion and another * @param q The other quaternion */ btScalar dot(const btQuaternion& q) const { #if defined BT_USE_SIMD_VECTOR3 && defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) __m128 vd; vd = _mm_mul_ps(mVec128, q.mVec128); __m128 t = _mm_movehl_ps(vd, vd); vd = _mm_add_ps(vd, t); t = _mm_shuffle_ps(vd, vd, 0x55); vd = _mm_add_ss(vd, t); return _mm_cvtss_f32(vd); #elif defined(BT_USE_NEON) float32x4_t vd = vmulq_f32(mVec128, q.mVec128); float32x2_t x = vpadd_f32(vget_low_f32(vd), vget_high_f32(vd)); x = vpadd_f32(x, x); return vget_lane_f32(x, 0); #else return m_floats[0] * q.x() + m_floats[1] * q.y() + m_floats[2] * q.z() + m_floats[3] * q.m_floats[3]; #endif } /**@brief Return the length squared of the quaternion */ btScalar length2() const { return dot(*this); } /**@brief Return the length of the quaternion */ btScalar length() const { return btSqrt(length2()); } btQuaternion& safeNormalize() { btScalar l2 = length2(); if (l2 > SIMD_EPSILON) { normalize(); } return *this; } /**@brief Normalize the quaternion * Such that x^2 + y^2 + z^2 +w^2 = 1 */ btQuaternion& normalize() { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) __m128 vd; vd = _mm_mul_ps(mVec128, mVec128); __m128 t = _mm_movehl_ps(vd, vd); vd = _mm_add_ps(vd, t); t = _mm_shuffle_ps(vd, vd, 0x55); vd = _mm_add_ss(vd, t); vd = _mm_sqrt_ss(vd); vd = _mm_div_ss(vOnes, vd); vd = bt_pshufd_ps(vd, 0); // splat mVec128 = _mm_mul_ps(mVec128, vd); return *this; #else return *this /= length(); #endif } /**@brief Return a scaled version of this quaternion * @param s The scale factor */ SIMD_FORCE_INLINE btQuaternion operator*(const btScalar& s) const { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) __m128 vs = _mm_load_ss(&s); // (S 0 0 0) vs = bt_pshufd_ps(vs, 0x00); // (S S S S) return btQuaternion(_mm_mul_ps(mVec128, vs)); #elif defined(BT_USE_NEON) return btQuaternion(vmulq_n_f32(mVec128, s)); #else return btQuaternion(x() * s, y() * s, z() * s, m_floats[3] * s); #endif } /**@brief Return an inversely scaled versionof this quaternion * @param s The inverse scale factor */ btQuaternion operator/(const btScalar& s) const { btAssert(s != btScalar(0.0)); return *this * (btScalar(1.0) / s); } /**@brief Inversely scale this quaternion * @param s The scale factor */ btQuaternion& operator/=(const btScalar& s) { btAssert(s != btScalar(0.0)); return *this *= btScalar(1.0) / s; } /**@brief Return a normalized version of this quaternion */ btQuaternion normalized() const { return *this / length(); } /**@brief Return the ***half*** angle between this quaternion and the other * @param q The other quaternion */ btScalar angle(const btQuaternion& q) const { btScalar s = btSqrt(length2() * q.length2()); btAssert(s != btScalar(0.0)); return btAcos(dot(q) / s); } /**@brief Return the angle between this quaternion and the other along the shortest path * @param q The other quaternion */ btScalar angleShortestPath(const btQuaternion& q) const { btScalar s = btSqrt(length2() * q.length2()); btAssert(s != btScalar(0.0)); if (dot(q) < 0) // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp return btAcos(dot(-q) / s) * btScalar(2.0); else return btAcos(dot(q) / s) * btScalar(2.0); } /**@brief Return the angle [0, 2Pi] of rotation represented by this quaternion */ btScalar getAngle() const { btScalar s = btScalar(2.) * btAcos(m_floats[3]); return s; } /**@brief Return the angle [0, Pi] of rotation represented by this quaternion along the shortest path */ btScalar getAngleShortestPath() const { btScalar s; if (m_floats[3] >= 0) s = btScalar(2.) * btAcos(m_floats[3]); else s = btScalar(2.) * btAcos(-m_floats[3]); return s; } /**@brief Return the axis of the rotation represented by this quaternion */ btVector3 getAxis() const { btScalar s_squared = 1.f - m_floats[3] * m_floats[3]; if (s_squared < btScalar(10.) * SIMD_EPSILON) //Check for divide by zero return btVector3(1.0, 0.0, 0.0); // Arbitrary btScalar s = 1.f / btSqrt(s_squared); return btVector3(m_floats[0] * s, m_floats[1] * s, m_floats[2] * s); } /**@brief Return the inverse of this quaternion */ btQuaternion inverse() const { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) return btQuaternion(_mm_xor_ps(mVec128, vQInv)); #elif defined(BT_USE_NEON) return btQuaternion((btSimdFloat4)veorq_s32((int32x4_t)mVec128, (int32x4_t)vQInv)); #else return btQuaternion(-m_floats[0], -m_floats[1], -m_floats[2], m_floats[3]); #endif } /**@brief Return the sum of this quaternion and the other * @param q2 The other quaternion */ SIMD_FORCE_INLINE btQuaternion operator+(const btQuaternion& q2) const { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) return btQuaternion(_mm_add_ps(mVec128, q2.mVec128)); #elif defined(BT_USE_NEON) return btQuaternion(vaddq_f32(mVec128, q2.mVec128)); #else const btQuaternion& q1 = *this; return btQuaternion(q1.x() + q2.x(), q1.y() + q2.y(), q1.z() + q2.z(), q1.m_floats[3] + q2.m_floats[3]); #endif } /**@brief Return the difference between this quaternion and the other * @param q2 The other quaternion */ SIMD_FORCE_INLINE btQuaternion operator-(const btQuaternion& q2) const { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) return btQuaternion(_mm_sub_ps(mVec128, q2.mVec128)); #elif defined(BT_USE_NEON) return btQuaternion(vsubq_f32(mVec128, q2.mVec128)); #else const btQuaternion& q1 = *this; return btQuaternion(q1.x() - q2.x(), q1.y() - q2.y(), q1.z() - q2.z(), q1.m_floats[3] - q2.m_floats[3]); #endif } /**@brief Return the negative of this quaternion * This simply negates each element */ SIMD_FORCE_INLINE btQuaternion operator-() const { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) return btQuaternion(_mm_xor_ps(mVec128, btvMzeroMask)); #elif defined(BT_USE_NEON) return btQuaternion((btSimdFloat4)veorq_s32((int32x4_t)mVec128, (int32x4_t)btvMzeroMask)); #else const btQuaternion& q2 = *this; return btQuaternion(-q2.x(), -q2.y(), -q2.z(), -q2.m_floats[3]); #endif } /**@todo document this and it's use */ SIMD_FORCE_INLINE btQuaternion farthest(const btQuaternion& qd) const { btQuaternion diff, sum; diff = *this - qd; sum = *this + qd; if (diff.dot(diff) > sum.dot(sum)) return qd; return (-qd); } /**@todo document this and it's use */ SIMD_FORCE_INLINE btQuaternion nearest(const btQuaternion& qd) const { btQuaternion diff, sum; diff = *this - qd; sum = *this + qd; if (diff.dot(diff) < sum.dot(sum)) return qd; return (-qd); } /**@brief Return the quaternion which is the result of Spherical Linear Interpolation between this and the other quaternion * @param q The other quaternion to interpolate with * @param t The ratio between this and q to interpolate. If t = 0 the result is this, if t=1 the result is q. * Slerp interpolates assuming constant velocity. */ btQuaternion slerp(const btQuaternion& q, const btScalar& t) const { const btScalar magnitude = btSqrt(length2() * q.length2()); btAssert(magnitude > btScalar(0)); const btScalar product = dot(q) / magnitude; const btScalar absproduct = btFabs(product); if (absproduct < btScalar(1.0 - SIMD_EPSILON)) { // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp const btScalar theta = btAcos(absproduct); const btScalar d = btSin(theta); btAssert(d > btScalar(0)); const btScalar sign = (product < 0) ? btScalar(-1) : btScalar(1); const btScalar s0 = btSin((btScalar(1.0) - t) * theta) / d; const btScalar s1 = btSin(sign * t * theta) / d; return btQuaternion( (m_floats[0] * s0 + q.x() * s1), (m_floats[1] * s0 + q.y() * s1), (m_floats[2] * s0 + q.z() * s1), (m_floats[3] * s0 + q.w() * s1)); } else { return *this; } } static const btQuaternion& getIdentity() { static const btQuaternion identityQuat(btScalar(0.), btScalar(0.), btScalar(0.), btScalar(1.)); return identityQuat; } SIMD_FORCE_INLINE const btScalar& getW() const { return m_floats[3]; } SIMD_FORCE_INLINE void serialize(struct btQuaternionData& dataOut) const; SIMD_FORCE_INLINE void deSerialize(const struct btQuaternionFloatData& dataIn); SIMD_FORCE_INLINE void deSerialize(const struct btQuaternionDoubleData& dataIn); SIMD_FORCE_INLINE void serializeFloat(struct btQuaternionFloatData& dataOut) const; SIMD_FORCE_INLINE void deSerializeFloat(const struct btQuaternionFloatData& dataIn); SIMD_FORCE_INLINE void serializeDouble(struct btQuaternionDoubleData& dataOut) const; SIMD_FORCE_INLINE void deSerializeDouble(const struct btQuaternionDoubleData& dataIn); }; /**@brief Return the product of two quaternions */ SIMD_FORCE_INLINE btQuaternion operator*(const btQuaternion& q1, const btQuaternion& q2) { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) __m128 vQ1 = q1.get128(); __m128 vQ2 = q2.get128(); __m128 A0, A1, B1, A2, B2; A1 = bt_pshufd_ps(vQ1, BT_SHUFFLE(0, 1, 2, 0)); // X Y z x // vtrn B1 = bt_pshufd_ps(vQ2, BT_SHUFFLE(3, 3, 3, 0)); // W W W X // vdup vext A1 = A1 * B1; A2 = bt_pshufd_ps(vQ1, BT_SHUFFLE(1, 2, 0, 1)); // Y Z X Y // vext B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(2, 0, 1, 1)); // z x Y Y // vtrn vdup A2 = A2 * B2; B1 = bt_pshufd_ps(vQ1, BT_SHUFFLE(2, 0, 1, 2)); // z x Y Z // vtrn vext B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(1, 2, 0, 2)); // Y Z x z // vext vtrn B1 = B1 * B2; // A3 *= B3 A0 = bt_splat_ps(vQ1, 3); // A0 A0 = A0 * vQ2; // A0 * B0 A1 = A1 + A2; // AB12 A0 = A0 - B1; // AB03 = AB0 - AB3 A1 = _mm_xor_ps(A1, vPPPM); // change sign of the last element A0 = A0 + A1; // AB03 + AB12 return btQuaternion(A0); #elif defined(BT_USE_NEON) float32x4_t vQ1 = q1.get128(); float32x4_t vQ2 = q2.get128(); float32x4_t A0, A1, B1, A2, B2, A3, B3; float32x2_t vQ1zx, vQ2wx, vQ1yz, vQ2zx, vQ2yz, vQ2xz; { float32x2x2_t tmp; tmp = vtrn_f32(vget_high_f32(vQ1), vget_low_f32(vQ1)); // {z x}, {w y} vQ1zx = tmp.val[0]; tmp = vtrn_f32(vget_high_f32(vQ2), vget_low_f32(vQ2)); // {z x}, {w y} vQ2zx = tmp.val[0]; } vQ2wx = vext_f32(vget_high_f32(vQ2), vget_low_f32(vQ2), 1); vQ1yz = vext_f32(vget_low_f32(vQ1), vget_high_f32(vQ1), 1); vQ2yz = vext_f32(vget_low_f32(vQ2), vget_high_f32(vQ2), 1); vQ2xz = vext_f32(vQ2zx, vQ2zx, 1); A1 = vcombine_f32(vget_low_f32(vQ1), vQ1zx); // X Y z x B1 = vcombine_f32(vdup_lane_f32(vget_high_f32(vQ2), 1), vQ2wx); // W W W X A2 = vcombine_f32(vQ1yz, vget_low_f32(vQ1)); B2 = vcombine_f32(vQ2zx, vdup_lane_f32(vget_low_f32(vQ2), 1)); A3 = vcombine_f32(vQ1zx, vQ1yz); // Z X Y Z B3 = vcombine_f32(vQ2yz, vQ2xz); // Y Z x z A1 = vmulq_f32(A1, B1); A2 = vmulq_f32(A2, B2); A3 = vmulq_f32(A3, B3); // A3 *= B3 A0 = vmulq_lane_f32(vQ2, vget_high_f32(vQ1), 1); // A0 * B0 A1 = vaddq_f32(A1, A2); // AB12 = AB1 + AB2 A0 = vsubq_f32(A0, A3); // AB03 = AB0 - AB3 // change the sign of the last element A1 = (btSimdFloat4)veorq_s32((int32x4_t)A1, (int32x4_t)vPPPM); A0 = vaddq_f32(A0, A1); // AB03 + AB12 return btQuaternion(A0); #else return btQuaternion( q1.w() * q2.x() + q1.x() * q2.w() + q1.y() * q2.z() - q1.z() * q2.y(), q1.w() * q2.y() + q1.y() * q2.w() + q1.z() * q2.x() - q1.x() * q2.z(), q1.w() * q2.z() + q1.z() * q2.w() + q1.x() * q2.y() - q1.y() * q2.x(), q1.w() * q2.w() - q1.x() * q2.x() - q1.y() * q2.y() - q1.z() * q2.z()); #endif } SIMD_FORCE_INLINE btQuaternion operator*(const btQuaternion& q, const btVector3& w) { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) __m128 vQ1 = q.get128(); __m128 vQ2 = w.get128(); __m128 A1, B1, A2, B2, A3, B3; A1 = bt_pshufd_ps(vQ1, BT_SHUFFLE(3, 3, 3, 0)); B1 = bt_pshufd_ps(vQ2, BT_SHUFFLE(0, 1, 2, 0)); A1 = A1 * B1; A2 = bt_pshufd_ps(vQ1, BT_SHUFFLE(1, 2, 0, 1)); B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(2, 0, 1, 1)); A2 = A2 * B2; A3 = bt_pshufd_ps(vQ1, BT_SHUFFLE(2, 0, 1, 2)); B3 = bt_pshufd_ps(vQ2, BT_SHUFFLE(1, 2, 0, 2)); A3 = A3 * B3; // A3 *= B3 A1 = A1 + A2; // AB12 A1 = _mm_xor_ps(A1, vPPPM); // change sign of the last element A1 = A1 - A3; // AB123 = AB12 - AB3 return btQuaternion(A1); #elif defined(BT_USE_NEON) float32x4_t vQ1 = q.get128(); float32x4_t vQ2 = w.get128(); float32x4_t A1, B1, A2, B2, A3, B3; float32x2_t vQ1wx, vQ2zx, vQ1yz, vQ2yz, vQ1zx, vQ2xz; vQ1wx = vext_f32(vget_high_f32(vQ1), vget_low_f32(vQ1), 1); { float32x2x2_t tmp; tmp = vtrn_f32(vget_high_f32(vQ2), vget_low_f32(vQ2)); // {z x}, {w y} vQ2zx = tmp.val[0]; tmp = vtrn_f32(vget_high_f32(vQ1), vget_low_f32(vQ1)); // {z x}, {w y} vQ1zx = tmp.val[0]; } vQ1yz = vext_f32(vget_low_f32(vQ1), vget_high_f32(vQ1), 1); vQ2yz = vext_f32(vget_low_f32(vQ2), vget_high_f32(vQ2), 1); vQ2xz = vext_f32(vQ2zx, vQ2zx, 1); A1 = vcombine_f32(vdup_lane_f32(vget_high_f32(vQ1), 1), vQ1wx); // W W W X B1 = vcombine_f32(vget_low_f32(vQ2), vQ2zx); // X Y z x A2 = vcombine_f32(vQ1yz, vget_low_f32(vQ1)); B2 = vcombine_f32(vQ2zx, vdup_lane_f32(vget_low_f32(vQ2), 1)); A3 = vcombine_f32(vQ1zx, vQ1yz); // Z X Y Z B3 = vcombine_f32(vQ2yz, vQ2xz); // Y Z x z A1 = vmulq_f32(A1, B1); A2 = vmulq_f32(A2, B2); A3 = vmulq_f32(A3, B3); // A3 *= B3 A1 = vaddq_f32(A1, A2); // AB12 = AB1 + AB2 // change the sign of the last element A1 = (btSimdFloat4)veorq_s32((int32x4_t)A1, (int32x4_t)vPPPM); A1 = vsubq_f32(A1, A3); // AB123 = AB12 - AB3 return btQuaternion(A1); #else return btQuaternion( q.w() * w.x() + q.y() * w.z() - q.z() * w.y(), q.w() * w.y() + q.z() * w.x() - q.x() * w.z(), q.w() * w.z() + q.x() * w.y() - q.y() * w.x(), -q.x() * w.x() - q.y() * w.y() - q.z() * w.z()); #endif } SIMD_FORCE_INLINE btQuaternion operator*(const btVector3& w, const btQuaternion& q) { #if defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) __m128 vQ1 = w.get128(); __m128 vQ2 = q.get128(); __m128 A1, B1, A2, B2, A3, B3; A1 = bt_pshufd_ps(vQ1, BT_SHUFFLE(0, 1, 2, 0)); // X Y z x B1 = bt_pshufd_ps(vQ2, BT_SHUFFLE(3, 3, 3, 0)); // W W W X A1 = A1 * B1; A2 = bt_pshufd_ps(vQ1, BT_SHUFFLE(1, 2, 0, 1)); B2 = bt_pshufd_ps(vQ2, BT_SHUFFLE(2, 0, 1, 1)); A2 = A2 * B2; A3 = bt_pshufd_ps(vQ1, BT_SHUFFLE(2, 0, 1, 2)); B3 = bt_pshufd_ps(vQ2, BT_SHUFFLE(1, 2, 0, 2)); A3 = A3 * B3; // A3 *= B3 A1 = A1 + A2; // AB12 A1 = _mm_xor_ps(A1, vPPPM); // change sign of the last element A1 = A1 - A3; // AB123 = AB12 - AB3 return btQuaternion(A1); #elif defined(BT_USE_NEON) float32x4_t vQ1 = w.get128(); float32x4_t vQ2 = q.get128(); float32x4_t A1, B1, A2, B2, A3, B3; float32x2_t vQ1zx, vQ2wx, vQ1yz, vQ2zx, vQ2yz, vQ2xz; { float32x2x2_t tmp; tmp = vtrn_f32(vget_high_f32(vQ1), vget_low_f32(vQ1)); // {z x}, {w y} vQ1zx = tmp.val[0]; tmp = vtrn_f32(vget_high_f32(vQ2), vget_low_f32(vQ2)); // {z x}, {w y} vQ2zx = tmp.val[0]; } vQ2wx = vext_f32(vget_high_f32(vQ2), vget_low_f32(vQ2), 1); vQ1yz = vext_f32(vget_low_f32(vQ1), vget_high_f32(vQ1), 1); vQ2yz = vext_f32(vget_low_f32(vQ2), vget_high_f32(vQ2), 1); vQ2xz = vext_f32(vQ2zx, vQ2zx, 1); A1 = vcombine_f32(vget_low_f32(vQ1), vQ1zx); // X Y z x B1 = vcombine_f32(vdup_lane_f32(vget_high_f32(vQ2), 1), vQ2wx); // W W W X A2 = vcombine_f32(vQ1yz, vget_low_f32(vQ1)); B2 = vcombine_f32(vQ2zx, vdup_lane_f32(vget_low_f32(vQ2), 1)); A3 = vcombine_f32(vQ1zx, vQ1yz); // Z X Y Z B3 = vcombine_f32(vQ2yz, vQ2xz); // Y Z x z A1 = vmulq_f32(A1, B1); A2 = vmulq_f32(A2, B2); A3 = vmulq_f32(A3, B3); // A3 *= B3 A1 = vaddq_f32(A1, A2); // AB12 = AB1 + AB2 // change the sign of the last element A1 = (btSimdFloat4)veorq_s32((int32x4_t)A1, (int32x4_t)vPPPM); A1 = vsubq_f32(A1, A3); // AB123 = AB12 - AB3 return btQuaternion(A1); #else return btQuaternion( +w.x() * q.w() + w.y() * q.z() - w.z() * q.y(), +w.y() * q.w() + w.z() * q.x() - w.x() * q.z(), +w.z() * q.w() + w.x() * q.y() - w.y() * q.x(), -w.x() * q.x() - w.y() * q.y() - w.z() * q.z()); #endif } /**@brief Calculate the dot product between two quaternions */ SIMD_FORCE_INLINE btScalar dot(const btQuaternion& q1, const btQuaternion& q2) { return q1.dot(q2); } /**@brief Return the length of a quaternion */ SIMD_FORCE_INLINE btScalar length(const btQuaternion& q) { return q.length(); } /**@brief Return the angle between two quaternions*/ SIMD_FORCE_INLINE btScalar btAngle(const btQuaternion& q1, const btQuaternion& q2) { return q1.angle(q2); } /**@brief Return the inverse of a quaternion*/ SIMD_FORCE_INLINE btQuaternion inverse(const btQuaternion& q) { return q.inverse(); } /**@brief Return the result of spherical linear interpolation betwen two quaternions * @param q1 The first quaternion * @param q2 The second quaternion * @param t The ration between q1 and q2. t = 0 return q1, t=1 returns q2 * Slerp assumes constant velocity between positions. */ SIMD_FORCE_INLINE btQuaternion slerp(const btQuaternion& q1, const btQuaternion& q2, const btScalar& t) { return q1.slerp(q2, t); } SIMD_FORCE_INLINE btVector3 quatRotate(const btQuaternion& rotation, const btVector3& v) { btQuaternion q = rotation * v; q *= rotation.inverse(); #if defined BT_USE_SIMD_VECTOR3 && defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE) return btVector3(_mm_and_ps(q.get128(), btvFFF0fMask)); #elif defined(BT_USE_NEON) return btVector3((float32x4_t)vandq_s32((int32x4_t)q.get128(), btvFFF0Mask)); #else return btVector3(q.getX(), q.getY(), q.getZ()); #endif } SIMD_FORCE_INLINE btQuaternion shortestArcQuat(const btVector3& v0, const btVector3& v1) // Game Programming Gems 2.10. make sure v0,v1 are normalized { btVector3 c = v0.cross(v1); btScalar d = v0.dot(v1); if (d < -1.0 + SIMD_EPSILON) { btVector3 n, unused; btPlaneSpace1(v0, n, unused); return btQuaternion(n.x(), n.y(), n.z(), 0.0f); // just pick any vector that is orthogonal to v0 } btScalar s = btSqrt((1.0f + d) * 2.0f); btScalar rs = 1.0f / s; return btQuaternion(c.getX() * rs, c.getY() * rs, c.getZ() * rs, s * 0.5f); } SIMD_FORCE_INLINE btQuaternion shortestArcQuatNormalize2(btVector3& v0, btVector3& v1) { v0.normalize(); v1.normalize(); return shortestArcQuat(v0, v1); } struct btQuaternionFloatData { float m_floats[4]; }; struct btQuaternionDoubleData { double m_floats[4]; }; SIMD_FORCE_INLINE void btQuaternion::serializeFloat(struct btQuaternionFloatData& dataOut) const { ///could also do a memcpy, check if it is worth it for (int i = 0; i < 4; i++) dataOut.m_floats[i] = float(m_floats[i]); } SIMD_FORCE_INLINE void btQuaternion::deSerializeFloat(const struct btQuaternionFloatData& dataIn) { for (int i = 0; i < 4; i++) m_floats[i] = btScalar(dataIn.m_floats[i]); } SIMD_FORCE_INLINE void btQuaternion::serializeDouble(struct btQuaternionDoubleData& dataOut) const { ///could also do a memcpy, check if it is worth it for (int i = 0; i < 4; i++) dataOut.m_floats[i] = double(m_floats[i]); } SIMD_FORCE_INLINE void btQuaternion::deSerializeDouble(const struct btQuaternionDoubleData& dataIn) { for (int i = 0; i < 4; i++) m_floats[i] = btScalar(dataIn.m_floats[i]); } SIMD_FORCE_INLINE void btQuaternion::serialize(struct btQuaternionData& dataOut) const { ///could also do a memcpy, check if it is worth it for (int i = 0; i < 4; i++) dataOut.m_floats[i] = m_floats[i]; } SIMD_FORCE_INLINE void btQuaternion::deSerialize(const struct btQuaternionFloatData& dataIn) { for (int i = 0; i < 4; i++) m_floats[i] = (btScalar)dataIn.m_floats[i]; } SIMD_FORCE_INLINE void btQuaternion::deSerialize(const struct btQuaternionDoubleData& dataIn) { for (int i = 0; i < 4; i++) m_floats[i] = (btScalar)dataIn.m_floats[i]; } #endif //BT_SIMD__QUATERNION_H_
{ "pile_set_name": "Github" }
import { task } from 'gulp'; import * as gulp from 'gulp'; const gulpClean = require('gulp-clean'); task('clean', [], (done:any) => { return gulp.src('dist', { read: false }).pipe(gulpClean(null)); });
{ "pile_set_name": "Github" }
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* vim: set sw=4 sts=4 expandtab: */ /* rsvg-cairo.h: SAX-based renderer for SVG files using cairo Copyright (C) 2005 Red Hat, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Author: Carl Worth <[email protected]> */ #if !defined (__RSVG_RSVG_H_INSIDE__) && !defined (RSVG_COMPILATION) #warning "Including <librsvg/rsvg-cairo.h> directly is deprecated." #endif #ifndef RSVG_CAIRO_H #define RSVG_CAIRO_H #include <cairo.h> G_BEGIN_DECLS RSVG_API gboolean rsvg_handle_render_cairo (RsvgHandle *handle, cairo_t *cr); RSVG_API gboolean rsvg_handle_render_cairo_sub (RsvgHandle *handle, cairo_t *cr, const char *id); RSVG_API gboolean rsvg_handle_render_document (RsvgHandle *handle, cairo_t *cr, const RsvgRectangle *viewport, GError **error); RSVG_API gboolean rsvg_handle_get_geometry_for_layer (RsvgHandle *handle, const char *id, const RsvgRectangle *viewport, RsvgRectangle *out_ink_rect, RsvgRectangle *out_logical_rect, GError **error); RSVG_API gboolean rsvg_handle_render_layer (RsvgHandle *handle, cairo_t *cr, const char *id, const RsvgRectangle *viewport, GError **error); RSVG_API gboolean rsvg_handle_get_geometry_for_element (RsvgHandle *handle, const char *id, RsvgRectangle *out_ink_rect, RsvgRectangle *out_logical_rect, GError **error); RSVG_API gboolean rsvg_handle_render_element (RsvgHandle *handle, cairo_t *cr, const char *id, const RsvgRectangle *element_viewport, GError **error); G_END_DECLS #endif
{ "pile_set_name": "Github" }
/*============================= * 二叉树的二叉链表存储结构 * * 包含算法: 6.1、6.2、6.3、6.4 =============================*/ #include "BiTree.h" #include "LinkQueue.h" //**▲03 栈和队列**// /* * 初始化 * * 构造空二叉树。 */ Status InitBiTree(BiTree* T) { if(T == NULL) { return ERROR; } *T = NULL; return OK; } /* * 判空 * * 判断二叉树是否为空树。 */ Status BiTreeEmpty(BiTree T) { return T == NULL ? TRUE : FALSE; } /* * 树深 * * 返回二叉树的深度(层数)。 */ int BiTreeDepth(BiTree T) { int LD, RD; if(T == NULL) { return 0; // 空树深度为0 } else { LD = BiTreeDepth(T->lchild); // 求左子树深度 RD = BiTreeDepth(T->rchild); // 求右子树深度 return (LD >= RD ? LD : RD) + 1; } } // 以图形化形式输出当前结构,仅限内部测试使用 void PrintTree(BiTree T) { int level, width; int i, j, k, w; int begin; int distance; TElemType** tmp; LinkQueue Q; BiTree e; // 遇到空树则无需继续计算 if(BiTreeEmpty(T)) { printf("\n"); return; } level = BiTreeDepth(T); // (完全)二叉树结构高度 width = (int)pow(2, level)-1; // (完全)二叉树结构宽度 // 动态创建行 tmp = (TElemType**)malloc(level* sizeof(TElemType*)); // 动态创建列 for(i = 0; i < level; i++) { tmp[i] = (TElemType*)malloc(width* sizeof(TElemType)); // 初始化内存值为空字符 memset(tmp[i], '\0', width); } // 借助队列实现层序遍历 InitQueue(&Q); EnQueue(&Q, T); // 遍历树中所有元素,将其安排到二维数组tmp中合适的位置 for(i = 0; i < level; i++) { w = (int) pow(2, i); // 二叉树当前层的宽度 distance = width / w; // 二叉树当前层的元素间隔 begin = width / (int) pow(2, i + 1); // 二叉树当前层首个元素之前的空格数 for(k = 0; k < w; k++) { DeQueue(&Q, &e); if(e == NULL) { EnQueue(&Q, NULL); EnQueue(&Q, NULL); } else { j = begin + k * (1 + distance); tmp[i][j] = e->data; // 左孩子入队 EnQueue(&Q, e->lchild); // 右孩子入队 EnQueue(&Q, e->rchild); } } } for(i = 0; i < level; i++) { for(j = 0; j < width; j++) { if(tmp[i][j] != '\0') { printf("%c", tmp[i][j]); } else { printf(" "); } } printf("\n"); } }
{ "pile_set_name": "Github" }
SECTIONS { .memory : { . = 0x000000; *(.init); *(.text); *(*); . = ALIGN(4); end = .; } }
{ "pile_set_name": "Github" }
gcr.io/google_containers/kube-proxy:v1.16.14-rc.0
{ "pile_set_name": "Github" }
/* ** $Id: lfunc.h,v 2.4.1.1 2007/12/27 13:02:25 roberto Exp $ ** Auxiliary functions to manipulate prototypes and closures ** See Copyright Notice in lua.h */ #ifndef lfunc_h #define lfunc_h #include "lobject.h" #define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ cast(int, sizeof(TValue)*((n)-1))) #define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ cast(int, sizeof(TValue *)*((n)-1))) LUAI_FUNC Proto *luaF_newproto (lua_State *L); LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e); LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e); LUAI_FUNC UpVal *luaF_newupval (lua_State *L); LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); LUAI_FUNC void luaF_close (lua_State *L, StkId level); LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c); LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv); LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, int pc); #endif
{ "pile_set_name": "Github" }
div.exhibit-lens { border: 1px solid #aaa; margin-bottom: 1em; } div.exhibit-lens-title { font-weight: bold; background: #eee; padding: 2px; } .exhibit-lens-copyButton { float: right; } div.exhibit-lens-body { padding: 0.3em; } table.exhibit-lens-properties { } tr.exhibit-lens-property { } td.exhibit-lens-property-name { color: #888; } td.exhibit-lens-property-values { }
{ "pile_set_name": "Github" }
// @flow import type {allocatedObject} from "./allocatedObjectType"; export default (home: Array<any>, activity: Array<any>, directmail: Array<any>): allocatedObject => ({ home, activity, directmail });
{ "pile_set_name": "Github" }
# # Copyright (C) 2006-2011 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # include $(TOPDIR)/rules.mk PKG_NAME:=glibc PKG_VERSION:=$(call qstrip,$(CONFIG_GLIBC_VERSION)) PKG_REVISION:=$(call qstrip,$(CONFIG_GLIBC_REVISION)) PKG_SOURCE_PROTO:=git PKG_SOURCE_URL:=git://sourceware.org/git/glibc.git PKG_SOURCE_VERSION:=$(PKG_REVISION) PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)-r$(PKG_REVISION) PKG_SOURCE:=$(PKG_SOURCE_SUBDIR).tar.bz2 GLIBC_PATH:= ifneq ($(CONFIG_EGLIBC_VERSION_2_19),) GLIBC_PATH:=libc/ PKG_SOURCE_PROTO:=svn PKG_SOURCE:=$(PKG_SOURCE_SUBDIR).tar.bz2 PKG_SOURCE_URL:=svn://svn.eglibc.org/branches/eglibc-2_19 endif PATCH_DIR:=$(PATH_PREFIX)/patches/$(PKG_VERSION) HOST_BUILD_DIR:=$(BUILD_DIR_TOOLCHAIN)/$(PKG_SOURCE_SUBDIR) CUR_BUILD_DIR:=$(HOST_BUILD_DIR)-$(VARIANT) include $(INCLUDE_DIR)/toolchain-build.mk HOST_STAMP_PREPARED:=$(HOST_BUILD_DIR)/.prepared HOST_STAMP_CONFIGURED:=$(CUR_BUILD_DIR)/.configured HOST_STAMP_BUILT:=$(CUR_BUILD_DIR)/.built HOST_STAMP_INSTALLED:=$(TOOLCHAIN_DIR)/stamp/.glibc_$(VARIANT)_installed ifeq ($(ARCH),mips64) ifdef CONFIG_MIPS64_ABI_N64 TARGET_CFLAGS += -mabi=64 endif ifdef CONFIG_MIPS64_ABI_N32 TARGET_CFLAGS += -mabi=n32 endif ifdef CONFIG_MIPS64_ABI_O32 TARGET_CFLAGS += -mabi=32 endif endif GLIBC_CONFIGURE:= \ BUILD_CC="$(HOSTCC)" \ $(TARGET_CONFIGURE_OPTS) \ CFLAGS="$(TARGET_CFLAGS)" \ libc_cv_slibdir="/lib" \ use_ldconfig=no \ $(HOST_BUILD_DIR)/$(GLIBC_PATH)configure \ --prefix= \ --build=$(GNU_HOST_NAME) \ --host=$(REAL_GNU_TARGET_NAME) \ --with-headers=$(TOOLCHAIN_DIR)/include \ --disable-profile \ --disable-werror \ --without-gd \ --without-cvs \ --enable-add-ons \ --$(if $(CONFIG_SOFT_FLOAT),without,with)-fp export libc_cv_ssp=no export ac_cv_header_cpuid_h=yes export HOST_CFLAGS := $(HOST_CFLAGS) -idirafter $(CURDIR)/$(PATH_PREFIX)/include define Host/SetToolchainInfo $(SED) 's,^\(LIBC_TYPE\)=.*,\1=$(PKG_NAME),' $(TOOLCHAIN_DIR)/info.mk ifneq ($(CONFIG_GLIBC_VERSION_2_21),) $(SED) 's,^\(LIBC_URL\)=.*,\1=http://www.gnu.org/software/libc/,' $(TOOLCHAIN_DIR)/info.mk else $(SED) 's,^\(LIBC_URL\)=.*,\1=http://www.eglibc.org/,' $(TOOLCHAIN_DIR)/info.mk endif $(SED) 's,^\(LIBC_VERSION\)=.*,\1=$(PKG_VERSION),' $(TOOLCHAIN_DIR)/info.mk $(SED) 's,^\(LIBC_SO_VERSION\)=.*,\1=$(PKG_VERSION),' $(TOOLCHAIN_DIR)/info.mk endef define Host/Configure [ -f $(HOST_BUILD_DIR)/.autoconf ] || { \ cd $(HOST_BUILD_DIR)/$(GLIBC_PATH); \ autoconf --force && \ touch $(HOST_BUILD_DIR)/.autoconf; \ } mkdir -p $(CUR_BUILD_DIR) grep 'CONFIG_EGLIBC_OPTION_' $(TOPDIR)/.config | sed -e "s,\\(# \)\\?CONFIG_EGLIBC_\\(.*\\),\\1\\2,g" > $(CUR_BUILD_DIR)/option-groups.config ( cd $(CUR_BUILD_DIR); rm -f config.cache; \ $(GLIBC_CONFIGURE) \ ); endef define Host/Prepare $(call Host/Prepare/Default) ln -snf $(PKG_SOURCE_SUBDIR) $(BUILD_DIR_TOOLCHAIN)/$(PKG_NAME) ifeq ($(CONFIG_GLIBC_VERSION_2_21),) $(SED) 's,y,n,' $(HOST_BUILD_DIR)/libc/option-groups.defaults endif endef define Host/Clean rm -rf $(CUR_BUILD_DIR)* \ $(BUILD_DIR_TOOLCHAIN)/$(LIBC)-dev \ $(BUILD_DIR_TOOLCHAIN)/$(PKG_NAME) endef
{ "pile_set_name": "Github" }
package com.arasthel.swissknife.annotations import android.widget.TextView import com.arasthel.swissknife.SwissKnife import com.arasthel.swissknife.utils.AnnotationUtils import groovyjarjarasm.asm.Opcodes import org.codehaus.groovy.ast.* import org.codehaus.groovy.ast.expr.ListExpression import org.codehaus.groovy.ast.stmt.BlockStatement import org.codehaus.groovy.ast.stmt.Statement import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.transform.ASTTransformation import org.codehaus.groovy.transform.GroovyASTTransformation import static org.codehaus.groovy.ast.tools.GeneralUtils.* /** * Created by Arasthel on 16/08/14. */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class OnEditorActionTransformation implements ASTTransformation, Opcodes { @Override void visit(ASTNode[] astNodes, SourceUnit sourceUnit) { MethodNode annotatedMethod = astNodes[1]; AnnotationNode annotation = astNodes[0]; ClassNode declaringClass = annotatedMethod.declaringClass; MethodNode injectMethod = AnnotationUtils.getInjectViewsMethod(declaringClass); def ids = []; String methodReturn = annotatedMethod.getReturnType().name; if (methodReturn != "boolean" && methodReturn != "java.lang.Boolean") { throw new Exception("OnEditorAction must return a boolean value. Return type: " + "$methodReturn"); } if (annotation.members.size() > 0) { if (annotation.members.value instanceof ListExpression) { annotation.members.value.getExpressions().each { ids << (String) it.property.getValue(); }; } else { ids << (String) annotation.members.value.property.getValue(); } } else { throw new Exception("OnChecked must have an id"); } List<Statement> statementList = ((BlockStatement) injectMethod.getCode()).getStatements(); ids.each { String id -> Statement statement = createInjectStatement(id, annotatedMethod, injectMethod); statementList.add(statement); } } private Statement createInjectStatement(String id, MethodNode method, MethodNode injectMethod) { Parameter viewParameter = injectMethod.parameters.first() Variable variable = varX("v", ClassHelper.make(TextView)) BlockStatement statement = block( AnnotationUtils.createInjectExpression(variable, viewParameter, id), stmt(callX(ClassHelper.make(SwissKnife), "setOnEditorAction", args(varX(variable), varX("this"), constX(method.name)))) ) return statement; } }
{ "pile_set_name": "Github" }
.dark{ padding: 20px; background-color: #3d414d; }
{ "pile_set_name": "Github" }
/* librtmp - Diffie-Hellmann Key Exchange * Copyright (C) 2009 Andrej Stepanchuk * * This file is part of librtmp. * * librtmp is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1, * or (at your option) any later version. * * librtmp 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 Lesser General Public License * along with librtmp see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/lgpl.html */ /* from RFC 3526, see http://www.ietf.org/rfc/rfc3526.txt */ /* 2^768 - 2 ^704 - 1 + 2^64 * { [2^638 pi] + 149686 } */ #define P768 \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF" /* 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 } */ #define P1024 \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381" \ "FFFFFFFFFFFFFFFF" /* Group morder largest prime factor: */ #define Q1024 \ "7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68" \ "948127044533E63A0105DF531D89CD9128A5043CC71A026E" \ "F7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122" \ "F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6" \ "F71C35FDAD44CFD2D74F9208BE258FF324943328F67329C0" \ "FFFFFFFFFFFFFFFF" /* 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 } */ #define P1536 \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF" /* 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } */ #define P2048 \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ "15728E5A8AACAA68FFFFFFFFFFFFFFFF" /* 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 } */ #define P3072 \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" /* 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 } */ #define P4096 \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \ "FFFFFFFFFFFFFFFF" /* 2^6144 - 2^6080 - 1 + 2^64 * { [2^6014 pi] + 929484 } */ #define P6144 \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" \ "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" \ "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" \ "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" \ "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" \ "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" \ "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" \ "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" \ "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" \ "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" \ "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" \ "12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF" /* 2^8192 - 2^8128 - 1 + 2^64 * { [2^8062 pi] + 4743158 } */ #define P8192 \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" \ "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" \ "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" \ "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" \ "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" \ "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" \ "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" \ "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" \ "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" \ "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" \ "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" \ "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" \ "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300" \ "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" \ "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" \ "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" \ "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A" \ "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" \ "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1" \ "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" \ "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47" \ "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" \ "60C980DD98EDD3DFFFFFFFFFFFFFFFFF"
{ "pile_set_name": "Github" }
package body Pkg1 with SPARK_Mode => Off is function F (X : Integer) return Integer; function F (X : Integer) return Integer is begin return X / 2; end F; X : constant Boolean := (for all X in Integer => F (X) = X); function P return Boolean is begin return X; end P; end Pkg1;
{ "pile_set_name": "Github" }
# frozen_string_literal: true require 'rails_helper' describe ThemeModifierHelper do fab!(:theme) { Fabricate(:theme).tap { |t| t.theme_modifier_set.update!(serialize_topic_excerpts: true) } } it "defines a getter for modifiers" do tmh = ThemeModifierHelper.new(theme_ids: [theme.id]) expect(tmh.serialize_topic_excerpts).to eq(true) end it "can extract theme ids from a request object" do request = Rack::Request.new({ resolved_theme_ids: [theme.id] }) tmh = ThemeModifierHelper.new(request: request) expect(tmh.serialize_topic_excerpts).to eq(true) end end
{ "pile_set_name": "Github" }
{ "commentStamp" : "", "super" : "WAFormTestCase", "category" : "Seaside-Tests-Pharo-Core", "classinstvars" : [ ], "pools" : [ ], "classvars" : [ ], "instvars" : [ ], "name" : "WAPharoDocumentHandlerTest", "type" : "normal" }
{ "pile_set_name": "Github" }
9
{ "pile_set_name": "Github" }
import json import os from click.testing import CliRunner from great_expectations import DataContext from great_expectations.cli import cli from tests.cli.utils import assert_no_logging_messages_or_tracebacks def test_validation_operator_run_interactive_golden_path( caplog, data_context_simple_expectation_suite, filesystem_csv_2 ): """ Interactive mode golden path - pass an existing suite name and an existing validation operator name, select an existing file. """ not_so_empty_data_context = data_context_simple_expectation_suite root_dir = not_so_empty_data_context.root_directory os.mkdir(os.path.join(root_dir, "uncommitted")) runner = CliRunner(mix_stderr=False) csv_path = os.path.join(filesystem_csv_2, "f1.csv") result = runner.invoke( cli, [ "validation-operator", "run", "-d", root_dir, "--name", "default", "--suite", "default", ], input=f"{csv_path}\n", catch_exceptions=False, ) stdout = result.stdout assert "Validation failed" in stdout assert result.exit_code == 1 assert_no_logging_messages_or_tracebacks(caplog, result) def test_validation_operator_run_interactive_pass_non_existing_expectation_suite( caplog, data_context_parameterized_expectation_suite, filesystem_csv_2 ): """ Interactive mode: pass an non-existing suite name and an existing validation operator name, select an existing file. """ not_so_empty_data_context = data_context_parameterized_expectation_suite root_dir = not_so_empty_data_context.root_directory os.mkdir(os.path.join(root_dir, "uncommitted")) runner = CliRunner(mix_stderr=False) csv_path = os.path.join(filesystem_csv_2, "f1.csv") result = runner.invoke( cli, [ "validation-operator", "run", "-d", root_dir, "--name", "default", "--suite", "this.suite.does.not.exist", ], input=f"{csv_path}\n", catch_exceptions=False, ) stdout = result.stdout assert "Could not find a suite named" in stdout assert result.exit_code == 1 assert_no_logging_messages_or_tracebacks(caplog, result) def test_validation_operator_run_interactive_pass_non_existing_operator_name( caplog, data_context_parameterized_expectation_suite, filesystem_csv_2 ): """ Interactive mode: pass an non-existing suite name and an existing validation operator name, select an existing file. """ not_so_empty_data_context = data_context_parameterized_expectation_suite root_dir = not_so_empty_data_context.root_directory os.mkdir(os.path.join(root_dir, "uncommitted")) runner = CliRunner(mix_stderr=False) csv_path = os.path.join(filesystem_csv_2, "f1.csv") result = runner.invoke( cli, [ "validation-operator", "run", "-d", root_dir, "--name", "this_val_op_does_not_exist", "--suite", "my_dag_node.default", ], input=f"{csv_path}\n", catch_exceptions=False, ) stdout = result.stdout assert "Could not find a validation operator" in stdout assert result.exit_code == 1 assert_no_logging_messages_or_tracebacks(caplog, result) def test_validation_operator_run_noninteractive_golden_path( caplog, data_context_simple_expectation_suite, filesystem_csv_2 ): """ Non-nteractive mode golden path - use the --validation_config_file argument to pass the path to a valid validation config file """ not_so_empty_data_context = data_context_simple_expectation_suite root_dir = not_so_empty_data_context.root_directory os.mkdir(os.path.join(root_dir, "uncommitted")) csv_path = os.path.join(filesystem_csv_2, "f1.csv") validation_config = { "validation_operator_name": "default", "batches": [ { "batch_kwargs": { "path": csv_path, "datasource": "mydatasource", "reader_method": "read_csv", }, "expectation_suite_names": ["default"], } ], } validation_config_file_path = os.path.join( root_dir, "uncommitted", "validation_config_1.json" ) with open(validation_config_file_path, "w") as f: json.dump(validation_config, f) runner = CliRunner(mix_stderr=False) result = runner.invoke( cli, [ "validation-operator", "run", "-d", root_dir, "--validation_config_file", validation_config_file_path, ], catch_exceptions=False, ) stdout = result.stdout assert "Validation failed" in stdout assert result.exit_code == 1 assert_no_logging_messages_or_tracebacks(caplog, result) def test_validation_operator_run_noninteractive_validation_config_file_does_not_exist( caplog, data_context_parameterized_expectation_suite, filesystem_csv_2 ): """ Non-nteractive mode. Use the --validation_config_file argument to pass the path to a validation config file that does not exist. """ not_so_empty_data_context = data_context_parameterized_expectation_suite root_dir = not_so_empty_data_context.root_directory os.mkdir(os.path.join(root_dir, "uncommitted")) validation_config_file_path = os.path.join( root_dir, "uncommitted", "validation_config_1.json" ) runner = CliRunner(mix_stderr=False) result = runner.invoke( cli, [ "validation-operator", "run", "-d", root_dir, "--validation_config_file", validation_config_file_path, ], catch_exceptions=False, ) stdout = result.stdout assert "Failed to process the --validation_config_file argument" in stdout assert result.exit_code == 1 assert_no_logging_messages_or_tracebacks(caplog, result) def test_validation_operator_run_noninteractive_validation_config_file_does_is_misconfigured( caplog, data_context_parameterized_expectation_suite, filesystem_csv_2 ): """ Non-nteractive mode. Use the --validation_config_file argument to pass the path to a validation config file that is misconfigured - one of the batches does not have expectation_suite_names attribute """ not_so_empty_data_context = data_context_parameterized_expectation_suite root_dir = not_so_empty_data_context.root_directory os.mkdir(os.path.join(root_dir, "uncommitted")) csv_path = os.path.join(filesystem_csv_2, "f1.csv") validation_config = { "validation_operator_name": "default", "batches": [ { "batch_kwargs": { "path": csv_path, "datasource": "mydatasource", "reader_method": "read_csv", }, "wrong_attribute_expectation_suite_names": ["my_dag_node.default1"], } ], } validation_config_file_path = os.path.join( root_dir, "uncommitted", "validation_config_1.json" ) with open(validation_config_file_path, "w") as f: json.dump(validation_config, f) runner = CliRunner(mix_stderr=False) result = runner.invoke( cli, [ "validation-operator", "run", "-d", root_dir, "--validation_config_file", validation_config_file_path, ], catch_exceptions=False, ) stdout = result.stdout assert ( "is misconfigured: Each batch must have a list of expectation suite names" in stdout ) assert result.exit_code == 1 assert_no_logging_messages_or_tracebacks(caplog, result) def test_validation_operator_list_with_one_operator(caplog, empty_data_context): project_dir = empty_data_context.root_directory context = DataContext(project_dir) context.create_expectation_suite("a.warning") def test_validation_operator_list_with_zero_validation_operators( caplog, empty_data_context ): project_dir = empty_data_context.root_directory context = DataContext(project_dir) context._project_config.validation_operators = {} context._save_project_config() runner = CliRunner(mix_stderr=False) result = runner.invoke( cli, "validation-operator list -d {}".format(project_dir), catch_exceptions=False, ) assert result.exit_code == 0 assert "No Validation Operators found" in result.output assert_no_logging_messages_or_tracebacks(caplog, result) def test_validation_operator_list_with_one_validation_operator( caplog, empty_data_context ): project_dir = empty_data_context.root_directory runner = CliRunner(mix_stderr=False) expected_result = """Heads up! This feature is Experimental. It may change. Please give us your feedback! 1 Validation Operator found:  - name: action_list_operator class_name: ActionListValidationOperator action_list: store_validation_result (StoreValidationResultAction) => store_evaluation_params (StoreEvaluationParametersAction) => update_data_docs (UpdateDataDocsAction)""" result = runner.invoke( cli, "validation-operator list -d {}".format(project_dir), catch_exceptions=False, ) assert result.exit_code == 0 # _capture_ansi_codes_to_file(result) assert result.output.strip() == expected_result assert_no_logging_messages_or_tracebacks(caplog, result) def test_validation_operator_list_with_multiple_validation_operators( caplog, empty_data_context ): project_dir = empty_data_context.root_directory runner = CliRunner(mix_stderr=False) context = DataContext(project_dir) context.add_validation_operator( "my_validation_operator", { "class_name": "WarningAndFailureExpectationSuitesValidationOperator", "action_list": [ { "name": "store_validation_result", "action": {"class_name": "StoreValidationResultAction"}, }, { "name": "store_evaluation_params", "action": {"class_name": "StoreEvaluationParametersAction"}, }, { "name": "update_data_docs", "action": {"class_name": "UpdateDataDocsAction"}, }, ], "base_expectation_suite_name": "new-years-expectations", "slack_webhook": "https://hooks.slack.com/services/dummy", }, ) context._save_project_config() expected_result = """Heads up! This feature is Experimental. It may change. Please give us your feedback! 2 Validation Operators found:  - name: action_list_operator class_name: ActionListValidationOperator action_list: store_validation_result (StoreValidationResultAction) => store_evaluation_params (StoreEvaluationParametersAction) => update_data_docs (UpdateDataDocsAction)  - name: my_validation_operator class_name: WarningAndFailureExpectationSuitesValidationOperator action_list: store_validation_result (StoreValidationResultAction) => store_evaluation_params (StoreEvaluationParametersAction) => update_data_docs (UpdateDataDocsAction) base_expectation_suite_name: new-years-expectations slack_webhook: https://hooks.slack.com/services/dummy""" result = runner.invoke( cli, "validation-operator list -d {}".format(project_dir), catch_exceptions=False, ) assert result.exit_code == 0 # _capture_ansi_codes_to_file(result) assert result.output.strip() == expected_result assert_no_logging_messages_or_tracebacks(caplog, result) def _capture_ansi_codes_to_file(result): """ Use this to capture the ANSI color codes when updating snapshots. NOT DEAD CODE. """ with open("ansi.txt", "w") as f: f.write(result.output.strip())
{ "pile_set_name": "Github" }
/*- * BSD LICENSE * * Copyright (c) Intel Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "json_internal.h" static int hex_value(uint8_t c) { #define V(x, y) [x] = y + 1 static const int8_t val[256] = { V('0', 0), V('1', 1), V('2', 2), V('3', 3), V('4', 4), V('5', 5), V('6', 6), V('7', 7), V('8', 8), V('9', 9), V('A', 0xA), V('B', 0xB), V('C', 0xC), V('D', 0xD), V('E', 0xE), V('F', 0xF), V('a', 0xA), V('b', 0xB), V('c', 0xC), V('d', 0xD), V('e', 0xE), V('f', 0xF), }; #undef V return val[c] - 1; } static int json_decode_string_escape_unicode(uint8_t **strp, uint8_t *buf_end, uint8_t *out) { uint8_t *str = *strp; int v0, v1, v2, v3; uint32_t val; uint32_t surrogate_high = 0; int rc; decode: /* \uXXXX */ assert(buf_end > str); if (*str++ != '\\') return SPDK_JSON_PARSE_INVALID; if (buf_end == str) return SPDK_JSON_PARSE_INCOMPLETE; if (*str++ != 'u') return SPDK_JSON_PARSE_INVALID; if (buf_end == str) return SPDK_JSON_PARSE_INCOMPLETE; if ((v3 = hex_value(*str++)) < 0) return SPDK_JSON_PARSE_INVALID; if (buf_end == str) return SPDK_JSON_PARSE_INCOMPLETE; if ((v2 = hex_value(*str++)) < 0) return SPDK_JSON_PARSE_INVALID; if (buf_end == str) return SPDK_JSON_PARSE_INCOMPLETE; if ((v1 = hex_value(*str++)) < 0) return SPDK_JSON_PARSE_INVALID; if (buf_end == str) return SPDK_JSON_PARSE_INCOMPLETE; if ((v0 = hex_value(*str++)) < 0) return SPDK_JSON_PARSE_INVALID; if (buf_end == str) return SPDK_JSON_PARSE_INCOMPLETE; val = v0 | (v1 << 4) | (v2 << 8) | (v3 << 12); if (surrogate_high) { /* We already parsed the high surrogate, so this should be the low part. */ if (!utf16_valid_surrogate_low(val)) { return SPDK_JSON_PARSE_INVALID; } /* Convert UTF-16 surrogate pair into codepoint and fall through to utf8_encode. */ val = utf16_decode_surrogate_pair(surrogate_high, val); } else if (utf16_valid_surrogate_high(val)) { surrogate_high = val; /* * We parsed a \uXXXX sequence that decoded to the first half of a * UTF-16 surrogate pair, so it must be immediately followed by another * \uXXXX escape. * * Loop around to get the low half of the surrogate pair. */ if (buf_end == str) return SPDK_JSON_PARSE_INCOMPLETE; goto decode; } else if (utf16_valid_surrogate_low(val)) { /* * We found the second half of surrogate pair without the first half; * this is an invalid encoding. */ return SPDK_JSON_PARSE_INVALID; } /* * Convert Unicode escape (or surrogate pair) to UTF-8 in place. * * This is safe (will not write beyond the buffer) because the \uXXXX sequence is 6 bytes * (or 12 bytes for surrogate pairs), and the longest possible UTF-8 encoding of a * single codepoint is 4 bytes. */ if (out) { rc = utf8_encode_unsafe(out, val); } else { rc = utf8_codepoint_len(val); } if (rc < 0) { return SPDK_JSON_PARSE_INVALID; } *strp = str; /* update input pointer */ return rc; /* return number of bytes decoded */ } static int json_decode_string_escape_twochar(uint8_t **strp, uint8_t *buf_end, uint8_t *out) { static const uint8_t escapes[256] = { ['b'] = '\b', ['f'] = '\f', ['n'] = '\n', ['r'] = '\r', ['t'] = '\t', ['/'] = '/', ['"'] = '"', ['\\'] = '\\', }; uint8_t *str = *strp; uint8_t c; assert(buf_end > str); if (buf_end - str < 2) { return SPDK_JSON_PARSE_INCOMPLETE; } assert(str[0] == '\\'); c = escapes[str[1]]; if (c) { if (out) { *out = c; } *strp += 2; /* consumed two bytes */ return 1; /* produced one byte */ } return SPDK_JSON_PARSE_INVALID; } /* * Decode JSON string backslash escape. * \param strp pointer to pointer to first character of escape (the backslash). * *strp is also advanced to indicate how much input was consumed. * * \return Number of bytes appended to out */ static int json_decode_string_escape(uint8_t **strp, uint8_t *buf_end, uint8_t *out) { int rc; rc = json_decode_string_escape_twochar(strp, buf_end, out); if (rc > 0) { return rc; } return json_decode_string_escape_unicode(strp, buf_end, out); } /* * Decode JSON string in place. * * \param str_start Pointer to the beginning of the string (the opening " character). * * \return Number of bytes in decoded string (beginning from start). */ static int json_decode_string(uint8_t *str_start, uint8_t *buf_end, uint8_t **str_end, uint32_t flags) { uint8_t *str = str_start; uint8_t *out = str_start + 1; /* Decode string in place (skip the initial quote) */ int rc; if (buf_end - str_start < 2) { /* * Shortest valid string (the empty string) is two bytes (""), * so this can't possibly be valid */ *str_end = str; return SPDK_JSON_PARSE_INCOMPLETE; } if (*str++ != '"') { *str_end = str; return SPDK_JSON_PARSE_INVALID; } while (str < buf_end) { if (str[0] == '"') { /* * End of string. * Update str_end to point at next input byte and return output length. */ *str_end = str + 1; return out - str_start - 1; } else if (str[0] == '\\') { rc = json_decode_string_escape(&str, buf_end, flags & SPDK_JSON_PARSE_FLAG_DECODE_IN_PLACE ? out : NULL); assert(rc != 0); if (rc < 0) { *str_end = str; return rc; } out += rc; } else if (str[0] <= 0x1f) { /* control characters must be escaped */ *str_end = str; return SPDK_JSON_PARSE_INVALID; } else { rc = utf8_valid(str, buf_end); if (rc == 0) { *str_end = str; return SPDK_JSON_PARSE_INCOMPLETE; } else if (rc < 0) { *str_end = str; return SPDK_JSON_PARSE_INVALID; } if (out && out != str && (flags & SPDK_JSON_PARSE_FLAG_DECODE_IN_PLACE)) { memmove(out, str, rc); } out += rc; str += rc; } } /* If execution gets here, we ran out of buffer. */ *str_end = str; return SPDK_JSON_PARSE_INCOMPLETE; } static int json_valid_number(uint8_t *start, uint8_t *buf_end) { uint8_t *p = start; uint8_t c; if (p >= buf_end) return -1; c = *p++; if (c >= '1' && c <= '9') goto num_int_digits; if (c == '0') goto num_frac_or_exp; if (c == '-') goto num_int_first_digit; p--; goto done_invalid; num_int_first_digit: if (spdk_likely(p != buf_end)) { c = *p++; if (c == '0') goto num_frac_or_exp; if (c >= '1' && c <= '9') goto num_int_digits; p--; } goto done_invalid; num_int_digits: if (spdk_likely(p != buf_end)) { c = *p++; if (c >= '0' && c <= '9') goto num_int_digits; if (c == '.') goto num_frac_first_digit; if (c == 'e' || c == 'E') goto num_exp_sign; p--; } goto done_valid; num_frac_or_exp: if (spdk_likely(p != buf_end)) { c = *p++; if (c == '.') goto num_frac_first_digit; if (c == 'e' || c == 'E') goto num_exp_sign; p--; } goto done_valid; num_frac_first_digit: if (spdk_likely(p != buf_end)) { c = *p++; if (c >= '0' && c <= '9') goto num_frac_digits; p--; } goto done_invalid; num_frac_digits: if (spdk_likely(p != buf_end)) { c = *p++; if (c >= '0' && c <= '9') goto num_frac_digits; if (c == 'e' || c == 'E') goto num_exp_sign; p--; } goto done_valid; num_exp_sign: if (spdk_likely(p != buf_end)) { c = *p++; if (c >= '0' && c <= '9') goto num_exp_digits; if (c == '-' || c == '+') goto num_exp_first_digit; p--; } goto done_invalid; num_exp_first_digit: if (spdk_likely(p != buf_end)) { c = *p++; if (c >= '0' && c <= '9') goto num_exp_digits; p--; } goto done_invalid; num_exp_digits: if (spdk_likely(p != buf_end)) { c = *p++; if (c >= '0' && c <= '9') goto num_exp_digits; p--; } goto done_valid; done_valid: /* Valid end state */ return p - start; done_invalid: /* Invalid end state */ if (p == buf_end) { /* Hit the end of the buffer - the stream is incomplete. */ return SPDK_JSON_PARSE_INCOMPLETE; } /* Found an invalid character in an invalid end state */ return SPDK_JSON_PARSE_INVALID; } static int json_valid_comment(const uint8_t *start, const uint8_t *buf_end) { const uint8_t *p = start; bool multiline; assert(buf_end > p); if (buf_end - p < 2) { return SPDK_JSON_PARSE_INCOMPLETE; } if (p[0] != '/') { return SPDK_JSON_PARSE_INVALID; } if (p[1] == '*') { multiline = true; } else if (p[1] == '/') { multiline = false; } else { return SPDK_JSON_PARSE_INVALID; } p += 2; if (multiline) { while (p != buf_end - 1) { if (p[0] == '*' && p[1] == '/') { /* Include the terminating star and slash in the comment */ return p - start + 2; } p++; } } else { while (p != buf_end) { if (*p == '\r' || *p == '\n') { /* Do not include the line terminator in the comment */ return p - start; } p++; } } return SPDK_JSON_PARSE_INCOMPLETE; } struct json_literal { enum spdk_json_val_type type; uint32_t len; uint8_t str[8]; }; /* * JSON only defines 3 possible literals; they can be uniquely identified by bits * 3 and 4 of the first character: * 'f' = 0b11[00]110 * 'n' = 0b11[01]110 * 't' = 0b11[10]100 * These two bits can be used as an index into the g_json_literals array. */ static const struct json_literal g_json_literals[] = { {SPDK_JSON_VAL_FALSE, 5, "false"}, {SPDK_JSON_VAL_NULL, 4, "null"}, {SPDK_JSON_VAL_TRUE, 4, "true"}, {} }; static int match_literal(const uint8_t *start, const uint8_t *end, const uint8_t *literal, size_t len) { assert(end >= start); if ((size_t)(end - start) < len) { return SPDK_JSON_PARSE_INCOMPLETE; } if (memcmp(start, literal, len) != 0) { return SPDK_JSON_PARSE_INVALID; } return len; } ssize_t spdk_json_parse(void *json, size_t size, struct spdk_json_val *values, size_t num_values, void **end, uint32_t flags) { uint8_t *json_end = json + size; enum spdk_json_val_type containers[SPDK_JSON_MAX_NESTING_DEPTH]; size_t con_value[SPDK_JSON_MAX_NESTING_DEPTH]; enum spdk_json_val_type con_type = SPDK_JSON_VAL_INVALID; bool trailing_comma = false; size_t depth = 0; /* index into containers */ size_t cur_value = 0; /* index into values */ size_t con_start_value; uint8_t *data = json; uint8_t *new_data; int rc = 0; const struct json_literal *lit; enum { STATE_VALUE, /* initial state */ STATE_VALUE_SEPARATOR, /* value separator (comma) */ STATE_NAME, /* "name": value */ STATE_NAME_SEPARATOR, /* colon */ STATE_END, /* parsed the complete value, so only whitespace is valid */ } state = STATE_VALUE; #define ADD_VALUE(t, val_start_ptr, val_end_ptr) \ if (values && cur_value < num_values) { \ values[cur_value].type = t; \ values[cur_value].start = val_start_ptr; \ values[cur_value].len = val_end_ptr - val_start_ptr; \ } \ cur_value++ while (data < json_end) { uint8_t c = *data; switch (c) { case ' ': case '\t': case '\r': case '\n': /* Whitespace is allowed between any tokens. */ data++; break; case 't': case 'f': case 'n': /* true, false, or null */ if (state != STATE_VALUE) goto done_invalid; lit = &g_json_literals[(c >> 3) & 3]; /* See comment above g_json_literals[] */ assert(lit->str[0] == c); rc = match_literal(data, json_end, lit->str, lit->len); if (rc < 0) goto done_rc; ADD_VALUE(lit->type, data, data + rc); data += rc; state = depth ? STATE_VALUE_SEPARATOR : STATE_END; trailing_comma = false; break; case '"': if (state != STATE_VALUE && state != STATE_NAME) goto done_invalid; rc = json_decode_string(data, json_end, &new_data, flags); if (rc < 0) { data = new_data; goto done_rc; } /* * Start is data + 1 to skip initial quote. * Length is data + rc - 1 to skip both quotes. */ ADD_VALUE(state == STATE_VALUE ? SPDK_JSON_VAL_STRING : SPDK_JSON_VAL_NAME, data + 1, data + rc - 1); data = new_data; if (state == STATE_NAME) { state = STATE_NAME_SEPARATOR; } else { state = depth ? STATE_VALUE_SEPARATOR : STATE_END; } trailing_comma = false; break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (state != STATE_VALUE) goto done_invalid; rc = json_valid_number(data, json_end); if (rc < 0) goto done_rc; ADD_VALUE(SPDK_JSON_VAL_NUMBER, data, data + rc); data += rc; state = depth ? STATE_VALUE_SEPARATOR : STATE_END; trailing_comma = false; break; case '{': case '[': if (state != STATE_VALUE) goto done_invalid; if (depth == SPDK_JSON_MAX_NESTING_DEPTH) { rc = SPDK_JSON_PARSE_MAX_DEPTH_EXCEEDED; goto done_rc; } if (c == '{') { con_type = SPDK_JSON_VAL_OBJECT_BEGIN; state = STATE_NAME; } else { con_type = SPDK_JSON_VAL_ARRAY_BEGIN; state = STATE_VALUE; } con_value[depth] = cur_value; containers[depth++] = con_type; ADD_VALUE(con_type, data, data + 1); data++; trailing_comma = false; break; case '}': case ']': if (trailing_comma) goto done_invalid; if (depth == 0) goto done_invalid; con_type = containers[--depth]; con_start_value = con_value[depth]; if (values && con_start_value < num_values) { values[con_start_value].len = cur_value - con_start_value - 1; } if (c == '}') { if (state != STATE_NAME && state != STATE_VALUE_SEPARATOR) { goto done_invalid; } if (con_type != SPDK_JSON_VAL_OBJECT_BEGIN) { goto done_invalid; } ADD_VALUE(SPDK_JSON_VAL_OBJECT_END, data, data + 1); } else { if (state != STATE_VALUE && state != STATE_VALUE_SEPARATOR) { goto done_invalid; } if (con_type != SPDK_JSON_VAL_ARRAY_BEGIN) { goto done_invalid; } ADD_VALUE(SPDK_JSON_VAL_ARRAY_END, data, data + 1); } con_type = depth == 0 ? SPDK_JSON_VAL_INVALID : containers[depth - 1]; data++; state = depth ? STATE_VALUE_SEPARATOR : STATE_END; trailing_comma = false; break; case ',': if (state != STATE_VALUE_SEPARATOR) goto done_invalid; data++; assert(con_type == SPDK_JSON_VAL_ARRAY_BEGIN || con_type == SPDK_JSON_VAL_OBJECT_BEGIN); state = con_type == SPDK_JSON_VAL_ARRAY_BEGIN ? STATE_VALUE : STATE_NAME; trailing_comma = true; break; case ':': if (state != STATE_NAME_SEPARATOR) goto done_invalid; data++; state = STATE_VALUE; break; case '/': if (!(flags & SPDK_JSON_PARSE_FLAG_ALLOW_COMMENTS)) { goto done_invalid; } rc = json_valid_comment(data, json_end); if (rc < 0) goto done_rc; /* Skip over comment */ data += rc; break; default: goto done_invalid; } if (state == STATE_END) { break; } } if (state == STATE_END) { /* Skip trailing whitespace */ while (data < json_end) { uint8_t c = *data; if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { data++; } else { break; } } /* * These asserts are just for sanity checking - they are guaranteed by the allowed * state transitions. */ assert(depth == 0); assert(trailing_comma == false); assert(data <= json_end); if (end) { *end = data; } return cur_value; } /* Invalid end state - ran out of data */ rc = SPDK_JSON_PARSE_INCOMPLETE; done_rc: assert(rc < 0); if (end) { *end = data; } return rc; done_invalid: rc = SPDK_JSON_PARSE_INVALID; goto done_rc; }
{ "pile_set_name": "Github" }
<?php /* * This file is part of ProgPilot, a static analyzer for security * * @copyright 2017 Eric Therond. All rights reserved * @license MIT See LICENSE at the root of the project for more info */ namespace progpilot\Inputs; class MyCustomFunction extends MySpecify { private $parameters; private $hasParameters; private $action; private $orderNumberExpected; private $orderNumberReal; private $minNbArgs; private $maxNbArgs; public function __construct($name, $language, $orderNumberExpected = 0) { parent::__construct($name, $language); $this->action = null; $this->orderNumberExpected = $orderNumberExpected; $this->orderNumberReal = -1; $this->minNbArgs = 0; $this->maxNbArgs = PHP_INT_MAX; $this->hasParameters = false; $this->parameters = []; } public function addParameter($parameter, $validbydefault, $fixed, $values = null) { $this->parameters[] = [$parameter, $values, $validbydefault, $fixed]; } public function getParameters() { return $this->parameters; } public function hasParameters() { return $this->hasParameters; } public function setHasParameters($hasParameters) { $this->hasParameters = $hasParameters; } public function isParameterFixed($i) { foreach ($this->parameters as $parameter) { $index = $parameter[0]; $values = $parameter[1]; $validbydefault = $parameter[2]; $fixed = $parameter[3]; if ($index === $i) { return $fixed; } } return false; } public function isParameterValidByDefault($i) { foreach ($this->parameters as $parameter) { $index = $parameter[0]; $values = $parameter[1]; $validbydefault = $parameter[2]; if ($index === $i) { return $validbydefault; } } return false; } public function getParameterValues($i) { foreach ($this->parameters as $parameter) { $index = $parameter[0]; $values = $parameter[1]; if ($index === $i) { return $values; } } return null; } public function setOrderNumberReal($orderNumberReal) { $this->orderNumberReal = $orderNumberReal; } public function getOrderNumberReal() { return $this->orderNumberReal; } public function setOrderNumberExpected($orderNumberExpected) { $this->orderNumberExpected = $orderNumberExpected; } public function getOrderNumberExpected() { return $this->orderNumberExpected; } public function getAction() { return $this->action; } public function setAction($action) { return $this->action = $action; } public function setMinNbArgs($minNbArgs) { return $this->minNbArgs = $minNbArgs; } public function getMinNbArgs() { return $this->minNbArgs; } public function setMaxNbArgs($maxNbArgs) { return $this->maxNbArgs = $maxNbArgs; } public function getMaxNbArgs() { return $this->maxNbArgs; } }
{ "pile_set_name": "Github" }
Barfoo foo-Bar foo-BAZ BAZ-foo BAZ-Bar
{ "pile_set_name": "Github" }
# model node attributes [group Node Attributes] [attr force_expand] default BOOL false label STRING "Expand Node" private BOOL true [input file] default FILE "" [group Outputs] [output outMesh] default NODE "" [output Alembic] default FILE "" visibility BOOL true
{ "pile_set_name": "Github" }
diff -uprN old/include/linux/log2.h new/include/linux/log2.h --- old/include/linux/log2.h 2017-01-06 17:40:28.000000000 +0800 +++ new/include/linux/log2.h 2020-06-05 14:52:55.645814146 +0800 @@ -16,12 +16,6 @@ #include <linux/bitops.h> /* - * deal with unrepresentable constant logarithms - */ -extern __attribute__((const, noreturn)) -int ____ilog2_NaN(void); - -/* * non-constant log of base 2 calculators * - the arch may override these in asm/bitops.h if they can be implemented * more efficiently than using fls() and fls64() @@ -85,7 +79,7 @@ unsigned long __rounddown_pow_of_two(uns #define ilog2(n) \ ( \ __builtin_constant_p(n) ? ( \ - (n) < 1 ? ____ilog2_NaN() : \ + (n) < 2 ? 0 : \ (n) & (1ULL << 63) ? 63 : \ (n) & (1ULL << 62) ? 62 : \ (n) & (1ULL << 61) ? 61 : \ @@ -148,10 +142,7 @@ unsigned long __rounddown_pow_of_two(uns (n) & (1ULL << 4) ? 4 : \ (n) & (1ULL << 3) ? 3 : \ (n) & (1ULL << 2) ? 2 : \ - (n) & (1ULL << 1) ? 1 : \ - (n) & (1ULL << 0) ? 0 : \ - ____ilog2_NaN() \ - ) : \ + 1) : \ (sizeof(n) <= 4) ? \ __ilog2_u32(n) : \ __ilog2_u64(n) \ diff -uprN old/tools/include/linux/log2.h new/tools/include/linux/log2.h --- old/tools/include/linux/log2.h 2017-01-06 17:40:28.000000000 +0800 +++ new/tools/include/linux/log2.h 2020-06-05 14:53:10.733954102 +0800 @@ -13,12 +13,6 @@ #define _TOOLS_LINUX_LOG2_H /* - * deal with unrepresentable constant logarithms - */ -extern __attribute__((const, noreturn)) -int ____ilog2_NaN(void); - -/* * non-constant log of base 2 calculators * - the arch may override these in asm/bitops.h if they can be implemented * more efficiently than using fls() and fls64() @@ -78,7 +72,7 @@ unsigned long __rounddown_pow_of_two(uns #define ilog2(n) \ ( \ __builtin_constant_p(n) ? ( \ - (n) < 1 ? ____ilog2_NaN() : \ + (n) < 2 ? 0 : \ (n) & (1ULL << 63) ? 63 : \ (n) & (1ULL << 62) ? 62 : \ (n) & (1ULL << 61) ? 61 : \ @@ -141,10 +135,7 @@ unsigned long __rounddown_pow_of_two(uns (n) & (1ULL << 4) ? 4 : \ (n) & (1ULL << 3) ? 3 : \ (n) & (1ULL << 2) ? 2 : \ - (n) & (1ULL << 1) ? 1 : \ - (n) & (1ULL << 0) ? 0 : \ - ____ilog2_NaN() \ - ) : \ + 1) : \ (sizeof(n) <= 4) ? \ __ilog2_u32(n) : \ __ilog2_u64(n) \
{ "pile_set_name": "Github" }
; RUN: not llvm-link %s %p/module-flags-5-b.ll -S -o - 2>&1 | FileCheck %s ; Test the 'override' error. ; CHECK: linking module flags 'foo': IDs have conflicting override values !0 = !{ i32 4, !"foo", i32 927 } !llvm.module.flags = !{ !0 }
{ "pile_set_name": "Github" }
<?xml version='1.0'?> <!-- 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. --> <!DOCTYPE driver PUBLIC '-//NetBeans//DTD JDBC Driver 1.1//EN' 'http://www.netbeans.org/dtds/jdbc-driver-1_1.dtd'> <driver> <name value='OracleOCI'/> <display-name value='Oracle OCI'/> <class value='oracle.jdbc.driver.OracleDriver'/> </driver>
{ "pile_set_name": "Github" }
module.exports = { 'at': require('./wrapperAt'), 'chain': require('./chain'), 'commit': require('./commit'), 'lodash': require('./wrapperLodash'), 'next': require('./next'), 'plant': require('./plant'), 'reverse': require('./wrapperReverse'), 'tap': require('./tap'), 'thru': require('./thru'), 'toIterator': require('./toIterator'), 'toJSON': require('./toJSON'), 'value': require('./wrapperValue'), 'valueOf': require('./valueOf'), 'wrapperChain': require('./wrapperChain') };
{ "pile_set_name": "Github" }
# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
{ "pile_set_name": "Github" }
// This is a generated file. Not intended for manual editing. package com.intellij.lang.jsgraphql.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.intellij.lang.jsgraphql.psi.GraphQLElementTypes.*; import com.intellij.lang.jsgraphql.psi.*; public class GraphQLTypeNameDefinitionImpl extends GraphQLNamedElementImpl implements GraphQLTypeNameDefinition { public GraphQLTypeNameDefinitionImpl(ASTNode node) { super(node); } public void accept(@NotNull GraphQLVisitor visitor) { visitor.visitTypeNameDefinition(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GraphQLVisitor) accept((GraphQLVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GraphQLIdentifier getNameIdentifier() { return findNotNullChildByClass(GraphQLIdentifier.class); } }
{ "pile_set_name": "Github" }
<template> <CommentForm operate="update" /> </template> <script> import CommentForm from './CommentForm' export default { components: { CommentForm } } </script>
{ "pile_set_name": "Github" }
from django.test import TestCase from django.utils.unittest import skipUnless from django.contrib.auth.models import User, AnonymousUser from django.core.management import call_command from StringIO import StringIO try: import crypt as crypt_module except ImportError: crypt_module = None class BasicTestCase(TestCase): def test_user(self): "Check that users can be created and can set their password" u = User.objects.create_user('testuser', '[email protected]', 'testpw') self.assertTrue(u.has_usable_password()) self.assertFalse(u.check_password('bad')) self.assertTrue(u.check_password('testpw')) # Check we can manually set an unusable password u.set_unusable_password() u.save() self.assertFalse(u.check_password('testpw')) self.assertFalse(u.has_usable_password()) u.set_password('testpw') self.assertTrue(u.check_password('testpw')) u.set_password(None) self.assertFalse(u.has_usable_password()) # Check authentication/permissions self.assertTrue(u.is_authenticated()) self.assertFalse(u.is_staff) self.assertTrue(u.is_active) self.assertFalse(u.is_superuser) # Check API-based user creation with no password u2 = User.objects.create_user('testuser2', '[email protected]') self.assertFalse(u.has_usable_password()) def test_user_no_email(self): "Check that users can be created without an email" u = User.objects.create_user('testuser1') self.assertEqual(u.email, '') u2 = User.objects.create_user('testuser2', email='') self.assertEqual(u2.email, '') u3 = User.objects.create_user('testuser3', email=None) self.assertEqual(u3.email, '') def test_anonymous_user(self): "Check the properties of the anonymous user" a = AnonymousUser() self.assertFalse(a.is_authenticated()) self.assertFalse(a.is_staff) self.assertFalse(a.is_active) self.assertFalse(a.is_superuser) self.assertEqual(a.groups.all().count(), 0) self.assertEqual(a.user_permissions.all().count(), 0) def test_superuser(self): "Check the creation and properties of a superuser" super = User.objects.create_superuser('super', '[email protected]', 'super') self.assertTrue(super.is_superuser) self.assertTrue(super.is_active) self.assertTrue(super.is_staff) def test_createsuperuser_management_command(self): "Check the operation of the createsuperuser management command" # We can use the management command to create a superuser new_io = StringIO() call_command("createsuperuser", interactive=False, username="joe", email="[email protected]", stdout=new_io ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = User.objects.get(username="joe") self.assertEqual(u.email, '[email protected]') # created password should be unusable self.assertFalse(u.has_usable_password()) # We can supress output on the management command new_io = StringIO() call_command("createsuperuser", interactive=False, username="joe2", email="[email protected]", verbosity=0, stdout=new_io ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, '') u = User.objects.get(username="joe2") self.assertEqual(u.email, '[email protected]') self.assertFalse(u.has_usable_password()) new_io = StringIO() call_command("createsuperuser", interactive=False, username="[email protected]", email="[email protected]", stdout=new_io ) u = User.objects.get(username="[email protected]") self.assertEqual(u.email, '[email protected]') self.assertFalse(u.has_usable_password())
{ "pile_set_name": "Github" }
#ifndef ARRAY_H #define ARRAY_H #include "Lib.h" typedef struct { int size; // 陣列目前的上限 int count; // 陣列目前的元素個數 void **item; // 每個陣列元素的指標 } Array; // 動態陣列的資料結構 typedef enum { KEEP_SPLITER, REMOVE_SPLITER } SplitMode; extern void ArrayTest(); extern Array* ArrayNew(int size);// 建立新陣列 extern void ArrayFree(Array *array, FuncPtr1 freeFuncPtr); // 釋放該陣列 extern void ArrayAdd(Array *array, void *item); // 新增一個元素 extern void ArrayPush(Array *array,void *item); // (模擬堆疊) 推入一個元素 extern void* ArrayPop(Array *array); //(模擬堆疊) 彈出一個元素 extern void* ArrayPeek(Array *array); //(模擬堆疊) 取得最上面的元素 extern void* ArrayLast(Array *array); // 取得最後一個元素 extern void ArrayEach(Array *array, FuncPtr1 f); //對每個元素都執行 f 函數 extern Array* split(char *str, char *spliter, SplitMode mode); #endif
{ "pile_set_name": "Github" }