text
stringlengths
2
99.9k
meta
dict
#include <vdgl/vdgl_digital_curve.h> #include <vbl/io/vbl_io_smart_ptr.hxx> VBL_IO_SMART_PTR_INSTANTIATE(vdgl_digital_curve);
{ "pile_set_name": "Github" }
package cn.itcast_03; /* * 我们针对学生可以设置学生的属性,也可以获取学生的属性。这里我们就把设置看成是生产,获取看成是消费就可以了。 * 基本的类: * 学生类 * 设置属性的线程 * 获取属性的线程 * 测试类 * * 问题1:写了一些简单的代码后,我们发现数据有问题,是null---0 * 原因: * 我们设置的对象和获取的对象不是同一个,所以,拿不到值 * 解决: * 把设置和获取的对象变成同一个 */ public class StudentDemo { public static void main(String[] args) { // 创建一个学生资源 Student s = new Student(); // 创建线程对象 SetThread st = new SetThread(s); GetThread gt = new GetThread(s); Thread t1 = new Thread(st); Thread t2 = new Thread(gt); t1.start(); t2.start(); } }
{ "pile_set_name": "Github" }
--- title: "Review supported editions and products for upgrading to SharePoint 2013" ms.reviewer: ms.author: serdars author: SerdarSoysal manager: serdars ms.date: 7/26/2017 audience: ITPro f1.keywords: - NOCSH ms.topic: article ms.prod: sharepoint-server-itpro localization_priority: Normal ms.collection: - IT_Sharepoint_Server - IT_Sharepoint_Server_Top ms.assetid: b1088a52-179f-4120-8fb5-0ed3e6c088b1 description: "Understand the editions or versions of SharePoint 2010 Products that you can upgrade to specific editions or versions of SharePoint 2013." --- # Review supported editions and products for upgrading to SharePoint 2013 [!INCLUDE[appliesto-2013-xxx-xxx-xxx-md](../includes/appliesto-2013-xxx-xxx-xxx-md.md)] When you plan an upgrade process, make sure that you verify that the intended upgrade path is supported. This article describes the editions and products that are supported and unsupported to upgrade to SharePoint Server 2016. Be aware that in-place upgrade is not supported for upgrades to SharePoint 2013. This includes upgrades across editions, such as from SharePoint Foundation 2013 to SharePoint Server 2016. For more information, see [What's new in SharePoint 2013 upgrade](/previous-versions/office/sharepoint-server-2010/ee617150(v=office.14)). > [!IMPORTANT] > Upgrade from a pre-release version of SharePoint 2013 to the release version of SharePoint 2013 is not supported. > Pre-release versions are intended for testing only and should not be used in production environments. Upgrading from one pre-release version to another is also not supported. ## Supported topologies <a name="topologies"> </a> For SharePoint 2013, the only upgrade method is the database-attach upgrade method. Because this method upgrades the databases instead of installing in place over an existing environment, you can attach the databases from a stand-alone installation to server farm (Complete) installation if you want to expand your environment. **Figure: Upgrade to either stand-alone or server farm (Complete) topologies** ![Upgrade to either stand-alone or farm](../media/SP15Upgrade_SupportedTopologiesforUpgrade.gif) Before you create your new SharePoint 2013 environment and attach and upgrade the databases, determine the type and size of the environment that you need. ### Physical topology guidance <a name="section6"> </a> The SQL Server topology — in addition to network, physical storage, and caching considerations — can significantly affect system performance. To learn more about how to map your solution design to the farm size and hardware that will support your business goals, see [Performance planning in SharePoint Server 2013](../administration/performance-planning-in-sharepoint-server-2013.md). For more information about requirements, see [Hardware and software requirements for SharePoint 2013](../install/hardware-and-software-requirements-0.md). ## Supported editions for upgrade <a name="editions"> </a> The following table lists the editions available for SharePoint Server 2010 and the supported and unsupported ending editions when you upgrade to SharePoint Server 2016. Note that in-place upgrade is not supported. Database-attach upgrade is the only supported upgrade method. |**Starting edition**|**Supported ending edition**|**Unsupported ending edition**| |:-----|:-----|:-----| |SharePoint Server 2010, Standard edition <br/> |SharePoint Server 2013, Standard edition <br/> |SharePoint Server 2013, Enterprise edition <br/> You can convert to Enterprise edition after upgrade. <br/> | |SharePoint Server 2010, Enterprise Edition <br/> |SharePoint Server 2013, Enterprise edition <br/> |SharePoint Server 2013, Standard edition. <br/> | |SharePoint Server 2010, Trial edition <br/> |SharePoint Server 2013, Trial edition <br/> |SharePoint Server 2013, full product (either edition) <br/> You can't upgrade directly from a trial version to the full product, but you can convert to the full product after upgrade. <br/> | ## Supported cross-product upgrades <a name="product"> </a> The following table lists which Microsoft server products can be upgraded to SharePoint Foundation 2013 or SharePoint Server 2013. Note that in-place upgrade is not supported. Database-attach upgrade is the only supported upgrade method. |**Starting product**|**Supported ending products**|**Unsupported ending product**| |:-----|:-----|:-----| |SharePoint Foundation 2010 <br/> |SharePoint Foundation 2013 <br/> SharePoint Server 2013 <br/> || |SharePoint Foundation 2013 <br/> |SharePoint Server 2013 <br/> || |SharePoint Server 2010 <br/> |SharePoint Server 2013 <br/> |SharePoint Foundation 2013 <br/> | |SharePoint Server 2013 <br/> |SharePoint Server 2013 <br/> |SharePoint Foundation 2013 <br/> | |Search Server 2010 <br/> |SharePoint Server 2013 <br/> |SharePoint Foundation 2013 <br/> | |Project Server 2010 with SharePoint Server 2010, Enterprise Edition <br/> |Project Server with SharePoint Server 2013, Enterprise Edition <br/> ||
{ "pile_set_name": "Github" }
#pragma once #include <catboost/private/libs/data_util/path_with_scheme.h> #include <catboost/private/libs/data_util/line_data_reader.h> #include <catboost/libs/helpers/exception.h> #include <util/generic/cast.h> #include <util/generic/maybe.h> #include <util/generic/ptr.h> #include <util/generic/scope.h> #include <util/generic/strbuf.h> #include <util/generic/string.h> #include <util/generic/vector.h> #include <util/stream/labeled.h> #include <util/string/cast.h> #include <util/string/escape.h> #include <util/string/split.h> #include <util/system/types.h> namespace NJson { class TJsonValue; } namespace NCB { class TBaselineReader { public: TBaselineReader() {} TBaselineReader(const TPathWithScheme& baselineFilePath, const TVector<TString>& classNames); bool Inited() const { return Inited_; } TMaybe<ui32> GetBaselineCount() const { if (Inited_) { return SafeIntegerCast<ui32>(BaselineIndexes_.size()); } else { return Nothing(); } } const TVector<ui32>& GetBaselineIndexes() const { return BaselineIndexes_; } bool ReadLine(TString* line) { return Reader_->ReadLine(line); } template <class TFunc> void Parse(TFunc addBaselineFunc, TStringBuf line, ui32 lineIdx) { ui32 baselineIdx = 0; ui32 columnIdx = 0; for (const TStringBuf token : StringSplitter(line).Split(DELIMITER_)) { Y_DEFER { ++columnIdx; }; CB_ENSURE(columnIdx < BaselineSize_, "Too many columns in baseline file line " << LabeledOutput(lineIdx)); if (baselineIdx >= BaselineIndexes_.size() || columnIdx != BaselineIndexes_[baselineIdx]) { continue; } CB_ENSURE(!token.empty(), "Empty token in baseline file line " << LabeledOutput(lineIdx)); float baseline; CB_ENSURE(TryFromString(token, baseline), "Failed to parse float " << LabeledOutput(token) << " in baseline file line " << LabeledOutput(lineIdx)); addBaselineFunc(baselineIdx, baseline); ++baselineIdx; } CB_ENSURE(columnIdx == BaselineSize_, "Not enough columns in baseline file line " << LabeledOutput(lineIdx)); } private: THolder<ILineDataReader> Reader_; TVector<ui32> BaselineIndexes_; ui32 BaselineSize_ = 0; bool Inited_ = false; constexpr static char DELIMITER_ = '\t'; }; /** * If classLabels are empty init them from baseline header, * check classLabels and baseline file header consistency otherwise */ void UpdateClassLabelsFromBaselineFile( const TPathWithScheme& baselineFilePath, TVector<NJson::TJsonValue>* classLabels ); }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectName>sub_string_finder_pretty</ProjectName> <ProjectGuid>{3AA40693-F93D-4D4B-B32E-068F511A2524}</ProjectGuid> <RootNamespace>sub_string_finder_pretty</RootNamespace> <Keyword>Win32Proj</Keyword> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <Import Project="..\..\..\common\toolset.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <CharacterSet>MultiByte</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <CharacterSet>MultiByte</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <CharacterSet>MultiByte</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <CharacterSet>MultiByte</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup> <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion> <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(TEMP)\tbb_examples\$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(TEMP)\tbb_examples\$(ProjectName)\$(Configuration)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</LinkIncremental> <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(TEMP)\tbb_examples\$(Platform)\$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(TEMP)\tbb_examples\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</LinkIncremental> <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(TEMP)\tbb_examples\$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(TEMP)\tbb_examples\$(ProjectName)\$(Configuration)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental> <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(TEMP)\tbb_examples\$(Platform)\$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(TEMP)\tbb_examples\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental> <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" /> <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" /> <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" /> <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" /> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <Optimization>Disabled</Optimization> <AdditionalIncludeDirectories>$(TBBROOT)\include;$(SolutionDir)\..\..\..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;TBB_USE_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <PrecompiledHeader> </PrecompiledHeader> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <AdditionalDependencies>tbb_debug.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(TBBROOT)\lib\ia32\vc_mt;$(TBBROOT)\lib\ia32\vc12;$(SolutionDir)\..\..\..\..\lib\ia32\vc_mt;$(SolutionDir)\..\..\..\..\lib\ia32\vc12;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <TargetMachine>MachineX86</TargetMachine> <FixedBaseAddress>false</FixedBaseAddress> </Link> <PostBuildEvent> <Message>Copying DLLs and PDBs</Message> <Command>call "$(SolutionDir)\..\..\..\common\copy_libraries.bat" ia32 debug "$(OutDir)"</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <Midl> <TargetEnvironment>X64</TargetEnvironment> </Midl> <ClCompile> <Optimization>Disabled</Optimization> <AdditionalIncludeDirectories>$(TBBROOT)\include;$(SolutionDir)\..\..\..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN64;_DEBUG;_CONSOLE;TBB_USE_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <PrecompiledHeader> </PrecompiledHeader> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <AdditionalDependencies>tbb_debug.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(TBBROOT)\lib\intel64\vc_mt;$(TBBROOT)\lib\intel64\vc12;$(SolutionDir)\..\..\..\..\lib\intel64\vc_mt;$(SolutionDir)\..\..\..\..\lib\intel64\vc12;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <TargetMachine>MachineX64</TargetMachine> <FixedBaseAddress>false</FixedBaseAddress> </Link> <PostBuildEvent> <Message>Copying DLLs and PDBs</Message> <Command>call "$(SolutionDir)\..\..\..\common\copy_libraries.bat" intel64 debug "$(OutDir)"</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <AdditionalIncludeDirectories>$(TBBROOT)\include;$(SolutionDir)\..\..\..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <PrecompiledHeader> </PrecompiledHeader> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <AdditionalDependencies>tbb.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(TBBROOT)\lib\ia32\vc_mt;$(TBBROOT)\lib\ia32\vc12;$(SolutionDir)\..\..\..\..\lib\ia32\vc_mt;$(SolutionDir)\..\..\..\..\lib\ia32\vc12;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <OptimizeReferences>true</OptimizeReferences> <EnableCOMDATFolding>true</EnableCOMDATFolding> <TargetMachine>MachineX86</TargetMachine> <FixedBaseAddress>false</FixedBaseAddress> </Link> <PostBuildEvent> <Message>Copying DLLs and PDBs</Message> <Command>call "$(SolutionDir)\..\..\..\common\copy_libraries.bat" ia32 release "$(OutDir)"</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <Midl> <TargetEnvironment>X64</TargetEnvironment> </Midl> <ClCompile> <AdditionalIncludeDirectories>$(TBBROOT)\include;$(SolutionDir)\..\..\..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN64;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <PrecompiledHeader> </PrecompiledHeader> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <AdditionalDependencies>tbb.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(TBBROOT)\lib\intel64\vc_mt;$(TBBROOT)\lib\intel64\vc12;$(SolutionDir)\..\..\..\..\lib\intel64\vc_mt;$(SolutionDir)\..\..\..\..\lib\intel64\vc12;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Console</SubSystem> <OptimizeReferences>true</OptimizeReferences> <EnableCOMDATFolding>true</EnableCOMDATFolding> <TargetMachine>MachineX64</TargetMachine> <FixedBaseAddress>false</FixedBaseAddress> </Link> <PostBuildEvent> <Message>Copying DLLs and PDBs</Message> <Command>call "$(SolutionDir)\..\..\..\common\copy_libraries.bat" intel64 release "$(OutDir)"</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="..\sub_string_finder_pretty.cpp" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
{ "pile_set_name": "Github" }
<template lang="pug"> v-list(subheader) div(:class="{'hidden-sm-and-up': tools}" v-if="tools || view" style="height: 8px") v-list-tile.hidden-sm-and-up(v-if="tools && SPEC && SPEC.securityDefinitions && Object.keys(SPEC.securityDefinitions).length", @click="UI_SET_DIALOG('security')") v-list-tile-action v-icon lock v-list-tile-content v-list-tile-title(style="min-width: 100px") Authorization v-divider.hidden-sm-and-up(v-if="tools && view && SPEC && SPEC.securityDefinitions && Object.keys(SPEC.securityDefinitions).length") v-list-tile(v-if="view", :class="{'hidden-sm-and-up': view && tools}", @click="nextNextTick(VIEW_SET_DARK)") v-list-tile-action v-icon brightness_4 v-list-tile-content v-list-tile-title Dark theme v-list-tile-action v-icon(v-if="VIEW_DARK") check v-divider(v-if="view && (VIEW_VIEW < 2)", :class="{'hidden-sm-and-up': view && tools}") v-list-tile(v-if="view && (VIEW_VIEW < 2)", :class="{'hidden-sm-and-up': view && tools}", @click="nextNextTick(VIEW_SET_PATH)") v-list-tile-action v-icon directions v-list-tile-content v-list-tile-title Path v-list-tile-action v-icon(v-if="VIEW_PATH") check v-list-tile(v-if="view && (VIEW_VIEW < 2)", :class="{'hidden-sm-and-up': view && tools}", @click="nextNextTick(VIEW_SET_SUMMARY)") v-list-tile-action v-icon speaker_notes v-list-tile-content v-list-tile-title Summary v-list-tile-action v-icon(v-if="VIEW_SUMMARY") check v-divider.hidden-xs-only(:class="{'hidden-sm-and-up': view && tools}" v-if="view && (VIEW_VIEW < 2 || VIEW_VIEW === 3)") v-list-tile.hidden-xs-only(:class="{'hidden-sm-and-up': view && tools}" v-if="view && (VIEW_VIEW < 2 || VIEW_VIEW === 3)", @click="nextNextTick(VIEW_SET_WIDE)") v-list-tile-action v-icon settings_ethernet v-list-tile-content v-list-tile-title Wide v-list-tile-action v-icon(v-if="VIEW_WIDE") check v-divider.hidden-sm-and-up(v-if="view && navigation") template(v-if="navigation") template(v-for="(i, k) in links") v-divider(v-if="!i", :key="k") v-subheader(v-else-if="!i.exact && i.header" style="min-width: 180px", :key="k") {{i.header}} v-list-tile(v-else-if="!i.exact", :to="i.to", :href="i.href", :target="i.blank ? '_blank' : null", :rel="i.blank ? 'noopener' : null" tag="a", :key="k") v-list-tile-action v-icon {{i.icon}} v-list-tile-title {{i.title}} </template> <script> import { mapMutations, mapActions, mapGetters } from 'vuex' import * as types from '../../store/types' import Vue from 'vue' import links from '../../assets/scripts/utils/links' export default { props: ['navigation', 'view', 'tools'], data: function () { return { links } }, computed: { ...mapGetters([ types.APP_API_PAGE, types.VIEW_DARK, types.VIEW_SUMMARY, types.VIEW_PATH, types.VIEW_VIEW, types.UI_LEFT_DRAWER, types.SETTINGS_URL, types.SPEC, types.APP_PAGE_NAME, types.SETTINGS_SEARCH, types.VIEW_WIDE ]) }, methods: { ...mapMutations([ types.VIEW_SET_DARK, types.VIEW_SET_VIEW, types.VIEW_SET_WIDE, types.VIEW_SET_SUMMARY, types.VIEW_SET_PATH, types.UI_SET_DIALOG, types.SETTINGS_SET_SEARCH, types.SPEC_SET_FILTER_RESOURCES, types.UI_SET_LEFT_DRAWER ]), ...mapActions([ types.SPEC_SET_LOAD_URL ]), nextNextTick: (d) => setTimeout(() => Vue.nextTick(d), 50) } } </script>
{ "pile_set_name": "Github" }
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test spending coinbase transactions. # The coinbase transaction in block N can appear in block # N+100... so is valid in the mempool when the best block # height is N+99. # This test makes sure coinbase spends that will be mature # in the next block are accepted into the memory pool, # but less mature coinbase spends are NOT. # from test_framework import BitcoinTestFramework from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from util import * import os import shutil # Create one-input, one-output, no-fee transaction: class MempoolSpendCoinbaseTest(BitcoinTestFramework): def setup_network(self): # Just need one node for this test args = ["-checkmempool", "-debug=mempool"] self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, args)) self.is_network_split = False def create_tx(self, from_txid, to_address, amount): inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = self.nodes[0].createrawtransaction(inputs, outputs) signresult = self.nodes[0].signrawtransaction(rawtx) assert_equal(signresult["complete"], True) return signresult["hex"] def run_test(self): chain_height = self.nodes[0].getblockcount() assert_equal(chain_height, 200) node0_address = self.nodes[0].getnewaddress() # Coinbase at height chain_height-100+1 ok in mempool, should # get mined. Coinbase at height chain_height-100+2 is # is too immature to spend. b = [ self.nodes[0].getblockhash(n) for n in range(101, 103) ] coinbase_txids = [ self.nodes[0].getblock(h)['tx'][0] for h in b ] spends_raw = [ self.create_tx(txid, node0_address, 50) for txid in coinbase_txids ] spend_101_id = self.nodes[0].sendrawtransaction(spends_raw[0]) # coinbase at height 102 should be too immature to spend assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, spends_raw[1]) # mempool should have just spend_101: assert_equal(self.nodes[0].getrawmempool(), [ spend_101_id ]) # mine a block, spend_101 should get confirmed self.nodes[0].setgenerate(True, 1) assert_equal(set(self.nodes[0].getrawmempool()), set()) # ... and now height 102 can be spent: spend_102_id = self.nodes[0].sendrawtransaction(spends_raw[1]) assert_equal(self.nodes[0].getrawmempool(), [ spend_102_id ]) if __name__ == '__main__': MempoolSpendCoinbaseTest().main()
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 2cb8a97d98d81224c8b7d0495d361558 timeCreated: 1477341665 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
{ "author": "Enalean Team", "name": "@tuleap/plugin-userlog", "homepage": "https://tuleap.org", "license": "GPL-2.0-or-later", "private": true, "config": { "bin": "../../node_modules/.bin" }, "scripts": { "build": "$npm_package_config_bin/webpack --config webpack.prod.js", "watch": "$npm_package_config_bin/webpack --config webpack.dev.js --watch" } }
{ "pile_set_name": "Github" }
package cppclassanalyzer.decompiler.action; import ghidra.app.plugin.core.decompile.DecompilerActionContext; import ghidra.app.plugin.core.decompile.actions.AbstractNonPackageDecompilerAction; import cppclassanalyzer.cmd.FillOutClassBackgroundCmd; import cppclassanalyzer.data.manager.ClassTypeInfoManagerDB; import cppclassanalyzer.plugin.ClassTypeInfoManagerPlugin; import docking.action.MenuData; public class FillOutClassAction extends AbstractNonPackageDecompilerAction { private static final String NAME = FillOutClassAction.class.getSimpleName(); private static final MenuData MENU_ENTRY = new MenuData(new String[] { "Fill Out Class" }, "Decompile"); private final ClassTypeInfoManagerPlugin plugin; public FillOutClassAction(ClassTypeInfoManagerPlugin plugin) { super(NAME); this.plugin = plugin; setPopupMenuData(MENU_ENTRY); setDescription("Automatically fill out class members"); } @Override protected boolean isEnabledForDecompilerContext(DecompilerActionContext context) { if (!context.hasRealFunction()) { return false; } ClassTypeInfoManagerDB manager = (ClassTypeInfoManagerDB) plugin.getManager(context.getProgram()); if (manager == null) { return false; } return manager.getType(context.getFunction()) != null; } @Override protected void decompilerActionPerformed(DecompilerActionContext context) { FillOutClassBackgroundCmd cmd = new FillOutClassBackgroundCmd(context); context.getTool().executeBackgroundCommand(cmd, context.getProgram()); } }
{ "pile_set_name": "Github" }
<meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1">
{ "pile_set_name": "Github" }
/* * Copyright (C) 2013-2015 RoboVM AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.robovm.apple.metalps; /*<imports>*/ import java.io.*; import java.nio.*; import java.util.*; import org.robovm.objc.*; import org.robovm.objc.annotation.*; import org.robovm.objc.block.*; import org.robovm.rt.*; import org.robovm.rt.annotation.*; import org.robovm.rt.bro.*; import org.robovm.rt.bro.annotation.*; import org.robovm.rt.bro.ptr.*; import org.robovm.apple.foundation.*; import org.robovm.apple.coregraphics.*; import org.robovm.apple.metal.*; /*</imports>*/ /*<javadoc>*/ /** * @since Available in iOS 11.0 and later. */ /*</javadoc>*/ /*<annotations>*/@Library("MetalPerformanceShaders") @NativeClass/*</annotations>*/ /*<visibility>*/public/*</visibility>*/ class /*<name>*/MPSNNMultiplicationNode/*</name>*/ extends /*<extends>*/MPSNNBinaryArithmeticNode/*</extends>*/ /*<implements>*//*</implements>*/ { /*<ptr>*/public static class MPSNNMultiplicationNodePtr extends Ptr<MPSNNMultiplicationNode, MPSNNMultiplicationNodePtr> {}/*</ptr>*/ /*<bind>*/static { ObjCRuntime.bind(MPSNNMultiplicationNode.class); }/*</bind>*/ /*<constants>*//*</constants>*/ /*<constructors>*/ protected MPSNNMultiplicationNode() {} protected MPSNNMultiplicationNode(Handle h, long handle) { super(h, handle); } protected MPSNNMultiplicationNode(SkipInit skipInit) { super(skipInit); } @Method(selector = "initWithSources:") public MPSNNMultiplicationNode(NSArray<MPSNNImageNode> sourceNodes) { super(sourceNodes); } @Method(selector = "initWithLeftSource:rightSource:") public MPSNNMultiplicationNode(MPSNNImageNode left, MPSNNImageNode right) { super(left, right); } /*</constructors>*/ /*<properties>*/ /*</properties>*/ /*<members>*//*</members>*/ /*<methods>*/ /*</methods>*/ }
{ "pile_set_name": "Github" }
function f(int[] ls) -> bool requires some { i in 0 .. 4 | (i >= 0) && (i < |ls|) && (ls[i] < 0) }: return true function g(int[] ls) requires |ls| > 0: f(ls)
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // 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/. #ifndef EIGEN_EULERANGLES_H #define EIGEN_EULERANGLES_H namespace Eigen { /** \geometry_module \ingroup Geometry_Module * * * \returns the Euler-angles of the rotation matrix \c *this using the convention defined by the triplet (\a a0,\a a1,\a a2) * * Each of the three parameters \a a0,\a a1,\a a2 represents the respective rotation axis as an integer in {0,1,2}. * For instance, in: * \code Vector3f ea = mat.eulerAngles(2, 0, 2); \endcode * "2" represents the z axis and "0" the x axis, etc. The returned angles are such that * we have the following equality: * \code * mat == AngleAxisf(ea[0], Vector3f::UnitZ()) * * AngleAxisf(ea[1], Vector3f::UnitX()) * * AngleAxisf(ea[2], Vector3f::UnitZ()); \endcode * This corresponds to the right-multiply conventions (with right hand side frames). * * The returned angles are in the ranges [0:pi]x[-pi:pi]x[-pi:pi]. * * \sa class AngleAxis */ template<typename Derived> inline Matrix<typename MatrixBase<Derived>::Scalar,3,1> MatrixBase<Derived>::eulerAngles(Index a0, Index a1, Index a2) const { using std::atan2; using std::sin; using std::cos; /* Implemented from Graphics Gems IV */ EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Derived,3,3) Matrix<Scalar,3,1> res; typedef Matrix<typename Derived::Scalar,2,1> Vector2; const Index odd = ((a0+1)%3 == a1) ? 0 : 1; const Index i = a0; const Index j = (a0 + 1 + odd)%3; const Index k = (a0 + 2 - odd)%3; if (a0==a2) { res[0] = atan2(coeff(j,i), coeff(k,i)); if((odd && res[0]<Scalar(0)) || ((!odd) && res[0]>Scalar(0))) { res[0] = (res[0] > Scalar(0)) ? res[0] - Scalar(EIGEN_PI) : res[0] + Scalar(EIGEN_PI); Scalar s2 = Vector2(coeff(j,i), coeff(k,i)).norm(); res[1] = -atan2(s2, coeff(i,i)); } else { Scalar s2 = Vector2(coeff(j,i), coeff(k,i)).norm(); res[1] = atan2(s2, coeff(i,i)); } // With a=(0,1,0), we have i=0; j=1; k=2, and after computing the first two angles, // we can compute their respective rotation, and apply its inverse to M. Since the result must // be a rotation around x, we have: // // c2 s1.s2 c1.s2 1 0 0 // 0 c1 -s1 * M = 0 c3 s3 // -s2 s1.c2 c1.c2 0 -s3 c3 // // Thus: m11.c1 - m21.s1 = c3 & m12.c1 - m22.s1 = s3 Scalar s1 = sin(res[0]); Scalar c1 = cos(res[0]); res[2] = atan2(c1*coeff(j,k)-s1*coeff(k,k), c1*coeff(j,j) - s1 * coeff(k,j)); } else { res[0] = atan2(coeff(j,k), coeff(k,k)); Scalar c2 = Vector2(coeff(i,i), coeff(i,j)).norm(); if((odd && res[0]<Scalar(0)) || ((!odd) && res[0]>Scalar(0))) { res[0] = (res[0] > Scalar(0)) ? res[0] - Scalar(EIGEN_PI) : res[0] + Scalar(EIGEN_PI); res[1] = atan2(-coeff(i,k), -c2); } else res[1] = atan2(-coeff(i,k), c2); Scalar s1 = sin(res[0]); Scalar c1 = cos(res[0]); res[2] = atan2(s1*coeff(k,i)-c1*coeff(j,i), c1*coeff(j,j) - s1 * coeff(k,j)); } if (!odd) res = -res; return res; } } // end namespace Eigen #endif // EIGEN_EULERANGLES_H
{ "pile_set_name": "Github" }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkvideoenhan.endpoint import endpoint_data class AbstractFilmVideoRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'videoenhan', '2020-03-20', 'AbstractFilmVideo','videoenhan') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_Length(self): return self.get_body_params().get('Length') def set_Length(self,Length): self.add_body_params('Length', Length) def get_VideoUrl(self): return self.get_body_params().get('VideoUrl') def set_VideoUrl(self,VideoUrl): self.add_body_params('VideoUrl', VideoUrl)
{ "pile_set_name": "Github" }
{ "_args": [ [ { "raw": "inherits@2", "scope": null, "escapedName": "inherits", "name": "inherits", "rawSpec": "2", "spec": ">=2.0.0 <3.0.0", "type": "range" }, "/home/daniel/el1/node_modules/glob" ] ], "_from": "inherits@>=2.0.0 <3.0.0", "_id": "[email protected]", "_inCache": true, "_location": "/inherits", "_nodeVersion": "6.5.0", "_npmOperationalInternal": { "host": "packages-16-east.internal.npmjs.com", "tmp": "tmp/inherits-2.0.3.tgz_1473295776489_0.08142363070510328" }, "_npmUser": { "name": "isaacs", "email": "[email protected]" }, "_npmVersion": "3.10.7", "_phantomChildren": {}, "_requested": { "raw": "inherits@2", "scope": null, "escapedName": "inherits", "name": "inherits", "rawSpec": "2", "spec": ">=2.0.0 <3.0.0", "type": "range" }, "_requiredBy": [ "/concat-stream", "/concat-stream/readable-stream", "/glob", "/readable-stream" ], "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", "_shasum": "633c2c83e3da42a502f52466022480f4208261de", "_shrinkwrap": null, "_spec": "inherits@2", "_where": "/home/daniel/el1/node_modules/glob", "browser": "./inherits_browser.js", "bugs": { "url": "https://github.com/isaacs/inherits/issues" }, "dependencies": {}, "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", "devDependencies": { "tap": "^7.1.0" }, "directories": {}, "dist": { "shasum": "633c2c83e3da42a502f52466022480f4208261de", "tarball": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz" }, "files": [ "inherits.js", "inherits_browser.js" ], "gitHead": "e05d0fb27c61a3ec687214f0476386b765364d5f", "homepage": "https://github.com/isaacs/inherits#readme", "keywords": [ "inheritance", "class", "klass", "oop", "object-oriented", "inherits", "browser", "browserify" ], "license": "ISC", "main": "./inherits.js", "maintainers": [ { "name": "isaacs", "email": "[email protected]" } ], "name": "inherits", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git://github.com/isaacs/inherits.git" }, "scripts": { "test": "node test" }, "version": "2.0.3" }
{ "pile_set_name": "Github" }
tool extends KinematicBody2D # Simple AI agent to teach game AI programming basics. # Patrols between two points, stopping at each point to wait for a moment. # Detects gaps and walls, and turns around instead of getting stuck or falling in holes. const ARRIVE_THRESHOLD := 3.0 onready var floor_detector: RayCast2D = $Pivot/FloorDetector onready var pivot: Position2D = $Pivot onready var timer: Timer = $Timer export var speed := 300.0 export var gravity := 1000.0 var waypoints := {} var _target: Vector2 var _velocity := Vector2(0, gravity) func _ready() -> void: if Engine.editor_hint: set_physics_process(false) else: timer.connect('timeout', self, '_on_Timer_timeout') position = floor_detector.get_floor_position() waypoints = { start=$Start.global_position, end=$End.global_position, } _target = waypoints.end update() func _physics_process(delta: float) -> void: _velocity = Steering.arrive_to( _velocity, global_position, _target, delta, speed) move_and_slide(_velocity) if not floor_detector.is_close_to_floor() or \ global_position.distance_to(_target) < ARRIVE_THRESHOLD: stop() func stop() -> void: set_physics_process(false) timer.start() func walk(): set_physics_process(true) func turn() -> void: _velocity.x *= -1 pivot.scale.x *= -1 _target = waypoints.start if _target == waypoints.end else waypoints.end func _on_Timer_timeout() -> void: if Engine.editor_hint: return turn() walk() # Draws the path the agent walks in the editor func _draw() -> void: if not Engine.editor_hint or not $Start: return var draw_radius := 20.0 var line_thickness := 6.0 var start: Vector2 = waypoints.start var end: Vector2 = waypoints.end # Path draw_line(start, end, DrawingUtils.COLOR_BLUE_LIGHT, line_thickness) draw_circle(start, draw_radius, DrawingUtils.COLOR_BLUE_DEEP) draw_circle(end, draw_radius, DrawingUtils.COLOR_BLUE_DEEP) # Arrow var center := (start + end) / 2 var angle := start.angle_to(end) DrawingUtils.draw_triangle(self, center, angle, draw_radius) func _get_configuration_warning() -> String: var warning := "" if not $Start or not $End: warning += "%s requires two Position2D children named Start and End to work." % name return warning
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.oap.server.storage.plugin.elasticsearch.query; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.skywalking.apm.util.StringUtil; import org.apache.skywalking.oap.server.core.profile.ProfileTaskRecord; import org.apache.skywalking.oap.server.core.query.type.ProfileTask; import org.apache.skywalking.oap.server.core.storage.profile.IProfileTaskQueryDAO; import org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient; import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.EsDAO; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; public class ProfileTaskQueryEsDAO extends EsDAO implements IProfileTaskQueryDAO { private final int queryMaxSize; public ProfileTaskQueryEsDAO(ElasticSearchClient client, int queryMaxSize) { super(client); this.queryMaxSize = queryMaxSize; } @Override public List<ProfileTask> getTaskList(String serviceId, String endpointName, Long startTimeBucket, Long endTimeBucket, Integer limit) throws IOException { SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource(); final BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); sourceBuilder.query(boolQueryBuilder); if (StringUtil.isNotEmpty(serviceId)) { boolQueryBuilder.must().add(QueryBuilders.termQuery(ProfileTaskRecord.SERVICE_ID, serviceId)); } if (StringUtil.isNotEmpty(endpointName)) { boolQueryBuilder.must().add(QueryBuilders.termQuery(ProfileTaskRecord.ENDPOINT_NAME, endpointName)); } if (startTimeBucket != null) { boolQueryBuilder.must() .add(QueryBuilders.rangeQuery(ProfileTaskRecord.TIME_BUCKET).gte(startTimeBucket)); } if (endTimeBucket != null) { boolQueryBuilder.must().add(QueryBuilders.rangeQuery(ProfileTaskRecord.TIME_BUCKET).lte(endTimeBucket)); } if (limit != null) { sourceBuilder.size(limit); } else { sourceBuilder.size(queryMaxSize); } sourceBuilder.sort(ProfileTaskRecord.START_TIME, SortOrder.DESC); final SearchResponse response = getClient().search(ProfileTaskRecord.INDEX_NAME, sourceBuilder); final LinkedList<ProfileTask> tasks = new LinkedList<>(); for (SearchHit searchHit : response.getHits().getHits()) { tasks.add(parseTask(searchHit)); } return tasks; } @Override public ProfileTask getById(String id) throws IOException { if (StringUtil.isEmpty(id)) { return null; } SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource(); sourceBuilder.query(QueryBuilders.idsQuery().addIds(id)); sourceBuilder.size(1); final SearchResponse response = getClient().search(ProfileTaskRecord.INDEX_NAME, sourceBuilder); if (response.getHits().getHits().length > 0) { return parseTask(response.getHits().getHits()[0]); } return null; } private ProfileTask parseTask(SearchHit data) { return ProfileTask.builder() .id(data.getId()) .serviceId((String) data.getSourceAsMap().get(ProfileTaskRecord.SERVICE_ID)) .endpointName((String) data.getSourceAsMap().get(ProfileTaskRecord.ENDPOINT_NAME)) .startTime(((Number) data.getSourceAsMap().get(ProfileTaskRecord.START_TIME)).longValue()) .createTime(((Number) data.getSourceAsMap() .get(ProfileTaskRecord.CREATE_TIME)).longValue()) .duration(((Number) data.getSourceAsMap().get(ProfileTaskRecord.DURATION)).intValue()) .minDurationThreshold(((Number) data.getSourceAsMap() .get( ProfileTaskRecord.MIN_DURATION_THRESHOLD)).intValue()) .dumpPeriod(((Number) data.getSourceAsMap() .get(ProfileTaskRecord.DUMP_PERIOD)).intValue()) .maxSamplingCount(((Number) data.getSourceAsMap() .get(ProfileTaskRecord.MAX_SAMPLING_COUNT)).intValue()) .build(); } }
{ "pile_set_name": "Github" }
# Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at <[email protected]>. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
{ "pile_set_name": "Github" }
package function external interface Fiber_ { var reset: () -> Any var run: (param: Any? /*= null*/) -> Any var throwInto: (ex: Any) -> Any } // ------------------------------------------------------------------------------------------ package function.fibers @JsModule("fibers") external fun Fiber(fn: Function<*>): Fiber_ = definedExternally // ------------------------------------------------------------------------------------------ @file:JsModule("fibers") package function.fibers.Fiber external var current: Fiber = definedExternally external fun yield(value: Any? = definedExternally /* null */): Any = definedExternally
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>zen3d - clipping planes</title> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <style> body { font-family: Monospace; background-color: #f0f0f0; margin: 0px; overflow: hidden; } #info { position: absolute; top: 0px; width: 100%; padding: 5px; text-align:center; color: white; } </style> <script src="../build/zen3d.js"></script> </head> <body> <div id="info"> <a href="http://github.com/shawn0326/zen-3d" target="_blank">zen3d</a> - clipping planes </div> <script> (function() { var width = window.innerWidth || 2; var height = window.innerHeight || 2; var canvas = document.createElement( 'canvas' ); canvas.width = width; canvas.height = height; document.body.appendChild( canvas ); var renderer = new zen3d.Renderer(canvas); var scene = new zen3d.Scene(); scene.clippingPlanes = [new zen3d.Plane(new zen3d.Vector3(-1, 0, 0), 4), new zen3d.Plane(new zen3d.Vector3(1, 0, 0), 4)]; var sphere_geometry = new zen3d.SphereGeometry(10, 20, 20); var phong = new zen3d.PhongMaterial(); phong.diffuse.setHex(0xffffff); phong.side = zen3d.DRAW_SIDE.DOUBLE; var sphere = new zen3d.Mesh(sphere_geometry, phong); scene.add(sphere); var plane_geometry = new zen3d.PlaneGeometry(100, 100); var lambert = new zen3d.LambertMaterial(); lambert.diffuse.setHex(0xffffff); var plane = new zen3d.Mesh(plane_geometry, lambert); plane.position.y = -10; scene.add(plane); var ambientLight = new zen3d.AmbientLight(0xbbcccc); scene.add(ambientLight); var directionalLight = new zen3d.DirectionalLight(0xffffff); directionalLight.position.set(-40, 40, 0); directionalLight.lookAt(new zen3d.Vector3(), new zen3d.Vector3(0, 1, 0)); directionalLight.shadow.windowSize = 100; directionalLight.shadow.bias = -0.003; scene.add(directionalLight); var lightBall_geometry = new zen3d.SphereGeometry(4, 10, 10); var basic = new zen3d.BasicMaterial(); basic.diffuse.setHex(0xffffff); var lightBall = new zen3d.Mesh(lightBall_geometry, basic); lightBall.position.set(-40, 40, 0); scene.add(lightBall); var camera = new zen3d.Camera(); camera.position.set(0, 80, 100); camera.lookAt(new zen3d.Vector3(0, 0, 0), new zen3d.Vector3(0, 1, 0)); camera.setPerspective(45 / 180 * Math.PI, width / height, 1, 1000); scene.add(camera); function toggleShadow() { sphere.castShadow = !sphere.castShadow; sphere.receiveShadow = !sphere.receiveShadow; plane.receiveShadow = !plane.receiveShadow; directionalLight.castShadow = !directionalLight.castShadow; } toggleShadow(); function loop(count) { requestAnimationFrame(loop); // rotate camera camera.position.x = 100 * Math.sin(count / 1000 * .5); camera.position.z = 100 * Math.cos(count / 1000 * .5); camera.lookAt(new zen3d.Vector3(0, 0, 0), new zen3d.Vector3(0, 1, 0)); renderer.render(scene, camera); } loop(0); function onWindowResize() { width = window.innerWidth || 2; height = window.innerHeight || 2; camera.setPerspective(45 / 180 * Math.PI, width / height, 1, 1000); renderer.backRenderTarget.resize(width, height); } window.addEventListener("resize", onWindowResize, false); })(); </script> </body> </html>
{ "pile_set_name": "Github" }
<?php namespace Concrete\Core\Backup\ContentImporter\Importer\Routine; use Concrete\Core\Attribute\Category\ExpressCategory; use Concrete\Core\Block\BlockType\BlockType; use Concrete\Core\Entity\Express\Entity; use Concrete\Core\Permission\Category; use Concrete\Core\Support\Facade\Facade; use Concrete\Core\Tree\Type\ExpressEntryResults; use Concrete\Core\Validation\BannedWord\BannedWord; use Doctrine\ORM\Id\UuidGenerator; class ImportExpressEntitiesRoutine extends AbstractRoutine { public function getHandle() { return 'express_entities'; } public function import(\SimpleXMLElement $sx) { $em = \Database::connection()->getEntityManager(); $em->getClassMetadata('Concrete\Core\Entity\Express\Entity')->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator()); if (isset($sx->expressentities)) { foreach ($sx->expressentities->entity as $entityNode) { $entity = $em->find('Concrete\Core\Entity\Express\Entity', (string) $entityNode['id']); if (!is_object($entity)) { $entity = new Entity(); $entity->setId((string) $entityNode['id']); $tree = ExpressEntryResults::get(); $node = $tree->getNodeByDisplayPath((string) $entityNode['results-folder']); $node = \Concrete\Core\Tree\Node\Type\ExpressEntryResults::add((string) $entityNode['name'], $node); $entity->setEntityResultsNodeId($node->getTreeNodeID()); } $entity->setPluralHandle((string) $entityNode['plural_handle']); $entity->setHandle((string) $entityNode['handle']); $entity->setDescription((string) $entityNode['description']); $entity->setName((string) $entityNode['name']); $entity->setPackage(static::getPackageObject($entityNode['package'])); if (((string) $entityNode['include_in_public_list']) == '') { $entity->setIncludeInPublicList(false); } if (((string) $entityNode['use_separate_site_result_buckets']) === '1') { $entity->setUseSeparateSiteResultBuckets(true); } $entity->setHandle((string) $entityNode['handle']); $em->persist($entity); // Import the attributes if (isset($entityNode->attributekeys)) { $app = Facade::getFacadeApplication(); $category = new ExpressCategory($entity, $app, $em); foreach($entityNode->attributekeys->attributekey as $keyNode) { $attributeKey = $category->getAttributeKeyByHandle((string) $keyNode['handle']); if (!$attributeKey) { $type = $app->make('Concrete\Core\Attribute\TypeFactory')->getByHandle( (string)$keyNode['type'] ); $category->import($type, $keyNode); } } } } } $em->flush(); $em->getClassMetadata('Concrete\Core\Entity\Express\Entity')->setIdGenerator(new UuidGenerator()); } }
{ "pile_set_name": "Github" }
// Copyright 2018 The Prometheus 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 util import "strconv" // ParseUint32s parses a slice of strings into a slice of uint32s. func ParseUint32s(ss []string) ([]uint32, error) { us := make([]uint32, 0, len(ss)) for _, s := range ss { u, err := strconv.ParseUint(s, 10, 32) if err != nil { return nil, err } us = append(us, uint32(u)) } return us, nil } // ParseUint64s parses a slice of strings into a slice of uint64s. func ParseUint64s(ss []string) ([]uint64, error) { us := make([]uint64, 0, len(ss)) for _, s := range ss { u, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } us = append(us, u) } return us, nil }
{ "pile_set_name": "Github" }
'use strict'; var isSymbol = require('./is-symbol'); module.exports = function (value) { if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); return value; };
{ "pile_set_name": "Github" }
#include "test/jemalloc_test.h" #define QUARANTINE_SIZE 8192 #define STRINGIFY_HELPER(x) #x #define STRINGIFY(x) STRINGIFY_HELPER(x) #ifdef JEMALLOC_FILL const char *malloc_conf = "abort:false,junk:true,redzone:true,quarantine:" STRINGIFY(QUARANTINE_SIZE); #endif void quarantine_clear(void) { void *p; p = mallocx(QUARANTINE_SIZE*2, 0); assert_ptr_not_null(p, "Unexpected mallocx() failure"); dallocx(p, 0); } TEST_BEGIN(test_quarantine) { #define SZ ZU(256) #define NQUARANTINED (QUARANTINE_SIZE/SZ) void *quarantined[NQUARANTINED+1]; size_t i, j; test_skip_if(!config_fill); assert_zu_eq(nallocx(SZ, 0), SZ, "SZ=%zu does not precisely equal a size class", SZ); quarantine_clear(); /* * Allocate enough regions to completely fill the quarantine, plus one * more. The last iteration occurs with a completely full quarantine, * but no regions should be drained from the quarantine until the last * deallocation occurs. Therefore no region recycling should occur * until after this loop completes. */ for (i = 0; i < NQUARANTINED+1; i++) { void *p = mallocx(SZ, 0); assert_ptr_not_null(p, "Unexpected mallocx() failure"); quarantined[i] = p; dallocx(p, 0); for (j = 0; j < i; j++) { assert_ptr_ne(p, quarantined[j], "Quarantined region recycled too early; " "i=%zu, j=%zu", i, j); } } #undef NQUARANTINED #undef SZ } TEST_END static bool detected_redzone_corruption; static void arena_redzone_corruption_replacement(void *ptr, size_t usize, bool after, size_t offset, uint8_t byte) { detected_redzone_corruption = true; } TEST_BEGIN(test_quarantine_redzone) { char *s; arena_redzone_corruption_t *arena_redzone_corruption_orig; test_skip_if(!config_fill); arena_redzone_corruption_orig = arena_redzone_corruption; arena_redzone_corruption = arena_redzone_corruption_replacement; /* Test underflow. */ detected_redzone_corruption = false; s = (char *)mallocx(1, 0); assert_ptr_not_null((void *)s, "Unexpected mallocx() failure"); s[-1] = 0xbb; dallocx(s, 0); assert_true(detected_redzone_corruption, "Did not detect redzone corruption"); /* Test overflow. */ detected_redzone_corruption = false; s = (char *)mallocx(1, 0); assert_ptr_not_null((void *)s, "Unexpected mallocx() failure"); s[sallocx(s, 0)] = 0xbb; dallocx(s, 0); assert_true(detected_redzone_corruption, "Did not detect redzone corruption"); arena_redzone_corruption = arena_redzone_corruption_orig; } TEST_END int main(void) { return (test( test_quarantine, test_quarantine_redzone)); }
{ "pile_set_name": "Github" }
require glibmm.inc SRC_URI[archive.md5sum] = "408054366f0acc01014f4c4af2304da5" SRC_URI[archive.sha256sum] = "f033f6f39c32fc17ecce63087e41408671a3a43d698c83de2528af3fc7276d28"
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016-2020 VMware, Inc. All Rights Reserved. * This software is released under MIT license. * The full license information can be found in LICENSE in the root directory of this project. */ import { isString } from '@clr/core/internal'; import { getInnerSvgFromShapes, renderIcon } from './icon.renderer.js'; import { IconShapeSources } from './interfaces/icon.interfaces.js'; import { IconDecorationClassnames, IconSvgClassnames } from './utils/icon.classnames.js'; import { dummyIconShape, testIcons } from './utils/test-icons.js'; describe('Icon renderer: ', () => { describe('renderIcon: ', () => { it('should return a string if passed a string or a shape', () => { expect(isString(renderIcon(dummyIconShape))).toEqual(true); expect(isString(renderIcon('<svg><path/></svg>'))).toEqual(true); }); }); describe('renderIconFromShapes: ', () => { describe(' - svg tags: ', () => { it('should have opening and closing svg tags', () => { const [, testShape] = testIcons.justOutline; const test = renderIcon(testShape); expect(test.indexOf('<svg') > -1).toEqual(true); expect(test.indexOf('</svg>') > -1).toEqual(true); }); it('should have expected classes on svg tag of solid icons', () => { const [, testShape] = testIcons.solidIcon; const test = renderIcon(testShape); expect(test.indexOf(IconSvgClassnames.Solid) > -1).toEqual(true); }); it('should have expected classes on svg tag of badged icons', () => { const [, testShape] = testIcons.badgedIcon; const test = renderIcon(testShape); expect(test.indexOf(IconSvgClassnames.Badged) > -1).toEqual(true); }); it('should have expected classes on svg tag of alerted icons', () => { const [, testShape] = testIcons.alertedIcon; const test = renderIcon(testShape); expect(test.indexOf(IconSvgClassnames.Alerted) > -1).toEqual(true); }); }); it('should add badge to badged shapes', () => { const [, testShape] = testIcons.badgedIcon; const test = renderIcon(testShape); expect(test.indexOf(IconDecorationClassnames.Badge) > -1).toEqual(true); }); it('should add alert to alerted shapes', () => { expect(isString(renderIcon(dummyIconShape))).toEqual(true); expect(isString(renderIcon('<svg><path/></svg>'))).toEqual(true); }); }); describe('renderIconFromString: ', () => { it('should return what it is given', () => { const testString = 'abcdefghijklmnop'; const test = renderIcon(testString); expect(test).toEqual(testString); }); }); describe('getInnerSvgFromShapes: ', () => { it('should return an array of functions equal to the number of shapes in the collection', () => { const [, shapes] = testIcons.allIcon; expect(getInnerSvgFromShapes(shapes as IconShapeSources).length).toEqual(6); }); }); });
{ "pile_set_name": "Github" }
#define HIGHP #define ALPHA 0.18 #define step 2.0 uniform sampler2D u_texture; uniform vec2 u_texsize; uniform vec2 u_invsize; uniform float u_time; uniform float u_dp; uniform vec2 u_offset; varying vec2 v_texCoords; void main(){ vec2 T = v_texCoords.xy; vec2 coords = (T * u_texsize) + u_offset; T += vec2(sin(coords.y / 3.0 + u_time / 20.0), sin(coords.x / 3.0 + u_time / 20.0)) / u_texsize; vec4 color = texture2D(u_texture, T); vec2 v = u_invsize; vec4 maxed = max(max(max(texture2D(u_texture, T + vec2(0, step) * v), texture2D(u_texture, T + vec2(0, -step) * v)), texture2D(u_texture, T + vec2(step, 0) * v)), texture2D(u_texture, T + vec2(-step, 0) * v)); if(texture2D(u_texture, T).a < 0.9 && maxed.a > 0.9){ gl_FragColor = vec4(maxed.rgb, maxed.a * 100.0); }else{ if(color.a > 0.0){ if(mod(coords.x / u_dp + coords.y / u_dp + sin(coords.x / u_dp / 5.0) * 3.0 + sin(coords.y / u_dp / 5.0) * 3.0 + u_time / 4.0, 10.0) < 2.0){ color *= 1.65; } color.a = ALPHA; } gl_FragColor = color; } }
{ "pile_set_name": "Github" }
var mkdirp = require('../'); var path = require('path'); var fs = require('fs'); var test = require('tap').test; test('return value', function (t) { t.plan(4); var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); var file = '/tmp/' + [x,y,z].join('/'); // should return the first dir created. // By this point, it would be profoundly surprising if /tmp didn't // already exist, since every other test makes things in there. mkdirp(file, function (err, made) { t.ifError(err); t.equal(made, '/tmp/' + x); mkdirp(file, function (err, made) { t.ifError(err); t.equal(made, null); }); }); });
{ "pile_set_name": "Github" }
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ package com.tangosol.coherence.dslquery.operator; import com.tangosol.coherence.dslquery.FilterBuilder; import com.tangosol.coherence.dsltools.precedence.TokenTable; import com.tangosol.coherence.dsltools.termtrees.Term; import com.tangosol.util.Filter; import com.tangosol.util.ValueExtractor; import com.tangosol.util.extractor.ReflectionExtractor; import com.tangosol.util.filter.EqualsFilter; import com.tangosol.util.filter.NotEqualsFilter; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; /** * @author jk 2013.12.31 */ public class EqualsOperatorTest extends BaseOperatorTest { @Test public void shouldHaveCorrectSymbol() throws Exception { EqualsOperator op = new EqualsOperator(); assertThat(op.getSymbol(), is("==")); } @Test public void shouldHaveCorrectAliases() throws Exception { EqualsOperator op = new EqualsOperator(); assertThat(op.getAliases(), is(new String[] {"=", "is"})); } @Test public void shouldAddToTokenTable() throws Exception { TokenTable tokens = new TokenTable(); EqualsOperator op = new EqualsOperator(); op.addToTokenTable(tokens); assertThat(tokens.lookup(op.getSymbol()), is(notNullValue())); for (String alias : op.getAliases()) { assertThat("Token missing for alias " + alias, tokens.lookup(alias), is(notNullValue())); } } @Test public void shouldCreateFilter() throws Exception { EqualsOperator op = new EqualsOperator(); ValueExtractor left = new ReflectionExtractor("getFoo"); Object right = new Object(); Filter result = op.makeFilter(left, right); Filter expected = new EqualsFilter(left, right); assertThat(result, is(expected)); } @Test public void shouldBuildFilterFromTerms() throws Exception { Term term = parse("foo == 100"); EqualsOperator op = new EqualsOperator(); Filter result = op.makeFilter(term.termAt(2), term.termAt(3), new FilterBuilder()); Filter expected = new EqualsFilter("getFoo", 100); assertThat(result, is(expected)); } @Test public void shouldBuildNotEqualsFilterFromTerms() throws Exception { Term term = parse("foo is not 100"); EqualsOperator op = new EqualsOperator(); Filter result = op.makeFilter(term.termAt(2), term.termAt(3), new FilterBuilder()); Filter expected = new NotEqualsFilter("getFoo", 100); assertThat(result, is(expected)); } @Test public void shouldReturnSelfWhenFlipped() throws Exception { EqualsOperator op = new EqualsOperator(); assertThat(op.flip(), is(sameInstance((ComparisonOperator) op))); } }
{ "pile_set_name": "Github" }
{ "description": "ServiceReference holds a reference to Service.legacy.k8s.io", "required": [ "namespace", "name" ], "properties": { "name": { "description": "`name` is the name of the service. Required", "type": [ "string", "null" ] }, "namespace": { "description": "`namespace` is the namespace of the service. Required", "type": [ "string", "null" ] }, "path": { "description": "`path` is an optional URL path which will be sent in any request to this service.", "type": [ "string", "null" ] } }, "$schema": "http://json-schema.org/schema#", "type": "object" }
{ "pile_set_name": "Github" }
;========================================================== ; ; ; ██████╗ ██████╗ ██╗ ██╗ ██╗██████╗ █████╗ ██████╗ ; ██╔══██╗██╔═══██╗██║ ╚██╗ ██╔╝██╔══██╗██╔══██╗██╔══██╗ ; ██████╔╝██║ ██║██║ ╚████╔╝ ██████╔╝███████║██████╔╝ ; ██╔═══╝ ██║ ██║██║ ╚██╔╝ ██╔══██╗██╔══██║██╔══██╗ ; ██║ ╚██████╔╝███████╗██║ ██████╔╝██║ ██║██║ ██║ ; ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ; ; ; To learn more about how to configure Polybar ; go to https://github.com/jaagr/polybar ; ; The README contains alot of information ; ;========================================================== [colors] ;background = ${xrdb:color0:#222} background = #222 background-alt = #444 ;foreground = ${xrdb:color7:#222} foreground = #dfdfdf foreground-alt = #555 primary = #ffb52a secondary = #e60053 alert = #bd2c40 [bar/example] ;monitor = ${env:MONITOR:HDMI-1} width = 100% height = 27 ;offset-x = 1% ;offset-y = 1% radius = 6.0 fixed-center = false background = ${colors.background} foreground = ${colors.foreground} line-size = 3 line-color = #f00 border-size = 4 border-color = #00000000 padding-left = 0 padding-right = 2 module-margin-left = 1 module-margin-right = 2 font-0 = fixed:pixelsize=10;1 font-1 = unifont:fontformat=truetype:size=8:antialias=false;0 font-2 = siji:pixelsize=10;1 modules-left = bspwm i3 modules-center = mpd modules-right = filesystem xbacklight alsa pulseaudio xkeyboard memory cpu wlan eth battery temperature date powermenu tray-position = right tray-padding = 2 ;tray-background = #0063ff ;wm-restack = bspwm ;wm-restack = i3 ;override-redirect = true ;scroll-up = bspwm-desknext ;scroll-down = bspwm-deskprev ;scroll-up = i3wm-wsnext ;scroll-down = i3wm-wsprev cursor-click = pointer cursor-scroll = ns-resize [module/xwindow] type = internal/xwindow label = %title:0:30:...% [module/xkeyboard] type = internal/xkeyboard blacklist-0 = num lock format-prefix = " " format-prefix-foreground = ${colors.foreground-alt} format-prefix-underline = ${colors.secondary} label-layout = %layout% label-layout-underline = ${colors.secondary} label-indicator-padding = 2 label-indicator-margin = 1 label-indicator-background = ${colors.secondary} label-indicator-underline = ${colors.secondary} [module/filesystem] type = internal/fs interval = 25 mount-0 = / label-mounted = %{F#0a81f5}%mountpoint%%{F-}: %percentage_used%% label-unmounted = %mountpoint% not mounted label-unmounted-foreground = ${colors.foreground-alt} [module/bspwm] type = internal/bspwm label-focused = %index% label-focused-background = ${colors.background-alt} label-focused-underline= ${colors.primary} label-focused-padding = 2 label-occupied = %index% label-occupied-padding = 2 label-urgent = %index%! label-urgent-background = ${colors.alert} label-urgent-padding = 2 label-empty = %index% label-empty-foreground = ${colors.foreground-alt} label-empty-padding = 2 ; Separator in between workspaces ; label-separator = | [module/i3] type = internal/i3 format = <label-state> <label-mode> index-sort = true wrapping-scroll = false ; Only show workspaces on the same output as the bar ;pin-workspaces = true label-mode-padding = 2 label-mode-foreground = #000 label-mode-background = ${colors.primary} ; focused = Active workspace on focused monitor label-focused = %index% label-focused-background = ${module/bspwm.label-focused-background} label-focused-underline = ${module/bspwm.label-focused-underline} label-focused-padding = ${module/bspwm.label-focused-padding} ; unfocused = Inactive workspace on any monitor label-unfocused = %index% label-unfocused-padding = ${module/bspwm.label-occupied-padding} ; visible = Active workspace on unfocused monitor label-visible = %index% label-visible-background = ${self.label-focused-background} label-visible-underline = ${self.label-focused-underline} label-visible-padding = ${self.label-focused-padding} ; urgent = Workspace with urgency hint set label-urgent = %index% label-urgent-background = ${module/bspwm.label-urgent-background} label-urgent-padding = ${module/bspwm.label-urgent-padding} ; Separator in between workspaces ; label-separator = | [module/mpd] type = internal/mpd format-online = <label-song> <icon-prev> <icon-stop> <toggle> <icon-next> icon-prev =  icon-stop =  icon-play =  icon-pause =  icon-next =  label-song-maxlen = 25 label-song-ellipsis = true [module/xbacklight] type = internal/xbacklight format = <label> <bar> label = BL bar-width = 10 bar-indicator = | bar-indicator-foreground = #fff bar-indicator-font = 2 bar-fill = ─ bar-fill-font = 2 bar-fill-foreground = #9f78e1 bar-empty = ─ bar-empty-font = 2 bar-empty-foreground = ${colors.foreground-alt} [module/backlight-acpi] inherit = module/xbacklight type = internal/backlight card = intel_backlight [module/cpu] type = internal/cpu interval = 2 format-prefix = " " format-prefix-foreground = ${colors.foreground-alt} format-underline = #f90000 label = %percentage:2%% [module/memory] type = internal/memory interval = 2 format-prefix = " " format-prefix-foreground = ${colors.foreground-alt} format-underline = #4bffdc label = %percentage_used%% [module/wlan] type = internal/network interface = net1 interval = 3.0 format-connected = <ramp-signal> <label-connected> format-connected-underline = #9f78e1 label-connected = %essid% format-disconnected = ;format-disconnected = <label-disconnected> ;format-disconnected-underline = ${self.format-connected-underline} ;label-disconnected = %ifname% disconnected ;label-disconnected-foreground = ${colors.foreground-alt} ramp-signal-0 =  ramp-signal-1 =  ramp-signal-2 =  ramp-signal-3 =  ramp-signal-4 =  ramp-signal-foreground = ${colors.foreground-alt} [module/eth] type = internal/network interface = eno1 interval = 3.0 format-connected-underline = #55aa55 format-connected-prefix = " " format-connected-prefix-foreground = ${colors.foreground-alt} label-connected = %local_ip% format-disconnected = ;format-disconnected = <label-disconnected> ;format-disconnected-underline = ${self.format-connected-underline} ;label-disconnected = %ifname% disconnected ;label-disconnected-foreground = ${colors.foreground-alt} [module/date] type = internal/date interval = 5 date = date-alt = " %Y-%m-%d" time = %H:%M time-alt = %H:%M:%S format-prefix =  format-prefix-foreground = ${colors.foreground-alt} format-underline = #0a6cf5 label = %date% %time% [module/pulseaudio] type = internal/pulseaudio format-volume = <label-volume> <bar-volume> label-volume = VOL %percentage%% label-volume-foreground = ${root.foreground} label-muted = 🔇 muted label-muted-foreground = #666 bar-volume-width = 10 bar-volume-foreground-0 = #55aa55 bar-volume-foreground-1 = #55aa55 bar-volume-foreground-2 = #55aa55 bar-volume-foreground-3 = #55aa55 bar-volume-foreground-4 = #55aa55 bar-volume-foreground-5 = #f5a70a bar-volume-foreground-6 = #ff5555 bar-volume-gradient = false bar-volume-indicator = | bar-volume-indicator-font = 2 bar-volume-fill = ─ bar-volume-fill-font = 2 bar-volume-empty = ─ bar-volume-empty-font = 2 bar-volume-empty-foreground = ${colors.foreground-alt} [module/alsa] type = internal/alsa format-volume = <label-volume> <bar-volume> label-volume = VOL label-volume-foreground = ${root.foreground} format-muted-prefix = " " format-muted-foreground = ${colors.foreground-alt} label-muted = sound muted bar-volume-width = 10 bar-volume-foreground-0 = #55aa55 bar-volume-foreground-1 = #55aa55 bar-volume-foreground-2 = #55aa55 bar-volume-foreground-3 = #55aa55 bar-volume-foreground-4 = #55aa55 bar-volume-foreground-5 = #f5a70a bar-volume-foreground-6 = #ff5555 bar-volume-gradient = false bar-volume-indicator = | bar-volume-indicator-font = 2 bar-volume-fill = ─ bar-volume-fill-font = 2 bar-volume-empty = ─ bar-volume-empty-font = 2 bar-volume-empty-foreground = ${colors.foreground-alt} [module/battery] type = internal/battery battery = BAT0 adapter = ADP1 full-at = 98 format-charging = <animation-charging> <label-charging> format-charging-underline = #ffb52a format-discharging = <animation-discharging> <label-discharging> format-discharging-underline = ${self.format-charging-underline} format-full-prefix = " " format-full-prefix-foreground = ${colors.foreground-alt} format-full-underline = ${self.format-charging-underline} ramp-capacity-0 =  ramp-capacity-1 =  ramp-capacity-2 =  ramp-capacity-foreground = ${colors.foreground-alt} animation-charging-0 =  animation-charging-1 =  animation-charging-2 =  animation-charging-foreground = ${colors.foreground-alt} animation-charging-framerate = 750 animation-discharging-0 =  animation-discharging-1 =  animation-discharging-2 =  animation-discharging-foreground = ${colors.foreground-alt} animation-discharging-framerate = 750 [module/temperature] type = internal/temperature thermal-zone = 0 warn-temperature = 60 format = <ramp> <label> format-underline = #f50a4d format-warn = <ramp> <label-warn> format-warn-underline = ${self.format-underline} label = %temperature-c% label-warn = %temperature-c% label-warn-foreground = ${colors.secondary} ramp-0 =  ramp-1 =  ramp-2 =  ramp-foreground = ${colors.foreground-alt} [module/powermenu] type = custom/menu expand-right = true format-spacing = 1 label-open =  label-open-foreground = ${colors.secondary} label-close =  cancel label-close-foreground = ${colors.secondary} label-separator = | label-separator-foreground = ${colors.foreground-alt} menu-0-0 = reboot menu-0-0-exec = menu-open-1 menu-0-1 = power off menu-0-1-exec = menu-open-2 menu-1-0 = cancel menu-1-0-exec = menu-open-0 menu-1-1 = reboot menu-1-1-exec = sudo reboot menu-2-0 = power off menu-2-0-exec = sudo poweroff menu-2-1 = cancel menu-2-1-exec = menu-open-0 [settings] screenchange-reload = true ;compositing-background = xor ;compositing-background = screen ;compositing-foreground = source ;compositing-border = over ;pseudo-transparency = false [global/wm] margin-top = 5 margin-bottom = 5 ; vim:ft=dosini
{ "pile_set_name": "Github" }
//+build !go1.9 package concurrent import "sync" // Map implements a thread safe map for go version below 1.9 using mutex type Map struct { lock sync.RWMutex data map[interface{}]interface{} } // NewMap creates a thread safe map func NewMap() *Map { return &Map{ data: make(map[interface{}]interface{}, 32), } } // Load is same as sync.Map Load func (m *Map) Load(key interface{}) (elem interface{}, found bool) { m.lock.RLock() elem, found = m.data[key] m.lock.RUnlock() return } // Load is same as sync.Map Store func (m *Map) Store(key interface{}, elem interface{}) { m.lock.Lock() m.data[key] = elem m.lock.Unlock() }
{ "pile_set_name": "Github" }
[ { "date": "2020-01-01 00:00:00", "start": "2020-01-01T03:00:00.000Z", "end": "2020-01-02T03:00:00.000Z", "name": "Nouvel An", "type": "public", "rule": "01-01", "_weekday": "Wed" }, { "date": "2020-04-13 00:00:00", "start": "2020-04-13T03:00:00.000Z", "end": "2020-04-14T03:00:00.000Z", "name": "Lundi de Pâques", "type": "public", "rule": "easter 1", "_weekday": "Mon" }, { "date": "2020-05-01 00:00:00", "start": "2020-05-01T03:00:00.000Z", "end": "2020-05-02T03:00:00.000Z", "name": "Fête du travail", "type": "public", "rule": "05-01", "_weekday": "Fri" }, { "date": "2020-05-08 00:00:00", "start": "2020-05-08T03:00:00.000Z", "end": "2020-05-09T03:00:00.000Z", "name": "Fête de la Victoire 1945", "type": "public", "rule": "05-08", "_weekday": "Fri" }, { "date": "2020-05-21 00:00:00", "start": "2020-05-21T03:00:00.000Z", "end": "2020-05-22T03:00:00.000Z", "name": "Ascension", "type": "public", "rule": "easter 39", "_weekday": "Thu" }, { "date": "2020-05-31 00:00:00", "start": "2020-05-31T03:00:00.000Z", "end": "2020-06-01T03:00:00.000Z", "name": "Fête des Mères", "type": "observance", "rule": "sunday before 06-01", "_weekday": "Sun" }, { "date": "2020-05-31 00:00:00", "start": "2020-05-31T03:00:00.000Z", "end": "2020-06-01T03:00:00.000Z", "name": "Pentecôte", "type": "public", "rule": "easter 49", "_weekday": "Sun" }, { "date": "2020-06-01 00:00:00", "start": "2020-06-01T03:00:00.000Z", "end": "2020-06-02T03:00:00.000Z", "name": "Lundi de Pentecôte", "type": "public", "rule": "easter 50", "_weekday": "Mon" }, { "date": "2020-06-10 00:00:00", "start": "2020-06-10T03:00:00.000Z", "end": "2020-06-11T03:00:00.000Z", "name": "Abolition de l’esclavage", "type": "public", "rule": "06-10", "_weekday": "Wed" }, { "date": "2020-07-14 00:00:00", "start": "2020-07-14T03:00:00.000Z", "end": "2020-07-15T03:00:00.000Z", "name": "Fête Nationale de la France", "type": "public", "rule": "07-14", "_weekday": "Tue" }, { "date": "2020-08-15 00:00:00", "start": "2020-08-15T03:00:00.000Z", "end": "2020-08-16T03:00:00.000Z", "name": "Assomption", "type": "public", "rule": "08-15", "_weekday": "Sat" }, { "date": "2020-11-01 00:00:00", "start": "2020-11-01T03:00:00.000Z", "end": "2020-11-02T03:00:00.000Z", "name": "Toussaint", "type": "public", "rule": "11-01", "_weekday": "Sun" }, { "date": "2020-11-11 00:00:00", "start": "2020-11-11T03:00:00.000Z", "end": "2020-11-12T03:00:00.000Z", "name": "Armistice 1918", "type": "public", "rule": "11-11", "_weekday": "Wed" }, { "date": "2020-12-25 00:00:00", "start": "2020-12-25T03:00:00.000Z", "end": "2020-12-26T03:00:00.000Z", "name": "Noël", "type": "public", "rule": "12-25", "_weekday": "Fri" } ]
{ "pile_set_name": "Github" }
logging: level: warn
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\Tests\Debug; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\Stopwatch\Stopwatch; class TraceableEventDispatcherTest extends TestCase { public function testStopwatchSections() { $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch = new Stopwatch()); $kernel = $this->getHttpKernel($dispatcher, function () { return new Response('', 200, ['X-Debug-Token' => '292e1e']); }); $request = Request::create('/'); $response = $kernel->handle($request); $kernel->terminate($request, $response); $events = $stopwatch->getSectionEvents($response->headers->get('X-Debug-Token')); $this->assertEquals([ '__section__', 'kernel.request', 'kernel.controller', 'kernel.controller_arguments', 'controller', 'kernel.response', 'kernel.terminate', ], array_keys($events)); } public function testStopwatchCheckControllerOnRequestEvent() { $stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch') ->setMethods(['isStarted']) ->getMock(); $stopwatch->expects($this->once()) ->method('isStarted') ->willReturn(false); $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch); $kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); }); $request = Request::create('/'); $kernel->handle($request); } public function testStopwatchStopControllerOnRequestEvent() { $stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch') ->setMethods(['isStarted', 'stop']) ->getMock(); $stopwatch->expects($this->once()) ->method('isStarted') ->willReturn(true); $stopwatch->expects($this->once()) ->method('stop'); $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch); $kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); }); $request = Request::create('/'); $kernel->handle($request); } public function testAddListenerNested() { $called1 = false; $called2 = false; $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $dispatcher->addListener('my-event', function () use ($dispatcher, &$called1, &$called2) { $called1 = true; $dispatcher->addListener('my-event', function () use (&$called2) { $called2 = true; }); }); $dispatcher->dispatch('my-event'); $this->assertTrue($called1); $this->assertFalse($called2); $dispatcher->dispatch('my-event'); $this->assertTrue($called2); } public function testListenerCanRemoveItselfWhenExecuted() { $eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $listener1 = function () use ($eventDispatcher, &$listener1) { $eventDispatcher->removeListener('foo', $listener1); }; $eventDispatcher->addListener('foo', $listener1); $eventDispatcher->addListener('foo', function () {}); $eventDispatcher->dispatch('foo'); $this->assertCount(1, $eventDispatcher->getListeners('foo'), 'expected listener1 to be removed'); } protected function getHttpKernel($dispatcher, $controller) { $controllerResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface')->getMock(); $controllerResolver->expects($this->once())->method('getController')->willReturn($controller); $argumentResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface')->getMock(); $argumentResolver->expects($this->once())->method('getArguments')->willReturn([]); return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{82A48153-1B86-4589-9379-641FA31DEE6D}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Algorithms</RootNamespace> <AssemblyName>Assertions</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="Microsoft.CSharp" /> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Utils.cs" /> <Compile Include="AssertionsTest.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="SearchingAlgorithms.cs" /> <Compile Include="SortingAlgorithms.cs" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
{ "pile_set_name": "Github" }
class ScheduledBuildTrigger attr_accessor :build_interval def initialize(triggered_project, opts={}) @triggered_project = triggered_project @build_interval = opts[:build_interval] || 24.hours @next_build_time = opts[:start_time] || calculate_next_build_time end def build_necessary?(reasons) if @triggered_project.build_requested? || time_for_new_build? @next_build_time = calculate_next_build_time true end end def calculate_next_build_time Time.now + @build_interval end def time_for_new_build? Time.now >= @next_build_time end end
{ "pile_set_name": "Github" }
/* * SonarQube * Copyright (C) 2009-2020 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.db.migration.version.v84.properties; import java.sql.SQLException; import java.util.Objects; import java.util.stream.Collectors; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DataChange; import static org.assertj.core.api.Assertions.assertThat; public class PopulatePropertiesUuidAndCreatedAtTest { @Rule public CoreDbTester db = CoreDbTester.createForSchema(PopulatePropertiesUuidAndCreatedAtTest.class, "schema.sql"); private UuidFactory uuidFactory = UuidFactoryFast.getInstance(); private DataChange underTest = new PopulatePropertiesUuid(db.database(), uuidFactory); @Test public void populate_uuids() throws SQLException { insertProperties(1L, "uuid1", "key1"); insertProperties(2L, "uuid2", "key2"); insertProperties(3L, "uuid3", "key3"); underTest.execute(); verifyUuidsAreNotNull(); } @Test public void migration_is_reentrant() throws SQLException { insertProperties(1L, "uuid1", "key1"); insertProperties(2L, "uuid2", "key2"); insertProperties(3L, "uuid3", "key3"); underTest.execute(); // re-entrant underTest.execute(); verifyUuidsAreNotNull(); } private void verifyUuidsAreNotNull() { assertThat(db.select("select uuid from properties") .stream() .map(row -> row.get("UUID")) .filter(Objects::isNull) .collect(Collectors.toList())).isEmpty(); } private void insertProperties(Long id, String uuid, String propKey) { db.executeInsert("properties", "id", id, "prop_key", propKey, "uuid", uuid, "is_empty", false, "created_at", 0); } }
{ "pile_set_name": "Github" }
<?php /** * HydrateSettingsDelegate * @author edgebal */ namespace Minds\Core\Pro\Delegates; use Minds\Core\Config; use Minds\Core\Di\Di; use Minds\Core\EntitiesBuilder; use Minds\Core\Pro\Settings; use Minds\Entities\User; use Minds\Helpers\Text; class HydrateSettingsDelegate { /** @var EntitiesBuilder */ protected $entitiesBuilder; /** @var Config */ protected $config; /** * HydrateSettingsDelegate constructor. * @param EntitiesBuilder $entitiesBuilder * @param Config $config */ public function __construct( $entitiesBuilder = null, $config = null ) { $this->entitiesBuilder = $entitiesBuilder ?: Di::_()->get('EntitiesBuilder'); $this->config = $config ?: Di::_()->get('Config'); } /** * @param User $user * @param Settings $settings * @return Settings */ public function onGet(User $user, Settings $settings): Settings { try { $logoImage = $settings->hasCustomLogo() ? sprintf( '%sfs/v1/pro/%s/logo/%s', $this->config->get('cdn_url'), $settings->getUserGuid(), $settings->getTimeUpdated() ) : $user->getIconURL('large'); if ($logoImage) { $settings ->setLogoImage($logoImage); } } catch (\Exception $e) { error_log($e); } try { $backgroundImage = null; if ($settings->hasCustomBackground()) { $backgroundImage = sprintf( '%sfs/v1/pro/%s/background/%s', $this->config->get('cdn_url'), $settings->getUserGuid(), $settings->getTimeUpdated() ); } if ($backgroundImage) { $settings ->setBackgroundImage($backgroundImage); } } catch (\Exception $e) { error_log($e); } try { if ($user->getPinnedPosts()) { $pinnedPosts = $this->entitiesBuilder->get(['guids' => Text::buildArray($user->getPinnedPosts())]); uasort($pinnedPosts, function ($a, $b) { if (!$a || !$b) { return 0; } return ($a->time_created < $b->time_created) ? 1 : -1; }); $featuredContent = Text::buildArray(array_values(array_filter(array_map(function ($pinnedPost) { return $pinnedPost->entity_guid ?: $pinnedPost->guid ?: null; }, $pinnedPosts)))); $settings->setFeaturedContent($featuredContent); } } catch (\Exception $e) { error_log($e); } $settings->setPublished($user->isProPublished()); return $settings; } }
{ "pile_set_name": "Github" }
TIMESTAMP = 1598238083 SHA256 (OISF-libhtp-0.5.33_GH0.tar.gz) = 953651fdfe828805bb82dc1aa8b56187b0e2f80781727343e68ccf8afd6a9122 SIZE (OISF-libhtp-0.5.33_GH0.tar.gz) = 496010
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../UtilsStrings.resx"> <body> <trans-unit id="buildProductName"> <source>Microsoft (R) F# Compiler version {0}</source> <target state="new">Microsoft (R) F# Compiler version {0}</target> <note /> </trans-unit> <trans-unit id="fSharpBannerVersion"> <source>{0} for F# {1}</source> <target state="new">{0} for F# {1}</target> <note /> </trans-unit> </body> </file> </xliff>
{ "pile_set_name": "Github" }
// Package errors provides simple error handling primitives. // // The traditional error handling idiom in Go is roughly akin to // // if err != nil { // return err // } // // which applied recursively up the call stack results in error reports // without context or debugging information. The errors package allows // programmers to add context to the failure path in their code in a way // that does not destroy the original value of the error. // // Adding context to an error // // The errors.Wrap function returns a new error that adds context to the // original error by recording a stack trace at the point Wrap is called, // and the supplied message. For example // // _, err := ioutil.ReadAll(r) // if err != nil { // return errors.Wrap(err, "read failed") // } // // If additional control is required the errors.WithStack and errors.WithMessage // functions destructure errors.Wrap into its component operations of annotating // an error with a stack trace and an a message, respectively. // // Retrieving the cause of an error // // Using errors.Wrap constructs a stack of errors, adding context to the // preceding error. Depending on the nature of the error it may be necessary // to reverse the operation of errors.Wrap to retrieve the original error // for inspection. Any error value which implements this interface // // type causer interface { // Cause() error // } // // can be inspected by errors.Cause. errors.Cause will recursively retrieve // the topmost error which does not implement causer, which is assumed to be // the original cause. For example: // // switch err := errors.Cause(err).(type) { // case *MyError: // // handle specifically // default: // // unknown error // } // // causer interface is not exported by this package, but is considered a part // of stable public API. // // Formatted printing of errors // // All error values returned from this package implement fmt.Formatter and can // be formatted by the fmt package. The following verbs are supported // // %s print the error. If the error has a Cause it will be // printed recursively // %v see %s // %+v extended format. Each Frame of the error's StackTrace will // be printed in detail. // // Retrieving the stack trace of an error or wrapper // // New, Errorf, Wrap, and Wrapf record a stack trace at the point they are // invoked. This information can be retrieved with the following interface. // // type stackTracer interface { // StackTrace() errors.StackTrace // } // // Where errors.StackTrace is defined as // // type StackTrace []Frame // // The Frame type represents a call site in the stack trace. Frame supports // the fmt.Formatter interface that can be used for printing information about // the stack trace of this error. For example: // // if err, ok := err.(stackTracer); ok { // for _, f := range err.StackTrace() { // fmt.Printf("%+s:%d", f) // } // } // // stackTracer interface is not exported by this package, but is considered a part // of stable public API. // // See the documentation for Frame.Format for more details. package errors import ( "fmt" "io" ) // New returns an error with the supplied message. // New also records the stack trace at the point it was called. func New(message string) error { return &fundamental{ msg: message, stack: callers(), } } // Errorf formats according to a format specifier and returns the string // as a value that satisfies error. // Errorf also records the stack trace at the point it was called. func Errorf(format string, args ...interface{}) error { return &fundamental{ msg: fmt.Sprintf(format, args...), stack: callers(), } } // fundamental is an error that has a message and a stack, but no caller. type fundamental struct { msg string *stack } func (f *fundamental) Error() string { return f.msg } func (f *fundamental) Format(s fmt.State, verb rune) { switch verb { case 'v': if s.Flag('+') { io.WriteString(s, f.msg) f.stack.Format(s, verb) return } fallthrough case 's': io.WriteString(s, f.msg) case 'q': fmt.Fprintf(s, "%q", f.msg) } } // WithStack annotates err with a stack trace at the point WithStack was called. // If err is nil, WithStack returns nil. func WithStack(err error) error { if err == nil { return nil } return &withStack{ err, callers(), } } type withStack struct { error *stack } func (w *withStack) Cause() error { return w.error } func (w *withStack) Format(s fmt.State, verb rune) { switch verb { case 'v': if s.Flag('+') { fmt.Fprintf(s, "%+v", w.Cause()) w.stack.Format(s, verb) return } fallthrough case 's': io.WriteString(s, w.Error()) case 'q': fmt.Fprintf(s, "%q", w.Error()) } } // Wrap returns an error annotating err with a stack trace // at the point Wrap is called, and the supplied message. // If err is nil, Wrap returns nil. func Wrap(err error, message string) error { if err == nil { return nil } err = &withMessage{ cause: err, msg: message, } return &withStack{ err, callers(), } } // Wrapf returns an error annotating err with a stack trace // at the point Wrapf is call, and the format specifier. // If err is nil, Wrapf returns nil. func Wrapf(err error, format string, args ...interface{}) error { if err == nil { return nil } err = &withMessage{ cause: err, msg: fmt.Sprintf(format, args...), } return &withStack{ err, callers(), } } // WithMessage annotates err with a new message. // If err is nil, WithMessage returns nil. func WithMessage(err error, message string) error { if err == nil { return nil } return &withMessage{ cause: err, msg: message, } } type withMessage struct { cause error msg string } func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } func (w *withMessage) Cause() error { return w.cause } func (w *withMessage) Format(s fmt.State, verb rune) { switch verb { case 'v': if s.Flag('+') { fmt.Fprintf(s, "%+v\n", w.Cause()) io.WriteString(s, w.msg) return } fallthrough case 's', 'q': io.WriteString(s, w.Error()) } } // Cause returns the underlying cause of the error, if possible. // An error value has a cause if it implements the following // interface: // // type causer interface { // Cause() error // } // // If the error does not implement Cause, the original error will // be returned. If the error is nil, nil will be returned without further // investigation. func Cause(err error) error { type causer interface { Cause() error } for err != nil { cause, ok := err.(causer) if !ok { break } err = cause.Cause() } return err }
{ "pile_set_name": "Github" }
'use strict' module.exports = require('./lib/verify')
{ "pile_set_name": "Github" }
[package] name = "libattr" version = "0.1.0" edition = "2018" publish = false build = "build.rs" [lib] path = "pkg.rs" [[package.metadata.build-package.external-files]] url = "https://download-mirror.savannah.gnu.org/releases/attr/attr-2.4.48.tar.gz" sha512 = "75f870a0e6e19b8975f3fdceee786fbaff3eadaa9ab9af01996ffa8e50fe5b2bba6e4c22c44a6722d11b55feb9e89895d0151d6811c1d2b475ef4ed145f0c923" [build-dependencies] glibc = { path = "../glibc" }
{ "pile_set_name": "Github" }
/* This file is provided under a dual BSD/GPLv2 license. When using or redistributing this file, you may do so under either license. GPL LICENSE SUMMARY Copyright(c) 2014 Intel Corporation. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Contact Information: [email protected] BSD LICENSE Copyright(c) 2014 Intel Corporation. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _ICP_QAT_FW_INIT_ADMIN_H_ #define _ICP_QAT_FW_INIT_ADMIN_H_ #include "icp_qat_fw.h" enum icp_qat_fw_init_admin_cmd_id { ICP_QAT_FW_INIT_ME = 0, ICP_QAT_FW_TRNG_ENABLE = 1, ICP_QAT_FW_TRNG_DISABLE = 2, ICP_QAT_FW_CONSTANTS_CFG = 3, ICP_QAT_FW_STATUS_GET = 4, ICP_QAT_FW_COUNTERS_GET = 5, ICP_QAT_FW_LOOPBACK = 6, ICP_QAT_FW_HEARTBEAT_SYNC = 7, ICP_QAT_FW_HEARTBEAT_GET = 8 }; enum icp_qat_fw_init_admin_resp_status { ICP_QAT_FW_INIT_RESP_STATUS_SUCCESS = 0, ICP_QAT_FW_INIT_RESP_STATUS_FAIL }; struct icp_qat_fw_init_admin_req { uint16_t init_cfg_sz; uint8_t resrvd1; uint8_t init_admin_cmd_id; uint32_t resrvd2; uint64_t opaque_data; uint64_t init_cfg_ptr; uint64_t resrvd3; }; struct icp_qat_fw_init_admin_resp_hdr { uint8_t flags; uint8_t resrvd1; uint8_t status; uint8_t init_admin_cmd_id; }; struct icp_qat_fw_init_admin_resp_pars { union { uint32_t resrvd1[ICP_QAT_FW_NUM_LONGWORDS_4]; struct { uint32_t version_patch_num; uint8_t context_id; uint8_t ae_id; uint16_t resrvd1; uint64_t resrvd2; } s1; struct { uint64_t req_rec_count; uint64_t resp_sent_count; } s2; } u; }; struct icp_qat_fw_init_admin_resp { struct icp_qat_fw_init_admin_resp_hdr init_resp_hdr; union { uint32_t resrvd2; struct { uint16_t version_minor_num; uint16_t version_major_num; } s; } u; uint64_t opaque_data; struct icp_qat_fw_init_admin_resp_pars init_resp_pars; }; #define ICP_QAT_FW_COMN_HEARTBEAT_OK 0 #define ICP_QAT_FW_COMN_HEARTBEAT_BLOCKED 1 #define ICP_QAT_FW_COMN_HEARTBEAT_FLAG_BITPOS 0 #define ICP_QAT_FW_COMN_HEARTBEAT_FLAG_MASK 0x1 #define ICP_QAT_FW_COMN_STATUS_RESRVD_FLD_MASK 0xFE #define ICP_QAT_FW_COMN_HEARTBEAT_HDR_FLAG_GET(hdr_t) \ ICP_QAT_FW_COMN_HEARTBEAT_FLAG_GET(hdr_t.flags) #define ICP_QAT_FW_COMN_HEARTBEAT_HDR_FLAG_SET(hdr_t, val) \ ICP_QAT_FW_COMN_HEARTBEAT_FLAG_SET(hdr_t, val) #define ICP_QAT_FW_COMN_HEARTBEAT_FLAG_GET(flags) \ QAT_FIELD_GET(flags, \ ICP_QAT_FW_COMN_HEARTBEAT_FLAG_BITPOS, \ ICP_QAT_FW_COMN_HEARTBEAT_FLAG_MASK) #endif
{ "pile_set_name": "Github" }
/** Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags 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 bftsmart.tom; import bftsmart.tom.core.TOMSender; import java.util.Arrays; import java.util.Comparator; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import bftsmart.reconfiguration.ReconfigureReply; import bftsmart.reconfiguration.views.View; import bftsmart.tom.core.messages.TOMMessage; import bftsmart.tom.core.messages.TOMMessageType; import bftsmart.tom.util.Extractor; import bftsmart.tom.util.KeyLoader; import bftsmart.tom.util.TOMUtil; import java.security.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class implements a TOMSender and represents a proxy to be used on the * client side of the replicated system. * It sends a request to the replicas, receives the reply, and delivers it to * the application. */ public class ServiceProxy extends TOMSender { private Logger logger = LoggerFactory.getLogger(this.getClass()); // Locks for send requests and receive replies protected ReentrantLock canReceiveLock = new ReentrantLock(); protected ReentrantLock canSendLock = new ReentrantLock(); private Semaphore sm = new Semaphore(0); private int reqId = -1; // request id private int operationId = -1; // request id private TOMMessageType requestType; private int replyQuorum = 0; // size of the reply quorum private TOMMessage replies[] = null; // Replies from replicas are stored here private int receivedReplies = 0; // Number of received replies private TOMMessage response = null; // Reply delivered to the application private int invokeTimeout = 40; private Comparator<byte[]> comparator; private Extractor extractor; private Random rand = new Random(System.currentTimeMillis()); private int replyServer; private HashResponseController hashResponseController; private int invokeUnorderedHashedTimeout = 10; /** * Constructor * * @see bellow */ public ServiceProxy(int processId) { this(processId, null, null, null, null); } /** * Constructor * * @see bellow */ public ServiceProxy(int processId, String configHome) { this(processId, configHome, null, null, null); } /** * Constructor * * @see bellow */ public ServiceProxy(int processId, String configHome, KeyLoader loader) { this(processId, configHome, null, null, loader); } /** * Constructor * * @param processId Process id for this client (should be different from replicas) * @param configHome Configuration directory for BFT-SMART * @param replyComparator Used for comparing replies from different servers * to extract one returned by f+1 * @param replyExtractor Used for extracting the response from the matching * quorum of replies * @param loader Used to load signature keys from disk */ public ServiceProxy(int processId, String configHome, Comparator<byte[]> replyComparator, Extractor replyExtractor, KeyLoader loader) { if (configHome == null) { init(processId, loader); } else { init(processId, configHome, loader); } replies = new TOMMessage[getViewManager().getCurrentViewN()]; comparator = (replyComparator != null) ? replyComparator : new Comparator<byte[]>() { @Override public int compare(byte[] o1, byte[] o2) { return Arrays.equals(o1, o2) ? 0 : -1; } }; extractor = (replyExtractor != null) ? replyExtractor : new Extractor() { @Override public TOMMessage extractResponse(TOMMessage[] replies, int sameContent, int lastReceived) { return replies[lastReceived]; } }; } /** * Get the amount of time (in seconds) that this proxy will wait for * servers replies before returning null. * * @return the timeout value in seconds */ public int getInvokeTimeout() { return invokeTimeout; } /** * Get the amount of time (in seconds) that this proxy will wait for * servers unordered hashed replies before returning null. * * @return the timeout value in seconds */ public int getInvokeUnorderedHashedTimeout() { return invokeUnorderedHashedTimeout; } /** * Set the amount of time (in seconds) that this proxy will wait for * servers replies before returning null. * * @param invokeTimeout the timeout value to set */ public void setInvokeTimeout(int invokeTimeout) { this.invokeTimeout = invokeTimeout; } /** * Set the amount of time (in seconds) that this proxy will wait for * servers unordered hashed replies before returning null. * * @param timeout the timeout value to set */ public void setInvokeUnorderedHashedTimeout(int timeout) { this.invokeUnorderedHashedTimeout = timeout; } /** * This method sends an ordered request to the replicas, and returns the related reply. * If the servers take more than invokeTimeout seconds the method returns null. * This method is thread-safe. * * @param request to be sent * @return The reply from the replicas related to request */ public byte[] invokeOrdered(byte[] request) { return invoke(request, TOMMessageType.ORDERED_REQUEST); } /** * This method sends an unordered request to the replicas, and returns the related reply. * If the servers take more than invokeTimeout seconds the method returns null. * This method is thread-safe. * * @param request to be sent * @return The reply from the replicas related to request */ public byte[] invokeUnordered(byte[] request) { return invoke(request, TOMMessageType.UNORDERED_REQUEST); } /** * This method sends an unordered request to the replicas, and returns the related reply. * This method chooses randomly one replica to send the complete response, while the others * only send a hash of that response. * If the servers take more than invokeTimeout seconds the method returns null. * This method is thread-safe. * * @param request to be sent * @return The reply from the replicas related to request */ public byte[] invokeUnorderedHashed(byte[] request) { return invoke(request, TOMMessageType.UNORDERED_HASHED_REQUEST); } /** * This method sends a request to the replicas, and returns the related reply. * If the servers take more than invokeTimeout seconds the method returns null. * This method is thread-safe. * * @param request Request to be sent * @param reqType ORDERED_REQUEST/UNORDERED_REQUEST/UNORDERED_HASHED_REQUEST for normal requests, and RECONFIG for * reconfiguration requests. * * @return The reply from the replicas related to request */ public byte[] invoke(byte[] request, TOMMessageType reqType) { try { canSendLock.lock(); // Clean all statefull data to prepare for receiving next replies Arrays.fill(replies, null); receivedReplies = 0; response = null; replyQuorum = getReplyQuorum(); // Send the request to the replicas, and get its ID reqId = generateRequestId(reqType); operationId = generateOperationId(); requestType = reqType; replyServer = -1; hashResponseController = null; if(requestType == TOMMessageType.UNORDERED_HASHED_REQUEST){ replyServer = getRandomlyServerId(); logger.debug("["+this.getClass().getName()+"] replyServerId("+replyServer+") " + "pos("+getViewManager().getCurrentViewPos(replyServer)+")"); hashResponseController = new HashResponseController(getViewManager().getCurrentViewPos(replyServer), getViewManager().getCurrentViewProcesses().length); TOMMessage sm = new TOMMessage(getProcessId(),getSession(), reqId, operationId, request, getViewManager().getCurrentViewId(), requestType); sm.setReplyServer(replyServer); TOMulticast(sm); }else{ TOMulticast(request, reqId, operationId, reqType); } logger.debug("Sending request (" + reqType + ") with reqId=" + reqId); logger.debug("Expected number of matching replies: " + replyQuorum); // This instruction blocks the thread, until a response is obtained. // The thread will be unblocked when the method replyReceived is invoked // by the client side communication system try { if(reqType == TOMMessageType.UNORDERED_HASHED_REQUEST){ if (!this.sm.tryAcquire(invokeUnorderedHashedTimeout, TimeUnit.SECONDS)) { logger.info("######## UNORDERED HASHED REQUEST TIMOUT ########"); canSendLock.unlock(); return invoke(request,TOMMessageType.ORDERED_REQUEST); } }else{ if (!this.sm.tryAcquire(invokeTimeout, TimeUnit.SECONDS)) { logger.info("###################TIMEOUT#######################"); logger.info("Reply timeout for reqId=" + reqId + ", Replies received: " + receivedReplies); canSendLock.unlock(); return null; } } } catch (InterruptedException ex) { logger.error("Problem aquiring semaphore",ex); } logger.debug("Response extracted = " + response); byte[] ret = null; if (response == null) { //the response can be null if n-f replies are received but there isn't //a replyQuorum of matching replies logger.debug("Received n-f replies and no response could be extracted."); canSendLock.unlock(); if (reqType == TOMMessageType.UNORDERED_REQUEST || reqType == TOMMessageType.UNORDERED_HASHED_REQUEST) { //invoke the operation again, whitout the read-only flag logger.debug("###################RETRY#######################"); return invokeOrdered(request); } else { throw new RuntimeException("Received n-f replies without f+1 of them matching."); } } else { //normal operation //******* EDUARDO BEGIN **************// if (reqType == TOMMessageType.ORDERED_REQUEST) { //Reply to a normal request! if (response.getViewID() == getViewManager().getCurrentViewId()) { ret = response.getContent(); // return the response } else {//if(response.getViewID() > getViewManager().getCurrentViewId()) //updated view received reconfigureTo((View) TOMUtil.getObject(response.getContent())); canSendLock.unlock(); return invoke(request, reqType); } } else if (reqType == TOMMessageType.UNORDERED_REQUEST || reqType == TOMMessageType.UNORDERED_HASHED_REQUEST){ if (response.getViewID() == getViewManager().getCurrentViewId()) { ret = response.getContent(); // return the response }else{ canSendLock.unlock(); return invoke(request,TOMMessageType.ORDERED_REQUEST); } } else { if (response.getViewID() > getViewManager().getCurrentViewId()) { //Reply to a reconfigure request! logger.debug("Reconfiguration request' reply received!"); Object r = TOMUtil.getObject(response.getContent()); if (r instanceof View) { //did not executed the request because it is using an outdated view reconfigureTo((View) r); canSendLock.unlock(); return invoke(request, reqType); } else if (r instanceof ReconfigureReply) { //reconfiguration executed! reconfigureTo(((ReconfigureReply) r).getView()); ret = response.getContent(); } else{ logger.debug("Unknown response type"); } } else { logger.debug("Unexpected execution flow"); } } } //******* EDUARDO END **************// return ret; } finally { if (canSendLock.isHeldByCurrentThread()) canSendLock.unlock(); //always release lock } } //******* EDUARDO BEGIN **************// /** * @deprecated */ protected void reconfigureTo(View v) { logger.debug("Installing a most up-to-date view with id=" + v.getId()); getViewManager().reconfigureTo(v); getViewManager().getViewStore().storeView(v); replies = new TOMMessage[getViewManager().getCurrentViewN()]; getCommunicationSystem().updateConnections(); } //******* EDUARDO END **************// /** * This is the method invoked by the client side communication system. * * @param reply The reply delivered by the client side communication system */ @Override public void replyReceived(TOMMessage reply) { logger.debug("Synchronously received reply from " + reply.getSender() + " with sequence number " + reply.getSequence()); try { canReceiveLock.lock(); if (reqId == -1) {//no message being expected logger.debug("throwing out request: sender=" + reply.getSender() + " reqId=" + reply.getSequence()); canReceiveLock.unlock(); return; } int pos = getViewManager().getCurrentViewPos(reply.getSender()); if (pos < 0) { //ignore messages that don't come from replicas canReceiveLock.unlock(); return; } int sameContent = 1; if (reply.getSequence() == reqId && reply.getReqType() == requestType) { logger.debug("Receiving reply from " + reply.getSender() + " with reqId:" + reply.getSequence() + ". Putting on pos=" + pos); if(requestType == TOMMessageType.UNORDERED_HASHED_REQUEST) { response = hashResponseController.getResponse(pos,reply); if(response !=null){ reqId = -1; this.sm.release(); // resumes the thread that is executing the "invoke" method canReceiveLock.unlock(); return; } }else{ if (replies[pos] == null) { receivedReplies++; } replies[pos] = reply; // Compare the reply just received, to the others for (int i = 0; i < replies.length; i++) { if ((i != pos || getViewManager().getCurrentViewN() == 1) && replies[i] != null && (comparator.compare(replies[i].getContent(), reply.getContent()) == 0)) { sameContent++; if (sameContent >= replyQuorum) { response = extractor.extractResponse(replies, sameContent, pos); reqId = -1; this.sm.release(); // resumes the thread that is executing the "invoke" method canReceiveLock.unlock(); return; } } } } if (response == null) { if (requestType.equals(TOMMessageType.ORDERED_REQUEST)) { if (receivedReplies == getViewManager().getCurrentViewN()) { reqId = -1; this.sm.release(); // resumes the thread that is executing the "invoke" method } }else if (requestType.equals(TOMMessageType.UNORDERED_HASHED_REQUEST)) { if (hashResponseController.getNumberReplies() == getViewManager().getCurrentViewN()) { reqId = -1; this.sm.release(); // resumes the thread that is executing the "invoke" method } } else { // UNORDERED if (receivedReplies != sameContent) { reqId = -1; this.sm.release(); // resumes the thread that is executing the "invoke" method } } } } else { logger.debug("Ignoring reply from " + reply.getSender() + " with reqId:" + reply.getSequence() + ". Currently wait reqId= " + reqId); } // Critical section ends here. The semaphore can be released canReceiveLock.unlock(); } catch (Exception ex) { logger.error("Problem processing reply", ex); canReceiveLock.unlock(); } } /** * Retrieves the required quorum size for the amount of replies * * @return The quorum size for the amount of replies */ protected int getReplyQuorum() { if (getViewManager().getStaticConf().isBFT()) { return (int) Math.ceil((getViewManager().getCurrentViewN() + getViewManager().getCurrentViewF()) / 2) + 1; } else { return (int) Math.ceil((getViewManager().getCurrentViewN()) / 2) + 1; } } private int getRandomlyServerId(){ int numServers = super.getViewManager().getCurrentViewProcesses().length; int pos = rand.nextInt(numServers); return super.getViewManager().getCurrentViewProcesses()[pos]; } private class HashResponseController{ private TOMMessage reply; private byte [][] hashReplies; private int replyServerPos; private int countHashReplies; public HashResponseController(int replyServerPos, int length) { this.replyServerPos = replyServerPos; this.hashReplies = new byte[length][]; this.reply = null; this.countHashReplies = 0; } public TOMMessage getResponse(int pos, TOMMessage tomMessage){ if(hashReplies[pos]==null){ countHashReplies++; } if(replyServerPos == pos){ reply = tomMessage; hashReplies[pos] = TOMUtil.computeHash(tomMessage.getContent()); }else{ hashReplies[pos] = tomMessage.getContent(); } logger.debug("["+this.getClass().getName()+"] hashReplies["+pos+"]="+Arrays.toString(hashReplies[pos])); if(hashReplies[replyServerPos]!=null){ int sameContent = 1; for (int i = 0; i < replies.length; i++) { if ((i != replyServerPos || getViewManager().getCurrentViewN() == 1) && hashReplies[i] != null && (Arrays.equals(hashReplies[i], hashReplies[replyServerPos]))) { sameContent++; if (sameContent >= replyQuorum) { return reply; } } } } return null; } public int getNumberReplies(){ return countHashReplies; } } }
{ "pile_set_name": "Github" }
#include <unistd.h> #include <signet/keys.h> #include <common/misc.h> #include <common/dcrypto.h> static void usage(const char *progname) { fprintf(stderr, "\nUsage: %s <-g or -d> [-p] [-f keyfile] where\n", progname); fprintf(stderr, " -g generates a new ED25519 keypair.\n"); fprintf(stderr, " -d dumps the ED25519 key data supplied by the user.\n"); fprintf(stderr, " -p can be used with -d to fetch the POK from a private keychain.\n"); fprintf(stderr, " -f specifies a keyfile to be used with -g or -d (otherwise stdout/stdin will be used by default).\n\n"); exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { ED25519_KEY *key; FILE *fp; char *filename = NULL, *pubb64, *privb64, *hexkey; int opt, generate = 0, dump = 0, pok = 0; while ((opt = getopt(argc, argv, "gdf:p")) != -1) { switch (opt) { case 'g': generate = 1; break; case 'd': dump = 1; break; case 'f': filename = optarg; break; case 'p': pok = 1; break; default: usage(argv[0]); break; } } if (!dump && !generate) { usage(argv[0]); } else if (dump && generate) { fprintf(stderr, "Error: -d and -g cannot be specified together.\n"); exit(EXIT_FAILURE); } if (optind != argc) { usage(argv[0]); } if (pok && (!dump || !filename)) { fprintf(stderr, "Error: -p must be specified together with the -d and -f options.\n"); exit(EXIT_FAILURE); } if (generate) { if (!(key = generate_ed25519_keypair())) { fprintf(stderr, "Error: Unable to generate new ED25519 key pair.\n"); dump_error_stack(); exit(EXIT_FAILURE); } fp = stdout; if (filename) { if (!(fp = fopen(filename, "w"))) { perror("fopen"); fprintf(stderr, "Error: Unable to open ED25519 key data file for writing.\n"); free_ed25519_key(key); exit(EXIT_FAILURE); } } if (!(privb64 = b64encode(key->private_key, sizeof(key->private_key)))) { fprintf(stderr, "Error: Unable to base64 encode ED25519 private key.\n"); dump_error_stack(); free_ed25519_key(key); exit(EXIT_FAILURE); } if (!(pubb64 = b64encode(key->public_key, sizeof(key->public_key)))) { fprintf(stderr, "Error: Unable to base64 encode ED25519 public key.\n"); dump_error_stack(); free_ed25519_key(key); free(privb64); exit(EXIT_FAILURE); } fprintf(fp, "-----BEGIN ED25519 PRIVATE KEY-----\n"); fprintf(fp, "%s\n", privb64); fprintf(fp, "-----END ED25519 PRIVATE KEY-----\n\n"); fprintf(fp, "-----BEGIN ED25519 PUBLIC KEY-----\n"); fprintf(fp, "%s\n", pubb64); fprintf(fp, "-----END ED25519 PUBLIC KEY-----\n"); free_ed25519_key(key); free(privb64); free(pubb64); } else if (dump) { if (pok) { if (!(key = keys_file_fetch_sign_key(filename))) { fprintf(stderr, "Error: could not read POK from keyfile.\n"); dump_error_stack(); exit(EXIT_FAILURE); } } else { if (filename) { if (!(fp = fopen(filename, "r"))) { perror("fopen"); fprintf(stderr, "Error: Unable to open ED25519 key data file for reading.\n"); exit(EXIT_FAILURE); } } if (!(key = load_ed25519_privkey(filename))) { fprintf(stderr, "Error: Unable to read in ED25519 key data.\n"); dump_error_stack(); exit(EXIT_FAILURE); } } if (!(hexkey = hex_encode(key->private_key, sizeof(key->private_key)))) { fprintf(stderr, "Error: Unable to encode ED25519 private key.\n"); dump_error_stack(); exit(EXIT_FAILURE); } printf("ED25519 private key: %s\n", hexkey); free(hexkey); if (!(hexkey = hex_encode(key->public_key, sizeof(key->public_key)))) { fprintf(stderr, "Error: Unable to encode ED25519 public key.\n"); dump_error_stack(); exit(EXIT_FAILURE); } printf("ED25519 public key: %s\n", hexkey); free(hexkey); } exit(EXIT_SUCCESS); }
{ "pile_set_name": "Github" }
powerpc/powerpc32/power5+/fpu/multiarch
{ "pile_set_name": "Github" }
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* 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/. */ #include "avmplus.h" #include "float4Support.h" #ifdef VMCFG_GENERIC_FLOAT4 namespace avmplus { /* Note: This file must be compiled with NEON turned on even for targets that don't have NEON, in order for the adapters to work. But VMCFG_NEON may be undefined, indicating that we don't want fast intrinsic implementation */ #ifdef VMCFG_FLOAT #ifdef VMCFG_ARM #include <arm_neon.h> #define float4_ret_t float32x4_t #elif defined VMCFG_SSE2 #include <xmmintrin.h> #define float4_ret_t __m128 #else #error Unsupported platform in float4Support.cpp #endif #else #endif typedef union { float4_ret_t f4_jit; float4_t f4; } rvtype; // Alignment is buggy in MSVC, do it by hand. #define DECLARE_ALIGNED_FLOAT4_PTR(v) \ float locals[8]; \ uintptr_t lptr = (uintptr_t)(&locals[0]);\ rvtype *v = reinterpret_cast<rvtype*>((lptr + 0xf) & ~0xf); float4_ret_t verifyEnterVECR_adapter_impl(avmplus::MethodEnv* env, int32_t argc, uint32_t* ap){ DECLARE_ALIGNED_FLOAT4_PTR(retval); retval->f4 = avmplus::BaseExecMgr::verifyEnterVECR(env, argc, ap); return retval->f4_jit; } float4_t thunkEnterVECR_adapter_impl(void* thunk_p, MethodEnv* env, int32_t argc, uint32_t* argv){ typedef float4_ret_t (*VecrThunk)(avmplus::MethodEnv* env, int32_t argc, uint32_t* argv); DECLARE_ALIGNED_FLOAT4_PTR(retval); if( thunk_p) // prevent ARM GCC from doing CSE, it crashes otherwise retval->f4_jit = ((VecrThunk) thunk_p)(env, argc, argv); return retval->f4; } #ifdef DEBUGGER float4_ret_t debugEnterVECR_adapter_impl(avmplus::MethodEnv* env, int32_t argc, uint32_t* ap){ DECLARE_ALIGNED_FLOAT4_PTR(retval); retval->f4 = avmplus::BaseExecMgr::debugEnterExitWrapperV(env, argc, ap); return retval->f4_jit; } const VecrMethodProc debugEnterVECR_adapter = (VecrMethodProc) debugEnterVECR_adapter_impl; #endif const VecrMethodProc verifyEnterVECR_adapter = (VecrMethodProc) verifyEnterVECR_adapter_impl; const VecrThunkProc thunkEnterVECR_adapter = thunkEnterVECR_adapter_impl; } #endif // TODO: leave these for "#if !defined(VMCFG_NEON) && !defined(VMCFG_SSE2)", add hardware-accellerated versions for NEON and SSE2 float4_t f4_add(const float4_t& x1, const float4_t& x2) { float4_t retval = { x1.x + x2.x, x1.y + x2.y, x1.z + x2.z, x1.w + x2.w }; return retval; } float4_t f4_sub(const float4_t& x1, const float4_t& x2) { float4_t retval = { x1.x - x2.x, x1.y - x2.y, x1.z - x2.z, x1.w - x2.w }; return retval; } float4_t f4_mul(const float4_t& x1, const float4_t& x2) { float4_t retval = { x1.x * x2.x, x1.y * x2.y, x1.z * x2.z, x1.w * x2.w }; return retval; } float4_t f4_div(const float4_t& x1, const float4_t& x2) { float4_t retval = { x1.x / x2.x, x1.y / x2.y, x1.z / x2.z, x1.w / x2.w }; return retval; }
{ "pile_set_name": "Github" }
# # Traffic control configuration. # menu "QoS and/or fair queueing" config NET_SCHED bool "QoS and/or fair queueing" select NET_SCH_FIFO ---help--- When the kernel has several packets to send out over a network device, it has to decide which ones to send first, which ones to delay, and which ones to drop. This is the job of the queueing disciplines, several different algorithms for how to do this "fairly" have been proposed. If you say N here, you will get the standard packet scheduler, which is a FIFO (first come, first served). If you say Y here, you will be able to choose from among several alternative algorithms which can then be attached to different network devices. This is useful for example if some of your network devices are real time devices that need a certain minimum data flow rate, or if you need to limit the maximum data flow rate for traffic which matches specified criteria. This code is considered to be experimental. To administer these schedulers, you'll need the user-level utilities from the package iproute2+tc at <ftp://ftp.tux.org/pub/net/ip-routing/>. That package also contains some documentation; for more, check out <http://linux-net.osdl.org/index.php/Iproute2>. This Quality of Service (QoS) support will enable you to use Differentiated Services (diffserv) and Resource Reservation Protocol (RSVP) on your Linux router if you also say Y to the corresponding classifiers below. Documentation and software is at <http://diffserv.sourceforge.net/>. If you say Y here and to "/proc file system" below, you will be able to read status information about packet schedulers from the file /proc/net/psched. The available schedulers are listed in the following questions; you can say Y to as many as you like. If unsure, say N now. config NET_SCH_FIFO bool if NET_SCHED comment "Queueing/Scheduling" config NET_SCH_CBQ tristate "Class Based Queueing (CBQ)" ---help--- Say Y here if you want to use the Class-Based Queueing (CBQ) packet scheduling algorithm. This algorithm classifies the waiting packets into a tree-like hierarchy of classes; the leaves of this tree are in turn scheduled by separate algorithms. See the top of <file:net/sched/sch_cbq.c> for more details. CBQ is a commonly used scheduler, so if you're unsure, you should say Y here. Then say Y to all the queueing algorithms below that you want to use as leaf disciplines. To compile this code as a module, choose M here: the module will be called sch_cbq. config NET_SCH_HTB tristate "Hierarchical Token Bucket (HTB)" ---help--- Say Y here if you want to use the Hierarchical Token Buckets (HTB) packet scheduling algorithm. See <http://luxik.cdi.cz/~devik/qos/htb/> for complete manual and in-depth articles. HTB is very similar to CBQ regarding its goals however is has different properties and different algorithm. To compile this code as a module, choose M here: the module will be called sch_htb. config NET_SCH_HFSC tristate "Hierarchical Fair Service Curve (HFSC)" ---help--- Say Y here if you want to use the Hierarchical Fair Service Curve (HFSC) packet scheduling algorithm. To compile this code as a module, choose M here: the module will be called sch_hfsc. config NET_SCH_ATM tristate "ATM Virtual Circuits (ATM)" depends on ATM ---help--- Say Y here if you want to use the ATM pseudo-scheduler. This provides a framework for invoking classifiers, which in turn select classes of this queuing discipline. Each class maps the flow(s) it is handling to a given virtual circuit. See the top of <file:net/sched/sch_atm.c>) for more details. To compile this code as a module, choose M here: the module will be called sch_atm. config NET_SCH_PRIO tristate "Multi Band Priority Queueing (PRIO)" ---help--- Say Y here if you want to use an n-band priority queue packet scheduler. To compile this code as a module, choose M here: the module will be called sch_prio. config NET_SCH_RED tristate "Random Early Detection (RED)" ---help--- Say Y here if you want to use the Random Early Detection (RED) packet scheduling algorithm. See the top of <file:net/sched/sch_red.c> for more details. To compile this code as a module, choose M here: the module will be called sch_red. config NET_SCH_SFQ tristate "Stochastic Fairness Queueing (SFQ)" ---help--- Say Y here if you want to use the Stochastic Fairness Queueing (SFQ) packet scheduling algorithm . See the top of <file:net/sched/sch_sfq.c> for more details. To compile this code as a module, choose M here: the module will be called sch_sfq. config NET_SCH_ESFQ tristate "Enhanced Stochastic Fairness Queueing (ESFQ)" ---help--- Say Y here if you want to use the Enhanced Stochastic Fairness Queueing (ESFQ) packet scheduling algorithm for some of your network devices or as a leaf discipline for a classful qdisc such as HTB or CBQ (see the top of <file:net/sched/sch_esfq.c> for details and references to the SFQ algorithm). This is an enchanced SFQ version which allows you to control some hardcoded values in the SFQ scheduler. ESFQ also adds control of the hash function used to identify packet flows. The original SFQ discipline hashes by connection; ESFQ add several other hashing methods, such as by src IP or by dst IP, which can be more fair to users in some networking situations. To compile this code as a module, choose M here: the module will be called sch_esfq. config NET_SCH_ESFQ_NFCT bool "Connection Tracking Hash Types" depends on NET_SCH_ESFQ && NF_CONNTRACK ---help--- Say Y here to enable support for hashing based on netfilter connection tracking information. This is useful for a router that is also using NAT to connect privately-addressed hosts to the Internet. If you want to provide fair distribution of upstream bandwidth, ESFQ must use connection tracking information, since all outgoing packets will share the same source address. config NET_SCH_TEQL tristate "True Link Equalizer (TEQL)" ---help--- Say Y here if you want to use the True Link Equalizer (TLE) packet scheduling algorithm. This queueing discipline allows the combination of several physical devices into one virtual device. See the top of <file:net/sched/sch_teql.c> for more details. To compile this code as a module, choose M here: the module will be called sch_teql. config NET_SCH_TBF tristate "Token Bucket Filter (TBF)" ---help--- Say Y here if you want to use the Token Bucket Filter (TBF) packet scheduling algorithm. See the top of <file:net/sched/sch_tbf.c> for more details. To compile this code as a module, choose M here: the module will be called sch_tbf. config NET_SCH_GRED tristate "Generic Random Early Detection (GRED)" ---help--- Say Y here if you want to use the Generic Random Early Detection (GRED) packet scheduling algorithm for some of your network devices (see the top of <file:net/sched/sch_red.c> for details and references about the algorithm). To compile this code as a module, choose M here: the module will be called sch_gred. config NET_SCH_DSMARK tristate "Differentiated Services marker (DSMARK)" ---help--- Say Y if you want to schedule packets according to the Differentiated Services architecture proposed in RFC 2475. Technical information on this method, with pointers to associated RFCs, is available at <http://www.gta.ufrj.br/diffserv/>. To compile this code as a module, choose M here: the module will be called sch_dsmark. config NET_SCH_NETEM tristate "Network emulator (NETEM)" ---help--- Say Y if you want to emulate network delay, loss, and packet re-ordering. This is often useful to simulate networks when testing applications or protocols. To compile this driver as a module, choose M here: the module will be called sch_netem. If unsure, say N. config NET_SCH_INGRESS tristate "Ingress Qdisc" ---help--- Say Y here if you want to use classifiers for incoming packets. If unsure, say Y. To compile this code as a module, choose M here: the module will be called sch_ingress. comment "Classification" config NET_CLS boolean config NET_CLS_BASIC tristate "Elementary classification (BASIC)" select NET_CLS ---help--- Say Y here if you want to be able to classify packets using only extended matches and actions. To compile this code as a module, choose M here: the module will be called cls_basic. config NET_CLS_TCINDEX tristate "Traffic-Control Index (TCINDEX)" select NET_CLS ---help--- Say Y here if you want to be able to classify packets based on traffic control indices. You will want this feature if you want to implement Differentiated Services together with DSMARK. To compile this code as a module, choose M here: the module will be called cls_tcindex. config NET_CLS_ROUTE4 tristate "Routing decision (ROUTE)" select NET_CLS_ROUTE select NET_CLS ---help--- If you say Y here, you will be able to classify packets according to the route table entry they matched. To compile this code as a module, choose M here: the module will be called cls_route. config NET_CLS_ROUTE bool config NET_CLS_FW tristate "Netfilter mark (FW)" select NET_CLS ---help--- If you say Y here, you will be able to classify packets according to netfilter/firewall marks. To compile this code as a module, choose M here: the module will be called cls_fw. config NET_CLS_U32 tristate "Universal 32bit comparisons w/ hashing (U32)" select NET_CLS ---help--- Say Y here to be able to classify packets using a universal 32bit pieces based comparison scheme. To compile this code as a module, choose M here: the module will be called cls_u32. config CLS_U32_PERF bool "Performance counters support" depends on NET_CLS_U32 ---help--- Say Y here to make u32 gather additional statistics useful for fine tuning u32 classifiers. config CLS_U32_MARK bool "Netfilter marks support" depends on NET_CLS_U32 ---help--- Say Y here to be able to use netfilter marks as u32 key. config NET_CLS_RSVP tristate "IPv4 Resource Reservation Protocol (RSVP)" select NET_CLS select NET_ESTIMATOR ---help--- The Resource Reservation Protocol (RSVP) permits end systems to request a minimum and maximum data flow rate for a connection; this is important for real time data such as streaming sound or video. Say Y here if you want to be able to classify outgoing packets based on their RSVP requests. To compile this code as a module, choose M here: the module will be called cls_rsvp. config NET_CLS_RSVP6 tristate "IPv6 Resource Reservation Protocol (RSVP6)" select NET_CLS select NET_ESTIMATOR ---help--- The Resource Reservation Protocol (RSVP) permits end systems to request a minimum and maximum data flow rate for a connection; this is important for real time data such as streaming sound or video. Say Y here if you want to be able to classify outgoing packets based on their RSVP requests and you are using the IPv6. To compile this code as a module, choose M here: the module will be called cls_rsvp6. config NET_EMATCH bool "Extended Matches" select NET_CLS ---help--- Say Y here if you want to use extended matches on top of classifiers and select the extended matches below. Extended matches are small classification helpers not worth writing a separate classifier for. A recent version of the iproute2 package is required to use extended matches. config NET_EMATCH_STACK int "Stack size" depends on NET_EMATCH default "32" ---help--- Size of the local stack variable used while evaluating the tree of ematches. Limits the depth of the tree, i.e. the number of encapsulated precedences. Every level requires 4 bytes of additional stack space. config NET_EMATCH_CMP tristate "Simple packet data comparison" depends on NET_EMATCH ---help--- Say Y here if you want to be able to classify packets based on simple packet data comparisons for 8, 16, and 32bit values. To compile this code as a module, choose M here: the module will be called em_cmp. config NET_EMATCH_NBYTE tristate "Multi byte comparison" depends on NET_EMATCH ---help--- Say Y here if you want to be able to classify packets based on multiple byte comparisons mainly useful for IPv6 address comparisons. To compile this code as a module, choose M here: the module will be called em_nbyte. config NET_EMATCH_U32 tristate "U32 key" depends on NET_EMATCH ---help--- Say Y here if you want to be able to classify packets using the famous u32 key in combination with logic relations. To compile this code as a module, choose M here: the module will be called em_u32. config NET_EMATCH_META tristate "Metadata" depends on NET_EMATCH ---help--- Say Y here if you want to be able to classify packets based on metadata such as load average, netfilter attributes, socket attributes and routing decisions. To compile this code as a module, choose M here: the module will be called em_meta. config NET_EMATCH_TEXT tristate "Textsearch" depends on NET_EMATCH select TEXTSEARCH select TEXTSEARCH_KMP select TEXTSEARCH_BM select TEXTSEARCH_FSM ---help--- Say Y here if you want to be able to classify packets based on textsearch comparisons. To compile this code as a module, choose M here: the module will be called em_text. config NET_CLS_ACT bool "Actions" select NET_ESTIMATOR ---help--- Say Y here if you want to use traffic control actions. Actions get attached to classifiers and are invoked after a successful classification. They are used to overwrite the classification result, instantly drop or redirect packets, etc. A recent version of the iproute2 package is required to use extended matches. config NET_ACT_POLICE tristate "Traffic Policing" depends on NET_CLS_ACT ---help--- Say Y here if you want to do traffic policing, i.e. strict bandwidth limiting. This action replaces the existing policing module. To compile this code as a module, choose M here: the module will be called police. config NET_ACT_GACT tristate "Generic actions" depends on NET_CLS_ACT ---help--- Say Y here to take generic actions such as dropping and accepting packets. To compile this code as a module, choose M here: the module will be called gact. config GACT_PROB bool "Probability support" depends on NET_ACT_GACT ---help--- Say Y here to use the generic action randomly or deterministically. config NET_ACT_MIRRED tristate "Redirecting and Mirroring" depends on NET_CLS_ACT ---help--- Say Y here to allow packets to be mirrored or redirected to other devices. To compile this code as a module, choose M here: the module will be called mirred. config NET_ACT_IPT tristate "IPtables targets" depends on NET_CLS_ACT && NETFILTER && IP_NF_IPTABLES ---help--- Say Y here to be able to invoke iptables targets after successful classification. To compile this code as a module, choose M here: the module will be called ipt. config NET_ACT_PEDIT tristate "Packet Editing" depends on NET_CLS_ACT ---help--- Say Y here if you want to mangle the content of packets. To compile this code as a module, choose M here: the module will be called pedit. config NET_ACT_SIMP tristate "Simple Example (Debug)" depends on NET_CLS_ACT ---help--- Say Y here to add a simple action for demonstration purposes. It is meant as an example and for debugging purposes. It will print a configured policy string followed by the packet count to the console for every packet that passes by. If unsure, say N. To compile this code as a module, choose M here: the module will be called simple. config NET_CLS_POLICE bool "Traffic Policing (obsolete)" depends on NET_CLS_ACT!=y select NET_ESTIMATOR ---help--- Say Y here if you want to do traffic policing, i.e. strict bandwidth limiting. This option is obsoleted by the traffic policer implemented as action, it stays here for compatibility reasons. config NET_CLS_IND bool "Incoming device classification" depends on NET_CLS_U32 || NET_CLS_FW ---help--- Say Y here to extend the u32 and fw classifier to support classification based on the incoming device. This option is likely to disappear in favour of the metadata ematch. config NET_ESTIMATOR bool "Rate estimator" ---help--- Say Y here to allow using rate estimators to estimate the current rate-of-flow for network devices, queues, etc. This module is automatically selected if needed but can be selected manually for statistical purposes. endif # NET_SCHED endmenu
{ "pile_set_name": "Github" }
/* * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "level_zero/core/source/debugger/debugger_l0.h" namespace L0 { std::unique_ptr<NEO::Debugger> DebuggerL0::create(NEO::Device *device) { auto debugger = debuggerL0Factory[device->getHardwareInfo().platform.eRenderCoreFamily](device); debugger->registerResourceClasses(); return std::unique_ptr<DebuggerL0>(debugger); } } // namespace L0
{ "pile_set_name": "Github" }
/* (No Comment) */ "NSHumanReadableDescription" = "Sociale filterlister med blokeringsregler"; /* Bundle display name */ "CFBundleDisplayName" = "AdGuard Social";
{ "pile_set_name": "Github" }
#include <AP_Common.h> #include <AP_Progmem.h> #include <AP_Param.h> #include <AP_Math.h> #include <AP_HAL.h> #include <AP_HAL_AVR.h> #include <AP_HAL_PX4.h> #include <AP_HAL_Empty.h> #include <AP_Buffer.h> #include <Filter.h> #include <AP_Baro.h> const AP_HAL::HAL& hal = AP_HAL_BOARD_DRIVER; #if CONFIG_HAL_BOARD == HAL_BOARD_PX4 AP_Baro_PX4 baro; static uint32_t timer; void setup() { hal.console->println("PX4 Barometer library test"); baro.init(); baro.calibrate(); timer = hal.scheduler->micros(); } void loop() { hal.scheduler->delay(100); baro.read(); if (!baro.healthy) { hal.console->println("not healthy"); return; } hal.console->print("Pressure:"); hal.console->print(baro.get_pressure()); hal.console->print(" Temperature:"); hal.console->print(baro.get_temperature()); hal.console->print(" Altitude:"); hal.console->print(baro.get_altitude()); hal.console->printf(" climb=%.2f samples=%u", baro.get_climb_rate(), (unsigned)baro.get_pressure_samples()); hal.console->println(); } #else // Non-PX4 #warning AP_Baro_PX4_test is PX4 specific void setup () {} void loop () {} #endif AP_HAL_MAIN();
{ "pile_set_name": "Github" }
import 'package:appwrite_dev/appwrite_dev.dart'; void main() { // Init SDK Client client = Client(); Account account = Account(client); client .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint .setProject('5df5acd0d48c2') // Your project ID ; Future result = account.updateEmail( email: '[email protected]', password: 'password', ); result .then((response) { print(response); }).catchError((error) { print(error.response); }); }
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="/benchmark/js/jquery.min.js"></script> <script type="text/javascript" src="/benchmark/js/js.cookie.js"></script> <title>BenchmarkTest01204</title> </head> <body> <form action="/benchmark/trustbound-00/BenchmarkTest01204" method="POST" id="FormBenchmarkTest01204"> <div><label>Please explain your answer:</label></div> <br/> <div><textarea rows="4" cols="50" id="BenchmarkTest01204Area" name="BenchmarkTest01204Area"></textarea></div> <div><label>Any additional note for the reviewer:</label></div> <div><input type="text" id="answer" name="answer"></input></div> <br/> <div><label>An AJAX request will be sent with a header named BenchmarkTest01204 and value:</label> <input type="text" id="BenchmarkTest01204" name="BenchmarkTest01204" value="my_user_id" class="safe"></input></div> <div><input type="button" id="login-btn" value="Login" onclick="submitForm()" /></div> </form> <div id="ajax-form-msg1"><pre><code class="prettyprint" id="code"></code></pre></div> <script> $('.safe').keypress(function (e) { if (e.which == 13) { submitForm(); return false; } }); function submitForm() { var formData = $("#FormBenchmarkTest01204").serialize(); var URL = $("#FormBenchmarkTest01204").attr("action"); var text = $("#FormBenchmarkTest01204 input[id=BenchmarkTest01204]").val(); var xhr = new XMLHttpRequest(); xhr.open("POST", URL, true); xhr.setRequestHeader('BenchmarkTest01204', text ); xhr.onreadystatechange = function () { if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { $("#code").html(xhr.responseText); }else{ $("#code").html("Error " + xhr.status + " ocurred."); } } xhr.send(formData); } function escapeRegExp(str) { return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } String.prototype.decodeEscapeSequence = function() { var txt = replaceAll(this,";",""); txt = replaceAll(txt,"&#","\\"); return txt.replace(/\\x([0-9A-Fa-f]{2})/g, function() { return String.fromCharCode(parseInt(arguments[1], 16)); }); }; </script> </body> </html>
{ "pile_set_name": "Github" }
#include "test/jemalloc_test.h" /* * Use a separate arena for xallocx() extension/contraction tests so that * internal allocation e.g. by heap profiling can't interpose allocations where * xallocx() would ordinarily be able to extend. */ static unsigned arena_ind(void) { static unsigned ind = 0; if (ind == 0) { size_t sz = sizeof(ind); assert_d_eq(mallctl("arenas.create", (void *)&ind, &sz, NULL, 0), 0, "Unexpected mallctl failure creating arena"); } return ind; } TEST_BEGIN(test_same_size) { void *p; size_t sz, tsz; p = mallocx(42, 0); assert_ptr_not_null(p, "Unexpected mallocx() error"); sz = sallocx(p, 0); tsz = xallocx(p, sz, 0, 0); assert_zu_eq(tsz, sz, "Unexpected size change: %zu --> %zu", sz, tsz); dallocx(p, 0); } TEST_END TEST_BEGIN(test_extra_no_move) { void *p; size_t sz, tsz; p = mallocx(42, 0); assert_ptr_not_null(p, "Unexpected mallocx() error"); sz = sallocx(p, 0); tsz = xallocx(p, sz, sz-42, 0); assert_zu_eq(tsz, sz, "Unexpected size change: %zu --> %zu", sz, tsz); dallocx(p, 0); } TEST_END TEST_BEGIN(test_no_move_fail) { void *p; size_t sz, tsz; p = mallocx(42, 0); assert_ptr_not_null(p, "Unexpected mallocx() error"); sz = sallocx(p, 0); tsz = xallocx(p, sz + 5, 0, 0); assert_zu_eq(tsz, sz, "Unexpected size change: %zu --> %zu", sz, tsz); dallocx(p, 0); } TEST_END static unsigned get_nsizes_impl(const char *cmd) { unsigned ret; size_t z; z = sizeof(unsigned); assert_d_eq(mallctl(cmd, (void *)&ret, &z, NULL, 0), 0, "Unexpected mallctl(\"%s\", ...) failure", cmd); return ret; } static unsigned get_nsmall(void) { return get_nsizes_impl("arenas.nbins"); } static unsigned get_nlarge(void) { return get_nsizes_impl("arenas.nlextents"); } static size_t get_size_impl(const char *cmd, size_t ind) { size_t ret; size_t z; size_t mib[4]; size_t miblen = 4; z = sizeof(size_t); assert_d_eq(mallctlnametomib(cmd, mib, &miblen), 0, "Unexpected mallctlnametomib(\"%s\", ...) failure", cmd); mib[2] = ind; z = sizeof(size_t); assert_d_eq(mallctlbymib(mib, miblen, (void *)&ret, &z, NULL, 0), 0, "Unexpected mallctlbymib([\"%s\", %zu], ...) failure", cmd, ind); return ret; } static size_t get_small_size(size_t ind) { return get_size_impl("arenas.bin.0.size", ind); } static size_t get_large_size(size_t ind) { return get_size_impl("arenas.lextent.0.size", ind); } TEST_BEGIN(test_size) { size_t small0, largemax; void *p; /* Get size classes. */ small0 = get_small_size(0); largemax = get_large_size(get_nlarge()-1); p = mallocx(small0, 0); assert_ptr_not_null(p, "Unexpected mallocx() error"); /* Test smallest supported size. */ assert_zu_eq(xallocx(p, 1, 0, 0), small0, "Unexpected xallocx() behavior"); /* Test largest supported size. */ assert_zu_le(xallocx(p, largemax, 0, 0), largemax, "Unexpected xallocx() behavior"); /* Test size overflow. */ assert_zu_le(xallocx(p, largemax+1, 0, 0), largemax, "Unexpected xallocx() behavior"); assert_zu_le(xallocx(p, SIZE_T_MAX, 0, 0), largemax, "Unexpected xallocx() behavior"); dallocx(p, 0); } TEST_END TEST_BEGIN(test_size_extra_overflow) { size_t small0, largemax; void *p; /* Get size classes. */ small0 = get_small_size(0); largemax = get_large_size(get_nlarge()-1); p = mallocx(small0, 0); assert_ptr_not_null(p, "Unexpected mallocx() error"); /* Test overflows that can be resolved by clamping extra. */ assert_zu_le(xallocx(p, largemax-1, 2, 0), largemax, "Unexpected xallocx() behavior"); assert_zu_le(xallocx(p, largemax, 1, 0), largemax, "Unexpected xallocx() behavior"); /* Test overflow such that largemax-size underflows. */ assert_zu_le(xallocx(p, largemax+1, 2, 0), largemax, "Unexpected xallocx() behavior"); assert_zu_le(xallocx(p, largemax+2, 3, 0), largemax, "Unexpected xallocx() behavior"); assert_zu_le(xallocx(p, SIZE_T_MAX-2, 2, 0), largemax, "Unexpected xallocx() behavior"); assert_zu_le(xallocx(p, SIZE_T_MAX-1, 1, 0), largemax, "Unexpected xallocx() behavior"); dallocx(p, 0); } TEST_END TEST_BEGIN(test_extra_small) { size_t small0, small1, largemax; void *p; /* Get size classes. */ small0 = get_small_size(0); small1 = get_small_size(1); largemax = get_large_size(get_nlarge()-1); p = mallocx(small0, 0); assert_ptr_not_null(p, "Unexpected mallocx() error"); assert_zu_eq(xallocx(p, small1, 0, 0), small0, "Unexpected xallocx() behavior"); assert_zu_eq(xallocx(p, small1, 0, 0), small0, "Unexpected xallocx() behavior"); assert_zu_eq(xallocx(p, small0, small1 - small0, 0), small0, "Unexpected xallocx() behavior"); /* Test size+extra overflow. */ assert_zu_eq(xallocx(p, small0, largemax - small0 + 1, 0), small0, "Unexpected xallocx() behavior"); assert_zu_eq(xallocx(p, small0, SIZE_T_MAX - small0, 0), small0, "Unexpected xallocx() behavior"); dallocx(p, 0); } TEST_END TEST_BEGIN(test_extra_large) { int flags = MALLOCX_ARENA(arena_ind()); size_t smallmax, large1, large2, large3, largemax; void *p; /* Get size classes. */ smallmax = get_small_size(get_nsmall()-1); large1 = get_large_size(1); large2 = get_large_size(2); large3 = get_large_size(3); largemax = get_large_size(get_nlarge()-1); p = mallocx(large3, flags); assert_ptr_not_null(p, "Unexpected mallocx() error"); assert_zu_eq(xallocx(p, large3, 0, flags), large3, "Unexpected xallocx() behavior"); /* Test size decrease with zero extra. */ assert_zu_ge(xallocx(p, large1, 0, flags), large1, "Unexpected xallocx() behavior"); assert_zu_ge(xallocx(p, smallmax, 0, flags), large1, "Unexpected xallocx() behavior"); if (xallocx(p, large3, 0, flags) != large3) { p = rallocx(p, large3, flags); assert_ptr_not_null(p, "Unexpected rallocx() failure"); } /* Test size decrease with non-zero extra. */ assert_zu_eq(xallocx(p, large1, large3 - large1, flags), large3, "Unexpected xallocx() behavior"); assert_zu_eq(xallocx(p, large2, large3 - large2, flags), large3, "Unexpected xallocx() behavior"); assert_zu_ge(xallocx(p, large1, large2 - large1, flags), large2, "Unexpected xallocx() behavior"); assert_zu_ge(xallocx(p, smallmax, large1 - smallmax, flags), large1, "Unexpected xallocx() behavior"); assert_zu_ge(xallocx(p, large1, 0, flags), large1, "Unexpected xallocx() behavior"); /* Test size increase with zero extra. */ assert_zu_le(xallocx(p, large3, 0, flags), large3, "Unexpected xallocx() behavior"); assert_zu_le(xallocx(p, largemax+1, 0, flags), large3, "Unexpected xallocx() behavior"); assert_zu_ge(xallocx(p, large1, 0, flags), large1, "Unexpected xallocx() behavior"); /* Test size increase with non-zero extra. */ assert_zu_le(xallocx(p, large1, SIZE_T_MAX - large1, flags), largemax, "Unexpected xallocx() behavior"); assert_zu_ge(xallocx(p, large1, 0, flags), large1, "Unexpected xallocx() behavior"); /* Test size increase with non-zero extra. */ assert_zu_le(xallocx(p, large1, large3 - large1, flags), large3, "Unexpected xallocx() behavior"); if (xallocx(p, large3, 0, flags) != large3) { p = rallocx(p, large3, flags); assert_ptr_not_null(p, "Unexpected rallocx() failure"); } /* Test size+extra overflow. */ assert_zu_le(xallocx(p, large3, largemax - large3 + 1, flags), largemax, "Unexpected xallocx() behavior"); dallocx(p, flags); } TEST_END static void print_filled_extents(const void *p, uint8_t c, size_t len) { const uint8_t *pc = (const uint8_t *)p; size_t i, range0; uint8_t c0; malloc_printf(" p=%p, c=%#x, len=%zu:", p, c, len); range0 = 0; c0 = pc[0]; for (i = 0; i < len; i++) { if (pc[i] != c0) { malloc_printf(" %#x[%zu..%zu)", c0, range0, i); range0 = i; c0 = pc[i]; } } malloc_printf(" %#x[%zu..%zu)\n", c0, range0, i); } static bool validate_fill(const void *p, uint8_t c, size_t offset, size_t len) { const uint8_t *pc = (const uint8_t *)p; bool err; size_t i; for (i = offset, err = false; i < offset+len; i++) { if (pc[i] != c) { err = true; } } if (err) { print_filled_extents(p, c, offset + len); } return err; } static void test_zero(size_t szmin, size_t szmax) { int flags = MALLOCX_ARENA(arena_ind()) | MALLOCX_ZERO; size_t sz, nsz; void *p; #define FILL_BYTE 0x7aU sz = szmax; p = mallocx(sz, flags); assert_ptr_not_null(p, "Unexpected mallocx() error"); assert_false(validate_fill(p, 0x00, 0, sz), "Memory not filled: sz=%zu", sz); /* * Fill with non-zero so that non-debug builds are more likely to detect * errors. */ memset(p, FILL_BYTE, sz); assert_false(validate_fill(p, FILL_BYTE, 0, sz), "Memory not filled: sz=%zu", sz); /* Shrink in place so that we can expect growing in place to succeed. */ sz = szmin; if (xallocx(p, sz, 0, flags) != sz) { p = rallocx(p, sz, flags); assert_ptr_not_null(p, "Unexpected rallocx() failure"); } assert_false(validate_fill(p, FILL_BYTE, 0, sz), "Memory not filled: sz=%zu", sz); for (sz = szmin; sz < szmax; sz = nsz) { nsz = nallocx(sz+1, flags); if (xallocx(p, sz+1, 0, flags) != nsz) { p = rallocx(p, sz+1, flags); assert_ptr_not_null(p, "Unexpected rallocx() failure"); } assert_false(validate_fill(p, FILL_BYTE, 0, sz), "Memory not filled: sz=%zu", sz); assert_false(validate_fill(p, 0x00, sz, nsz-sz), "Memory not filled: sz=%zu, nsz-sz=%zu", sz, nsz-sz); memset((void *)((uintptr_t)p + sz), FILL_BYTE, nsz-sz); assert_false(validate_fill(p, FILL_BYTE, 0, nsz), "Memory not filled: nsz=%zu", nsz); } dallocx(p, flags); } TEST_BEGIN(test_zero_large) { size_t large0, large1; /* Get size classes. */ large0 = get_large_size(0); large1 = get_large_size(1); test_zero(large1, large0 * 2); } TEST_END int main(void) { return test( test_same_size, test_extra_no_move, test_no_move_fail, test_size, test_size_extra_overflow, test_extra_small, test_extra_large, test_zero_large); }
{ "pile_set_name": "Github" }
// +build windows package getter import ( "fmt" "net/url" "os" "os/exec" "path/filepath" "strings" "syscall" ) func (g *FileGetter) Get(dst string, u *url.URL) error { ctx := g.Context() path := u.Path if u.RawPath != "" { path = u.RawPath } // The source path must exist and be a directory to be usable. if fi, err := os.Stat(path); err != nil { return fmt.Errorf("source path error: %s", err) } else if !fi.IsDir() { return fmt.Errorf("source path must be a directory") } fi, err := os.Lstat(dst) if err != nil && !os.IsNotExist(err) { return err } // If the destination already exists, it must be a symlink if err == nil { mode := fi.Mode() if mode&os.ModeSymlink == 0 { return fmt.Errorf("destination exists and is not a symlink") } // Remove the destination if err := os.Remove(dst); err != nil { return err } } // Create all the parent directories if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil { return err } sourcePath := toBackslash(path) // Use mklink to create a junction point output, err := exec.CommandContext(ctx, "cmd", "/c", "mklink", "/J", dst, sourcePath).CombinedOutput() if err != nil { return fmt.Errorf("failed to run mklink %v %v: %v %q", dst, sourcePath, err, output) } return nil } func (g *FileGetter) GetFile(dst string, u *url.URL) error { ctx := g.Context() path := u.Path if u.RawPath != "" { path = u.RawPath } // The source path must exist and be a directory to be usable. if fi, err := os.Stat(path); err != nil { return fmt.Errorf("source path error: %s", err) } else if fi.IsDir() { return fmt.Errorf("source path must be a file") } _, err := os.Lstat(dst) if err != nil && !os.IsNotExist(err) { return err } // If the destination already exists, it must be a symlink if err == nil { // Remove the destination if err := os.Remove(dst); err != nil { return err } } // Create all the parent directories if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil { return err } // If we're not copying, just symlink and we're done if !g.Copy { if err = os.Symlink(path, dst); err == nil { return err } lerr, ok := err.(*os.LinkError) if !ok { return err } switch lerr.Err { case syscall.ERROR_PRIVILEGE_NOT_HELD: // no symlink privilege, let's // fallback to a copy to avoid an error. break default: return err } } // Copy srcF, err := os.Open(path) if err != nil { return err } defer srcF.Close() dstF, err := os.Create(dst) if err != nil { return err } defer dstF.Close() _, err = Copy(ctx, dstF, srcF) return err } // toBackslash returns the result of replacing each slash character // in path with a backslash ('\') character. Multiple separators are // replaced by multiple backslashes. func toBackslash(path string) string { return strings.Replace(path, "/", "\\", -1) }
{ "pile_set_name": "Github" }
# usage: python app_models.py 1 - train the dave-orig model from __future__ import print_function import sys from keras.layers import Activation, Input, Dense from data_utils import * from utils import * def Model1(input_tensor=None, load_weights=False, num_features=545334): # original dave if input_tensor is None: input_tensor = Input(shape=(num_features,)) x = Dense(200, input_dim=num_features, activation='relu', name='fc1')(input_tensor) x = Dense(200, activation='relu', name='fc2')(x) x = Dense(2, name='before_softmax')(x) x = Activation('softmax', name='predictions')(x) m = Model(input_tensor, x) if load_weights: m.load_weights('./Model1.h5') # compiling m.compile(loss='binary_crossentropy', optimizer='adadelta', metrics=['accuracy']) print(bcolors.OKGREEN + 'Model compiled' + bcolors.ENDC) return m def Model2(input_tensor=None, load_weights=False, num_features=545334): # original dave with normal initialization if input_tensor is None: input_tensor = Input(shape=(num_features,)) x = Dense(50, input_dim=num_features, activation='relu', name='fc1')(input_tensor) x = Dense(50, activation='relu', name='fc2')(x) x = Dense(2, name='before_softmax')(x) x = Activation('softmax', name='predictions')(x) m = Model(input_tensor, x) if load_weights: m.load_weights('./Model2.h5') # compiling m.compile(loss='binary_crossentropy', optimizer='adadelta', metrics=['accuracy']) print(bcolors.OKGREEN + 'Model compiled' + bcolors.ENDC) return m def Model3(input_tensor=None, load_weights=False, num_features=545334): # simplified dave if input_tensor is None: input_tensor = Input(shape=(num_features,)) x = Dense(200, input_dim=num_features, activation='relu', name='fc1')(input_tensor) x = Dense(10, activation='relu', name='fc2')(x) x = Dense(2, name='before_softmax')(x) x = Activation('softmax', name='predictions')(x) m = Model(input_tensor, x) if load_weights: m.load_weights('./Model3.h5') # compiling m.compile(loss='binary_crossentropy', optimizer='adadelta', metrics=['accuracy']) print(bcolors.OKGREEN + 'Model compiled' + bcolors.ENDC) return m if __name__ == '__main__': # train the model batch_size = 64 nb_epoch = 10 model_name = sys.argv[1] # the data, shuffled and split between train and test sets feats, nb_train, nb_test, train_generator, test_grnerator = load_data(batch_size, False) if model_name == '1': model = Model1(num_features=len(feats)) save_model_name = './Model1.h5' elif model_name == '2': model = Model2(num_features=len(feats)) save_model_name = './Model2.h5' elif model_name == '3': model = Model3(num_features=len(feats)) save_model_name = './Model3.h5' else: print(bcolors.FAIL + 'invalid model name, must one of 1, 2 or 3' + bcolors.ENDC) # trainig model.fit_generator(train_generator, steps_per_epoch=nb_train // batch_size, epochs=nb_epoch, workers=8, use_multiprocessing=True) # save model model.save_weights(save_model_name) # evaluate the model score = model.evaluate_generator(test_grnerator, steps=nb_test // batch_size) print('\n') print('Overall Test score:', score[0]) print('Overall Test accuracy:', score[1])
{ "pile_set_name": "Github" }
(function ($) { $.Redactor.opts.langs['es'] = { html: 'HTML', video: 'Insertar video...', image: 'Insertar imagen...', table: 'Tabla', link: 'Enlace', link_insert: 'Insertar enlace ...', link_edit: 'Editar enlace', unlink: 'Desenlazar', formatting: 'Estilos', paragraph: 'Texto normal', quote: 'Cita', code: 'Código', header1: 'Cabecera 1', header2: 'Cabecera 2', header3: 'Cabecera 3', header4: 'Cabecera 4', header5: 'Cabecera 5', bold: 'Negrita', italic: 'Itálica', fontcolor: 'Color de fuente', backcolor: 'Color de fondo', unorderedlist: 'Lista desordenada', orderedlist: 'Lista ordenada', outdent: 'Disminuir sangrado', indent: 'Aumentar sangrado', cancel: 'Cancelar', insert: 'Insertar', save: 'Guardar', _delete: 'Borrar', insert_table: 'Insertar tabla...', insert_row_above: 'Añadir fila encima', insert_row_below: 'Añadir fila debajo', insert_column_left: 'Añadir columna a la izquierda', insert_column_right: 'Añadir column a la derecha', delete_column: 'Borrar columna', delete_row: 'Borrar fila', delete_table: 'Borrar tabla', rows: 'Filas', columns: 'Columnas', add_head: 'Añadir cabecera', delete_head: 'Borrar cabecera', title: 'Título', image_position: 'Posición', none: 'Ninguna', left: 'Izquierda', right: 'Derecha', image_web_link: 'Enlace web de la imágen', text: 'Texto', mailto: 'Email', web: 'URL', video_html_code: 'Código de inserción de video', file: 'Insertar archivo...', upload: 'Cargar', download: 'Descargar', choose: 'Elegir', or_choose: 'O elegir', drop_file_here: 'Arrastra y suelta el archivo aqui', align_left: 'Alinear texto a la izquierda', align_center: 'Centrar texto', align_right: 'Alinear texto a la derecha', align_justify: 'Justificar texto', horizontalrule: 'Insertar línea horizontal', deleted: 'Borrado', anchor: 'Anchor', link_new_tab: 'Abrir enlace en una nueva pestaña', underline: 'Subrayado', alignment: 'Alineación', filename: 'Nombre (opcional)', edit: 'Editar', center: 'Center' }; })( jQuery );
{ "pile_set_name": "Github" }
--- fixes: - | Addresses a condition where the Compute Service may have been unable to remove VIF attachment records while a baremetal node is being unprovisiond. This condition resulted in VIF records being orphaned, blocking future deployments without manual intervention. See `bug 1743652 <https://bugs.launchpad.net/ironic/+bug/1743652>`_ for more details.
{ "pile_set_name": "Github" }
hydra.Prms-testRequirement = "Test for long running scenario using north wind schema, data and queries"; hydra.Prms-testDescription = "This test uses the same cluster started using startDualModeCluster test. Test runs the spark App for creating and loading data in column tables using northwind schema and data. It then executes the snappy job, spark app and sql script in parallel. Snappy job executes and validate the northwind queries on the tables created and loaded through split mode along with lead, locator and server node HA. Spark app executes and validate the northwind queries on the tables created and loaded through split mode along with lead, locator and server node HA. sql script only executes the northwind queries on the tables created and loaded through split mode along with lead, locator and server node HA."; INCLUDE $JTESTS/hydraconfig/hydraparams1.inc; INCLUDE $JTESTS/hydraconfig/topology_1.inc; THREADGROUP snappyThreads totalThreads = fcn "(${${A}Hosts} * ${${A}VMsPerHost} * ${${A}ThreadsPerVM}) -1 " ncf totalVMs = fcn "(${${A}Hosts} * ${${A}VMsPerHost})" ncf clientNames = fcn "hydra.TestConfigFcns.generateNames(\"${A}\", ${${A}Hosts}, true)" ncf; THREADGROUP snappySingleThread totalThreads = 1 totalVMs = 1 clientNames = fcn "hydra.TestConfigFcns.generateNames(\"${A}\", ${${A}Hosts}, true)" ncf; INITTASK taskClass = io.snappydata.hydra.cluster.SnappyTest taskMethod = HydraTask_initializeSnappyTest runMode = always threadGroups = snappyThreads, snappySingleThread; INITTASK taskClass = io.snappydata.hydra.cluster.SnappyTest taskMethod = HydraTask_executeSQLScripts io.snappydata.hydra.cluster.SnappyPrms-sqlScriptNames = create_and_load_columnTables_persistent.sql io.snappydata.hydra.cluster.SnappyPrms-dataLocation = ${dataFilesLocation} threadGroups = snappySingleThread ; TASK taskClass = io.snappydata.hydra.cluster.SnappyTest taskMethod = HydraTask_executeSnappyJob io.snappydata.hydra.cluster.SnappyPrms-jobClassNames = io.snappydata.hydra.northwind.ValidateNWQueriesJob io.snappydata.hydra.cluster.SnappyPrms-appPropsForJobServer = "dataFilesLocation=${dataFilesLocation},tableType=${tableType},fullResultSetValidation=${fullResultSetValidation},isSmokeRun=${isSmokeRun},numRowsValidation=${numRowsValidation}" io.snappydata.hydra.cluster.SnappyPrms-userAppJar = snappydata-store-scala-tests*tests.jar threadGroups = snappyThreads maxThreads = 1 maxTimesToRun = 1; TASK taskClass = io.snappydata.hydra.cluster.SnappyTest taskMethod = HydraTask_executeSparkJob io.snappydata.hydra.cluster.SnappyPrms-sparkJobClassNames = io.snappydata.hydra.northwind.ValidateNWQueriesApp io.snappydata.hydra.cluster.SnappyPrms-userAppArgs = "${dataFilesLocation} ${tableType} ${fullResultSetValidation} ${isSmokeRun} ${numRowsValidation}" io.snappydata.hydra.cluster.SnappyPrms-userAppJar = snappydata-store-scala-tests*tests.jar maxThreads = 1 maxTimesToRun = 1 threadGroups = snappyThreads; TASK taskClass = io.snappydata.hydra.cluster.SnappyTest taskMethod = HydraTask_executeSQLScripts io.snappydata.hydra.cluster.SnappyPrms-sqlScriptNames = nw_queries_startUp.sql threadGroups = snappyThreads ; hydra.Prms-totalTaskTimeSec = 3600; hydra.Prms-maxResultWaitSec = 3600; hydra.Prms-maxCloseTaskResultWaitSec = 3600; io.snappydata.hydra.cluster.SnappyPrms-isStopMode = true; io.snappydata.hydra.cluster.SnappyPrms-isLongRunningTest = true; io.snappydata.hydra.cluster.SnappyPrms-useSmartConnectorMode = true; io.snappydata.hydra.cluster.SnappyPrms-userAppJar = snappydata-store-scala-tests*tests.jar;
{ "pile_set_name": "Github" }
(def [x0 y0 w h sep] [50 120 20 90 25]) (def n 15!{3-30}) (def xi (\i (+ x0 (* i sep)))) (def yi (\i (- y0 (* 100 (sin (* i (/ twoPi n))))))) (def ci (\i (let b (elem i [2 4 5]) ; TODO add tokens (if b 'orange' 'lightblue')))) (def boxi (\i (rect (ci i) (xi i) (yi i) w h))) (svg (map boxi (zeroTo n)))
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <language> <resources prefix="Core"> <resource name="about_bugs">:אנא דווח באגים בכתובת</resource> <resource name="about_donations">:אם את\ה נהנה\ית משימוש בתוכנה, את\ה מוזמן לתרום לנו</resource> <resource name="about_host">Greenshot is hosted by GitHub at</resource> <resource name="about_icons">Icons from Yusuke Kamiyamane's Fugue icon set (Creative Commons Attribution 3.0 license)</resource> <resource name="about_license"> Copyright (C) 2007-2020 Thomas Braun, Jens Klingen, Robin Krom Greenshot comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. Details about the GNU General Public License: </resource> <resource name="about_title">Greenshot אודות התוכנה</resource> <resource name="application_title">Greenshot - התוכנה המהפכנית ללכידת מסך</resource> <resource name="bugreport_cancel">סגור</resource> <resource name="bugreport_info"> סליחה, שגיאה בלתי צפויה אירעה .החדשות הטובות הן: את\ה יכול\ה לעזור לנו לפתור אותה באמצעות דיווח באגים .אנא בקר\י בכתובת שמלטמה, צור\י דוח באגים והדבק אותו בעמוד שנפתח .נא להוסיף תקציר של התקלה וכל מידע שנראה חיוני לזיהוי התקלה תודה רבה :) </resource> <resource name="bugreport_title">שגיאה</resource> <resource name="clipboard_error">שגיאה לא-צפויה קרתה בכתיבה אל לוח העריכה</resource> <resource name="clipboard_inuse">התוכנה לא יכלה לכתוב אל הלוח מאחר והתוכנה {0} חסמה את הגישה</resource> <resource name="colorpicker_alpha">אלפא</resource> <resource name="colorpicker_apply">החל</resource> <resource name="colorpicker_blue">כחול</resource> <resource name="colorpicker_green">ירוק</resource> <resource name="colorpicker_htmlcolor">HTML צבע</resource> <resource name="colorpicker_recentcolors">צבעים בשימוש אחרון</resource> <resource name="colorpicker_red">אדום</resource> <resource name="colorpicker_title">בוחר צבע</resource> <resource name="colorpicker_transparent">שקיפות</resource> <resource name="config_unauthorizedaccess_write">לא ניתן לשמור את הגדרות התוכנה. אנא בדוק את הרשאות הכתיבה עבור '{0}'.</resource> <resource name="contextmenu_about">Greenshot אודות</resource> <resource name="contextmenu_capturearea">לכידת אזור</resource> <resource name="contextmenu_captureclipboard">פתח תמונה מלוח העריכה</resource> <resource name="contextmenu_capturefullscreen">לכידת מסך מלא</resource> <resource name="contextmenu_capturelastregion">לכידת האזור האחרון</resource> <resource name="contextmenu_capturewindow">לכידת חלון</resource> <resource name="contextmenu_donate">Greenshot תמוך ב</resource> <resource name="contextmenu_exit">יציאה</resource> <resource name="contextmenu_help">עזרה</resource> <resource name="contextmenu_openfile">פתח תמונה מקובץ</resource> <resource name="contextmenu_quicksettings">הגדרות מהירות</resource> <resource name="contextmenu_settings">...הגדרות</resource> <resource name="error">שגיאה</resource> <resource name="error_multipleinstances">עותק אחד של התוכנה כבר פתוח</resource> <resource name="error_nowriteaccess"> לא ניתן לשמור קובץ אל {0}. . נא לבדוק את הרשאות הכתיבה אל הנתיב שצוין </resource> <resource name="error_openfile">הקובץ "{0}" לא ניתן לפתיחה.</resource> <resource name="error_openlink">לא ניתן לפתוח קישור</resource> <resource name="error_save">לא ניתן לשמור לכידה, אנא בחר מיקום מתאים</resource> <resource name="help_title">Greenshot עזרה</resource> <resource name="jpegqualitydialog_choosejpegquality">JPEG אנא בחר את איכות תמונת</resource> <resource name="jpegqualitydialog_dontaskagain">ואל תשאל שוב JPEG שמור כאיכות</resource> <resource name="jpegqualitydialog_title">Greenshot JPEG איכות</resource> <resource name="print_error">חלה שגיאה בהדפסה</resource> <resource name="printoptions_allowcenter">מירכוז הדפסה בעמוד</resource> <resource name="printoptions_allowenlarge">הגדל פלט לגודל העמוד</resource> <resource name="printoptions_allowrotate">סובב פלט לכיוון הדף</resource> <resource name="printoptions_allowshrink">הקטן פלט לגודל העמוד</resource> <resource name="printoptions_dontaskagain">שמור הגדרות כברירת מחדל ואל תשאל שוב</resource> <resource name="printoptions_timestamp">הדפס תאריך\שעה בתחתית העמוד</resource> <resource name="printoptions_title">Greenshot אפשרויות הדפסה</resource> <resource name="quicksettings_destination_file">שמור ישירות: תוך שימוש בהעדפות שמירת קובץ</resource> <resource name="settings_alwaysshowjpegqualitydialog">בכל פעם שתמונה כזו נשמרת JPEG הצג דיאלוג לאיכות</resource> <resource name="settings_alwaysshowprintoptionsdialog">הצג חלון אפשרויות הדפסה בכל פעם שתמונה מודפסת</resource> <resource name="settings_applicationsettings">הגדרות התוכנה</resource> <resource name="settings_autostartshortcut">הפעל את התוכנה עם הפעלת המחשב</resource> <resource name="settings_capture">לכידה</resource> <resource name="settings_capture_mousepointer">לכידת סמן העכבר</resource> <resource name="settings_capture_windows_interactive">השתמש במצב לכידת חלון אינטראקטיבית</resource> <resource name="settings_copypathtoclipboard">העתק נתיב אל הלוח בכל פעם שתמונה נשמרת</resource> <resource name="settings_destination">יעד הלכידה</resource> <resource name="settings_destination_clipboard">העתק אל הלוח</resource> <resource name="settings_destination_email">דואר אלקטרוני</resource> <resource name="settings_destination_file">שמור ישירות: תוך שימוש בהגדרות שלמטה</resource> <resource name="settings_destination_fileas">שמירה בשם: פתח תיבת דו-שיח</resource> <resource name="settings_destination_printer">שלח למדפסת</resource> <resource name="settings_filenamepattern">תבנית שם-קובץ</resource> <resource name="settings_general">כללי</resource> <resource name="settings_jpegquality">JPEG איכות</resource> <resource name="settings_jpegsettings">JPEG הגדרות</resource> <resource name="settings_language">שפה</resource> <resource name="settings_message_filenamepattern"> :המשתנים הבאים יוחלפו אוטומטית בתבנית שתוגדר להלן ${YYYY} ספרות 4 ,שנה ${MM} ספרות 2 , חודש ${DD} ספרות 2 ,יום ${hh} ספרות 2 ,שעה ${mm} ספרות 2 ,דקות ${ss} ספרות 2 ,שניות ${NUM} ספרות 6 , מספר עולה ${title} כותרת החלון ${user} שם המשתמש במחשב ${domain} שם הדומיין של המחשב ${hostname} שם המחשב .ניתן לאפשר לתוכנה ליצור תיקיות באופן דינמי .יש להוסיף סמל אלכסון אחורי (\) כדי להפריד בין תיקיות לשם-קובץ ${YYYY}-${MM}-${DD}\${hh}-${mm}-${ss} :לדוגמה ,התבנית תייצר תיקייה עם תאריך היום בתיקיית השמירה שהוגדרה ,למשל 2008-06-29 ,ושם הקובץ של לכידת המסך יהיה לפי השעה של השמירה ,למשל 11-58-32 .ובסוף סיומת הקובץ לפי הפורמט שהוגדר </resource> <resource name="settings_output">פלט</resource> <resource name="settings_playsound">השמעת צליל של מצלמה</resource> <resource name="settings_preferredfilesettings">הגדרות מועדפות לפלט קובץ</resource> <resource name="settings_primaryimageformat">פורמט תמונה</resource> <resource name="settings_printer">מדפסת</resource> <resource name="settings_printoptions">אפשרויות הדפסה</resource> <resource name="settings_registerhotkeys">הפעל מקשים חמים</resource> <resource name="settings_showflashlight">הצגת תאורת פלאש</resource> <resource name="settings_storagelocation">מיקום איחסון</resource> <resource name="settings_title">הגדרות</resource> <resource name="settings_tooltip_filenamepattern">תבנית ליצירת שם-קובץ בשמירת לכידות מסך</resource> <resource name="settings_tooltip_language">שפת ממשק התוכנה: דורש איתחול מחדש של התוכנה</resource> <resource name="settings_tooltip_primaryimageformat">פורמט תמונה בברירת-מחדל</resource> <resource name="settings_tooltip_registerhotkeys">.מוצמדים בלעדית לתוכנה עד לסגירתה Prnt, Ctrl + Print, Alt + Prnt :קובע באם קיצורי המקשים</resource> <resource name="settings_tooltip_storagelocation">מיקום שמירת הלכידות כברירת-מחדל: השאר ריק לשמירה על שולחן העבודה</resource> <resource name="settings_visualization">אפקטים</resource> <resource name="settings_waittime">מספר מילי-שניות לפני לכידה</resource> <resource name="tooltip_firststart">קליק ימני כאן או לחץ על כפתור הדפסה במקלדת</resource> <resource name="warning">אזהרה</resource> <resource name="warning_hotkeys"> .אחד או מספר מקשים חמים לא הופעלו. לכן, ייתכן שחלקם לא יפעלו עם התוכנה .כנראה שתוכנה אחרת משתמשת במקשים הללו. אנאסגור תוכנות אחרות המשתמשות במקשי ההדפסה .ניתן להשתמש בתפריט התוכנה שבצלמית בפינת הסמלים כדי לבצע פעולות </resource> </resources> </language>
{ "pile_set_name": "Github" }
################################################################################ # # zsh # ################################################################################ ZSH_VERSION = 5.6.2 ZSH_SITE = http://www.zsh.org/pub ZSH_SOURCE = zsh-$(ZSH_VERSION).tar.xz ZSH_DEPENDENCIES = ncurses ZSH_CONF_OPTS = --bindir=/bin ZSH_CONF_ENV = zsh_cv_sys_nis=no zsh_cv_sys_nis_plus=no ZSH_LICENSE = MIT-like ZSH_LICENSE_FILES = LICENCE ifeq ($(BR2_PACKAGE_GDBM),y) ZSH_CONF_OPTS += --enable-gdbm ZSH_DEPENDENCIES += gdbm else ZSH_CONF_OPTS += --disable-gdbm endif ifeq ($(BR2_PACKAGE_LIBCAP),y) ZSH_CONF_OPTS += --enable-cap ZSH_DEPENDENCIES += libcap else ZSH_CONF_OPTS += --disable-cap endif ifeq ($(BR2_PACKAGE_PCRE),y) ZSH_CONF_OPTS += --enable-pcre ZSH_CONF_ENV += ac_cv_prog_PCRECONF=$(STAGING_DIR)/usr/bin/pcre-config ZSH_DEPENDENCIES += pcre else ZSH_CONF_OPTS += --disable-pcre endif # Add /bin/zsh to /etc/shells otherwise some login tools like dropbear # can reject the user connection. See man shells. define ZSH_ADD_ZSH_TO_SHELLS grep -qsE '^/bin/zsh$$' $(TARGET_DIR)/etc/shells \ || echo "/bin/zsh" >> $(TARGET_DIR)/etc/shells endef ZSH_TARGET_FINALIZE_HOOKS += ZSH_ADD_ZSH_TO_SHELLS # Remove versioned zsh-x.y.z binary taking up space define ZSH_TARGET_INSTALL_FIXUPS rm -f $(TARGET_DIR)/bin/zsh-$(ZSH_VERSION) endef ZSH_POST_INSTALL_TARGET_HOOKS += ZSH_TARGET_INSTALL_FIXUPS $(eval $(autotools-package))
{ "pile_set_name": "Github" }
<?php use PHPUnit\Framework\TestCase; class PHPUnit_Framework_TestCase extends TestCase {}
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Scheme LastUpgradeVersion = "1010" version = "1.3"> <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES"> <BuildActionEntries> <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "CF12E27D19A6C783001EB38A" BuildableName = "AdManagerBannerExample.app" BlueprintName = "AdManagerBannerExample" ReferencedContainer = "container:AdManagerBannerExample.xcodeproj"> </BuildableReference> </BuildActionEntry> </BuildActionEntries> </BuildAction> <TestAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"> <Testables> </Testables> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "CF12E27D19A6C783001EB38A" BuildableName = "AdManagerBannerExample.app" BlueprintName = "AdManagerBannerExample" ReferencedContainer = "container:AdManagerBannerExample.xcodeproj"> </BuildableReference> </MacroExpansion> <AdditionalOptions> </AdditionalOptions> </TestAction> <LaunchAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "CF12E27D19A6C783001EB38A" BuildableName = "AdManagerBannerExample.app" BlueprintName = "AdManagerBannerExample" ReferencedContainer = "container:AdManagerBannerExample.xcodeproj"> </BuildableReference> </BuildableProductRunnable> <AdditionalOptions> </AdditionalOptions> </LaunchAction> <ProfileAction buildConfiguration = "Release" shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES"> <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "CF12E27D19A6C783001EB38A" BuildableName = "AdManagerBannerExample.app" BlueprintName = "AdManagerBannerExample" ReferencedContainer = "container:AdManagerBannerExample.xcodeproj"> </BuildableReference> </BuildableProductRunnable> </ProfileAction> <AnalyzeAction buildConfiguration = "Debug"> </AnalyzeAction> <ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES"> </ArchiveAction> </Scheme>
{ "pile_set_name": "Github" }
/* Example for the u8x8_UserInterfaceInputValue procedure. */ #include "u8x8.h" u8x8_t u8x8; int main(void) { uint8_t value = 0; u8x8_Setup_SDL_128x64(&u8x8); u8x8_InitDisplay(&u8x8); u8x8_SetFont(&u8x8, u8x8_font_amstrad_cpc_extended_f); u8x8_UserInterfaceInputValue(&u8x8, "Title\n-----\n", "X=", &value, 0, 19, 2, "m"); return 0; }
{ "pile_set_name": "Github" }
/** * Copyright 2009 Jorge Ortiz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **/ package org.scala_tools.time import org.joda.time._ class RichLocalDateTime(underlying: LocalDateTime) { def -(duration: ReadableDuration): LocalDateTime = underlying.minus(duration) def -(period: ReadablePeriod): LocalDateTime = underlying.minus(period) def -(builder: DurationBuilder): LocalDateTime = underlying.minus(builder.underlying) def +(duration: ReadableDuration): LocalDateTime = underlying.plus(duration) def +(period: ReadablePeriod): LocalDateTime = underlying.plus(period) def +(builder: DurationBuilder): LocalDateTime = underlying.plus(builder.underlying) def second: LocalDateTime.Property = underlying.secondOfMinute def minute: LocalDateTime.Property = underlying.minuteOfHour def hour: LocalDateTime.Property = underlying.hourOfDay def day: LocalDateTime.Property = underlying.dayOfMonth def week: LocalDateTime.Property = underlying.weekOfWeekyear def month: LocalDateTime.Property = underlying.monthOfYear def year: LocalDateTime.Property = underlying.year def century: LocalDateTime.Property = underlying.centuryOfEra def era: LocalDateTime.Property = underlying.era def withSecond(second: Int) = underlying.withSecondOfMinute(second) def withMinute(minute: Int) = underlying.withMinuteOfHour(minute) def withHour(hour: Int) = underlying.withHourOfDay(hour) def withDay(day: Int) = underlying.withDayOfMonth(day) def withWeek(week: Int) = underlying.withWeekOfWeekyear(week) def withMonth(month: Int) = underlying.withMonthOfYear(month) def withYear(year: Int) = underlying.withYear(year) def withCentury(century: Int) = underlying.withCenturyOfEra(century) def withEra(era: Int) = underlying.withEra(era) }
{ "pile_set_name": "Github" }
/** Copyright 2013 BlackBerry Inc. Copyright (c) 2014-2017 Chukong Technologies 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. Original file from GamePlay3D: http://gameplay3d.org This file was modified to fit the cocos2d-x project */ #ifndef MATHUTIL_H_ #define MATHUTIL_H_ #ifdef __SSE__ #include <xmmintrin.h> #endif #include "math/CCMathBase.h" /** * @addtogroup base * @{ */ NS_CC_MATH_BEGIN /** * Defines a math utility class. * * This is primarily used for optimized internal math operations. */ class CC_DLL MathUtil { friend class Mat4; friend class Vec3; public: /** * Updates the given scalar towards the given target using a smoothing function. * The given response time determines the amount of smoothing (lag). A longer * response time yields a smoother result and more lag. To force the scalar to * follow the target closely, provide a response time that is very small relative * to the given elapsed time. * * @param x the scalar to update. * @param target target value. * @param elapsedTime elapsed time between calls. * @param responseTime response time (in the same units as elapsedTime). */ static void smooth(float* x, float target, float elapsedTime, float responseTime); /** * Updates the given scalar towards the given target using a smoothing function. * The given rise and fall times determine the amount of smoothing (lag). Longer * rise and fall times yield a smoother result and more lag. To force the scalar to * follow the target closely, provide rise and fall times that are very small relative * to the given elapsed time. * * @param x the scalar to update. * @param target target value. * @param elapsedTime elapsed time between calls. * @param riseTime response time for rising slope (in the same units as elapsedTime). * @param fallTime response time for falling slope (in the same units as elapsedTime). */ static void smooth(float* x, float target, float elapsedTime, float riseTime, float fallTime); /** * Linearly interpolates between from value to to value by alpha which is in * the range [0,1] * * @param from the from value. * @param to the to value. * @param alpha the alpha value between [0,1] * * @return interpolated float value */ static float lerp(float from, float to, float alpha); private: //Indicates that if neon is enabled static bool isNeon32Enabled(); static bool isNeon64Enabled(); private: #ifdef __SSE__ static void addMatrix(const __m128 m[4], float scalar, __m128 dst[4]); static void addMatrix(const __m128 m1[4], const __m128 m2[4], __m128 dst[4]); static void subtractMatrix(const __m128 m1[4], const __m128 m2[4], __m128 dst[4]); static void multiplyMatrix(const __m128 m[4], float scalar, __m128 dst[4]); static void multiplyMatrix(const __m128 m1[4], const __m128 m2[4], __m128 dst[4]); static void negateMatrix(const __m128 m[4], __m128 dst[4]); static void transposeMatrix(const __m128 m[4], __m128 dst[4]); static void transformVec4(const __m128 m[4], const __m128& v, __m128& dst); #endif static void addMatrix(const float* m, float scalar, float* dst); static void addMatrix(const float* m1, const float* m2, float* dst); static void subtractMatrix(const float* m1, const float* m2, float* dst); static void multiplyMatrix(const float* m, float scalar, float* dst); static void multiplyMatrix(const float* m1, const float* m2, float* dst); static void negateMatrix(const float* m, float* dst); static void transposeMatrix(const float* m, float* dst); static void transformVec4(const float* m, float x, float y, float z, float w, float* dst); static void transformVec4(const float* m, const float* v, float* dst); static void crossVec3(const float* v1, const float* v2, float* dst); }; NS_CC_MATH_END /** end of base group @} */ #define MATRIX_SIZE ( sizeof(float) * 16) #endif
{ "pile_set_name": "Github" }
# -*- encoding: utf-8 -*- # stub: mime-types 2.3 ruby lib Gem::Specification.new do |s| s.name = "mime-types" s.version = "2.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Austin Ziegler"] s.cert_chain = ["-----BEGIN CERTIFICATE-----\nMIIDNjCCAh6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBBMQ8wDQYDVQQDDAZhdXN0\naW4xGTAXBgoJkiaJk/IsZAEZFglydWJ5Zm9yZ2UxEzARBgoJkiaJk/IsZAEZFgNv\ncmcwHhcNMTQwMjIyMDM0MTQzWhcNMTUwMjIyMDM0MTQzWjBBMQ8wDQYDVQQDDAZh\ndXN0aW4xGTAXBgoJkiaJk/IsZAEZFglydWJ5Zm9yZ2UxEzARBgoJkiaJk/IsZAEZ\nFgNvcmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC2mPNf4L37GhKI\nSPCYsvYWXA2/R9u5+pyUnbJ2R1o2CiRq2ZA/AIzY6N3hGnsgoWnh5RzvgTN1Lt08\nDNIrsIG2VDYk/JVt6f9J6zZ8EQHbznWa3cWYoCFaaICdk7jV1n/42hg70jEDYXl9\ngDOl0k6JmyF/rtfFu/OIkFGWeFYIuFHvRuLyUbw66+QDTOzKb3t8o55Ihgy1GVwT\ni6pkDs8LhZWXdOD+921l2Z1NZGZa9KNbJIg6vtgYKU98jQ5qr9iY3ikBAspHrFas\nK6USvGgAg8fCD5YiotBEvCBMYtfqmfrhpdU2p+gvTgeLW1Kaevwqd7ngQmFUrFG1\neUJSURv5AgMBAAGjOTA3MAkGA1UdEwQCMAAwCwYDVR0PBAQDAgSwMB0GA1UdDgQW\nBBQLSSjKemGDapYEd/U4mS1qry2oEjANBgkqhkiG9w0BAQUFAAOCAQEANm2agTdD\n9S2NwXMW0jansInXtQmB44qk/psWujtGnn+oT+a9KXO5p/gx2mmx8hMF02wUBx1H\nk96HUI/jR3HdhYCfG6oJuEzgXrFiSBJw/cOJiM8v3aHsAwI3NeLeIrRwBYB3kI3j\n1qfJXcOWw7c63TrsDX37xj2e4P0DNJ1cTrDmyD2yTQ5776M13Gb6nXjreSeq0t/n\n60Nj91J1oHYk6LFa0eo/gykTbLyaZrsaXlNb3j7CjhUzOpYOhiCUH3s9tKTGXd/+\nLmZ7BxTMsDhZHy3k/ETFhi+7pIUWlFo0imrdyLhd+Jw3boVj3CmvyhcwmpoM0K9l\nAOmrUiElUqLOZA==\n-----END CERTIFICATE-----\n"] s.date = "2014-05-23" s.description = "The mime-types library provides a library and registry for information about\nMIME content type definitions. It can be used to determine defined filename\nextensions for MIME types, or to use filename extensions to look up the likely\nMIME type definitions.\n\nMIME content types are used in MIME-compliant communications, as in e-mail or\nHTTP traffic, to indicate the type of content which is transmitted. The\nmime-types library provides the ability for detailed information about MIME\nentities (provided as an enumerable collection of MIME::Type objects) to be\ndetermined and used programmatically. There are many types defined by RFCs and\nvendors, so the list is long but by definition incomplete; don't hesitate to to\nadd additional type definitions (see Contributing.rdoc). The primary sources\nfor MIME type definitions found in mime-types is the IANA collection of\nregistrations (see below for the link), RFCs, and W3C recommendations.\n\nThis is release 2.2, mostly changing how the MIME type registry is updated from\nthe IANA registry (the format of which was incompatibly changed shortly before\nthis release) and taking advantage of the extra data available from IANA\nregistry in the form of MIME::Type#xrefs. In addition, the {LTSW\nlist}[http://www.ltsw.se/knbase/internet/mime.htp] has been dropped as a\nsupported list.\n\nAs a reminder, mime-types 2.x is no longer compatible with Ruby 1.8 and\nmime-types 1.x is only being maintained for security issues. No new MIME types\nor features will be added.\n\nmime-types (previously called MIME::Types for Ruby) was originally based on\nMIME::Types for Perl by Mark Overmeer, copyright 2001 - 2009. It is built to\nconform to the MIME types of RFCs 2045 and 2231. It tracks the {IANA Media\nTypes registry}[https://www.iana.org/assignments/media-types/media-types.xhtml]\nwith some types added by the users of mime-types." s.email = ["[email protected]"] s.extra_rdoc_files = ["Contributing.rdoc", "History-Types.rdoc", "History.rdoc", "Licence.rdoc", "Manifest.txt", "README.rdoc", "docs/COPYING.txt", "docs/artistic.txt"] s.files = ["Contributing.rdoc", "History-Types.rdoc", "History.rdoc", "Licence.rdoc", "Manifest.txt", "README.rdoc", "docs/COPYING.txt", "docs/artistic.txt"] s.homepage = "https://github.com/halostatue/mime-types/" s.licenses = ["MIT", "Artistic 2.0", "GPL-2"] s.rdoc_options = ["--main", "README.rdoc"] s.required_ruby_version = Gem::Requirement.new(">= 1.9.2") s.rubygems_version = "2.2.2" s.summary = "The mime-types library provides a library and registry for information about MIME content type definitions" s.installed_by_version = "2.2.2" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<minitest>, ["~> 5.3"]) s.add_development_dependency(%q<rdoc>, ["~> 4.0"]) s.add_development_dependency(%q<hoe-doofus>, ["~> 1.0"]) s.add_development_dependency(%q<hoe-gemspec2>, ["~> 1.1"]) s.add_development_dependency(%q<hoe-git>, ["~> 1.6"]) s.add_development_dependency(%q<hoe-rubygems>, ["~> 1.0"]) s.add_development_dependency(%q<hoe-travis>, ["~> 1.2"]) s.add_development_dependency(%q<rake>, ["~> 10.0"]) s.add_development_dependency(%q<simplecov>, ["~> 0.7"]) s.add_development_dependency(%q<coveralls>, ["~> 0.7"]) s.add_development_dependency(%q<hoe>, ["~> 3.12"]) else s.add_dependency(%q<minitest>, ["~> 5.3"]) s.add_dependency(%q<rdoc>, ["~> 4.0"]) s.add_dependency(%q<hoe-doofus>, ["~> 1.0"]) s.add_dependency(%q<hoe-gemspec2>, ["~> 1.1"]) s.add_dependency(%q<hoe-git>, ["~> 1.6"]) s.add_dependency(%q<hoe-rubygems>, ["~> 1.0"]) s.add_dependency(%q<hoe-travis>, ["~> 1.2"]) s.add_dependency(%q<rake>, ["~> 10.0"]) s.add_dependency(%q<simplecov>, ["~> 0.7"]) s.add_dependency(%q<coveralls>, ["~> 0.7"]) s.add_dependency(%q<hoe>, ["~> 3.12"]) end else s.add_dependency(%q<minitest>, ["~> 5.3"]) s.add_dependency(%q<rdoc>, ["~> 4.0"]) s.add_dependency(%q<hoe-doofus>, ["~> 1.0"]) s.add_dependency(%q<hoe-gemspec2>, ["~> 1.1"]) s.add_dependency(%q<hoe-git>, ["~> 1.6"]) s.add_dependency(%q<hoe-rubygems>, ["~> 1.0"]) s.add_dependency(%q<hoe-travis>, ["~> 1.2"]) s.add_dependency(%q<rake>, ["~> 10.0"]) s.add_dependency(%q<simplecov>, ["~> 0.7"]) s.add_dependency(%q<coveralls>, ["~> 0.7"]) s.add_dependency(%q<hoe>, ["~> 3.12"]) end end
{ "pile_set_name": "Github" }
// Base settings for all themes that can optionally be // overridden by the super-theme // Background of the presentation $backgroundColor: #2b2b2b; // Primary/body text $mainFont: 'Lato', sans-serif; $mainFontSize: 40px; $mainColor: #eee; // Vertical spacing between blocks of text $blockMargin: 20px; // Headings $headingMargin: 0 0 $blockMargin 0; $headingFont: 'League Gothic', Impact, sans-serif; $headingColor: #eee; $headingLineHeight: 1.2; $headingLetterSpacing: normal; $headingTextTransform: uppercase; $headingTextShadow: none; $headingFontWeight: normal; $heading1TextShadow: $headingTextShadow; $heading1Size: 3.77em; $heading2Size: 2.11em; $heading3Size: 1.55em; $heading4Size: 1.00em; $codeFont: monospace; // Links and actions $linkColor: #13DAEC; $linkColorHover: lighten( $linkColor, 20% ); // Text selection $selectionBackgroundColor: #FF5E99; $selectionColor: #fff; // Generates the presentation background, can be overridden // to return a background image or gradient @mixin bodyBackground() { background: $backgroundColor; }
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wicketstuff.javaee.naming.global; import org.wicketstuff.javaee.naming.IJndiNamingStrategy; /** * Simple Java EE 6 Global JNDI naming support for java:global prefixed JNDI names based on the EJB * 3.1 specification Section 4.4.1, page 83 <br /> * With this you can use JNDI names in the following format: <br /> * <code>java:global/[&lt;appName&gt;]/&lt;moduleName&gt;/&lt;bean-name&gt;[!&lt;fully-qualified-interface-name&gt;]</code> * <br /> * <p> * The <i>appName</i> only applies, if the application is packaged as an .ear file. It defaults to * the base name of the .ear file with no filename extension, unless specified by the * application.xml deployment descriptor. * </p> * <p> * The <i>moduleName</i> is the name of the module in which the session bean is packaged. In a * stand-alone ejb-jar file or .war file, the <i>moduleName</i> defaults to the base name of the * module with any filename extension removed. In an ear file, the <i>moduleName</i> defaults to the * pathname of the module with any filename extension removed, but with any directory names * included. The default <i>moduleName</i> can be overriden using the module-name element of * ejb-jar.xml (for ejb-jar files) or web.xml (for .war files). * </p> * * @see <a href="http://jcp.org/aboutJava/communityprocess/final/jsr318/index.html"> EJB 3.1 * specification</a> * * @author Peter Major */ public class GlobalJndiNamingStrategy implements IJndiNamingStrategy { private static final long serialVersionUID = 1L; private String baseName; /** * This naming strategy will use the java:global JNDI name format for lookups. Use this * constructor, if the app-name is not defined. * * @param moduleName * The name of the module */ public GlobalJndiNamingStrategy(String moduleName) { this(null, moduleName); } /** * This naming strategy will use the java:global JNDI name format for lookups. * * @param appName * The name of the application (defined in application.xml or name of the ear) * @param moduleName * The name of the module (defined in ejb-jar.xml or name of the ejb-jar) */ public GlobalJndiNamingStrategy(String appName, String moduleName) { if (appName == null || appName.isEmpty()) { baseName = "java:global/" + moduleName + "/"; } else { baseName = "java:global/" + appName + "/" + moduleName + "/"; } } /** * {@inheritDoc} */ @Override public String calculateName(String ejbName, Class<?> ejbType) { if (ejbName == null) { return baseName + ejbType.getName(); } return baseName + ejbName + "!" + ejbType.getName(); } }
{ "pile_set_name": "Github" }
<p align="center"> <a href="https://natasha.dotnetcore.xyz/"> 返回 </a> | <a href="https://natasha.dotnetcore.xyz/en/api/extensions-samples.html"> English </a> </p> #### 使用Natasha的类型扩展: ```C# Example: typeof(Dictionary<string,List<int>>[]).GetDevelopName(); //result: "System.Collections.Generic.Dictionary<System.String,System.Collections.Generic.List<Int32>>[]" typeof(Dictionary<string,List<int>>[]).GetAvailableName(); //result: "Dictionary_String_List_Int32____" typeof(Dictionary<string,List<int>>).GetAllGenericTypes(); //result: [string,list<>,int] typeof(Dictionary<string,List<int>>).IsImplementFrom<IDictionary>(); //result: true typeof(Dictionary<string,List<int>>).IsSimpleType(); //result: false typeof(List<>).With(typeof(int)); //result: List<int> ``` <br/> <br/>
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <!--Converted with LaTeX2HTML 96.1-d (Mar 10, 1996) by Nikos Drakos ([email protected]), CBLU, University of Leeds --> <HTML> <HEAD> <TITLE> r = jacob(a,b,eps)</TITLE> <META NAME="description" CONTENT=" r = jacob(a,b,eps)"> <META NAME="keywords" CONTENT="kirja"> <META NAME="resource-type" CONTENT="document"> <META NAME="distribution" CONTENT="global"> <LINK REL=STYLESHEET HREF="kirja.css"> </HEAD> <BODY LANG="EN"> <A NAME="tex2html449" HREF="node36.html"><IMG WIDTH=37 HEIGHT=24 ALIGN=BOTTOM ALT="next" SRC="lh-figs/next_motif.gif"></A> <A NAME="tex2html447" HREF="node5.html"><IMG WIDTH=26 HEIGHT=24 ALIGN=BOTTOM ALT="up" SRC="lh-figs/up_motif.gif"></A> <A NAME="tex2html441" HREF="node34.html"><IMG WIDTH=63 HEIGHT=24 ALIGN=BOTTOM ALT="previous" SRC="lh-figs/previous_motif.gif"></A> <BR> <B> Next:</B> <A NAME="tex2html450" HREF="node36.html"> r = lud(matrix)</A> <B>Up:</B> <A NAME="tex2html448" HREF="node5.html">MATC Internal Functions</A> <B> Previous:</B> <A NAME="tex2html442" HREF="node34.html"> r = eig(matrix)</A> <BR> <P> <H1><A NAME="SECTION005300000000000000000"> r = jacob(a,b,eps)</A></H1> <P> Solve symmetric positive definite eigenvalue problem by Jacob iteration. Return values are the eigenvalues. Also a variable eigv is created containing eigenvectors. <P> <BR> <HR> <P><ADDRESS> <I>Juha Ruokolainen <BR> Fri Feb 14 15:59:30 EET 1997</I> </ADDRESS> </BODY> </HTML>
{ "pile_set_name": "Github" }
EXE_INC = \ -I$(LIB_SRC)/finiteVolume/lnInclude \ -I$(LIB_SRC)/meshTools/lnInclude \ -I$(LIB_SRC)/surfMesh/lnInclude \ -I$(LIB_SRC)/fileFormats/lnInclude \ -I$(LIB_SRC)/triSurface/lnInclude \ -I$(LIB_SRC)/conversion/lnInclude \ -I$(LIB_SRC)/lagrangian/basic/lnInclude LIB_LIBS = \ -lfiniteVolume \ -lmeshTools \ -lsurfMesh \ -lfileFormats \ -ltriSurface \ -llagrangian \ -lconversion
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo.Presentation { internal partial class QuickInfoPresenter { private class QuickInfoPresenterSession : ForegroundThreadAffinitizedObject, IQuickInfoPresenterSession { private readonly IQuickInfoBroker _quickInfoBroker; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; private IQuickInfoSession _editorSessionOpt; private QuickInfoItem _item; private ITrackingSpan _triggerSpan; public event EventHandler<EventArgs> Dismissed; public QuickInfoPresenterSession(IQuickInfoBroker quickInfoBroker, ITextView textView, ITextBuffer subjectBuffer) : this(quickInfoBroker, textView, subjectBuffer, null) { } public QuickInfoPresenterSession(IQuickInfoBroker quickInfoBroker, ITextView textView, ITextBuffer subjectBuffer, IQuickInfoSession sessionOpt) { _quickInfoBroker = quickInfoBroker; _textView = textView; _subjectBuffer = subjectBuffer; _editorSessionOpt = sessionOpt; } public void PresentItem(ITrackingSpan triggerSpan, QuickInfoItem item, bool trackMouse) { AssertIsForeground(); _triggerSpan = triggerSpan; _item = item; // It's a new list of items. Either create the editor session if this is the first time, or ask the // editor session that we already have to recalculate. if (_editorSessionOpt == null || _editorSessionOpt.IsDismissed) { // We're tracking the caret. Don't have the editor do it. var triggerPoint = triggerSpan.GetStartTrackingPoint(PointTrackingMode.Negative); _editorSessionOpt = _quickInfoBroker.CreateQuickInfoSession(_textView, triggerPoint, trackMouse: trackMouse); _editorSessionOpt.Dismissed += (s, e) => OnEditorSessionDismissed(); } // So here's the deal. We cannot create the editor session and give it the right // signatures (even though we know what they are). Instead, the sessino with // call back into the ISignatureHelpSourceProvider (which is us) to get those // values. It will pass itself along with the calls back into // ISignatureHelpSourceProvider. So, in order to make that connection work, we // add properties to the session so that we can call back into ourselves, get // the signatures and add it to the session. if (!_editorSessionOpt.Properties.ContainsProperty(s_augmentSessionKey)) { _editorSessionOpt.Properties.AddProperty(s_augmentSessionKey, this); } _editorSessionOpt.Recalculate(); } public void Dismiss() { AssertIsForeground(); if (_editorSessionOpt == null) { // No editor session, nothing to do here. return; } if (_item == null) { // We don't have an item, so we're being asked to augment a session. // Since we didn't put anything in the session, don't dismiss it either. return; } _editorSessionOpt.Dismiss(); _editorSessionOpt = null; } private void OnEditorSessionDismissed() { AssertIsForeground(); var dismissed = this.Dismissed; if (dismissed != null) { dismissed(this, new EventArgs()); } } internal void AugmentQuickInfoSession(IList<object> quickInfoContent, out ITrackingSpan applicableToSpan) { applicableToSpan = _triggerSpan; quickInfoContent.Add(_item.Content.Create()); } } } }
{ "pile_set_name": "Github" }
#!/bin/sh /etc/rc.common START=18 start() { MODE=`/sbin/uci get wireless.@wifi-iface[0].mode` SSID=`/sbin/uci get wireless.@wifi-iface[0].ssid` if [ "$SSID" != "Arduino" -a "$SSID" != "Linino" ] then return fi if [ "$MODE" == "ap" ] then SSID_SUFFIX=`/sbin/ifconfig wlan0 | /usr/bin/head -n 1 | /bin/grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | /bin/sed 's/://g'` SSID="$SSID-$SSID_SUFFIX" /sbin/uci "set" "wireless.@wifi-iface[0].ssid=$SSID" /sbin/uci commit wireless logger -t rename "WiFi renamed $SSID" fi }
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0-only */ #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <b64_decode.h> #include <tests/test.h> struct messages_t { const char *enc; const char *dec; } messages[] = { {"QQ==", "A"}, {"Q\r\nUI=", "AB"}, {"QUJD", "ABC"}, {"\nQUJDRA==", "ABCD"}, {"SGVsbG8\r=", "Hello"}, {"SGVsbG8h", "Hello!"} }; const char *invalid[] = { "QQ=-=", "SGVsbG-8=" }; static void test_b64_decode(void **state) { uint8_t *decoded; size_t res; for (int i = 0; i < ARRAY_SIZE(messages); i++) { decoded = malloc(strlen(messages[i].enc) * sizeof(char)); res = b64_decode((uint8_t *)messages[i].enc, strlen(messages[i].enc), decoded); assert_int_equal(res, (strlen(messages[i].dec))); assert_string_equal(decoded, messages[i].dec); free(decoded); } for (int i = 0; i < ARRAY_SIZE(invalid); i++) { decoded = malloc(strlen(invalid[i]) * sizeof(char)); res = b64_decode((uint8_t *)invalid[i], strlen(invalid[i]), decoded); assert_int_equal(res, 0); free(decoded); } } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_b64_decode), }; return cmocka_run_group_tests(tests, NULL, NULL); }
{ "pile_set_name": "Github" }
● firewalld.service - firewalld - dynamic firewall daemon Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled) Active: active (running) since Tue 2017-03-14 15:33:24 CET; 1h 34min ago Docs: man:firewalld(1) Main PID: 698 (firewalld) CGroup: /system.slice/firewalld.service └─698 /usr/bin/python3 -Es /usr/sbin/firewalld --nofork --nopid Mar 14 15:33:20 localhost.localdomain systemd[1]: Starting firewalld - dynamic firewall daemon... Mar 14 15:33:24 localhost.localdomain systemd[1]: Started firewalld - dynamic firewall daemon. Mar 14 15:33:29 localhost.localdomain /firewalld[698]: WARNING: FedoraServer: INVALID_SERVICE: cockpit
{ "pile_set_name": "Github" }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.ServiceLoader; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Factory for classes supplied by hadoop compatibility modules. Only one of each class will be * created. */ @InterfaceAudience.Private public class CompatibilitySingletonFactory extends CompatibilityFactory { public static enum SingletonStorage { INSTANCE; private final Object lock = new Object(); private final Map<Class, Object> instances = new HashMap<>(); } private static final Logger LOG = LoggerFactory.getLogger(CompatibilitySingletonFactory.class); /** * This is a static only class don't let anyone create an instance. */ protected CompatibilitySingletonFactory() { } /** * Get the singleton instance of Any classes defined by compatibiliy jar's * * @return the singleton */ @SuppressWarnings("unchecked") public static <T> T getInstance(Class<T> klass) { synchronized (SingletonStorage.INSTANCE.lock) { T instance = (T) SingletonStorage.INSTANCE.instances.get(klass); if (instance == null) { try { ServiceLoader<T> loader = ServiceLoader.load(klass); Iterator<T> it = loader.iterator(); instance = it.next(); if (it.hasNext()) { StringBuilder msg = new StringBuilder(); msg.append("ServiceLoader provided more than one implementation for class: ") .append(klass) .append(", using implementation: ").append(instance.getClass()) .append(", other implementations: {"); while (it.hasNext()) { msg.append(it.next()).append(" "); } msg.append("}"); LOG.warn(msg.toString()); } } catch (Exception e) { throw new RuntimeException(createExceptionString(klass), e); } catch (Error e) { throw new RuntimeException(createExceptionString(klass), e); } // If there was nothing returned and no exception then throw an exception. if (instance == null) { throw new RuntimeException(createExceptionString(klass)); } SingletonStorage.INSTANCE.instances.put(klass, instance); } return instance; } } }
{ "pile_set_name": "Github" }
.. include:: ../README.rst
{ "pile_set_name": "Github" }
package main import ( "github.com/veandco/go-sdl2/sdl" ) const ( width = 640 height = 480 ) func main() { if err := sdl.Init(sdl.INIT_VIDEO); err != nil { panic(err) } defer sdl.Quit() window, err := sdl.CreateWindow("SDL2 example #14", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, width, height, sdl.WINDOW_SHOWN) if err != nil { panic(err) } defer window.Destroy() primarySurface, err := window.GetSurface() if err != nil { panic(err) } primarySurface.FillRect(nil, sdl.MapRGB(primarySurface.Format, 192, 255, 192)) dstRect := sdl.Rect{} dstRect.Y = 10 primarySurface.Lock() var y int32 for y = 0; y < primarySurface.H; y++ { scanLine := primarySurface.Pitch p := primarySurface.Pixels() offset := scanLine * y var x int32 for x = 0; x < scanLine; x++ { p[offset+x] = byte(y) } } primarySurface.Unlock() window.UpdateSurface() sdl.Delay(5000) }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2012-2015 cketti and contributors * https://github.com/cketti/ckChangeLog/graphs/contributors * * Portions Copyright (C) 2012 Martin van Zuilekom (http://martin.cubeactive.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. * * * Based on android-change-log: * * Copyright (C) 2011, Karsten Priegnitz * * Permission to use, copy, modify, and distribute this piece of software * for any purpose with or without fee is hereby granted, provided that * the above copyright notice and this permission notice appear in the * source code of all copies. * * It would be appreciated if you mention the author in your change log, * contributors list or the like. * * http://code.google.com/p/android-change-log/ */ package de.cketti.library.changelog; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.XmlResourceParser; import android.preference.PreferenceManager; import android.util.Log; import android.util.SparseArray; import android.webkit.WebView; /** * Display a dialog showing a full or partial (What's New) change log. */ @SuppressWarnings("UnusedDeclaration") public class ChangeLog { /** * Tag that is used when sending error/debug messages to the log. */ protected static final String LOG_TAG = "ckChangeLog"; /** * This is the key used when storing the version code in SharedPreferences. */ protected static final String VERSION_KEY = "ckChangeLog_last_version_code"; /** * Constant that used when no version code is available. */ protected static final int NO_VERSION = -1; /** * Default CSS styles used to format the change log. */ public static final String DEFAULT_CSS = "h1 { margin-left: 0px; font-size: 1.2em; }" + "\n" + "li { margin-left: 0px; }" + "\n" + "ul { padding-left: 2em; }"; /** * Context that is used to access the resources and to create the ChangeLog dialogs. */ protected final Context mContext; /** * Contains the CSS rules used to format the change log. */ protected final String mCss; /** * Last version code read from {@code SharedPreferences} or {@link #NO_VERSION}. */ private int mLastVersionCode; /** * Version code of the current installation. */ private int mCurrentVersionCode; /** * Version name of the current installation. */ private String mCurrentVersionName; /** * Contains constants for the root element of {@code changelog.xml}. */ protected interface ChangeLogTag { static final String NAME = "changelog"; } /** * Contains constants for the release element of {@code changelog.xml}. */ protected interface ReleaseTag { static final String NAME = "release"; static final String ATTRIBUTE_VERSION = "version"; static final String ATTRIBUTE_VERSION_CODE = "versioncode"; } /** * Contains constants for the change element of {@code changelog.xml}. */ protected interface ChangeTag { static final String NAME = "change"; } /** * Create a {@code ChangeLog} instance using the default {@link SharedPreferences} file. * * @param context * Context that is used to access the resources and to create the ChangeLog dialogs. */ public ChangeLog(Context context) { this(context, PreferenceManager.getDefaultSharedPreferences(context), DEFAULT_CSS); } /** * Create a {@code ChangeLog} instance using the default {@link SharedPreferences} file. * * @param context * Context that is used to access the resources and to create the ChangeLog dialogs. * @param css * CSS styles that will be used to format the change log. */ public ChangeLog(Context context, String css) { this(context, PreferenceManager.getDefaultSharedPreferences(context), css); } /** * Create a {@code ChangeLog} instance using the supplied {@code SharedPreferences} instance. * * @param context * Context that is used to access the resources and to create the ChangeLog dialogs. * @param preferences * {@code SharedPreferences} instance that is used to persist the last version code. * @param css * CSS styles used to format the change log (excluding {@code <style>} and * {@code </style>}). * */ public ChangeLog(Context context, SharedPreferences preferences, String css) { mContext = context; mCss = css; // Get last version code mLastVersionCode = preferences.getInt(VERSION_KEY, NO_VERSION); // Get current version code and version name try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); mCurrentVersionCode = packageInfo.versionCode; mCurrentVersionName = packageInfo.versionName; } catch (NameNotFoundException e) { mCurrentVersionCode = NO_VERSION; Log.e(LOG_TAG, "Could not get version information from manifest!", e); } } /** * Get version code of last installation. * * @return The version code of the last installation of this app (as described in the former * manifest). This will be the same as returned by {@link #getCurrentVersionCode()} the * second time this version of the app is launched (more precisely: the second time * {@code ChangeLog} is instantiated). * * @see <a href="http://developer.android.com/guide/topics/manifest/manifest-element.html#vcode">android:versionCode</a> */ public int getLastVersionCode() { return mLastVersionCode; } /** * Get version code of current installation. * * @return The version code of this app as described in the manifest. * * @see <a href="http://developer.android.com/guide/topics/manifest/manifest-element.html#vcode">android:versionCode</a> */ public int getCurrentVersionCode() { return mCurrentVersionCode; } /** * Get version name of current installation. * * @return The version name of this app as described in the manifest. * * @see <a href="http://developer.android.com/guide/topics/manifest/manifest-element.html#vname">android:versionName</a> */ public String getCurrentVersionName() { return mCurrentVersionName; } /** * Check if this is the first execution of this app version. * * @return {@code true} if this version of your app is started the first time. */ public boolean isFirstRun() { return mLastVersionCode < mCurrentVersionCode; } /** * Check if this is a new installation. * * @return {@code true} if your app including {@code ChangeLog} is started the first time ever. * Also {@code true} if your app was uninstalled and installed again. */ public boolean isFirstRunEver() { return mLastVersionCode == NO_VERSION; } /** * Skip the "What's new" dialog for this app version. * * <p> * Future calls to {@link #isFirstRun()} and {@link #isFirstRunEver()} will return {@code false} * for the current app version. * </p> */ public void skipLogDialog() { updateVersionInPreferences(); } /** * Get the "What's New" dialog. * * @return An AlertDialog displaying the changes since the previous installed version of your * app (What's New). But when this is the first run of your app including * {@code ChangeLog} then the full log dialog is show. */ public AlertDialog getLogDialog() { return getDialog(isFirstRunEver()); } /** * Get a dialog with the full change log. * * @return An AlertDialog with a full change log displayed. */ public AlertDialog getFullLogDialog() { return getDialog(true); } /** * Create a dialog containing (parts of the) change log. * * @param full * If this is {@code true} the full change log is displayed. Otherwise only changes for * versions newer than the last version are displayed. * * @return A dialog containing the (partial) change log. */ protected AlertDialog getDialog(boolean full) { WebView wv = new WebView(mContext); //wv.setBackgroundColor(0); // transparent wv.loadDataWithBaseURL(null, getLog(full), "text/html", "UTF-8", null); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle( mContext.getResources().getString( full ? R.string.changelog_full_title : R.string.changelog_title)) .setView(wv) .setCancelable(false) // OK button .setPositiveButton( mContext.getResources().getString(R.string.changelog_ok_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // The user clicked "OK" so save the current version code as // "last version code". updateVersionInPreferences(); } }); if (!full) { // Show "More…" button if we're only displaying a partial change log. builder.setNegativeButton(R.string.changelog_show_full, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { getFullLogDialog().show(); } }); } return builder.create(); } /** * Write current version code to the preferences. */ protected void updateVersionInPreferences() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); SharedPreferences.Editor editor = sp.edit(); editor.putInt(VERSION_KEY, mCurrentVersionCode); // TODO: Update preferences from a background thread editor.commit(); } /** * Get changes since last version as HTML string. * * @return HTML string containing the changes since the previous installed version of your app * (What's New). */ public String getLog() { return getLog(false); } /** * Get full change log as HTML string. * * @return HTML string containing the full change log. */ public String getFullLog() { return getLog(true); } /** * Get (partial) change log as HTML string. * * @param full * If this is {@code true} the full change log is returned. Otherwise only changes for * versions newer than the last version are returned. * * @return The (partial) change log. */ protected String getLog(boolean full) { StringBuilder sb = new StringBuilder(); sb.append("<html><head><style type=\"text/css\">"); sb.append(mCss); sb.append("</style></head><body>"); String versionFormat = mContext.getResources().getString(R.string.changelog_version_format); List<ReleaseItem> changelog = getChangeLog(full); for (ReleaseItem release : changelog) { sb.append("<h1>"); sb.append(String.format(versionFormat, release.versionName)); sb.append("</h1><ul>"); for (String change : release.changes) { sb.append("<li>"); sb.append(change); sb.append("</li>"); } sb.append("</ul>"); } sb.append("</body></html>"); return sb.toString(); } /** * Returns the merged change log. * * @param full * If this is {@code true} the full change log is returned. Otherwise only changes for * versions newer than the last version are returned. * * @return A sorted {@code List} containing {@link ReleaseItem}s representing the (partial) * change log. * * @see #getChangeLogComparator() */ public List<ReleaseItem> getChangeLog(boolean full) { SparseArray<ReleaseItem> masterChangelog = getMasterChangeLog(full); SparseArray<ReleaseItem> changelog = getLocalizedChangeLog(full); List<ReleaseItem> mergedChangeLog = new ArrayList<ReleaseItem>(masterChangelog.size()); for (int i = 0, len = masterChangelog.size(); i < len; i++) { int key = masterChangelog.keyAt(i); // Use release information from localized change log and fall back to the master file // if necessary. ReleaseItem release = changelog.get(key, masterChangelog.get(key)); mergedChangeLog.add(release); } Collections.sort(mergedChangeLog, getChangeLogComparator()); return mergedChangeLog; } /** * Read master change log from {@code xml/changelog_master.xml} * * @see #readChangeLogFromResource(int, boolean) */ protected SparseArray<ReleaseItem> getMasterChangeLog(boolean full) { return readChangeLogFromResource(R.xml.changelog_master, full); } /** * Read localized change log from {@code xml[-lang]/changelog.xml} * * @see #readChangeLogFromResource(int, boolean) */ protected SparseArray<ReleaseItem> getLocalizedChangeLog(boolean full) { return readChangeLogFromResource(R.xml.changelog, full); } /** * Read change log from XML resource file. * * @param resId * Resource ID of the XML file to read the change log from. * @param full * If this is {@code true} the full change log is returned. Otherwise only changes for * versions newer than the last version are returned. * * @return A {@code SparseArray} containing {@link ReleaseItem}s representing the (partial) * change log. */ protected final SparseArray<ReleaseItem> readChangeLogFromResource(int resId, boolean full) { XmlResourceParser xml = mContext.getResources().getXml(resId); try { return readChangeLog(xml, full); } finally { xml.close(); } } /** * Read the change log from an XML file. * * @param xml * The {@code XmlPullParser} instance used to read the change log. * @param full * If {@code true} the full change log is read. Otherwise only the changes since the * last (saved) version are read. * * @return A {@code SparseArray} mapping the version codes to release information. */ protected SparseArray<ReleaseItem> readChangeLog(XmlPullParser xml, boolean full) { SparseArray<ReleaseItem> result = new SparseArray<ReleaseItem>(); try { int eventType = xml.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG && xml.getName().equals(ReleaseTag.NAME)) { if (parseReleaseTag(xml, full, result)) { // Stop reading more elements if this entry is not newer than the last // version. break; } } eventType = xml.next(); } } catch (XmlPullParserException e) { Log.e(LOG_TAG, e.getMessage(), e); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } return result; } /** * Parse the {@code release} tag of a change log XML file. * * @param xml * The {@code XmlPullParser} instance used to read the change log. * @param full * If {@code true} the contents of the {@code release} tag are always added to * {@code changelog}. Otherwise only if the item's {@code versioncode} attribute is * higher than the last version code. * @param changelog * The {@code SparseArray} to add a new {@link ReleaseItem} instance to. * * @return {@code true} if the {@code release} element is describing changes of a version older * or equal to the last version. In that case {@code changelog} won't be modified and * {@link #readChangeLog(XmlPullParser, boolean)} will stop reading more elements from * the change log file. * * @throws XmlPullParserException * @throws IOException */ private boolean parseReleaseTag(XmlPullParser xml, boolean full, SparseArray<ReleaseItem> changelog) throws XmlPullParserException, IOException { String version = xml.getAttributeValue(null, ReleaseTag.ATTRIBUTE_VERSION); int versionCode; try { String versionCodeStr = xml.getAttributeValue(null, ReleaseTag.ATTRIBUTE_VERSION_CODE); versionCode = Integer.parseInt(versionCodeStr); } catch (NumberFormatException e) { versionCode = NO_VERSION; } if (!full && versionCode <= mLastVersionCode) { return true; } int eventType = xml.getEventType(); List<String> changes = new ArrayList<String>(); while (eventType != XmlPullParser.END_TAG || xml.getName().equals(ChangeTag.NAME)) { if (eventType == XmlPullParser.START_TAG && xml.getName().equals(ChangeTag.NAME)) { eventType = xml.next(); changes.add(xml.getText()); } eventType = xml.next(); } ReleaseItem release = new ReleaseItem(versionCode, version, changes); changelog.put(versionCode, release); return false; } /** * Returns a {@link Comparator} that specifies the sort order of the {@link ReleaseItem}s. * * <p> * The default implementation returns the items in reverse order (latest version first). * </p> */ protected Comparator<ReleaseItem> getChangeLogComparator() { return new Comparator<ReleaseItem>() { @Override public int compare(ReleaseItem lhs, ReleaseItem rhs) { if (lhs.versionCode < rhs.versionCode) { return 1; } else if (lhs.versionCode > rhs.versionCode) { return -1; } else { return 0; } } }; } /** * Container used to store information about a release/version. */ public static class ReleaseItem { /** * Version code of the release. */ public final int versionCode; /** * Version name of the release. */ public final String versionName; /** * List of changes introduced with that release. */ public final List<String> changes; ReleaseItem(int versionCode, String versionName, List<String> changes) { this.versionCode = versionCode; this.versionName = versionName; this.changes = changes; } } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="shortcut icon" href="favicon.png" /> <title>Line Numbers ▲ Prism plugins</title> <base href="../.." /> <link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="themes/prism.css" data-noprefix /> <link rel="stylesheet" href="plugins/line-numbers/prism-line-numbers.css" data-noprefix /> <script src="prefixfree.min.js"></script> <script>var _gaq = [['_setAccount', 'UA-33746269-1'], ['_trackPageview']];</script> <script src="http://www.google-analytics.com/ga.js" async></script> </head> <body> <header> <div class="intro" data-src="templates/header-plugins.html" data-type="text/html"></div> <h2>Line Numbers</h2> <p>Line number at the beginning of code lines.</p> </header> <section class="language-markup"> <h1>How to use</h1> <p>Obviously, this is supposed to work only for code blocks (<code>&lt;pre>&lt;code></code>) and not for inline code.</p> <p>Add class <strong>line-numbers</strong> to your desired <code>&lt;pre></code> and line-numbers plugin will take care.</p> <p>Optional: You can specify the <code>data-start</code> (Number) attribute on the <code>&lt;pre></code> element. It will shift the line counter.</p> </section> <section> <h1>Examples</h1> <h2>JavaScript</h2> <pre class="line-numbers" data-src="plugins/line-numbers/prism-line-numbers.js"></pre> <h2>CSS</h2> <pre class="line-numbers" data-src="plugins/line-numbers/prism-line-numbers.css"></pre> <h2>HTML</h2> <p>Please note the <code>data-start="-5"</code> in the code below.</p> <pre class="line-numbers" data-src="plugins/line-numbers/index.html" data-start="-5"></pre> <h2>Unknown languages</h2> <pre class="language-none line-numbers"><code>This raw text is not highlighted but it still has lines numbers</code></pre> </section> <footer data-src="templates/footer.html" data-type="text/html"></footer> <script src="prism.js"></script> <script src="plugins/line-numbers/prism-line-numbers.js"></script> <script src="utopia.js"></script> <script src="components.js"></script> <script src="code.js"></script> </body> </html>
{ "pile_set_name": "Github" }
<?php namespace ParserHooks\Tests; use ParamProcessor\ProcessedParam; use ParamProcessor\ProcessingResult; use ParserHooks\FunctionRunner; use ParserHooks\HookDefinition; /** * @covers ParserHooks\FunctionRunner * @covers ParserHooks\Internal\Runner * * @group ParserHooks * * @licence GNU GPL v2+ * @author Jeroen De Dauw < [email protected] > */ class FunctionRunnerTest extends \PHPUnit_Framework_TestCase { public function optionsProvider() { return array( array( array( FunctionRunner::OPT_DO_PARSE => true, ), ), array( array( FunctionRunner::OPT_DO_PARSE => false, ), ), ); } const HOOK_HANDLER_RESULT = 'hook handler result'; protected $options; protected $parser; /** * @dataProvider optionsProvider */ public function testRun( array $options ) { $this->options = $options; $definition = new HookDefinition( 'someHook' ); $this->parser = $this->getMock( 'Parser' ); $inputParams = array( 'foo=bar', 'baz=42', ); $processedParams = new ProcessingResult( array( 'foo' => new ProcessedParam( 'foo', 'bar', false ) ) ); $paramProcessor = $this->newMockParamProcessor( $inputParams, $processedParams ); $hookHandler = $this->newMockHookHandler( $processedParams ); $runner = new FunctionRunner( $definition, $hookHandler, $this->options, $paramProcessor ); $frame = $this->getMock( 'PPFrame' ); $frame->expects( $this->exactly( count( $inputParams ) ) ) ->method( 'expand' ) ->will( $this->returnArgument( 0 ) ); $result = $runner->run( $this->parser, $inputParams, $frame ); $this->assertResultIsValid( $result ); } protected function assertResultIsValid( $result ) { $expected = array( self::HOOK_HANDLER_RESULT ); if ( !$this->options[FunctionRunner::OPT_DO_PARSE] ) { $expected['noparse'] = true; $expected['isHTML'] = true; } $this->assertEquals( $expected, $result ); } protected function newMockHookHandler( $expectedParameters ) { $hookHandler = $this->getMock( 'ParserHooks\HookHandler' ); $hookHandler->expects( $this->once() ) ->method( 'handle' ) ->with( $this->equalTo( $this->parser ), $this->equalTo( $expectedParameters ) ) ->will( $this->returnValue( self::HOOK_HANDLER_RESULT ) ); return $hookHandler; } protected function newMockParamProcessor( $expandedParams, $processedParams ) { $paramProcessor = $this->getMockBuilder( 'ParamProcessor\Processor' ) ->disableOriginalConstructor()->getMock(); $paramProcessor->expects( $this->once() ) ->method( 'setFunctionParams' ) ->with( $this->equalTo( $expandedParams ) ); $paramProcessor->expects( $this->once() ) ->method( 'processParameters' ) ->will( $this->returnValue( $processedParams ) ); return $paramProcessor; } }
{ "pile_set_name": "Github" }
#!/bin/bash # Copyright 2015 Insight Data Science # # 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. # must be called from top level # check input arguments if [ "$#" -ne 1 ]; then echo "Please specify cluster name!" && exit 1 fi PEG_ROOT=$(dirname ${BASH_SOURCE})/../.. source ${PEG_ROOT}/util.sh CLUSTER_NAME=$1 MASTER_DNS=$(fetch_cluster_master_public_dns ${CLUSTER_NAME}) WORKER_DNS=$(fetch_cluster_worker_public_dns ${CLUSTER_NAME}) HOSTNAMES=$(fetch_cluster_hostnames ${CLUSTER_NAME}) restart_sshagent_if_needed ${CLUSTER_NAME} # Enable passwordless SSH from local to master if ! [ -f ~/.ssh/id_rsa ]; then ssh-keygen -f ~/.ssh/id_rsa -t rsa -P "" fi cat ~/.ssh/id_rsa.pub | run_cmd_on_node ${MASTER_DNS} 'cat >> ~/.ssh/authorized_keys' # Enable passwordless SSH from master to slaves SCRIPT=${PEG_ROOT}/config/ssh/setup_ssh.sh ARGS="${WORKER_DNS}" run_script_on_node ${MASTER_DNS} ${SCRIPT} ${ARGS} # Add NameNode, DataNodes, and Secondary NameNode to known hosts SCRIPT=${PEG_ROOT}/config/ssh/add_to_known_hosts.sh ARGS="${MASTER_DNS} ${HOSTNAMES}" run_script_on_node ${MASTER_DNS} ${SCRIPT} ${ARGS}
{ "pile_set_name": "Github" }
/* * Copyright (C) 2003-2006 Gabest * http://www.gabest.org * * 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, 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 GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif #include <afx.h> #include <afxwin.h> // MFC core and standard components // TODO: reference additional headers your program requires here #include <dshow.h> #include <streams.h> #include <dvdmedia.h> #include "..\..\..\DSUtil\DSUtil.h"
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- generated on Fri Apr 17 08:19:45 2020 by Eclipse SUMO Version v1_5_0+1182-c674b91ce6 This data file and the accompanying materials are made available under the terms of the Eclipse Public License v2.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v20.html SPDX-License-Identifier: EPL-2.0 <configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/sumoConfiguration.xsd"> <input> <net-file value="net2.net.xml"/> <route-files value="input_routes.rou.xml"/> </input> <output> <write-license value="true"/> <fcd-output value="fcd.xml"/> <tripinfo-output value="tripinfos.xml"/> </output> <processing> <step-method.ballistic value="true"/> <default.speeddev value="0"/> </processing> <report> <xml-validation value="never"/> <no-step-log value="true"/> </report> </configuration> --> <fcd-export xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/fcd_file.xsd"> <timestep time="0.00"> <vehicle id="overtaking" x="0.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="0.00" lane="VODUGES_beg_0" slope="0.00"/> <vehicle id="stopped" x="40.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="40.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="1.00"> <vehicle id="overtaking" x="1.30" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="2.60" pos="1.30" lane="VODUGES_beg_0" slope="0.00"/> <vehicle id="stopped" x="41.30" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="2.60" pos="41.30" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="2.00"> <vehicle id="overtaking" x="5.20" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="5.20" pos="5.20" lane="VODUGES_beg_0" slope="0.00"/> <vehicle id="stopped" x="44.06" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="2.91" pos="44.06" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="3.00"> <vehicle id="overtaking" x="11.70" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="7.80" pos="11.70" lane="VODUGES_beg_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="4.00"> <vehicle id="overtaking" x="20.80" y="1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="10.40" pos="24.50" lane="-VODUGES_beg_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="5.00"> <vehicle id="overtaking" x="32.50" y="1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.00" pos="12.80" lane="-VODUGES_beg_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="6.00"> <vehicle id="overtaking" x="45.95" y="1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="8.75" lane=":C_3_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="7.00"> <vehicle id="overtaking" x="59.83" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="5.13" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="8.00"> <vehicle id="overtaking" x="73.72" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="19.02" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="9.00"> <vehicle id="overtaking" x="87.62" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="32.91" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="10.00"> <vehicle id="overtaking" x="101.50" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="46.80" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="11.00"> <vehicle id="overtaking" x="115.40" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="60.69" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="12.00"> <vehicle id="overtaking" x="129.29" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="74.58" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="13.00"> <vehicle id="overtaking" x="143.18" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="88.47" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="14.00"> <vehicle id="overtaking" x="157.06" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="102.36" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="15.00"> <vehicle id="overtaking" x="170.96" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="116.25" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="16.00"> <vehicle id="overtaking" x="184.85" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="130.14" lane="VODUGES_end_0" slope="0.00"/> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="17.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="18.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="19.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="20.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="21.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="22.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="23.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="24.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="25.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="26.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="27.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="28.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="29.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="30.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="31.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="32.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="33.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="34.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="35.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="36.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="37.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="38.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="39.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="40.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="41.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="42.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="43.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="44.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="45.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="46.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="47.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="48.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="49.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="50.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="51.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="52.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="53.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="54.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="55.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="56.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="57.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="58.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="59.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="60.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="61.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="62.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="63.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="64.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="65.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="66.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="67.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="68.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="69.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="70.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="71.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="72.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="73.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="74.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="75.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="76.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="77.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="78.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="79.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="80.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="81.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="82.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="83.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="84.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="85.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="86.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="87.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="88.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="89.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="90.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="91.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="92.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="93.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="94.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="95.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="96.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="97.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="98.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="99.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="100.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="101.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="102.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="103.00"> <vehicle id="stopped" x="45.00" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.00" pos="45.00" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="104.00"> <vehicle id="stopped" x="45.27" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="0.53" pos="45.27" lane="VODUGES_beg_0" slope="0.00"/> </timestep> <timestep time="105.00"> <vehicle id="stopped" x="47.10" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="3.13" pos="1.80" lane=":C_4_0" slope="0.00"/> </timestep> <timestep time="106.00"> <vehicle id="stopped" x="51.54" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="5.73" pos="6.24" lane=":C_4_0" slope="0.00"/> </timestep> <timestep time="107.00"> <vehicle id="stopped" x="58.57" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="8.33" pos="3.87" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="108.00"> <vehicle id="stopped" x="68.21" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="10.93" pos="13.51" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="109.00"> <vehicle id="stopped" x="80.44" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.53" pos="25.74" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="110.00"> <vehicle id="stopped" x="94.15" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="39.45" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="111.00"> <vehicle id="stopped" x="108.04" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="53.34" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="112.00"> <vehicle id="stopped" x="121.93" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="67.23" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="113.00"> <vehicle id="stopped" x="135.82" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="81.12" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="114.00"> <vehicle id="stopped" x="149.71" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="95.01" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="115.00"> <vehicle id="stopped" x="163.60" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="108.90" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="116.00"> <vehicle id="stopped" x="177.49" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="122.79" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="117.00"> <vehicle id="stopped" x="191.38" y="-1.60" angle="90.00" type="DEFAULT_VEHTYPE" speed="13.89" pos="136.68" lane="VODUGES_end_0" slope="0.00"/> </timestep> <timestep time="118.00"/> </fcd-export>
{ "pile_set_name": "Github" }
/** * @file moduleFrechetShortcut.dox * @author Isabelle Sivignon (\c [email protected] ) * gipsa-lab Grenoble Images Parole Signal Automatique (CNRS, UMR 5216), CNRS, France * * @date 2012/11/15 * * Documentation file for feature moduleFrechetShortcut * * This file is part of the DGtal library. */ /* * Useful to avoid writing DGtal:: in front of every class. * Do not forget to add an entry in src/DGtal/base/Config.h.in ! */ namespace DGtal { //---------------------------------------- /*! @page moduleFrechetShortcut Fréchet Shortcuts @writers Isabelle Sivignon [TOC] \section FS_sectOverview Overview The algorithm implemented in the class FrechetShortcut is the one presented in the article @cite sivignon2011. We present here the basic ideas of the algorithm and at the end, give pointers to the relative structures used in the implementation. Given a polygonal curve, the curve simplification problem consists in computing another polygonal curve that (i) approximates the original curve, (ii) satisfies a given error criterion, (iii) with as few vertices as possible. This problem arises in a wide range of applications, such as geographic information systems (GIS), computer graphics or computer vision, where the management of the level of details is of crucial importance to save memory space or to speed-up analysis algorithms. Given a 4- or 8-connected digital curve and a maximum error, we propose an algorithm that computes a simplification of the curve (a polygonal curve) such that the Fréchet distance between the original and the simplified curve is less than the error. The Fréchet distance is known to nicely measure the similarity between two curves. It can be intuitively defined considering a man walking his dog. Each protagonist walks along a path, and controls its speed independently, but cannot go backwards. The Fréchet distance between the two pathes is the minimal length of the leash required. The algorithm implemented uses an approximation of the Fréchet distance, but a guarantee over the quality of the simplification is proved. Moreover, even if the theoretical complexity of the algorithm is in O(n log(n)), experiments show a linear behaviour in practice. \subsection subsectFrechet Fréchet distance Given two curves @f$ f @f$ and @f$ g @f$ specified by functions @f$ f:[0,1] \rightarrow \mathbb{R}^2 @f$ and @f$g:[0,1] \rightarrow \mathbb{R}^2 @f$, and two non-decreasing continuous functions @f$ \alpha:[0,1] \rightarrow [0,1] @f$ and @f$ \beta:[0,1] \rightarrow [0,1] @f$ with @f$ \alpha(0)=0,\alpha(1)=1,\beta(0)=0,\beta(1)=1 @f$, the **Fréchet distance** @f$ \delta_F(f,g) @f$ between two curves f and g is defined as @f$ \delta_F(f,g)=\inf_{\alpha,\beta} \max_{0\leq t \leq 1} d(f(\alpha(t)),g(\beta(t))) @f$ As illustrated in the figure below, contrary to the Hausdorff distance denoted by @f$ \delta_H(f,g) @f$, the Fréchet distance takes into account the course of the curves. @image html hausdorff.png "Difference between the Fréchet distance and the Hausdorff distance" @image latex hausdorff.png "Difference between the Fréchet distance and the Hausdorff distance" width=5cm \subsection subsectCurve Curve simplification problem Given a polygonal curve @f$ P=\langle p_1,\dots p_n\rangle @f$, A curve @f$ P'=\langle p_{i_1},\dots p_{i_k}\rangle @f$ with @f$ 1=i_1 < \dots < i_k=n @f$ is said to @b simplify the curve @f$ P @f$. @f$ P(i,j) @f$ denotes the subpath from @f$ p_i @f$ to @f$ p_j @f$. Given a pair of indices @f$ 1 \leq i \leq j \leq n @f$, @f$ \delta_F(p_ip_j,P) @f$ denotes the Fréchet distance between the segment @f$ p_ip_j @f$ and the part @f$ P(i,j) @f$ of the curve. For the sake of clarity, the simplified notation @f$ error(i,j) = \delta_F(p_ip_j,P) @f$ will sometimes be used. We also say that @f$ p_ip_j @f$ is a @b shortcut. In other words, the vertices of @f$ P' @f$ form a subset of the vertices of @f$ P @f$, and the computation of @f$ P' @f$ comes down to the selection of "shortcuts" @f$ p_ip_j @f$. @image html curve_simplification.png "The red curve P' is a simplification of the blue curve P" @image latex curve_simplification.png "The red curve P' is a simplification of the blue curve P" width=5cm All in all, to <b>find @f$ P' @f$ an @f$ \varepsilon @f$-simplification of</b> @f$ P @f$ we have to: -# <b>Find shortcuts @f$ p_ip_j @f$ such that @f$ error(i,j) = \delta_F(p_ip_j,P) \leq \varepsilon @f$</b> -# <b>Minimize the number of vertices of @f$ P' @f$</b>. The following nice local property of the Fréchet distance proved in @cite DBLP:journals/algorithmica/AgarwalHMW05 will be very useful to prove a guarantee on the quality of the result produced by our algorithm (see illustration below): Let @f$ P=\{p_1, p_2, \dots , p_n\} @f$ be a polygonal curve. \\ For all @f$ i, j, l, r, 1 \leq i\leq l \leq r \leq j \leq n @f$, @f$ error(l,r) \leq 2 error(i,j) @f$. In other words, the shortcuts of any @f$ \frac{\varepsilon}{2} @f$-simplification cannot strictly enclose the shortcuts of a @f$ \varepsilon @f$-simplification. @image html local.png "Illustration of the local property." @image latex local.png "Illustration of the local property." width=5cm \section FS_sectAlgo Guaranteed algorithm using an approximated distance \subsection FS_subsectDef Definitions and overall algorithm Using the exact Fréchet distance appears to be too expensive to design an efficient algorithm. Instead, we use an approximation of the Fréchet distance proposed in @cite Abam1247103. More precisely, they show that @f$error(i,j)@f$ can be upper and lower bounded by functions of two values namely @f$\omega(i,j)@f$ and @f$b(i,j)@f$. @f$\omega(i,j)@f$ is the width of the points of @f$P(i,j)@f$ in the direction @f$\overrightarrow{p_ip_j}@f$. @f$b(i,j)@f$ is the length of the longest backpath in the direction @f$\overrightarrow{p_ip_j}@f$. @image html def_width_backpath.png "Illustration of the definition of the width and the backpath length." @image latex def_width_backpath.png "Illustration of the definition of the width and the backpath length." @image html def_width_backpath_2.png "When a new point is considered, the width and backpath lengths may totally change." @image latex def_width_backpath_2.png "When a new point is considered, the width and backpath lengths may totally change." We have the following property from @cite Abam1247103 : The Fréchet error of a shortcut @f$p_ip_j@f$ satisfies: @image html approx_distance.png "" @image latex approx_distance.png "" Using this Fréchet distance approximation to greedily compute a shortcut requires a fast update of the quantities @f$\omega(i,j)@f$ and @f$b(i,j)@f$ when a new point is taken into account. This is not an easy task since these values can change drastically as illustrated above. \subsection subsectWidth Updating the width efficiently Instead of updating @f$\omega(i,j)@f$, it is enough to consider the maximal distance between any point of @f$P(i,j)@f$ and the vector @f$\overrightarrow{p_ip_j}@f$. This is done using the algorithm of Chan and Chin @cite Chan687965 illustrated below: Given an origin point @f$p_i"@f$ and a set of points @f$P(i,j)@f$ we construct the set @f$S_{ij}@f$ of straight lines @f$l@f$ going through @f$p_i@f$ such that @f$\max_{p \in P(i,j)}d(p,l) \leq r@f$. As a result, deciding whether @f$d_{max}(i,j)@f$ is lower than @f$r@f$ or not is equivalent to checking whether the straight line @f$(p_i,p_j)@f$ belongs to @f$S_{ij}@f$ or not. All in all, the update of the cone and the decision are both done in constant time. @image html update_width.png "The cone (dark gray) is computed incrementally as the intersection of the light gray cones." @image latex update_width.png "The cone (dark gray) is computed incrementally as the intersection of the light gray cones." \subsection subsectBackpath Updating the backpath length efficiently This update is trickier. When a new point @f$p_{j+1}@f$ is considered, we want to ckeck if there exists a backpath longer than a threshold in the direction @f$\overrightarrow{p_ip_j}@f$. Let us first give some definitions: @image html definition1.png "" @image latex definition1.png "" To do so, we consider a set of points named *occulters* which are the furthest points for a given direction: @image html definition_occulter.png "" @image latex definition_occulter.png "" We can prove easily (see @cite sivignon2011) that the origin of the longest backpath is an occulter. @image html occulters.png "Occulters for the direction @e d in red. Green arrows represent backpathes: the length of the plain arrows is to be checked, whereas we know that the backpathes represented by dashed arrows are not the longest ones." @image latex occulters.png "Occulters for the direction @e d in red. Green arrows represent backpathes: the length of the plain arrows is to be checked, whereas we know that the backpathes represented by dashed arrows are not the longest ones." Considering whether the last movement @f$\overrightarrow{p_jp_{j+1}}@f$ is forward or backward in the direction @f$\overrightarrow{p_ip_j}@f$, we can decide if there is a new backpath possibly longer than the threshold or not. This is done according to Algorithm 2 below. @image html algo2.png "" @image latex algo2.png "" According to Algorithm 1 we see that Algorithm 2 must be applied for any possible direction for a given curve @f$P@f$, which is computationally expensive. However, the computation of backpathes can be mutualized in the case of digital curves. Indeed for a digital curve, the set of elementary shifts @f$\overrightarrow{p_jp_{j+1}}@f$ is well defined and it is actually possible to cluster the set of directions such that given an elementary shift @f$e@f$, this shift is either forward (positive) or backward (negative) for all the directions of the cluster. @image html clusters.png "Left: The directions of the plane are clustered into 8 octants. For instance, direction @e d is in octant 0. Right: Illustration of the positive (or forward) elementary shifts for each octant." @image latex clusters.png "Left: The directions of the plane are clustered into 8 octants. For instance, direction @e d is in octant 0. Right: Illustration of the positive (or forward) elementary shifts for each octant." If we now go back to Algorithm 2, we see that the result of the test lines 2-3 is the same for all the directions of a given octant. This test can thus be done jointly for all the directions of an octant. Nevertheless, to determine if a new point @f$p_k@f$ is the new active occulter (the furthest point for the direction studied), the projection of the current active occulter and the point @f$p_k@f$ on a direction are compared: the furthest of the two points is the active occulter. There, for any two points @f$p_k@f$ and @f$q@f$ the result of this comparison is not the same for all the directions of a given octant. This fact is illustrated in the figures below for the octant @f$0@f$: * for any point @f$q@f$ in the grey area, and for any direction in octant @f$0@f$, @f$q@f$ is after @f$p@f$. * for any point @f$q@f$ in the dashed area, and for any direction in octant @f$0@f$, @f$p@f$ is after @f$q@f$. * in the white area, the order changes, as illustrated below. @image html zones.png "" @image latex zones.png "" @image html ordre_projections.png "For two points @e p and @e q and a direction @e &alpha;: on the left, @e q is @e after @e p, and is the active occulter for direction @e &alpha;, whereas on the right, @e p is after @e q and is the active occulter." @image latex ordre_projections.png "For two points @e p and @e q and a direction @e &alpha;: on the left, @e q is @e after @e p, and is the active occulter for direction @e &alpha;, whereas on the right, @e p is after @e q and is the active occulter." Algorithm 3 below puts together these observations to update the list of active occulters for one octant. @image html algo3.png "" @image latex algo3.png "" \subsection subsectDirections Memorizing the directions for which there exists a too long backpath From Algorithm 1, we see that the length of the longest backpath is tested for each new point, which defines a new direction. Moreover, we see from Algorithm 2 line 6 that for each negative shift, we can have as many backpathes as active occulters. All in all, testing individually all the possible backpathes when a new point is added is too expensive. To solve this problem, we propose to maintain a ``set'' of the directions for which there exists a backpath of length greater than the error @f$\varepsilon@f$. This set actually consists in a list of intervals: for a given backpath of length *l* and a given error @f$\varepsilon@f$, the interval of directions for which the projection of the backpath is longer than @f$\varepsilon@f$ is computed easily. The union of all these intervals is stored. \section sectQuality Quality of the result and complexity analysis \subsection subsectGuarantee A guaranteed algorithm An important issue when designing an algorithm that is known not to be optimal is to prove that the result of this algorithm is not so far from the optimal. In this work, the optimal solution is to compute the @f$\varepsilon@f$-simplification of a digital curve P according to the Fréchet distance with a minimum number of vertices. The algorithm we propose here is not optimal for two reasons: * it is greedy: the simplification is computed from a given starting point, in a given scanning order. * the distance used is an approximation of the Fréchet distance. However, we prove that the number of vertices of the simplified curve computed by our algorithm is upper bounded by a function of the optimal solution: @image html lemma3.png "" @image latex lemma3.png "" For more details about this proof, please refer to @cite sivignon2011. \subsection subsectComplexity Complexity The theoretical complexity of this algorithm is @f$\mathcal{O}(n\log(n_i))@f$, for a digital curve of @f$n@f$ points. @f$n_i@f$ is the number of intervals used to store the directions for which there exist a backpath of length greater than the error. @f$n_i@f$ is upper bounded by @f$n@f$. Nevertheless, experiments on noisy shapes show that the general behaviour of the algorithm in linear in time. \section FS_sectImplementation Implementation in DGtal In DGtal, the FrechetShortcut should be used with a Curve object, using its PointsRange, as in the example below: @snippet geometry/curves/exampleFrechetShortcut.cpp FrechetShortcutUsage The function FrechetShortcut::extendFront() is called when a new point is added to the current shortcut. It calls FrechetShortcut::updateWidth() and FrechetShortcut::updateBackpath(). The function FrechetShortcut::updateWidth() implements the update of the width @f$\omega(i,j)@f$ and uses the subclass FrechetShortcut::Cone for the cone definition and manipulation. The length of the longest backpath is managed in the function FrechetShortcut::updateBackpath(). It updates a vector of $8$ backpaths, one per each octant. The subclass FrechetShortcut::Backpath contains all the necessary structures - FrechetShortcut::Backpath::myQuad is the octant number - FrechetShortcut::Backpath::myOcculters is the list of occulters - FrechetShortcut::Backpath::addPositivePoint() is called when the next elementary move is forward for the octant - FrechetShortcut::Backpath::addNegativePoint() is called when the next elementary move is backward for the octant: it implements Algorithm 2 and calls updateOcculters() - FrechetShortcut::Backpath::updateOcculters() implements Algorithm 3 - the list of interval used to memorize the directions for which there exist a too long backpath is implemented through FrechetShortcut::Backpath::myForbiddenIntervals using the Boost Interval Container Library (http://www.boost.org/doc/libs/1_52_0/libs/icl). It is updated with the function FrechetShortcut::Backpath::updateIntervals(). An output using the Board mecanism is provided (see example above to output an eps file). */ }
{ "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 mips64 mips64le #include "textflag.h" TEXT ·Asin(SB),NOSPLIT,$0 JMP ·asin(SB) TEXT ·Acos(SB),NOSPLIT,$0 JMP ·acos(SB) TEXT ·Asinh(SB),NOSPLIT,$0 JMP ·asinh(SB) TEXT ·Acosh(SB),NOSPLIT,$0 JMP ·acosh(SB) TEXT ·Atan2(SB),NOSPLIT,$0 JMP ·atan2(SB) TEXT ·Atan(SB),NOSPLIT,$0 JMP ·atan(SB) TEXT ·Atanh(SB),NOSPLIT,$0 JMP ·atanh(SB) TEXT ·Min(SB),NOSPLIT,$0 JMP ·min(SB) TEXT ·Max(SB),NOSPLIT,$0 JMP ·max(SB) TEXT ·Erf(SB),NOSPLIT,$0 JMP ·erf(SB) TEXT ·Erfc(SB),NOSPLIT,$0 JMP ·erfc(SB) TEXT ·Exp2(SB),NOSPLIT,$0 JMP ·exp2(SB) TEXT ·Expm1(SB),NOSPLIT,$0 JMP ·expm1(SB) TEXT ·Exp(SB),NOSPLIT,$0 JMP ·exp(SB) TEXT ·Floor(SB),NOSPLIT,$0 JMP ·floor(SB) TEXT ·Ceil(SB),NOSPLIT,$0 JMP ·ceil(SB) TEXT ·Trunc(SB),NOSPLIT,$0 JMP ·trunc(SB) TEXT ·Frexp(SB),NOSPLIT,$0 JMP ·frexp(SB) TEXT ·Hypot(SB),NOSPLIT,$0 JMP ·hypot(SB) TEXT ·Ldexp(SB),NOSPLIT,$0 JMP ·ldexp(SB) TEXT ·Log10(SB),NOSPLIT,$0 JMP ·log10(SB) TEXT ·Log2(SB),NOSPLIT,$0 JMP ·log2(SB) TEXT ·Log1p(SB),NOSPLIT,$0 JMP ·log1p(SB) TEXT ·Log(SB),NOSPLIT,$0 JMP ·log(SB) TEXT ·Modf(SB),NOSPLIT,$0 JMP ·modf(SB) TEXT ·Mod(SB),NOSPLIT,$0 JMP ·mod(SB) TEXT ·Remainder(SB),NOSPLIT,$0 JMP ·remainder(SB) TEXT ·Sin(SB),NOSPLIT,$0 JMP ·sin(SB) TEXT ·Sinh(SB),NOSPLIT,$0 JMP ·sinh(SB) TEXT ·Cos(SB),NOSPLIT,$0 JMP ·cos(SB) TEXT ·Cosh(SB),NOSPLIT,$0 JMP ·cosh(SB) TEXT ·Sqrt(SB),NOSPLIT,$0 JMP ·sqrt(SB) TEXT ·Tan(SB),NOSPLIT,$0 JMP ·tan(SB) TEXT ·Tanh(SB),NOSPLIT,$0 JMP ·tanh(SB) TEXT ·Cbrt(SB),NOSPLIT,$0 JMP ·cbrt(SB) TEXT ·Pow(SB),NOSPLIT,$0 JMP ·pow(SB)
{ "pile_set_name": "Github" }
using Util.Ui.Angular.Base; using Util.Ui.Builders; using Util.Ui.Configs; using Util.Ui.Material.Panels.Builders; namespace Util.Ui.Material.Panels.Renders { /// <summary> /// 手风琴渲染器 /// </summary> public class AccordionRender : AngularRenderBase { /// <summary> /// 配置 /// </summary> private readonly IConfig _config; /// <summary> /// 初始化手风琴渲染器 /// </summary> /// <param name="config">配置</param> public AccordionRender( IConfig config ) : base( config ) { _config = config; } /// <summary> /// 获取标签生成器 /// </summary> protected override TagBuilder GetTagBuilder() { var builder = new AccordionBuilder(); Config( builder ); return builder; } /// <summary> /// 配置 /// </summary> protected void Config( TagBuilder builder ) { ConfigId( builder ); ConfigMultiple( builder ); ConfigDisplayMode( builder ); ConfigContent( builder ); } /// <summary> /// 配置多展开状态 /// </summary> private void ConfigMultiple( TagBuilder builder ) { builder.AddAttribute( "multi", _config.GetBoolValue( UiConst.Multiple ) ); } /// <summary> /// 配置显示模式 /// </summary> private void ConfigDisplayMode( TagBuilder builder ) { builder.AddAttribute( "displayMode", _config.GetBoolValue( MaterialConst.DisplayMode ) ); } } }
{ "pile_set_name": "Github" }
// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: [email protected] (Zhanyong Wan) #include <gtest/internal/gtest-tuple.h> #include <utility> #include <gtest/gtest.h> namespace { using ::std::tr1::get; using ::std::tr1::make_tuple; using ::std::tr1::tuple; using ::std::tr1::tuple_element; using ::std::tr1::tuple_size; using ::testing::StaticAssertTypeEq; // Tests that tuple_element<K, tuple<T0, T1, ..., TN> >::type returns TK. TEST(tuple_element_Test, ReturnsElementType) { StaticAssertTypeEq<int, tuple_element<0, tuple<int, char> >::type>(); StaticAssertTypeEq<int&, tuple_element<1, tuple<double, int&> >::type>(); StaticAssertTypeEq<bool, tuple_element<2, tuple<double, int, bool> >::type>(); } // Tests that tuple_size<T>::value gives the number of fields in tuple // type T. TEST(tuple_size_Test, ReturnsNumberOfFields) { EXPECT_EQ(0, +tuple_size<tuple<> >::value); EXPECT_EQ(1, +tuple_size<tuple<void*> >::value); EXPECT_EQ(1, +tuple_size<tuple<char> >::value); EXPECT_EQ(1, +(tuple_size<tuple<tuple<int, double> > >::value)); EXPECT_EQ(2, +(tuple_size<tuple<int&, const char> >::value)); EXPECT_EQ(3, +(tuple_size<tuple<char*, void, const bool&> >::value)); } // Tests comparing a tuple with itself. TEST(ComparisonTest, ComparesWithSelf) { const tuple<int, char, bool> a(5, 'a', false); EXPECT_TRUE(a == a); EXPECT_FALSE(a != a); } // Tests comparing two tuples with the same value. TEST(ComparisonTest, ComparesEqualTuples) { const tuple<int, bool> a(5, true), b(5, true); EXPECT_TRUE(a == b); EXPECT_FALSE(a != b); } // Tests comparing two different tuples that have no reference fields. TEST(ComparisonTest, ComparesUnequalTuplesWithoutReferenceFields) { typedef tuple<const int, char> FooTuple; const FooTuple a(0, 'x'); const FooTuple b(1, 'a'); EXPECT_TRUE(a != b); EXPECT_FALSE(a == b); const FooTuple c(1, 'b'); EXPECT_TRUE(b != c); EXPECT_FALSE(b == c); } // Tests comparing two different tuples that have reference fields. TEST(ComparisonTest, ComparesUnequalTuplesWithReferenceFields) { typedef tuple<int&, const char&> FooTuple; int i = 5; const char ch = 'a'; const FooTuple a(i, ch); int j = 6; const FooTuple b(j, ch); EXPECT_TRUE(a != b); EXPECT_FALSE(a == b); j = 5; const char ch2 = 'b'; const FooTuple c(j, ch2); EXPECT_TRUE(b != c); EXPECT_FALSE(b == c); } // Tests that a tuple field with a reference type is an alias of the // variable it's supposed to reference. TEST(ReferenceFieldTest, IsAliasOfReferencedVariable) { int n = 0; tuple<bool, int&> t(true, n); n = 1; EXPECT_EQ(n, get<1>(t)) << "Changing a underlying variable should update the reference field."; // Makes sure that the implementation doesn't do anything funny with // the & operator for the return type of get<>(). EXPECT_EQ(&n, &(get<1>(t))) << "The address of a reference field should equal the address of " << "the underlying variable."; get<1>(t) = 2; EXPECT_EQ(2, n) << "Changing a reference field should update the underlying variable."; } // Tests tuple's default constructor. TEST(TupleConstructorTest, DefaultConstructor) { // We are just testing that the following compiles. tuple<> empty; tuple<int> one_field; tuple<double, char, bool*> three_fields; } // Tests constructing a tuple from its fields. TEST(TupleConstructorTest, ConstructsFromFields) { int n = 1; // Reference field. tuple<int&> a(n); EXPECT_EQ(&n, &(get<0>(a))); // Non-reference fields. tuple<int, char> b(5, 'a'); EXPECT_EQ(5, get<0>(b)); EXPECT_EQ('a', get<1>(b)); // Const reference field. const int m = 2; tuple<bool, const int&> c(true, m); EXPECT_TRUE(get<0>(c)); EXPECT_EQ(&m, &(get<1>(c))); } // Tests tuple's copy constructor. TEST(TupleConstructorTest, CopyConstructor) { tuple<double, bool> a(0.0, true); tuple<double, bool> b(a); EXPECT_DOUBLE_EQ(0.0, get<0>(b)); EXPECT_TRUE(get<1>(b)); } // Tests constructing a tuple from another tuple that has a compatible // but different type. TEST(TupleConstructorTest, ConstructsFromDifferentTupleType) { tuple<int, int, char> a(0, 1, 'a'); tuple<double, long, int> b(a); EXPECT_DOUBLE_EQ(0.0, get<0>(b)); EXPECT_EQ(1, get<1>(b)); EXPECT_EQ('a', get<2>(b)); } // Tests constructing a 2-tuple from an std::pair. TEST(TupleConstructorTest, ConstructsFromPair) { ::std::pair<int, char> a(1, 'a'); tuple<int, char> b(a); tuple<int, const char&> c(a); } // Tests assigning a tuple to another tuple with the same type. TEST(TupleAssignmentTest, AssignsToSameTupleType) { const tuple<int, long> a(5, 7L); tuple<int, long> b; b = a; EXPECT_EQ(5, get<0>(b)); EXPECT_EQ(7L, get<1>(b)); } // Tests assigning a tuple to another tuple with a different but // compatible type. TEST(TupleAssignmentTest, AssignsToDifferentTupleType) { const tuple<int, long, bool> a(1, 7L, true); tuple<long, int, bool> b; b = a; EXPECT_EQ(1L, get<0>(b)); EXPECT_EQ(7, get<1>(b)); EXPECT_TRUE(get<2>(b)); } // Tests assigning an std::pair to a 2-tuple. TEST(TupleAssignmentTest, AssignsFromPair) { const ::std::pair<int, bool> a(5, true); tuple<int, bool> b; b = a; EXPECT_EQ(5, get<0>(b)); EXPECT_TRUE(get<1>(b)); tuple<long, bool> c; c = a; EXPECT_EQ(5L, get<0>(c)); EXPECT_TRUE(get<1>(c)); } // A fixture for testing big tuples. class BigTupleTest : public testing::Test { protected: typedef tuple<int, int, int, int, int, int, int, int, int, int> BigTuple; BigTupleTest() : a_(1, 0, 0, 0, 0, 0, 0, 0, 0, 2), b_(1, 0, 0, 0, 0, 0, 0, 0, 0, 3) {} BigTuple a_, b_; }; // Tests constructing big tuples. TEST_F(BigTupleTest, Construction) { BigTuple a; BigTuple b(b_); } // Tests that get<N>(t) returns the N-th (0-based) field of tuple t. TEST_F(BigTupleTest, get) { EXPECT_EQ(1, get<0>(a_)); EXPECT_EQ(2, get<9>(a_)); // Tests that get() works on a const tuple too. const BigTuple a(a_); EXPECT_EQ(1, get<0>(a)); EXPECT_EQ(2, get<9>(a)); } // Tests comparing big tuples. TEST_F(BigTupleTest, Comparisons) { EXPECT_TRUE(a_ == a_); EXPECT_FALSE(a_ != a_); EXPECT_TRUE(a_ != b_); EXPECT_FALSE(a_ == b_); } TEST(MakeTupleTest, WorksForScalarTypes) { tuple<bool, int> a; a = make_tuple(true, 5); EXPECT_TRUE(get<0>(a)); EXPECT_EQ(5, get<1>(a)); tuple<char, int, long> b; b = make_tuple('a', 'b', 5); EXPECT_EQ('a', get<0>(b)); EXPECT_EQ('b', get<1>(b)); EXPECT_EQ(5, get<2>(b)); } TEST(MakeTupleTest, WorksForPointers) { int a[] = { 1, 2, 3, 4 }; const char* const str = "hi"; int* const p = a; tuple<const char*, int*> t; t = make_tuple(str, p); EXPECT_EQ(str, get<0>(t)); EXPECT_EQ(p, get<1>(t)); } } // namespace
{ "pile_set_name": "Github" }
import { shallowMount } from '@vue/test-utils' import AvatarWrapper from './AvatarWrapper' describe('AvatarWrapper.vue', () => { it('Renders user avatars properly', () => { const wrapper = shallowMount(AvatarWrapper, { propsData: { id: 'test-id', source: 'users', name: 'test-name', }, }) expect(wrapper.vm.iconClass).toBe('') // Check that the first child is the avatar component expect(wrapper.element.firstChild.nodeName).toBe('AVATAR-STUB') expect(wrapper.props().size).toBe(32) }) it('Renders group icons properly', () => { const wrapper = shallowMount(AvatarWrapper, { propsData: { id: '', source: 'groups', name: '', }, }) expect(wrapper.vm.iconClass).toBe('icon-contacts') // Check that the first child is a div expect(wrapper.element.firstChild.nodeName).toBe('DIV') }) it('Renders email icons properly', () => { const wrapper = shallowMount(AvatarWrapper, { propsData: { id: '', source: 'emails', name: '', }, }) expect(wrapper.vm.iconClass).toBe('icon-mail') // Check that the first child is a div expect(wrapper.element.firstChild.nodeName).toBe('DIV') // proper size expect(wrapper.element.firstChild.classList).toContain('avatar-32px') }) it('Renders guests icons properly', () => { const wrapper = shallowMount(AvatarWrapper, { propsData: { id: '', name: '', size: 24, }, }) expect(wrapper.element.firstChild.classList).toContain('guest') expect(wrapper.element.firstChild.nodeName).toBe('DIV') // proper size expect(wrapper.element.firstChild.classList).toContain('avatar-24px') }) })
{ "pile_set_name": "Github" }
import argparse import gzip import hashlib import logging import os.path import pkgutil import platform from typing import List, Iterable import numpy as np from joblib import Parallel, delayed from guacamol.utils.chemistry import canonicalize_list, filter_and_canonicalize, \ initialise_neutralisation_reactions, split_charged_mol, get_fingerprints_from_smileslist from guacamol.utils.data import download_if_not_present from guacamol.utils.helpers import setup_default_logger logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) TRAIN_HASH = '05ad85d871958a05c02ab51a4fde8530' VALID_HASH = 'e53db4bff7dc4784123ae6df72e3b1f0' TEST_HASH = '677b757ccec4809febd83850b43e1616' CHEMBL_URL = 'ftp://ftp.ebi.ac.uk/pub/databases/chembl/ChEMBLdb/releases/chembl_24_1/chembl_24_1_chemreps.txt.gz' CHEMBL_FILE_NAME = 'chembl_24_1_chemreps.txt.gz' # Threshold to remove molecules too similar to the holdout set TANIMOTO_CUTOFF = 0.323 def get_argparser(): parser = argparse.ArgumentParser(description='Data Preparation for GuacaMol', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-o', '--destination', default='.', help='Download and Output location') parser.add_argument('--n_jobs', default=8, type=int, help='Number of cores to use') return parser def extract_chembl(line) -> str: """ Extract smiles from chembl tsv Returns: SMILES string """ return line.split('\t')[1] def extract_smilesfile(line) -> str: """ Extract smiles from SMILES file Returns: SMILES string """ return line.split(' ')[0].strip() class AllowedSmilesCharDictionary(object): """ A fixed dictionary for druglike SMILES. """ def __init__(self) -> None: self.forbidden_symbols = {'Ag', 'Al', 'Am', 'Ar', 'At', 'Au', 'D', 'E', 'Fe', 'G', 'K', 'L', 'M', 'Ra', 'Re', 'Rf', 'Rg', 'Rh', 'Ru', 'T', 'U', 'V', 'W', 'Xe', 'Y', 'Zr', 'a', 'd', 'f', 'g', 'h', 'k', 'm', 'si', 't', 'te', 'u', 'v', 'y'} def allowed(self, smiles: str) -> bool: """ Determine if SMILES string has illegal symbols Args: smiles: SMILES string Returns: True if all legal """ for symbol in self.forbidden_symbols: if symbol in smiles: print('Forbidden symbol {:<2} in {}'.format(symbol, smiles)) return False return True def get_raw_smiles(file_name, smiles_char_dict, open_fn, extract_fn) -> List[str]: """ Extracts the raw smiles from an input file. open_fn will open the file to iterate over it (e.g. use open_fn=open or open_fn=filegzip.open) extract_fn specifies how to process the lines, choose from Pre-filter molecules of 5 <= length <= 200, because processing larger molecules (e.g. peptides) takes very long. Returns: a list of SMILES strings """ data = [] # open the gzipped chembl filegzip.open with open_fn(file_name, 'rt') as f: line_count = 0 for line in f: line_count += 1 # extract the canonical smiles column if platform.system() == "Windows": line = line.decode("utf-8") # smiles = line.split('\t')[1] smiles = extract_fn(line) # only keep reasonably sized molecules if 5 <= len(smiles) <= 200: smiles = split_charged_mol(smiles) if smiles_char_dict.allowed(smiles): # check whether the molecular graph consists of # multiple connected components (eg. in salts) # if so, just keep the largest one data.append(smiles) print(f'Processed {line_count} lines.') return data def write_smiles(dataset: Iterable[str], filename: str): """ Dumps a list of SMILES into a file, one per line """ n_lines = 0 with open(filename, 'w') as out: for smiles_str in dataset: out.write('%s\n' % smiles_str) n_lines += 1 print(f'{filename} contains {n_lines} molecules') def compare_hash(output_file: str, correct_hash: str) -> bool: """ Computes the md5 hash of a SMILES file and check it against a given one Returns false if hashes are different """ output_hash = hashlib.md5(open(output_file, 'rb').read()).hexdigest() if output_hash != correct_hash: logger.error(f'{output_file} file has different hash, {output_hash}, than expected, {correct_hash}!') return False return True def main(): """ Get Chembl-23. Preprocessing steps: 1) filter SMILES shorter than 5 and longer than 200 chars and those with forbidden symbols 2) canonicalize, neutralize, only permit smiles shorter than 100 chars 3) shuffle, write files, check if they are consistently hashed. """ setup_default_logger() argparser = get_argparser() args = argparser.parse_args() # Set constants np.random.seed(1337) neutralization_rxns = initialise_neutralisation_reactions() smiles_dict = AllowedSmilesCharDictionary() print('Preprocessing ChEMBL molecules...') chembl_file = os.path.join(args.destination, CHEMBL_FILE_NAME) data = pkgutil.get_data('guacamol.data', 'holdout_set_gcm_v1.smiles').decode('utf-8').splitlines() holdout_mols = [i.split(' ')[0] for i in data] holdout_set = set(canonicalize_list(holdout_mols, False)) holdout_fps = get_fingerprints_from_smileslist(holdout_set) # Download Chembl23 if needed. download_if_not_present(chembl_file, uri=CHEMBL_URL) raw_smiles = get_raw_smiles(chembl_file, smiles_char_dict=smiles_dict, open_fn=gzip.open, extract_fn=extract_chembl) file_prefix = 'chembl24_canon' print(f'and standardizing {len(raw_smiles)} molecules using {args.n_jobs} cores, ' f'and excluding molecules based on ECFP4 similarity of > {TANIMOTO_CUTOFF} to the holdout set.') # Process all the SMILES in parallel runner = Parallel(n_jobs=args.n_jobs, verbose=2) joblist = (delayed(filter_and_canonicalize)(smiles_str, holdout_set, holdout_fps, neutralization_rxns, TANIMOTO_CUTOFF, False) for smiles_str in raw_smiles) output = runner(joblist) # Put all nonzero molecules in a list, remove duplicates, sort and shuffle all_good_mols = sorted(list(set([item[0] for item in output if item]))) np.random.shuffle(all_good_mols) print(f'Ended up with {len(all_good_mols)} molecules. Preparing splits...') # Split into train-dev-test # Check whether the md5-hashes of the generated smiles files match # the precomputed hashes, this ensures everyone works with the same splits. VALID_SIZE = int(0.05 * len(all_good_mols)) TEST_SIZE = int(0.15 * len(all_good_mols)) dev_set = all_good_mols[0:VALID_SIZE] dev_path = os.path.join(args.destination, f'{file_prefix}_dev-valid.smiles') write_smiles(dev_set, dev_path) test_set = all_good_mols[VALID_SIZE:VALID_SIZE + TEST_SIZE] test_path = os.path.join(args.destination, f'{file_prefix}_test.smiles') write_smiles(test_set, test_path) train_set = all_good_mols[VALID_SIZE + TEST_SIZE:] train_path = os.path.join(args.destination, f'{file_prefix}_train.smiles') write_smiles(train_set, train_path) # check the hashes valid_hashes = [ compare_hash(train_path, TRAIN_HASH), compare_hash(dev_path, VALID_HASH), compare_hash(test_path, TEST_HASH), ] if not all(valid_hashes): raise SystemExit(f'Invalid hashes for the dataset files') print('Dataset generation successful. You are ready to go.') if __name__ == '__main__': main()
{ "pile_set_name": "Github" }
# Please don't modify this file as your changes might be overwritten with # the next update. # {% if helpers.exists('OPNsense.Rspamd.general.enabled') and OPNsense.Rspamd.general.enabled == '1' and helpers.exists('OPNsense.Rspamd.general.enable_bayes_autolearn') %} {% if helpers.exists('OPNsense.Rspamd.general.enable_bayes_autolearn') and OPNsense.Rspamd.general.enable_bayes_autolearn == '1' %} autolearn = true; {% endif %} {% endif %}
{ "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. #ifndef PPAPI_TESTS_TEST_RESOURCE_ARRAY_H_ #define PPAPI_TESTS_TEST_RESOURCE_ARRAY_H_ #include <string> #include "ppapi/tests/test_case.h" class TestResourceArray : public TestCase { public: explicit TestResourceArray(TestingInstance* instance); virtual ~TestResourceArray(); // TestCase implementation. virtual void RunTests(const std::string& test_filter); private: std::string TestBasics(); std::string TestOutOfRangeAccess(); std::string TestEmptyArray(); std::string TestInvalidElement(); }; #endif // PPAPI_TESTS_TEST_RESOURCE_ARRAY_H_
{ "pile_set_name": "Github" }
/* * Copyright 2020 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.run.tasks; import com.android.tools.idea.run.LaunchOptions; import com.google.common.collect.ImmutableMap; import com.intellij.openapi.project.Project; import java.io.File; import java.util.List; /** Compat class for {@link DeployTask} */ public class DeployTasksCompat { private DeployTasksCompat() {} // #api4.0 : Constructor signature changed in 4.1 public static LaunchTask createDeployTask( Project project, ImmutableMap<String, List<File>> filesToInstall, LaunchOptions launchOptions) { return new DeployTask(project, filesToInstall, launchOptions.getPmInstallOptions()); } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <!-- Arcana by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) --> <html> <head> <title>夸夸大本营</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="../assets/css/main.css" /> </head> <body class="is-preload"> <div id="page-wrapper"> <!-- Header --> <div id="header"> <!-- Logo --> <h1><a href="../index.html" id="logo">夸夸世界 <em>人生赢家</em></a></h1> <!-- Nav --> <nav id="nav"> <ul> <li><a href="../index.html">Home</a></li> <li> <a href="#">夸夸赢家实用资料</a> <ul> <li><a href="toefl.html">托福</a></li> <li><a href="ielts.html">雅思</a></li> <li><a href="greandgmat.html">GRE and GMAT</a></li> </ul> </li> <li class="current"><a href="main_sugesstion.html">备考建议区</a></li> <li><a href="qqgroup.html">学霸qq群</a></li> <li><a href="friends.html">夸夸群友互助计划</a></li> <li><a href="https://github.com/Jackwire/Jackwire.github.io">Github原址</a></li> </ul> </nav> </div> <!-- Main --> <section class="wrapper style1"> <div class="container"> <div id="content"> <!-- Content --> <article> <header> <h2>群友考试升学经验帖</h2> </header> <li><a href="https://github.com/Jackwire/Jackwire.github.io/blob/master/files/sugestions/toefl1.md">72-108!托福提分攻略全揭秘&新政首考体验&机构选择</a></li> </article> </div> </div> </section> <!-- Footer --> <div id="footer"> <!-- Copyright --> <div class="copyright"> <ul class="menu"> <li>&copy; 夸夸先生设计</li><li><a href="#">在此致敬</a></li> </ul> </div> </div> </div> <!-- Scripts --> <script src="../assets/js/jquery.min.js"></script> <script src="../assets/js/jquery.dropotron.min.js"></script> <script src="../assets/js/browser.min.js"></script> <script src="../assets/js/breakpoints.min.js"></script> <script src="../assets/js/util.js"></script> <script src="../assets/js/main.js"></script> </body> </html>
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Gael Guennebaud <[email protected]> // Copyright (C) 2009 Hauke Heibel <[email protected]> // // 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/. #ifndef EIGEN_STDVECTOR_MODULE_H #define EIGEN_STDVECTOR_MODULE_H #include "Core" #include <vector> #if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ #define EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(...) #else #include "src/StlSupport/StdVector.h" #endif #endif // EIGEN_STDVECTOR_MODULE_H
{ "pile_set_name": "Github" }