code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_12) on Sun Feb 08 17:24:27 PST 2009 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> CompilationUnit (PMD 4.2.5 API) </TITLE> <META NAME="date" CONTENT="2009-02-08"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="CompilationUnit (PMD 4.2.5 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/CompilationUnit.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../net/sourceforge/pmd/ast/Comment.html" title="class in net.sourceforge.pmd.ast"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../net/sourceforge/pmd/ast/Dimensionable.html" title="interface in net.sourceforge.pmd.ast"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?net/sourceforge/pmd/ast/CompilationUnit.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CompilationUnit.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;METHOD</FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> net.sourceforge.pmd.ast</FONT> <BR> Interface CompilationUnit</H2> <DL> <DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../net/sourceforge/pmd/ast/ASTCompilationUnit.html" title="class in net.sourceforge.pmd.ast">ASTCompilationUnit</A>, <A HREF="../../../../net/sourceforge/pmd/jsp/ast/ASTCompilationUnit.html" title="class in net.sourceforge.pmd.jsp.ast">ASTCompilationUnit</A></DD> </DL> <HR> <DL> <DT><PRE>public interface <B>CompilationUnit</B></DL> </PRE> <P> Marker interface for root nodes of the AST of compilation units in source files. <P> <P> <DL> <DT><B>Author:</B></DT> <DD>pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be</DD> </DL> <HR> <P> <P> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/CompilationUnit.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../net/sourceforge/pmd/ast/Comment.html" title="class in net.sourceforge.pmd.ast"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../net/sourceforge/pmd/ast/Dimensionable.html" title="interface in net.sourceforge.pmd.ast"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?net/sourceforge/pmd/ast/CompilationUnit.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CompilationUnit.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;METHOD</FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2002-2009 InfoEther. All Rights Reserved. </BODY> </HTML>
deleidos/digitaledge-platform
commons/buildtools/pmd/docs/apidocs/net/sourceforge/pmd/ast/CompilationUnit.html
HTML
apache-2.0
7,494
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Tue Feb 06 09:38:12 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>SecurityManagerSupplier (BOM: * : All 2017.10.2 API)</title> <meta name="date" content="2018-02-06"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="SecurityManagerSupplier (BOM: * : All 2017.10.2 API)"; } } catch(err) { } //--> var methods = {"i0":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/SecurityManagerSupplier.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.10.2</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/wildfly/swarm/config/SecurityManagerConsumer.html" title="interface in org.wildfly.swarm.config"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/wildfly/swarm/config/SecuritySupplier.html" title="interface in org.wildfly.swarm.config"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/wildfly/swarm/config/SecurityManagerSupplier.html" target="_top">Frames</a></li> <li><a href="SecurityManagerSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.wildfly.swarm.config</div> <h2 title="Interface SecurityManagerSupplier" class="title">Interface SecurityManagerSupplier&lt;T extends <a href="../../../../org/wildfly/swarm/config/SecurityManager.html" title="class in org.wildfly.swarm.config">SecurityManager</a>&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Functional Interface:</dt> <dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd> </dl> <hr> <br> <pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a> public interface <span class="typeNameLabel">SecurityManagerSupplier&lt;T extends <a href="../../../../org/wildfly/swarm/config/SecurityManager.html" title="class in org.wildfly.swarm.config">SecurityManager</a>&gt;</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../../../org/wildfly/swarm/config/SecurityManager.html" title="class in org.wildfly.swarm.config">SecurityManager</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/wildfly/swarm/config/SecurityManagerSupplier.html#get--">get</a></span>()</code> <div class="block">Constructed instance of SecurityManager resource</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="get--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>get</h4> <pre><a href="../../../../org/wildfly/swarm/config/SecurityManager.html" title="class in org.wildfly.swarm.config">SecurityManager</a>&nbsp;get()</pre> <div class="block">Constructed instance of SecurityManager resource</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>The instance</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/SecurityManagerSupplier.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.10.2</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/wildfly/swarm/config/SecurityManagerConsumer.html" title="interface in org.wildfly.swarm.config"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/wildfly/swarm/config/SecuritySupplier.html" title="interface in org.wildfly.swarm.config"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/wildfly/swarm/config/SecurityManagerSupplier.html" target="_top">Frames</a></li> <li><a href="SecurityManagerSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2017.10.2/apidocs/org/wildfly/swarm/config/SecurityManagerSupplier.html
HTML
apache-2.0
9,099
# Aplectrum viminale Blume SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Diplectria/Aplectrum viminale/README.md
Markdown
apache-2.0
174
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/elasticloadbalancing/ElasticLoadBalancing_EXPORTS.h> #include <aws/elasticloadbalancing/ElasticLoadBalancingRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/elasticloadbalancing/model/Instance.h> #include <utility> namespace Aws { namespace ElasticLoadBalancing { namespace Model { /** * <p>Contains the parameters for DescribeInstanceHealth.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancing-2012-06-01/DescribeEndPointStateInput">AWS * API Reference</a></p> */ class AWS_ELASTICLOADBALANCING_API DescribeInstanceHealthRequest : public ElasticLoadBalancingRequest { public: DescribeInstanceHealthRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DescribeInstanceHealth"; } Aws::String SerializePayload() const override; protected: void DumpBodyToUrl(Aws::Http::URI& uri ) const override; public: /** * <p>The name of the load balancer.</p> */ inline const Aws::String& GetLoadBalancerName() const{ return m_loadBalancerName; } /** * <p>The name of the load balancer.</p> */ inline bool LoadBalancerNameHasBeenSet() const { return m_loadBalancerNameHasBeenSet; } /** * <p>The name of the load balancer.</p> */ inline void SetLoadBalancerName(const Aws::String& value) { m_loadBalancerNameHasBeenSet = true; m_loadBalancerName = value; } /** * <p>The name of the load balancer.</p> */ inline void SetLoadBalancerName(Aws::String&& value) { m_loadBalancerNameHasBeenSet = true; m_loadBalancerName = std::move(value); } /** * <p>The name of the load balancer.</p> */ inline void SetLoadBalancerName(const char* value) { m_loadBalancerNameHasBeenSet = true; m_loadBalancerName.assign(value); } /** * <p>The name of the load balancer.</p> */ inline DescribeInstanceHealthRequest& WithLoadBalancerName(const Aws::String& value) { SetLoadBalancerName(value); return *this;} /** * <p>The name of the load balancer.</p> */ inline DescribeInstanceHealthRequest& WithLoadBalancerName(Aws::String&& value) { SetLoadBalancerName(std::move(value)); return *this;} /** * <p>The name of the load balancer.</p> */ inline DescribeInstanceHealthRequest& WithLoadBalancerName(const char* value) { SetLoadBalancerName(value); return *this;} /** * <p>The IDs of the instances.</p> */ inline const Aws::Vector<Instance>& GetInstances() const{ return m_instances; } /** * <p>The IDs of the instances.</p> */ inline bool InstancesHasBeenSet() const { return m_instancesHasBeenSet; } /** * <p>The IDs of the instances.</p> */ inline void SetInstances(const Aws::Vector<Instance>& value) { m_instancesHasBeenSet = true; m_instances = value; } /** * <p>The IDs of the instances.</p> */ inline void SetInstances(Aws::Vector<Instance>&& value) { m_instancesHasBeenSet = true; m_instances = std::move(value); } /** * <p>The IDs of the instances.</p> */ inline DescribeInstanceHealthRequest& WithInstances(const Aws::Vector<Instance>& value) { SetInstances(value); return *this;} /** * <p>The IDs of the instances.</p> */ inline DescribeInstanceHealthRequest& WithInstances(Aws::Vector<Instance>&& value) { SetInstances(std::move(value)); return *this;} /** * <p>The IDs of the instances.</p> */ inline DescribeInstanceHealthRequest& AddInstances(const Instance& value) { m_instancesHasBeenSet = true; m_instances.push_back(value); return *this; } /** * <p>The IDs of the instances.</p> */ inline DescribeInstanceHealthRequest& AddInstances(Instance&& value) { m_instancesHasBeenSet = true; m_instances.push_back(std::move(value)); return *this; } private: Aws::String m_loadBalancerName; bool m_loadBalancerNameHasBeenSet; Aws::Vector<Instance> m_instances; bool m_instancesHasBeenSet; }; } // namespace Model } // namespace ElasticLoadBalancing } // namespace Aws
cedral/aws-sdk-cpp
aws-cpp-sdk-elasticloadbalancing/include/aws/elasticloadbalancing/model/DescribeInstanceHealthRequest.h
C
apache-2.0
5,122
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.simplesystemsmanagement.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.simplesystemsmanagement.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * GetMaintenanceWindowTaskRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetMaintenanceWindowTaskRequestMarshaller { private static final MarshallingInfo<String> WINDOWID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("WindowId").build(); private static final MarshallingInfo<String> WINDOWTASKID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("WindowTaskId").build(); private static final GetMaintenanceWindowTaskRequestMarshaller instance = new GetMaintenanceWindowTaskRequestMarshaller(); public static GetMaintenanceWindowTaskRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(GetMaintenanceWindowTaskRequest getMaintenanceWindowTaskRequest, ProtocolMarshaller protocolMarshaller) { if (getMaintenanceWindowTaskRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getMaintenanceWindowTaskRequest.getWindowId(), WINDOWID_BINDING); protocolMarshaller.marshall(getMaintenanceWindowTaskRequest.getWindowTaskId(), WINDOWTASKID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/GetMaintenanceWindowTaskRequestMarshaller.java
Java
apache-2.0
2,464
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/parameter/parameter_client.h" #include <gtest/gtest.h> #include <memory> #include <vector> #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/message/protobuf_factory.h" #include "cyber/parameter/parameter_server.h" namespace apollo { namespace cyber { using apollo::cyber::proto::Param; using apollo::cyber::proto::ParamType; class ParameterClientTest : public ::testing::Test { protected: ParameterClientTest() {} virtual ~ParameterClientTest() {} std::shared_ptr<Node> node_; std::shared_ptr<ParameterServer> ps_; std::shared_ptr<ParameterClient> pc_; virtual void SetUp() { // Called before every TEST_F(ParameterClientTest, *) apollo::cyber::Init("parameter_client_test"); node_ = CreateNode("parameter_server"); ps_.reset(new ParameterServer(node_)); pc_.reset(new ParameterClient(node_, "parameter_server")); } virtual void TearDown() { // Called after every TEST_F(ParameterClientTest, *) ps_.reset(); pc_.reset(); node_.reset(); } }; TEST_F(ParameterClientTest, set_parameter) { EXPECT_TRUE(pc_->SetParameter(Parameter("int", 1))); usleep(100000); ps_.reset(); EXPECT_FALSE(pc_->SetParameter(Parameter("int", 1))); } TEST_F(ParameterClientTest, get_parameter) { ps_->SetParameter(Parameter("int", 1)); Parameter parameter; EXPECT_TRUE(pc_->GetParameter("int", &parameter)); EXPECT_EQ("int", parameter.Name()); EXPECT_EQ(1, parameter.AsInt64()); EXPECT_FALSE(pc_->GetParameter("double", &parameter)); ps_.reset(); EXPECT_FALSE(pc_->GetParameter("int", &parameter)); } TEST_F(ParameterClientTest, list_parameter) { ps_->SetParameter(Parameter("int", 1)); std::vector<Parameter> parameters; EXPECT_TRUE(pc_->ListParameters(&parameters)); EXPECT_EQ(1, parameters.size()); EXPECT_EQ("int", parameters[0].Name()); EXPECT_EQ(1, parameters[0].AsInt64()); ps_.reset(); EXPECT_FALSE(pc_->ListParameters(&parameters)); } } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
wanglei828/apollo
cyber/parameter/parameter_client_test.cc
C++
apache-2.0
2,881
<?php namespace backend\models; use Yii; /** * This is the model class for table "product_origin". * * @property integer $origin_id * @property string $name * @property integer $order * @property string $disabled * * @property Product[] $products */ class ProductOrigin extends \yii\db\ActiveRecord { public $filename; public $file; public $img_id; public $id; public $path_s; /** * @inheritdoc */ public static function tableName() { return 'product_origin'; } /** * @inheritdoc */ public function rules() { return [[['name','order','disabled'],'required'],[['order'],'integer'],[['disabled'],'string'],[['name'],'string','max'=>50]]; } /** * @inheritdoc */ public function attributeLabels() { return ['origin_id'=>'Origin ID','name'=>'Name','order'=>'Order','disabled'=>'Disabled']; } /** * * @return \yii\db\ActiveQuery */ public function getProducts() { return $this->hasMany ( Product::className (), ['origin_id'=>'origin_id'] ); } public function getImages() { /** * 第一个参数为要关联的字表模型类名称, * 第二个参数指定 通过子表的 id 去关联主表的 id 字段 */ return $this->hasOne ( Images::className (), ['related_id'=>'origin_id'] )->onCondition ( ['images.model'=>'product-origin'] ); } }
n34n/nxshop
backend/models/ProductOrigin.php
PHP
apache-2.0
1,372
# Vaccinium xerampelinum Sleumer SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Vaccinium/Vaccinium xerampelinum/README.md
Markdown
apache-2.0
180
/* * Copyright 2013 Henrik Baerbak Christensen, Aarhus University * * 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 cs.karibu.helloworld.testdoubles; import java.util.Date; import dk.au.cs.karibu.backend.StatisticHandler; /** Null object statistics handler - doing nothing. * * @author Henrik Baerbak Christensen, Aarhus University * */ public class NullStatisticsHandler implements StatisticHandler { @Override public void flushToStorage() { } @Override public String getDaemonIP() { return "none"; } @Override public Date getEndTimestamp() { return null; } @Override public String getMaxChunkProducerCode() { return null; } @Override public long getMaxChunkSize() { return 0; } @Override public Date getStartTimestamp() { return null; } @Override public String getStatusAsString() { return null; } @Override public long getTotalBytesSent() { return 0; } @Override public long getTotalCountMsg() { return 0; } @Override public void notifyReceive(String arg0, long arg1) { } }
ecosense-au-dk/karibu-tutorial
test/cs/karibu/helloworld/testdoubles/NullStatisticsHandler.java
Java
apache-2.0
1,612
namespace Fabrikam.Infrastructure.Command.Interface { public interface ICommandHandler<T> where T : ICommand { void Execute(T command); } public interface ICommandHandler { void Execute(object message); } }
yuva2achieve/fabrikam-vnext
src/Fabrikam.Infrastructure.Interfaces/Command/ICommandHandler.cs
C#
apache-2.0
251
package com.xinghai.framework.utils; import android.annotation.TargetApi; import android.os.Build; import android.os.Environment; import android.os.StatFs; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; /** * created at 16/10/27 18:02 * @author yuanbaoyu * SD卡相关工具类 */ public class SDCardUtils { private SDCardUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 判断SD卡是否可用 * * @return true : 可用<br>false : 不可用 */ public static boolean isSDCardEnable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } /** * 获取SD卡路径 * <p>先用shell,shell失败再普通方法获取,一般是/storage/emulated/0/</p> * * @return SD卡路径 */ public static String getSDCardPath() { if (!isSDCardEnable()) return "sdcard unable!"; String cmd = "cat /proc/mounts"; Runtime run = Runtime.getRuntime(); BufferedReader bufferedReader = null; try { Process p = run.exec(cmd); bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream()))); String lineStr; while ((lineStr = bufferedReader.readLine()) != null) { if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray.length >= 5) { return strArray[1].replace("/.android_secure", "") + File.separator; } } if (p.waitFor() != 0 && p.exitValue() == 1) { return " 命令执行失败"; } } } catch (Exception e) { e.printStackTrace(); } finally { CloseUtils.closeIO(bufferedReader); } return Environment.getExternalStorageDirectory().getPath() + File.separator; } /** * 获取SD卡data路径 * * @return SD卡data路径 */ public static String getDataPath() { if (!isSDCardEnable()) return "sdcard unable!"; return Environment.getExternalStorageDirectory().getPath() + File.separator + "data" + File.separator; } /** * 获取SD卡剩余空间 * * @return SD卡剩余空间 */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static String getFreeSpace() { if (!isSDCardEnable()) return "sdcard unable!"; StatFs stat = new StatFs(getSDCardPath()); long blockSize, availableBlocks; availableBlocks = stat.getAvailableBlocksLong(); blockSize = stat.getBlockSizeLong(); return ConvertUtils.byte2FitSize(availableBlocks * blockSize); } /** * 获取SD卡信息 * * @return SDCardInfo */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static String getSDCardInfo() { SDCardInfo sd = new SDCardInfo(); if (!isSDCardEnable()) return "sdcard unable!"; sd.isExist = true; StatFs sf = new StatFs(Environment.getExternalStorageDirectory().getPath()); sd.totalBlocks = sf.getBlockCountLong(); sd.blockByteSize = sf.getBlockSizeLong(); sd.availableBlocks = sf.getAvailableBlocksLong(); sd.availableBytes = sf.getAvailableBytes(); sd.freeBlocks = sf.getFreeBlocksLong(); sd.freeBytes = sf.getFreeBytes(); sd.totalBytes = sf.getTotalBytes(); return sd.toString(); } public static class SDCardInfo { boolean isExist; long totalBlocks; long freeBlocks; long availableBlocks; long blockByteSize; long totalBytes; long freeBytes; long availableBytes; @Override public String toString() { return "isExist=" + isExist + "\ntotalBlocks=" + totalBlocks + "\nfreeBlocks=" + freeBlocks + "\navailableBlocks=" + availableBlocks + "\nblockByteSize=" + blockByteSize + "\ntotalBytes=" + totalBytes + "\nfreeBytes=" + freeBytes + "\navailableBytes=" + availableBytes; } } }
yuanbaoyu/Android-Framework
framework/src/main/java/com/xinghai/framework/utils/SDCardUtils.java
Java
apache-2.0
4,582
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Reflection; using Template10.Services.KeyboardService; using Template10.Services.NavigationService; using Template10.Utils; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Markup; using Windows.UI.Xaml.Media; namespace Template10.Controls { // DOCS: https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-HamburgerMenu [ContentProperty(Name = nameof(PrimaryButtons))] public sealed partial class HamburgerMenu : UserControl, INotifyPropertyChanged { public HamburgerMenu() { InitializeComponent(); if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) { // nothing } else { PrimaryButtons = new ObservableItemCollection<HamburgerButtonInfo>(); SecondaryButtons = new ObservableItemCollection<HamburgerButtonInfo>(); new KeyboardService().AfterWindowZGesture = () => { HamburgerCommand.Execute(null); }; ShellSplitView.RegisterPropertyChangedCallback(SplitView.IsPaneOpenProperty, (d, e) => { if (SecondaryButtonOrientation.Equals(Orientation.Horizontal) && ShellSplitView.IsPaneOpen) _SecondaryButtonStackPanel.Orientation = Orientation.Horizontal; else _SecondaryButtonStackPanel.Orientation = Orientation.Vertical; }); ShellSplitView.RegisterPropertyChangedCallback(SplitView.DisplayModeProperty, (d, e) => { DisplayMode = ShellSplitView.DisplayMode; }); Loaded += (s, e) => { var any = GetType().GetRuntimeProperties() .Where(x => x.PropertyType == typeof(SolidColorBrush)) .Any(x => x.GetValue(this) != null); if (!any) // this is the default color if the user supplies none AccentColor = Colors.DarkOrange; }; } } public SplitViewDisplayMode DisplayMode { get { return (SplitViewDisplayMode)GetValue(DisplayModeProperty); } private set { SetValue(DisplayModeProperty, value); } } public static readonly DependencyProperty DisplayModeProperty = DependencyProperty.Register(nameof(DisplayMode), typeof(SplitViewDisplayMode), typeof(HamburgerMenu), new PropertyMetadata(null)); public void HighlightCorrectButton(Type pageType = null, object pageParam = null) { pageType = pageType ?? NavigationService.CurrentPageType; pageParam = pageParam ?? NavigationService.CurrentPageParam; var values = _navButtons.Select(x => x.Value); var button = values.FirstOrDefault(x => x.PageType == pageType && x.PageParameter == pageParam); Selected = button; } #region commands Mvvm.DelegateCommand _hamburgerCommand; internal Mvvm.DelegateCommand HamburgerCommand => _hamburgerCommand ?? (_hamburgerCommand = new Mvvm.DelegateCommand(ExecuteHamburger)); void ExecuteHamburger() { IsOpen = !IsOpen; } Mvvm.DelegateCommand<HamburgerButtonInfo> _navCommand; public Mvvm.DelegateCommand<HamburgerButtonInfo> NavCommand => _navCommand ?? (_navCommand = new Mvvm.DelegateCommand<HamburgerButtonInfo>(ExecuteNav)); void ExecuteNav(HamburgerButtonInfo commandInfo) { if (commandInfo == null) throw new NullReferenceException("CommandParameter is not set"); try { if (commandInfo.PageType != null) Selected = commandInfo; } finally { if (commandInfo.ClearHistory) NavigationService.ClearHistory(); } } #endregion #region VisualStateValues public double VisualStateNarrowMinWidth { get { return VisualStateNarrowTrigger.MinWindowWidth; } set { SetValue(VisualStateNarrowMinWidthProperty, VisualStateNarrowTrigger.MinWindowWidth = value); } } public static readonly DependencyProperty VisualStateNarrowMinWidthProperty = DependencyProperty.Register(nameof(VisualStateNarrowMinWidth), typeof(double), typeof(HamburgerMenu), new PropertyMetadata(null, (d, e) => { (d as HamburgerMenu).VisualStateNarrowMinWidth = (double)e.NewValue; })); public double VisualStateNormalMinWidth { get { return VisualStateNormalTrigger.MinWindowWidth; } set { SetValue(VisualStateNormalMinWidthProperty, VisualStateNormalTrigger.MinWindowWidth = value); } } public static readonly DependencyProperty VisualStateNormalMinWidthProperty = DependencyProperty.Register(nameof(VisualStateNormalMinWidth), typeof(double), typeof(HamburgerMenu), new PropertyMetadata(null, (d, e) => { (d as HamburgerMenu).VisualStateNormalMinWidth = (double)e.NewValue; })); public double VisualStateWideMinWidth { get { return VisualStateWideTrigger.MinWindowWidth; } set { SetValue(VisualStateWideMinWidthProperty, VisualStateWideTrigger.MinWindowWidth = value); } } public static readonly DependencyProperty VisualStateWideMinWidthProperty = DependencyProperty.Register(nameof(VisualStateWideMinWidth), typeof(double), typeof(HamburgerMenu), new PropertyMetadata(null, (d, e) => { (d as HamburgerMenu).VisualStateWideMinWidth = (double)e.NewValue; })); #endregion #region Style Properties public Orientation SecondaryButtonOrientation { get { return (Orientation)GetValue(SecondaryButtonOrientationProperty); } set { SetValue(SecondaryButtonOrientationProperty, value); } } public static readonly DependencyProperty SecondaryButtonOrientationProperty = DependencyProperty.Register(nameof(SecondaryButtonOrientation), typeof(Orientation), typeof(HamburgerMenu), new PropertyMetadata(Orientation.Vertical)); public Color AccentColor { get { return (Color)GetValue(AccentColorProperty); } set { SetValue(AccentColorProperty, value); } } public static readonly DependencyProperty AccentColorProperty = DependencyProperty.Register(nameof(AccentColor), typeof(Color), typeof(HamburgerMenu), new PropertyMetadata(null, (d, e) => (d as HamburgerMenu).RefreshStyles((Color)e.NewValue))); public void RefreshStyles(ApplicationTheme? theme = null) { RequestedTheme = theme?.ToElementTheme() ?? RequestedTheme; RefreshStyles(AccentColor); } public void RefreshStyles(Color? color = null) { if (color == null) { // manually setting the brushes is a way of ignoring the themes // in this block we will unset, then re-set the values var hamburgerBackground = HamburgerBackground; var hamburgerForeground = HamburgerForeground; var navAreaBackground = NavAreaBackground; var navButtonBackground = NavButtonBackground; var navButtonForeground = NavButtonForeground; var navButtonCheckedBackground = NavButtonCheckedBackground; var navButtonPressedBackground = NavButtonPressedBackground; var navButtonHoverBackground = NavButtonHoverBackground; var navButtonCheckedForeground = NavButtonCheckedForeground; var secondarySeparator = SecondarySeparator; HamburgerBackground = null; HamburgerForeground = null; NavAreaBackground = null; NavButtonBackground = null; NavButtonForeground = null; NavButtonCheckedBackground = null; NavButtonPressedBackground = null; NavButtonHoverBackground = null; NavButtonCheckedForeground = null; SecondarySeparator = null; HamburgerBackground = hamburgerBackground; HamburgerForeground = hamburgerForeground; NavAreaBackground = navAreaBackground; NavButtonBackground = navButtonBackground; NavButtonForeground = navButtonForeground; NavButtonCheckedBackground = navButtonCheckedBackground; NavButtonPressedBackground = navButtonPressedBackground; NavButtonHoverBackground = navButtonHoverBackground; NavButtonCheckedForeground = navButtonCheckedForeground; SecondarySeparator = secondarySeparator; } else { // since every brush will be based on one color, // we will do so with theme in mind. switch (RequestedTheme) { case ElementTheme.Light: HamburgerBackground = color?.ToSolidColorBrush(); HamburgerForeground = Colors.White.ToSolidColorBrush(); NavAreaBackground = Colors.DimGray.ToSolidColorBrush(); NavButtonBackground = Colors.Transparent.ToSolidColorBrush(); NavButtonForeground = Colors.White.ToSolidColorBrush(); NavButtonCheckedForeground = Colors.White.ToSolidColorBrush(); NavButtonCheckedBackground = color?.Lighten(ColorUtils.Accents.Plus20).ToSolidColorBrush(); NavButtonPressedBackground = Colors.Gainsboro.Darken(ColorUtils.Accents.Plus40).ToSolidColorBrush(); NavButtonHoverBackground = Colors.Gainsboro.Darken(ColorUtils.Accents.Plus60).ToSolidColorBrush(); NavButtonCheckedForeground = Colors.White.ToSolidColorBrush(); SecondarySeparator = Colors.Gainsboro.Darken(ColorUtils.Accents.Plus40).ToSolidColorBrush(); break; case ElementTheme.Default: case ElementTheme.Dark: HamburgerBackground = color?.ToSolidColorBrush(); HamburgerForeground = Colors.White.ToSolidColorBrush(); NavAreaBackground = Colors.Gainsboro.Darken(ColorUtils.Accents.Plus80).ToSolidColorBrush(); NavButtonBackground = Colors.Transparent.ToSolidColorBrush(); NavButtonForeground = Colors.White.ToSolidColorBrush(); NavButtonCheckedForeground = Colors.White.ToSolidColorBrush(); NavButtonCheckedBackground = color?.Darken(ColorUtils.Accents.Plus40).ToSolidColorBrush(); NavButtonPressedBackground = Colors.Gainsboro.Lighten(ColorUtils.Accents.Plus40).ToSolidColorBrush(); NavButtonHoverBackground = Colors.Gainsboro.Lighten(ColorUtils.Accents.Plus60).ToSolidColorBrush(); NavButtonCheckedForeground = Colors.White.ToSolidColorBrush(); SecondarySeparator = Colors.Gainsboro.ToSolidColorBrush(); break; } } } public SolidColorBrush HamburgerBackground { get { return GetValue(HamburgerBackgroundProperty) as SolidColorBrush; } set { SetValue(HamburgerBackgroundProperty, value); } } public static readonly DependencyProperty HamburgerBackgroundProperty = DependencyProperty.Register(nameof(HamburgerBackground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush HamburgerForeground { get { return GetValue(HamburgerForegroundProperty) as SolidColorBrush; } set { SetValue(HamburgerForegroundProperty, value); } } public static readonly DependencyProperty HamburgerForegroundProperty = DependencyProperty.Register(nameof(HamburgerForeground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush NavAreaBackground { get { return GetValue(NavAreaBackgroundProperty) as SolidColorBrush; } set { SetValue(NavAreaBackgroundProperty, value); } } public static readonly DependencyProperty NavAreaBackgroundProperty = DependencyProperty.Register(nameof(NavAreaBackground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush NavButtonBackground { get { return GetValue(NavButtonBackgroundProperty) as SolidColorBrush; } set { SetValue(NavButtonBackgroundProperty, value); } } public static readonly DependencyProperty NavButtonBackgroundProperty = DependencyProperty.Register(nameof(NavButtonBackground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush NavButtonForeground { get { return GetValue(NavButtonForegroundProperty) as SolidColorBrush; } set { SetValue(NavButtonForegroundProperty, value); } } public static readonly DependencyProperty NavButtonForegroundProperty = DependencyProperty.Register(nameof(NavButtonForeground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush SecondarySeparator { get { return GetValue(SecondarySeparatorProperty) as SolidColorBrush; } set { SetValue(SecondarySeparatorProperty, value); } } public static readonly DependencyProperty SecondarySeparatorProperty = DependencyProperty.Register(nameof(SecondarySeparator), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush NavButtonCheckedBackground { get { return GetValue(NavButtonCheckedBackgroundProperty) as SolidColorBrush; } set { SetValue(NavButtonCheckedBackgroundProperty, value); } } public static readonly DependencyProperty NavButtonCheckedBackgroundProperty = DependencyProperty.Register(nameof(NavButtonCheckedBackground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush NavButtonCheckedForeground { get { return GetValue(NavButtonCheckedForegroundProperty) as SolidColorBrush; } set { SetValue(NavButtonCheckedForegroundProperty, value); } } public static readonly DependencyProperty NavButtonCheckedForegroundProperty = DependencyProperty.Register(nameof(NavButtonCheckedForeground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush NavButtonPressedBackground { get { return GetValue(NavButtonPressedBackgroundProperty) as SolidColorBrush; } set { SetValue(NavButtonPressedBackgroundProperty, value); } } public static readonly DependencyProperty NavButtonPressedBackgroundProperty = DependencyProperty.Register(nameof(NavButtonPressedBackground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); public SolidColorBrush NavButtonHoverBackground { get { return GetValue(NavButtonHoverBackgroundProperty) as SolidColorBrush; } set { SetValue(NavButtonHoverBackgroundProperty, value); } } public static readonly DependencyProperty NavButtonHoverBackgroundProperty = DependencyProperty.Register(nameof(NavButtonHoverBackground), typeof(SolidColorBrush), typeof(HamburgerMenu), new PropertyMetadata(null)); #endregion #region Properties public HamburgerButtonInfo Selected { get { return GetValue(SelectedProperty) as HamburgerButtonInfo; } set { if (value?.Equals(Selected) ?? false) value.IsChecked = true; SetValue(SelectedProperty, value); } } public static readonly DependencyProperty SelectedProperty = DependencyProperty.Register(nameof(Selected), typeof(HamburgerButtonInfo), typeof(HamburgerMenu), new PropertyMetadata(null, (d, e) => { (d as HamburgerMenu).SetSelected((HamburgerButtonInfo)e.OldValue, (HamburgerButtonInfo)e.NewValue); })); private void SetSelected(HamburgerButtonInfo previous, HamburgerButtonInfo value) { IsOpen = false; // undo previous if (previous != null && previous != value) { previous.RaiseUnselected(); } // reset all var values = _navButtons.Select(x => x.Value); foreach (var item in values.Where(x => x != value)) { item.IsChecked = false; } // that's it if null if (value == null) { return; } else { value.IsChecked = true; if (previous != value) { value.RaiseSelected(); } } // navigate only to new pages if (value.PageType == null) return; if (value.PageType.Equals(NavigationService.CurrentPageType) && (value.PageParameter?.Equals(NavigationService.CurrentPageParam) ?? false)) return; NavigationService.Navigate(value.PageType, value.PageParameter); } public bool IsOpen { get { var open = ShellSplitView.IsPaneOpen; if (open != (bool)GetValue(IsOpenProperty)) SetValue(IsOpenProperty, open); return open; } set { var open = ShellSplitView.IsPaneOpen; if (open == value) return; if (value) { ShellSplitView.IsPaneOpen = true; } else { // collapse the window if (ShellSplitView.DisplayMode == SplitViewDisplayMode.Overlay && ShellSplitView.IsPaneOpen) ShellSplitView.IsPaneOpen = false; else if (ShellSplitView.DisplayMode == SplitViewDisplayMode.CompactOverlay && ShellSplitView.IsPaneOpen) ShellSplitView.IsPaneOpen = false; } SetValue(IsOpenProperty, value); } } public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register(nameof(IsOpen), typeof(bool), typeof(HamburgerMenu), new PropertyMetadata(false, (d, e) => { (d as HamburgerMenu).IsOpen = (bool)e.NewValue; })); public ObservableCollection<HamburgerButtonInfo> PrimaryButtons { get { var PrimaryButtons = (ObservableCollection<HamburgerButtonInfo>)base.GetValue(PrimaryButtonsProperty); if (PrimaryButtons == null) base.SetValue(PrimaryButtonsProperty, PrimaryButtons = new ObservableCollection<HamburgerButtonInfo>()); return PrimaryButtons; } set { SetValue(PrimaryButtonsProperty, value); } } public static readonly DependencyProperty PrimaryButtonsProperty = DependencyProperty.Register(nameof(PrimaryButtons), typeof(ObservableCollection<HamburgerButtonInfo>), typeof(HamburgerMenu), new PropertyMetadata(null)); private NavigationService _navigationService; public NavigationService NavigationService { get { return _navigationService; } set { _navigationService = value; if (NavigationService.Frame.BackStackDepth > 0) { // display content inside the splitview ShellSplitView.Content = NavigationService.Frame; } else { // display content without splitview (splash scenario) NavigationService.AfterRestoreSavedNavigation += (s, e) => UpdateFullScreen(IsFullScreen); NavigationService.FrameFacade.Navigated += (s, e) => UpdateFullScreen(IsFullScreen); UpdateFullScreen(true); } NavigationService.FrameFacade.Navigated += (s, e) => HighlightCorrectButton(e.PageType, e.Parameter); NavigationService.AfterRestoreSavedNavigation += (s, e) => HighlightCorrectButton(); ShellSplitView.RegisterPropertyChangedCallback(SplitView.IsPaneOpenProperty, (s, e) => { // update width PaneWidth = !ShellSplitView.IsPaneOpen ? ShellSplitView.CompactPaneLength : ShellSplitView.OpenPaneLength; }); UpdateFullScreen(); } } public bool IsFullScreen { get { return (bool)GetValue(IsFullScreenProperty); } set { SetValue(IsFullScreenProperty, value); } } public static readonly DependencyProperty IsFullScreenProperty = DependencyProperty.Register(nameof(IsFullScreen), typeof(bool), typeof(HamburgerMenu), new PropertyMetadata(false, (d, e) => (d as HamburgerMenu).UpdateFullScreen())); private void UpdateFullScreen(bool? manual = null) { if (manual ?? IsFullScreen) { if (NavigationService == null || RootGrid.Children.Contains(NavigationService.Frame)) return; NavigationService.Frame.SetValue(Grid.ColumnProperty, 0); ShellSplitView.Content = null; NavigationService.Frame.SetValue(Grid.ColumnSpanProperty, int.MaxValue); NavigationService.Frame.SetValue(Grid.RowProperty, 0); NavigationService.Frame.SetValue(Grid.RowSpanProperty, int.MaxValue); RootGrid.Children.Add(NavigationService.Frame); } else { if (RootGrid.Children.Contains(NavigationService.Frame)) RootGrid.Children.Remove(NavigationService.Frame); ShellSplitView.Content = NavigationService.Frame; } } public ObservableCollection<HamburgerButtonInfo> SecondaryButtons { get { var SecondaryButtons = (ObservableCollection<HamburgerButtonInfo>)base.GetValue(SecondaryButtonsProperty); if (SecondaryButtons == null) base.SetValue(SecondaryButtonsProperty, SecondaryButtons = new ObservableCollection<HamburgerButtonInfo>()); return SecondaryButtons; } set { SetValue(SecondaryButtonsProperty, value); } } public static readonly DependencyProperty SecondaryButtonsProperty = DependencyProperty.Register(nameof(SecondaryButtons), typeof(ObservableCollection<HamburgerButtonInfo>), typeof(HamburgerMenu), new PropertyMetadata(null)); public double PaneWidth { get { return (double)GetValue(PaneWidthProperty); } set { SetValue(PaneWidthProperty, value); } } public static readonly DependencyProperty PaneWidthProperty = DependencyProperty.Register(nameof(PaneWidth), typeof(double), typeof(HamburgerMenu), new PropertyMetadata(220d)); public UIElement HeaderContent { get { return (UIElement)GetValue(HeaderContentProperty); } set { SetValue(HeaderContentProperty, value); } } public static readonly DependencyProperty HeaderContentProperty = DependencyProperty.Register(nameof(HeaderContent), typeof(UIElement), typeof(HamburgerMenu), null); #endregion Dictionary<RadioButton, HamburgerButtonInfo> _navButtons = new Dictionary<RadioButton, HamburgerButtonInfo>(); void NavButton_Loaded(object sender, RoutedEventArgs e) { // add this radio to the list var radio = sender as RadioButton; var info = radio.DataContext as HamburgerButtonInfo; _navButtons.Add(radio, info); // map clicked radio.Checked += (s, args) => { info.RaiseChecked(args); Selected = radio.DataContext as HamburgerButtonInfo; }; radio.Unchecked += (s, args) => HighlightCorrectButton(); radio.Unchecked += (s, args) => info.RaiseUnchecked(args); // udpate UI HighlightCorrectButton(); } private void PaneContent_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { HamburgerCommand.Execute(null); } private void NavButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { var radio = sender as RadioButton; var info = radio.DataContext as HamburgerButtonInfo; info.RaiseTapped(e); // why is it handled? // so we don't re-select e.Handled = true; } public event PropertyChangedEventHandler PropertyChanged; StackPanel _SecondaryButtonStackPanel; private void SecondaryButtonStackPanel_Loaded(object sender, RoutedEventArgs e) { _SecondaryButtonStackPanel = sender as StackPanel; } } }
h82258652/Template10
Template10 (Library)/Controls/HamburgerMenu.xaml.cs
C#
apache-2.0
26,785
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>HBase 0.98.8-hadoop2 Reference Package org.apache.hadoop.hbase.codec.prefixtree.timestamp</title> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="style" /> </head> <body> <div class="overview"> <ul> <li> <a href="../../../../../../../overview-summary.html">Overview</a> </li> <li class="selected">Package</li> </ul> </div> <div class="framenoframe"> <ul> <li> <a href="../../../../../../../index.html" target="_top">FRAMES</a> </li> <li> <a href="package-summary.html" target="_top">NO FRAMES</a> </li> </ul> </div> <h2>Package org.apache.hadoop.hbase.codec.prefixtree.timestamp</h2> <table class="summary"> <thead> <tr> <th>Class Summary</th> </tr> </thead> <tbody> <tr> <td> <a href="TestTimestampData.html" target="classFrame">InMemory</a> </td> </tr> <tr> <td> <a href="TestTimestampData.html" target="classFrame">TestTimestampData</a> </td> </tr> <tr> <td> <a href="TestTimestampEncoder.html" target="classFrame">TestTimestampEncoder</a> </td> </tr> </tbody> </table> <div class="overview"> <ul> <li> <a href="../../../../../../../overview-summary.html">Overview</a> </li> <li class="selected">Package</li> </ul> </div> <div class="framenoframe"> <ul> <li> <a href="../../../../../../../index.html" target="_top">FRAMES</a> </li> <li> <a href="package-summary.html" target="_top">NO FRAMES</a> </li> </ul> </div> <hr /> Copyright &#169; 2014 The Apache Software Foundation. All Rights Reserved. </body> </html>
devansh2015/hbase-0.98.8
docs/xref-test/org/apache/hadoop/hbase/codec/prefixtree/timestamp/package-summary.html
HTML
apache-2.0
2,415
import { Class, Enum } from 'meteor/jagi:astronomy' import 'jagi:astronomy-timestamp-behavior' export const ApplicationStatus = Enum.create({ name: 'ApplicationStatus', identifiers: { DRAFT: 0, ACTIVE: 1, INACTIVE: 2 } }) export const Application = Class.create({ name: 'Application', collection: new Mongo.Collection('applications'), fields: { name: { type: String, validators: [{ type: 'maxLength', param: 50, message: 'application_name_max_length' }] }, description: { type: String, optional: true, validators: [{ type: 'maxLength', param: 500, message: 'application_description_max_length' }] }, userId: String, status: { type: ApplicationStatus, default: ApplicationStatus.DRAFT } }, behaviors: { softremove: { removedFieldName: 'removed', hasRemovedAtField: true, removedAtFieldName: 'removedAt' }, timestamp: { hasCreatedField: true, createdFieldName: 'createdAt', hasUpdatedField: true, updatedFieldName: 'updatedAt' } }, indexes: { unique_application_name: { fields: { name: 1 }, options: { unique: true } } } })
openmarketplace/openmarketplace
imports/api/applications/application-model.js
JavaScript
apache-2.0
1,262
package org.tribbloid.spookystuff.pages /** * Created by peng on 2/5/15. */ class UnknownElement( override val uri: String ) extends Unstructured { override def text: Option[String] = None override def children(selector: String) = new Elements(Seq()) override def childrenWithSiblings(start: String, range: Range) = new Elements(Seq()) override def code: Option[String] = None override def ownText: Option[String] = None override def boilerPipe: Option[String] = None override def attr(attr: String, noEmpty: Boolean): Option[String] = None}
chenUT/spookystuff
core/src/main/scala/org/tribbloid/spookystuff/pages/UnknownElement.scala
Scala
apache-2.0
609
/* By: facug91 From: http://coj.uci.cu/24h/problem.xhtml?abb=1188 Name: Cow Multiplication Number: 1188 Date: 11/11/2013 */ #include <iostream> #include <cstdio> #include <string> #include <cstring> #include <list> #include <iterator> #include <cstdlib> #include <set> using namespace std; int main () { string a, b; int i, j, total = 0; cin>>a>>b; for (i=0; i<a.size(); i++) { for (j=0; j<b.size(); j++) { total += ((a[i]-'0') * (b[j]-'0')); } } printf("%d\n",total); return 0; }
facug91/OJ-Solutions
coj.uci.cu/CowMultiplication.cpp
C++
apache-2.0
509
# ffead-cpp-plugins Language Interface plugins for ffead-cpp HTTP server
sumeetchhetri/ffead-cpp-plugins
README.md
Markdown
apache-2.0
73
<div class="modal-header"> <h1 class="modal-title">OKTA QUARANTINE GROUP</h1> </div> <div class="modal-body"> <div class="row"> <form class="config-add-form form-horizontal m-t-xs"> <div class="form-group" id="fgQuarantineGroup"> <label class="col-xs-4 control-label">QUARANTINE GROUP</label> <div class="col-xs-6"> <input type="text" ng-model="vm.quarantine_group" class="form-control" placeholder="Quarantine Group"> </div> </div> </form> </div> </div> <div class="modal-footer"> <button ng-disabled="!vm.valid()" class="btn btn-primary btn-sm" type="button" ng-click="vm.save()">OK</button> <button class="btn btn-warning btn-sm" type="button" ng-click="vm.cancel()">CANCEL</button> </div>
fvigo/minemeld-okta
mmokta/webui/okta.output.quarantinegroup.html
HTML
apache-2.0
821
package com.alipay.api.request; import com.alipay.api.domain.AlipayOpenPublicUserFollowQueryModel; import java.util.Map; import com.alipay.api.AlipayRequest; import com.alipay.api.internal.util.AlipayHashMap; import com.alipay.api.response.AlipayOpenPublicUserFollowQueryResponse; import com.alipay.api.AlipayObject; /** * ALIPAY API: alipay.open.public.user.follow.query request * * @author auto create * @since 1.0, 2017-11-02 16:05:24 */ public class AlipayOpenPublicUserFollowQueryRequest implements AlipayRequest<AlipayOpenPublicUserFollowQueryResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * 生活号用户关注查询接口 */ private String bizContent; public void setBizContent(String bizContent) { this.bizContent = bizContent; } public String getBizContent() { return this.bizContent; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; public String getNotifyUrl() { return this.notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return this.returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getApiVersion() { return this.apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public void setTerminalType(String terminalType){ this.terminalType=terminalType; } public String getTerminalType(){ return this.terminalType; } public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public String getTerminalInfo(){ return this.terminalInfo; } public void setProdCode(String prodCode) { this.prodCode=prodCode; } public String getProdCode() { return this.prodCode; } public String getApiMethodName() { return "alipay.open.public.user.follow.query"; } public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("biz_content", this.bizContent); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } public Class<AlipayOpenPublicUserFollowQueryResponse> getResponseClass() { return AlipayOpenPublicUserFollowQueryResponse.class; } public boolean isNeedEncrypt() { return this.needEncrypt; } public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } public AlipayObject getBizModel() { return this.bizModel; } public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
wendal/alipay-sdk
src/main/java/com/alipay/api/request/AlipayOpenPublicUserFollowQueryRequest.java
Java
apache-2.0
3,025
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cluster.Names.Api { public enum NameTypes { WesternName = 1 //For illustration: //ChineseName = 2, //IndianName = 3, // IrishName = 4 } }
NakedObjectsGroup/Clusters
Cluster.Names.Api/NameTypes.cs
C#
apache-2.0
321
<!DOCTYPE html> <html class="theme-next mist use-motion" lang="zh-Hans"> <head><meta name="generator" content="Hexo 3.8.0"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="theme-color" content="#222"> <meta http-equiv="Cache-Control" content="no-transform"> <meta http-equiv="Cache-Control" content="no-siteapp"> <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"> <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"> <link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css"> <meta name="keywords" content="linux,centos,software,"> <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2"> <meta name="description" content="无线网络相关在使用Linux的过程中,有过一段神奇的经历。 那是我刚换x550本子的时候,我发现无线网络偶尔会抽风。 具体表现为连接了一会儿之后莫名其妙的断开连接,但是桌面指示却还是显示为已连接状态。 一开始我以为是Network Manager和Network的冲突所导致。为此我查阅了Aarchlinux的wiki去简略学习了一下这个东西,链接是NetworkManager。 但折腾了半天之后发"> <meta name="keywords" content="linux,centos,software"> <meta property="og:type" content="article"> <meta property="og:title" content="Linux零碎经验整理"> <meta property="og:url" content="http://infonook.org/linux-useful-bits-and-pieces-01/index.html"> <meta property="og:site_name" content="INFONOOK"> <meta property="og:description" content="无线网络相关在使用Linux的过程中,有过一段神奇的经历。 那是我刚换x550本子的时候,我发现无线网络偶尔会抽风。 具体表现为连接了一会儿之后莫名其妙的断开连接,但是桌面指示却还是显示为已连接状态。 一开始我以为是Network Manager和Network的冲突所导致。为此我查阅了Aarchlinux的wiki去简略学习了一下这个东西,链接是NetworkManager。 但折腾了半天之后发"> <meta property="og:locale" content="zh-Hans"> <meta property="og:updated_time" content="2018-01-18T23:56:53.000Z"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="Linux零碎经验整理"> <meta name="twitter:description" content="无线网络相关在使用Linux的过程中,有过一段神奇的经历。 那是我刚换x550本子的时候,我发现无线网络偶尔会抽风。 具体表现为连接了一会儿之后莫名其妙的断开连接,但是桌面指示却还是显示为已连接状态。 一开始我以为是Network Manager和Network的冲突所导致。为此我查阅了Aarchlinux的wiki去简略学习了一下这个东西,链接是NetworkManager。 但折腾了半天之后发"> <script type="text/javascript" id="hexo.configurations"> var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Mist', sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false}, fancybox: true, tabs: true, motion: true, duoshuo: { userId: '0', author: '博主' }, algolia: { applicationID: '', apiKey: '', indexName: '', hits: {"per_page":10}, labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"} } }; </script> <link rel="canonical" href="http://infonook.org/linux-useful-bits-and-pieces-01/"> <title>Linux零碎经验整理 | INFONOOK</title> </head> <body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"> <div class="container sidebar-position-left page-post-detail "> <div class="headband"></div> <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"> <div class="header-inner"><div class="site-brand-wrapper"> <div class="site-meta "> <div class="custom-logo-site-title"> <a href="/" class="brand" rel="start"> <span class="logo-line-before"><i></i></span> <span class="site-title">INFONOOK</span> <span class="logo-line-after"><i></i></span> </a> </div> <h1 class="site-subtitle" itemprop="description">一块普通人的信息格子</h1> </div> <div class="site-nav-toggle"> <button> <span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span> </button> </div> </div> <nav class="site-nav"> <ul id="menu" class="menu"> <li class="menu-item menu-item-home"> <a href="/" rel="section"> <i class="menu-item-icon fa fa-fw fa-home"></i> <br> 首页 </a> </li> <li class="menu-item menu-item-categories"> <a href="/categories/" rel="section"> <i class="menu-item-icon fa fa-fw fa-th"></i> <br> 分类 </a> </li> <li class="menu-item menu-item-tags"> <a href="/tags/" rel="section"> <i class="menu-item-icon fa fa-fw fa-tags"></i> <br> 标签 </a> </li> <li class="menu-item menu-item-archives"> <a href="/archives/" rel="section"> <i class="menu-item-icon fa fa-fw fa-archive"></i> <br> 归档 </a> </li> <li class="menu-item menu-item-about"> <a href="/about/" rel="section"> <i class="menu-item-icon fa fa-fw fa-user"></i> <br> 关于 </a> </li> <li class="menu-item menu-item-links"> <a href="/links/" rel="section"> <i class="menu-item-icon fa fa-fw fa-link"></i> <br> 链接 </a> </li> </ul> </nav> </div> </header> <main id="main" class="main"> <div class="main-inner"> <div class="content-wrap"> <div id="content" class="content"> <div id="posts" class="posts-expand"> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <div class="post-block"> <link itemprop="mainEntityOfPage" href="http://infonook.org/linux-useful-bits-and-pieces-01/"> <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"> <meta itemprop="name" content="wuhuarou"> <meta itemprop="description" content> <meta itemprop="image" content="/images/alutouxiang150.png"> </span> <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"> <meta itemprop="name" content="INFONOOK"> </span> <header class="post-header"> <h2 class="post-title" itemprop="name headline">Linux零碎经验整理</h2> <div class="post-meta"> <span class="post-time"> <span class="post-meta-item-icon"> <i class="fa fa-calendar-o"></i> </span> <span class="post-meta-item-text">发表于</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-16T20:56:45+08:00"> 2017-06-16 </time> </span> <span class="post-category"> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"> <i class="fa fa-folder-o"></i> </span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"> <a href="/categories/develop/" itemprop="url" rel="index"> <span itemprop="name">develop</span> </a> </span> </span> <span class="post-comments-count"> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"> <i class="fa fa-comment-o"></i> </span> <a href="/linux-useful-bits-and-pieces-01/#comments" itemprop="discussionUrl"> <span class="post-comments-count disqus-comment-count" data-disqus-identifier="linux-useful-bits-and-pieces-01/" itemprop="commentCount"></span> </a> </span> </div> </header> <div class="post-body" itemprop="articleBody"> <h2 id="无线网络相关"><a href="#无线网络相关" class="headerlink" title="无线网络相关"></a>无线网络相关</h2><p>在使用Linux的过程中,有过一段神奇的经历。</p> <p>那是我刚换x550本子的时候,我发现无线网络偶尔会抽风。</p> <p>具体表现为连接了一会儿之后莫名其妙的断开连接,但是桌面指示却还是显示为已连接状态。</p> <p>一开始我以为是Network Manager和Network的冲突所导致。为此我查阅了Aarchlinux的wiki去简略学习了一下这个东西,链接是NetworkManager。</p> <p>但折腾了半天之后发现并不是这个问题,于是我换了个思路。<br><a id="more"></a><br>首先我打印了我的网卡信息和驱动信息,看了看感觉并没什么问题<br>。<br>那难道是等待回复的时间过短导致认为我已经超时?我改了配置之后发现也不是这么回事。</p> <p>无奈我去社区提问,发现和我有相似经历的人是有很多的。</p> <p>最后一哥们回复说,他是这么解决这个问题的。</p> <p><code>sudo modprobe -r rtl8723be</code></p> <p>然后在/etc/modeprobe.d/这个路径下新建一个配置文件rtl8723be.conf</p> <p><code>sudo touch /etc/modprobe.d/rtl8723be.conf</code></p> <p>用文本编辑器打开它,添加</p> <p><code>options rtl8723be ips=0 fwlps=0 swenc=1</code></p> <p>我参考了他的方法发现真的就解决了这个问题。</p> <p>这里再放上一个ubuntu论坛的rtl8723be无线网卡问题的帖子作为参考资料:<a href="http://forum.ubuntu.org.cn/viewtopic.php?t=462588" target="_blank" rel="noopener">ubuntu14.04 amd64 无线网卡rtl8723be安装与问题资料整理</a></p> <h2 id="播放器相关"><a href="#播放器相关" class="headerlink" title="播放器相关"></a>播放器相关</h2><p>本人用的是centos,桌面是集成的gnome,所以默认已经装上了一个播放器叫Videos(没错它就叫这个)。</p> <p>因为最近需要看一些教程视频,所以得弄下播放器,我一看环境里已经自带了一个,就寻思直接用吧。</p> <p>体验结果是,无fuck说。</p> <p>这玩意简直不是体验差那么简单了,默认什么格式都不支持,需要现搜索解码。</p> <p>这也就算了,大哥,搜索之后各种安装不了是什么意思。</p> <p>于是我选择了我比较喜欢的vlc。</p> <p>但是问题来了,这货(Videos)无论我怎么设置,默认打开方式还是它。</p> <p>诶哟脾气还挺大啊。</p> <p>我寻思卸载了吧,结果我猜了半天的名字也没猜对这货真实包名。</p> <p>我就很气。</p> <p>百度了半天也没找到个所以然(垃圾百度),换谷歌,在ubuntu论坛又找到了答案(ubuntu桌面问题真的挺全的,毕竟桌面大户)。</p> <p><code>sudo apt-get purge totem totem-plugins</code></p> <p>我去,你叫totem啊……</p> <p>赶紧卸载了,真的是闹不住。</p> <p>参考资料:<a href="https://askubuntu.com/questions/768487/how-do-i-remove-the-gnomes-video-applications" target="_blank" rel="noopener">Videos,How do I remove the Gnome’s video applications?</a></p> </div> <div> <ul class="post-copyright"> <li class="post-copyright-author"> <strong>本文作者:</strong> wuhuarou </li> <li class="post-copyright-link"> <strong>本文链接:</strong> <a href="http://infonook.org/linux-useful-bits-and-pieces-01/" title="Linux零碎经验整理">http://infonook.org/linux-useful-bits-and-pieces-01/</a> </li> <li class="post-copyright-license"> <strong>版权声明: </strong> 本博客所有文章除特别声明外,均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处! </li> </ul> </div> <footer class="post-footer"> <div class="post-tags"> <a href="/tags/linux/" rel="tag"># linux</a> <a href="/tags/centos/" rel="tag"># centos</a> <a href="/tags/software/" rel="tag"># software</a> </div> <div class="post-nav"> <div class="post-nav-next post-nav-item"> <a href="/centos1611-intel-skylake-nvidia/" rel="next" title="CentOS 7.3(1611)对于intel核心(6代以后)+Nvidia显卡笔记本的x界面定稿"> <i class="fa fa-chevron-left"></i> CentOS 7.3(1611)对于intel核心(6代以后)+Nvidia显卡笔记本的x界面定稿 </a> </div> <span class="post-nav-divider"></span> <div class="post-nav-prev post-nav-item"> <a href="/hexo-beginner-notes/" rel="prev" title="如何使用Hexo建立个人博客(新手参考笔记)"> 如何使用Hexo建立个人博客(新手参考笔记) <i class="fa fa-chevron-right"></i> </a> </div> </div> </footer> </div> </article> <div class="post-spread"> </div> </div> </div> <div class="comments" id="comments"> <div id="disqus_thread"> <noscript> Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a> </noscript> </div> </div> </div> <div class="sidebar-toggle"> <div class="sidebar-toggle-line-wrap"> <span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span> </div> </div> <aside id="sidebar" class="sidebar"> <div class="sidebar-inner"> <ul class="sidebar-nav motion-element"> <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap"> 文章目录 </li> <li class="sidebar-nav-overview" data-target="site-overview"> 站点概览 </li> </ul> <section class="site-overview sidebar-panel"> <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="/images/alutouxiang150.png" alt="wuhuarou"> <p class="site-author-name" itemprop="name">wuhuarou</p> <p class="site-description motion-element" itemprop="description"></p> </div> <nav class="site-state motion-element"> <div class="site-state-item site-state-posts"> <a href="/archives/"> <span class="site-state-item-count">13</span> <span class="site-state-item-name">日志</span> </a> </div> <div class="site-state-item site-state-categories"> <a href="/categories/index.html"> <span class="site-state-item-count">4</span> <span class="site-state-item-name">分类</span> </a> </div> <div class="site-state-item site-state-tags"> <a href="/tags/index.html"> <span class="site-state-item-count">18</span> <span class="site-state-item-name">标签</span> </a> </div> </nav> <div class="links-of-author motion-element"> </div> </section> <!--noindex--> <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"> <div class="post-toc"> <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#无线网络相关"><span class="nav-number">1.</span> <span class="nav-text">无线网络相关</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#播放器相关"><span class="nav-number">2.</span> <span class="nav-text">播放器相关</span></a></li></ol></div> </div> </section> <!--/noindex--> </div> </aside> </div> </main> <footer id="footer" class="footer"> <div class="footer-inner"> <div class="copyright"> &copy; 2013 - <span itemprop="copyrightYear">2019</span> <span class="with-love"> <i class="fa fa-heart"></i> </span> <span class="author" itemprop="copyrightHolder">wuhuarou</span> </div> <div class="powered-by"> 由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动 </div> <div class="theme-info"> 主题 - <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next"> NexT.Mist </a> </div> </div> </footer> <div class="back-to-top"> <i class="fa fa-arrow-up"></i> </div> </div> <script type="text/javascript"> if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } </script> <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script> <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script> <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script> <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script> <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script> <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script> <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script> <script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script> <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script> <script id="dsq-count-scr" src="https://wuhuarou.disqus.com/count.js" async></script> <script type="text/javascript"> var disqus_config = function () { this.page.url = 'http://infonook.org/linux-useful-bits-and-pieces-01/'; this.page.identifier = 'linux-useful-bits-and-pieces-01/'; this.page.title = 'Linux零碎经验整理'; }; var d = document, s = d.createElement('script'); s.src = 'https://wuhuarou.disqus.com/embed.js'; s.setAttribute('data-timestamp', '' + +new Date()); (d.head || d.body).appendChild(s); </script> </body> </html>
wuhuaroulol/wuhuaroulol.github.io
linux-useful-bits-and-pieces-01/index.html
HTML
apache-2.0
20,939
package net.floodlightcontroller.QoSPolicyManager; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import org.codehaus.jackson.map.MappingJsonFactory; import org.openflow.util.U16; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RestrictionResource extends ServerResource { protected static Logger logger = LoggerFactory .getLogger(RestrictionResource.class); String status = null; @Get("json") public Object handleRequest() { IPolicyManager PM = (IPolicyManager) getContext().getAttributes().get( IPolicyManager.class.getCanonicalName()); // gets the list of policies currently being implemented if(PM!=null) return PM.getRestrictions(); else return "error\n"; } @Post public String add(String qosJson) { IPolicyManager PM = (IPolicyManager) getContext().getAttributes().get( IPolicyManager.class.getCanonicalName()); PolicyRestriction restriction; try{ restriction = jsonToRestriction(qosJson); } catch(IOException e){ logger.error("Error Parsing Restriction of Policy to JSON: {}, Error: {}", qosJson, e); e.printStackTrace(); return "{\"status\" : \"Error! Could not parse policy, see log for details.\"}"; } String status = "add Restriction"; if(checkIfRestrictionExists(restriction,PM.getRestrictions())){ status = "Error!, This policy already exists!"; logger.error(status); } else{ PM.addRestriction(restriction); } return ("{\"status\" : \"" + status + "\"}"); } @Delete public String delete(String qosJson) { IPolicyManager PM = (IPolicyManager) getContext().getAttributes().get( IPolicyManager.class.getCanonicalName()); PolicyRestriction restriction; try{ restriction = jsonToRestriction(qosJson); } catch(IOException e){ logger.debug("Error Parsing QoS Policy to JSON: {}, Error: {}", qosJson, e); e.printStackTrace(); return "{\"status\" : \"Error! Could not parse policy, see log for details.\"}"; } String status = null; boolean found = false; Iterator<PolicyRestriction> sIter = PM.getRestrictions().iterator(); while(sIter.hasNext()){ PolicyRestriction pm = sIter.next(); if(pm.restrictionid == restriction.restrictionid){ restriction = pm; //returned the entire policy found = true; break; } } if(!found){ status = "Error! Cannot delete a rule with this ID or NAME, does not exist."; logger.error(status); } else{ PM.deleteRestriction(restriction); status = "Type Of Service Service-ID: "+restriction.restrictionid+" Deleted"; } return ("{\"status\" : \"" + status + "\"}"); } public static PolicyRestriction jsonToRestriction(String rJson) throws IOException{ PolicyRestriction restriction = new PolicyRestriction(); //initialize needs json tools MappingJsonFactory jf = new MappingJsonFactory(); JsonParser jp; try{ jp = jf.createJsonParser(rJson); }catch(JsonParseException e){ throw new IOException(e); } JsonToken tkn = jp.getCurrentToken(); if(tkn != JsonToken.START_OBJECT){ jp.nextToken(); if(jp.getCurrentToken() != JsonToken.START_OBJECT){ logger.error("Did not recieve json start token, current " + "token is: {}",jp.getCurrentToken()); } } while(jp.nextToken() != JsonToken.END_OBJECT){ if(jp.getCurrentToken() != JsonToken.FIELD_NAME){ throw new IOException("FIELD_NAME expected"); } try{ String tmpS = jp.getCurrentName(); jp.nextToken(); /** may be worth: jsonText = jp.getText(); to avoid over * use of jp.getText() method call **/ //get current text of the FIELD_NAME logger.info("Current text is "+ jp.getText()); //debug for dev if(jp.getText().equals("")){ //back to beginning of loop continue; } if (tmpS == "restriction-id" || tmpS == "sid" ){ restriction.restrictionid = Long.parseLong(jp.getText()); //logger.info("[JSON PARSER]Policy Name: {}" , jp.getText()); } if (tmpS == "name"){ if(jp.getText().equals("null")) // for handle the case : policy from storage transfered by Json restriction.name = null; else restriction.name = jp.getText(); //logger.info("[JSON PARSER]Policy Name: {}" , jp.getText()); } else if(tmpS == "protocol"){ // i.e "protocol": "6" restriction.protocol = Byte.parseByte(jp.getText()); //logger.info("[JSON PARSER]Policy Protocol: {}", jp.getText()); } else if(tmpS == "eth-type" || tmpS == "ethtype"){ // i.e if "eth-type":"0x0800" if (jp.getText().startsWith("0x")) { restriction.ethtype = U16.t(Integer.valueOf (jp.getText().replaceFirst("0x",""),16)); } //return the short value of number i.e 8 else{restriction.ethtype = (short) Integer.parseInt(jp.getText());} //logger.info("[JSON PARSER]Policy Eth-type: {}", jp.getText()); } else if(tmpS == "tos"){ //This is so you can enter a binary number or a integer number. //It will be stored as a Byte try{ //Try to get binary number first Integer tmpInt = Integer.parseInt(jp.getText(),2); restriction.tos = tmpInt.byteValue(); }catch(NumberFormatException e){ //logger.debug("Number entered was not binary, processing as int..."); //Must be entered as 0-64 Integer tmpInt = Integer.parseInt(jp.getText()); restriction.tos = tmpInt.byteValue(); } //logger.info("[JSON PARSER]Policy TOS Bits: {}", jp.getText()); } else if(tmpS == "src-port" || tmpS == "tcpudpsrcport"){ restriction.tcpudpsrcport = Short.parseShort(jp.getText()); //logger.info("[JSON PARSER]Policy Src-Port: {}", jp.getText()); } else if(tmpS == "dst-port" || tmpS == "tcpudpdstport"){ restriction.tcpudpdstport = Short.parseShort(jp.getText()); //logger.info("[JSON PARSER]Policy Dst-Port: {}", jp.getText()); } else if(tmpS == "queue"){ restriction.queue = Short.parseShort(jp.getText()); //logger.info("[JSON PARSER]Policy QUEUE: {}", jp.getText()); } else if(tmpS == "priority"){ restriction.priority = Short.parseShort(jp.getText()); //logger.info("[JSON PARSER]Policy Priority: {}", jp.getText()); } }catch(JsonParseException e){ logger.debug("Error getting current FIELD_NAME {}", e); }catch(IOException e){ logger.debug("Error procession Json {}", e); } } return restriction; } private static boolean checkIfRestrictionExists(PolicyRestriction restriction, List<PolicyRestriction> policies) { Iterator<PolicyRestriction> pIter = policies.iterator(); while(pIter.hasNext()){ PolicyRestriction p = pIter.next(); if(restriction.isSameAs(p) || restriction.name.equals(p.name)){ return true; } } return false; } }
jimmyoic/floodlight-qosmanager
src/main/java/net/floodlightcontroller/QoSPolicyManager/RestrictionResource.java
Java
apache-2.0
7,505
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class LancamentoDizimo extends My_controller { public function __constructor(){ parent::__constructor(); $this->load->model('admissao_model'); } public function index(){ $this->load->model('admissao_model'); $data = array(); $data ['AdmissaoID'] = ''; $data ['AdmissaoNome'] = ''; $data ['BLC_DADOS'] = array(); $data ['BLC_SEMDADOS'] = array(); $data ['BLC_MENSAGEM'] = array(); $pagina = $this->input->get('pagina'); if (!$pagina){ $pagina = 0; } else { $pagina = ($pagina-1) *30; } $res = $this->admissao_model->get (array(), FALSE, $pagina); if ($res) { foreach ($res as $r) { $data ['BLC_DADOS'] [] = array( "ID" => $r->AdmissaoID, "NOME" => $r->AdmissaoDescricao, "URLEDITAR" => site_url ('secretaria/admissao/editar/'.$r->AdmissaoID), "URLEXCLUIR" => site_url ('secretaria/admissao/excluir/'.$r->AdmissaoID) ); } } else { $data ['BLC_SEMDADOS'] [] = array(); } $this->setURL ($data); $this->layout = 'dashboard'; $this->parser->parse('secretaria/admissao_form', $data); } public function salvar(){ $this->load->model('admissao_model'); $AdmissaoID = $this->input->post ('AdmissaoID'); $AdmissaoNome = $this->input->post ('AdmissaoNome'); $erros = FALSE; $mensagem = null; if (!$AdmissaoNome) { $erros = TRUE; $mensagem .= 'Informe a Situação Cadastral'; } if (!$erros) { $itens = array( "AdmissaoDescricao" => $AdmissaoNome, ); if ($AdmissaoID){ $this->admissao_model->update($itens, $AdmissaoID); } else { $this->admissao_model->post($itens); } if ($AdmissaoID){ $this->session->set_flashdata('Sucesso', 'Dados Inseridos com sucesso'); redirect('secretaria/Admissao', 'refresh'); } else { $this->session->set_flashdata('erro', 'Ocorreu um erro ao realizar a inserção'); echo $mensagem; if ($AdmissaoID){ redirect('secretaria/Admissao/editar/'.$AdmissaoID); } else { redirect('secretaria/Admissao', 'refresh'); } } } else { $this->session->set_flashdata('erro', nl2br($mensagem)); if ($situacaoID){ redirect('situacao/editar/'.$situacaoID); } else { redirect('situacao/adicionar/adicionar'); } } } private function setURL (&$data){ $data ['ACAOFORM'] = base_url ('secretaria/Admissao/salvar'); } public function excluir ($AdmissaoID) { $this->load->model('admissao_model'); $res = $this->admissao_model->excluir($AdmissaoID); if ($res) { $this->session->set_flashdata('Sucesso', 'Usuário removido com sucesso'); } else { $this->session->set_flashdata('erro', 'Usuário não pode ser removido'); } redirect('secretaria/Admissao', 'refresh'); } public function editar($AdmissaoID) { $this->load->model('admissao_model'); $data = array(); $data ['ACAO'] = 'Edição'; $data ['BLC_DADOS'] = array(); $data ['BLC_SEMDADOS'] = array(); $pagina = $this->input->get('pagina'); if (!$pagina){ $pagina = 0; } else { $pagina = ($pagina-1) *30; } $res = $this->admissao_model->get (array(), FALSE, $pagina); if ($res) { foreach ($res as $r) { $data ['BLC_DADOS'] [] = array( "ID" => $r->AdmissaoID, "NOME" => $r->AdmissaoDescricao, "URLEDITAR" => site_url ('secretaria/Admissao/editar/'.$r->AdmissaoID), "URLEXCLUIR" => site_url ('secretaria/Admissao/excluir/'.$r->AdmissaoID) ); } } else { $data ['BLC_SEMDADOS'] [] = array(); } $edit = $this->admissao_model->get(array ("AdmissaoID" => $AdmissaoID), FALSE); if ($edit) { foreach($edit as $item) { $data['AdmissaoID'] = $item->AdmissaoID; $data['AdmissaoNome'] = $item->AdmissaoDescricao; } } else { show_error ('Não foram encontrados os dados'); } $this->setURL ($data); $this->layout = 'dashboard'; $this->parser->parse('secretaria/admissao_form', $data); } }
hsystemherbert/sigiad
application/controllers/financeiro/LancamentoDizimo.php
PHP
apache-2.0
4,103
package me.lake.sample; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
lakeinchina/Live4Danmaku
sample/src/androidTest/java/me/lake/sample/ApplicationTest.java
Java
apache-2.0
345
# Batopedina pulvinellata Robbr. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Batopedina/Batopedina pulvinellata/README.md
Markdown
apache-2.0
188
package io.udash.logging import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory class UdashLogger(clazz: Class[_]) extends CrossLogger { private val internalLogger = Logger(LoggerFactory.getLogger(clazz.getName)) override def debug(message: String, params: Any*): Unit = internalLogger.debug(message, params) override def debug(message: String, cause: Throwable): Unit = internalLogger.debug(message, cause) override def info(message: String, params: Any*): Unit = internalLogger.info(message, params) override def info(message: String, cause: Throwable): Unit = internalLogger.info(message, cause) override def warn(message: String, params: Any*): Unit = internalLogger.warn(message, params) override def warn(message: String, cause: Throwable): Unit = internalLogger.warn(message, cause) override def error(message: String, params: Any*): Unit = internalLogger.error(message, params) override def error(message: String, cause: Throwable): Unit = internalLogger.error(message, cause) }
UdashFramework/udash-core
utils/.jvm/src/main/scala/io/udash/logging/UdashLogger.scala
Scala
apache-2.0
1,063
(function() { window.WallTime || (window.WallTime = {}); window.WallTime.data = { rules: {}, zones: {"Etc/GMT+10":[{"name":"Etc/GMT+10","_offset":"-10","_rule":"-","format":"GMT+10","_until":""}]} }; window.WallTime.autoinit = true; }).call(this);
badlogicmanpreet/aura
aura-resources/src/main/resources/aura/resources/walltime-js/olson/walltime-data_Etc-GMT+10.js
JavaScript
apache-2.0
280
@charset "UTF-8"; /* CSS Document */ #container { position: absolute; left: 50%; top: 0px; background-image: url(../Images/ALLPRODUCTS/backgroundallproducts.jpg); height: 2000px; width: 1676px; margin-top: 0px; margin-left: -840px; background-repeat: no-repeat; } #Table_01 { width: 960px; height: 2000px; margin-top: 0px; margin-right: auto; margin-left: auto; } #top_ { left: 0px; top: 0px; width: 960px; height: 92px; float: left; } #logo_ { left: 0px; top: 0px; width: 121px; height: 86px; background-repeat: no-repeat; float: left; } #balkboven_ { left: 121px; top: 0px; width: 839px; height: 56px; float: left; background-repeat: no-repeat; } #menu_ { left: 121px; top: 56px; width: 800px; height: 30px; float: left; background-image: url(../Images/HOME/menu.png); background-repeat: no-repeat; } #naastmenu_ { left: 921px; top: 56px; width: 39px; height: 30px; float: left; background-image: url(../Images/HOME/naastmenu.png); background-repeat: no-repeat; } #lijnondermenuwit_ { left: 0px; top: 86px; width: 960px; height: 7px; float: left; background-image: url(../Images/HOME/lijnondermenuwit.png); background-repeat: no-repeat; } #banner_ { left: 0px; top: 92px; width: 960px; height: 320px; float: left; background-image: url(../Images/Bannerfotos/Header-Category_Community_980x545-01.jpg); background-repeat: no-repeat; } #lijnonderbanner_ { left: 0px; top: 412px; width: 960px; height: 28px; float: left; background-image: url(../Images/ALLPRODUCTS/lijnonderbanner.png); background-repeat: no-repeat; } #blauw_ { left: 0px; top: 440px; width: 205px; height: 500px; float: left; background-image: url(../Images/ATHLETES/normaal/blauw.png); background-repeat: no-repeat; padding-top: 10px; padding-left: 25px; padding-right: 30px; padding-bottom: 750px; } #tussenblauwenathletes_ { left: 0px; top: 440px; width: 61px; height: 480px; float: left; background-repeat: no-repeat; } #titelproduct_ { left: 244px; top: 440px; width: 700px; height: 31px; float: left; background-image: url(../Images/ALLPRODUCTS/titelproduct.png); background-repeat: no-repeat; padding-top: 35px; padding-bottom: 1px; } #grijzeblokjesbalk_ { left: 244px; top: 507px; width: 459px; height: 21px; float: left; background-image: url(../Images/ALLPRODUCTS/grijzeblokjesbalk.png); background-repeat: no-repeat; } #allproducts-07_ { left: 703px; top: 507px; width: 21px; height: 21px; float: left; background-image: url(../Images/ALLPRODUCTS/allproducts_07.png); background-repeat: no-repeat; } #grijzeblokjesbalk008_ { left: 724px; top: 507px; width: 220px; height: 21px; background-image: url(../Images/ALLPRODUCTS/grijzeblokjesbalk-08.png); background-repeat: no-repeat; float: left; } #maintekst_ { left: 244px; top: 440px; width: 700px; height: 90px; float: left; background-repeat: no-repeat; padding-top: 5px; } #blokvoorathletes_ { left: 244px; top: 440px; width: 700px; height: 1069px; float: left; background-repeat: no-repeat; } #andypotts_ { left: 260px; top: 440px; width: 220px; height: 191px; float: left; background-repeat: no-repeat; } #wit1_ { left:480px; top:440px; width:20px; height:191px; float: left; } #camdye_ { left:500px; top:440px; width:220px; height:191px; float: left; } #wit2_ { left:720px; top:440px; width:20px; height:191px; float: left; } #iantorrence_ { left:740px; top:440px; width:220px; height:191px; float: left; } #balk1_ { left:260px; top:631px; width:700px; height:20px; float: left; } #holdencomeau_ { left:260px; top:651px; width:220px; height:191px; float: left; } #athlets-17_ { left:480px; top:651px; width:20px; height:191px; float: left; } #jammesbonnet_ { left:500px; top:651px; width:220px; height:191px; float: left; } #athlets-19_ { left:720px; top:651px; width:20px; height:191px; float: left; } #paulettezillmer_ { left:740px; top:651px; width:220px; height:191px; float: left; } #balk2_ { left:260px; top:842px; width:700px; height:20px; float: left; } #maxfennell_ { left:260px; top:862px; width:220px; height:192px; float: left; } #athlets-23_ { left:480px; top:862px; width:20px; height:192px; float: left; } #briantinder_ { left:500px; top:862px; width:220px; height:192px; float: left; } #athlets-25_ { left:720px; top:862px; width:20px; height:192px; float: left; } #mikewardian_ { left:740px; top:862px; width:220px; height:192px; float: left; } #athlets-27_ { left:260px; top:1054px; width:700px; height:20px; float: left; } #joshbrimhall_ { left:260px; top:1074px; width:220px; height:191px; float: left; } #athlets-29_ { left:480px; top:1074px; width:20px; height:191px; float: left; } #krentbriney_ { left:500px; top:1074px; width:220px; height:191px; float: left; } #athlets-31_ { left:720px; top:1074px; width:20px; height:191px; float: left; } #breelambert_ { left:740px; top:1074px; width:220px; height:191px; float: left; } #pamreed_ { left:260px; top:1265px; width:700px; height:20px; float: left; } #athlets-34_ { left:260px; top:1285px; width:220px; height:191px; float: left; } #athlets-35_ { left:480px; top:1285px; width:20px; height:191px; float: left; } #mikemorton_ { left:500px; top:1285px; width:220px; height:191px; float: left; } #athlets-37_ { left:720px; top:1285px; width:20px; height:191px; float: left; } #emilyharrison_ { left:740px; top:1285px; width:220px; height:191px; float: left; } #onder_ { left:260px; top:1476px; width:700px; height:33px; float: left; } #balkonderfotos_ { left: 0px; top: 1475px; width: 960px; height: 34px; background-repeat: no-repeat; float: left; background-color: #FFF; } #footerblok_ { left: 0px; top: 1087px; width: 960px; height: 422px; background-repeat: no-repeat; float: left; } #balkgrijsoranjevanfooterboven_ { left: 0px; top: 1087px; width: 960px; height: 19px; background-image: url(../Images/HOME/balkgrijsoranjevanfooterboven.png); background-repeat: no-repeat; float: left; } #footerfoto1_ { left: 0px; top: 1106px; width: 300px; height: 257px; background-image: url(../Images/HOME/footerfoto1.png); background-repeat: no-repeat; float: left; } #geel1_ { left: 300px; top: 1106px; width: 30px; height: 257px; background-image: url(../Images/HOME/geel1.png); background-repeat: no-repeat; float: left; } #footerfoto2_ { left: 330px; top: 1106px; width: 300px; height: 257px; background-image: url(../Images/HOME/footerfoto2.png); background-repeat: no-repeat; float: left; } #geel2_ { left: 630px; top: 1106px; width: 30px; height: 257px; background-image: url(../Images/HOME/geel2.png); background-repeat: no-repeat; float: left; } #footerfoto3_ { left: 660px; top: 1106px; width: 300px; height: 257px; background-image: url(../Images/HOME/footerfoto3.png); background-repeat: no-repeat; float: left; } #geelbalkfooter_ { left: 0px; top: 1363px; width: 960px; height: 10px; background-image: url(../Images/HOME/geelbalkfooter.png); background-repeat: no-repeat; float: left; } #footeronder_ { left: 0px; top: 1373px; width: 840px; height: 116px; background-image: url(../Images/HOME/footeronder.png); background-repeat: no-repeat; float: left; padding-top: 20px; padding-left: 120px; } .maintekst { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #575656; text-decoration: none; font-weight: normal; line-height: 20px; text-align: left; text-transform: uppercase; } .maintekstvet { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #575656; text-decoration: none; font-weight: bold; line-height: 20px; text-align: left; text-transform: uppercase; } .Hoofdtekstgrijsblok { font-family: Arial, Helvetica, sans-serif; font-size: 16px; color: #FFFFFF; text-decoration: none; font-weight: normal; line-height: 30px; text-align: left; text-transform: uppercase; } .Tekstgrijsblokmain { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #FFFFFF; text-decoration: none; font-weight: normal; line-height: 20px; text-align: left; text-transform: uppercase; } .Hoofdfootertekst { font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: #FFFFFF; text-decoration: none; font-weight: normal; line-height: 30px; text-align: left; text-transform: uppercase; word-spacing: 0.4cm; } .Onderfootertekst { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #FFFFFF; text-decoration: none; font-weight: normal; line-height: 20px; text-align: left; word-spacing: 0.2cm; text-transform: uppercase; } .copyright{ font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #FFFFFF; text-decoration: none; font-weight: normal; line-height: 20px; text-align: left; text-transform: uppercase; } .Producttitel { font-family: Arial, Helvetica, sans-serif; font-size: 24px; color: #484743; text-decoration: none; font-weight: bold; line-height: 30px; text-align: left; text-transform: uppercase; } .Submenu { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #FFFFFF; text-decoration: none; font-weight: normal; line-height: 30px; text-align: left; text-transform: uppercase; } .Submenutop { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #000000; text-decoration: none; font-weight: bold; line-height: 20px; text-align: left; text-transform: uppercase; } .Tekstgrijsblokmainklein { font-family: Arial, Helvetica, sans-serif; font-size: 11px; color: #FFFFFF; text-decoration: none; font-weight: normal; line-height: 20px; text-align: left; text-transform: uppercase; } .Oranjegroot { font-family: Arial, Helvetica, sans-serif; font-size: 24px; color: #f8a01a; text-decoration: none; font-weight: bold; line-height: 30px; text-align: left; text-transform: uppercase; } .kruimelpad { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #289dde; text-decoration: none; font-weight: bold; line-height: 20px; text-align: left; text-transform: uppercase; }
Sparring/sparring-v1.0-beta
assets/Include/athletes.css
CSS
apache-2.0
10,205
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_14) on Wed Sep 10 22:04:22 CST 2014 --> <TITLE> Àà darks.orm.core.data.tags.express.impl.AndOper µÄʹÓà </TITLE> <META NAME="date" CONTENT="2014-09-10"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Àà darks.orm.core.data.tags.express.impl.AndOper µÄʹÓÃ"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Ìø¹ýµ¼º½Á´½Ó"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>¸ÅÊö</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Èí¼þ°ü</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../darks/orm/core/data/tags/express/impl/AndOper.html" title="darks.orm.core.data.tags.express.impl ÖеÄÀà"><FONT CLASS="NavBarFont1"><B>Àà</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>ʹÓÃ</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Ê÷</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Òѹýʱ</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Ë÷Òý</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>°ïÖú</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;ÉÏÒ»¸ö&nbsp; &nbsp;ÏÂÒ»¸ö</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?darks/orm/core/data/tags/express/impl/\class-useAndOper.html" target="_top"><B>¿ò¼Ü</B></A> &nbsp; &nbsp;<A HREF="AndOper.html" target="_top"><B>ÎÞ¿ò¼Ü</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Àà darks.orm.core.data.tags.express.impl.AndOper<br>µÄʹÓÃ</B></H2> </CENTER> ûÓÐ darks.orm.core.data.tags.express.impl.AndOper µÄÓ÷¨ <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Ìø¹ýµ¼º½Á´½Ó"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>¸ÅÊö</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Èí¼þ°ü</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../darks/orm/core/data/tags/express/impl/AndOper.html" title="darks.orm.core.data.tags.express.impl ÖеÄÀà"><FONT CLASS="NavBarFont1"><B>Àà</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>ʹÓÃ</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Ê÷</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Òѹýʱ</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Ë÷Òý</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>°ïÖú</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;ÉÏÒ»¸ö&nbsp; &nbsp;ÏÂÒ»¸ö</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?darks/orm/core/data/tags/express/impl/\class-useAndOper.html" target="_top"><B>¿ò¼Ü</B></A> &nbsp; &nbsp;<A HREF="AndOper.html" target="_top"><B>ÎÞ¿ò¼Ü</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
liulhdarks/darks-orm
doc/darks/orm/core/data/tags/express/impl/class-use/AndOper.html
HTML
apache-2.0
6,063
/** * :copyright: (c) 2014 Building Energy Inc * :license: see LICENSE for more details. */ angular.module('BE.seed.controller.dataset', []) .controller('dataset_list_controller', [ '$scope', 'datasets_payload', '$modal', 'urls', 'dataset_service', '$location', function ($scope, datasets_payload, $modal, urls, dataset_service, $location) { $scope.datasets = datasets_payload.datasets; $scope.columns = [ { title: "Data Set Name" }, { title: "# Of Files" }, { title: "Last Changed" }, { title: "Changed By" }, { title: "Actions" } ]; /** * Functions for dealing with editing a dataset's name */ $scope.edit_dataset_name = function (dataset) { dataset.edit_form_showing = true; dataset.old_name = dataset.name; }; $scope.cancel_edit_name = function (dataset) { dataset.name = dataset.old_name; dataset.edit_form_showing = false; }; $scope.save_dataset_name = function (dataset) { if (dataset.name !== dataset.old_name) { $scope.update_dataset(dataset); dataset.edit_form_showing = false; } }; /** * open_data_upload_modal: opens the data upload modal to step 4, add energy files */ $scope.open_data_upload_modal = function(dataset) { var step = 2; if (typeof dataset === "undefined"){ step = 1; dataset = {}; } else if ($scope.missing_assessor_files(dataset)) { step = 2; } var dataModalInstance = $modal.open({ templateUrl: urls.static_url + 'seed/partials/data_upload_modal.html', controller: 'data_upload_modal_ctrl', resolve: { step: function(){ return step; }, dataset: function(){ return dataset; } } }); dataModalInstance.result.then( // modal close() function function () { init(); // modal dismiss() function }, function (message) { init(); }); }; $scope.confirm_delete = function (dataset) { var yes = confirm("Are you sure you want to PERMANENTLY delete '" + dataset.name + "'?"); if (yes) { $scope.delete_dataset(dataset); } }; $scope.delete_dataset = function(dataset) { dataset_service.delete_dataset(dataset.id).then(function(data) { // resolve promise init(); }); }; $scope.update_dataset = function(dataset) { dataset_service.update_dataset(dataset).then(function(data){ // resolve promise init(); }); }; /** * goto_mapping: changes browser location to the first assessed file * mapping page */ $scope.goto_mapping = function(dataset) { for (var i=0; i < dataset.importfiles.length; i++){ var importfile = dataset.importfiles[i]; if (importfile.source_type === "Assessed Raw") { $location.path('/data/mapping/' + importfile.id); break; } } }; /** * goto_mapping: changes browser location to the first portfolio file * matching page */ $scope.goto_matching = function(dataset) { for (var i=0; i < dataset.importfiles.length; i++){ var importfile = dataset.importfiles[i]; if (importfile.source_type === "Portfolio Raw") { $location.path('/data/matching/' + importfile.id); break; } } }; /** * missing_assessor_files: true if the dataset has no assessed files */ $scope.missing_assessor_files = function(dataset) { for (var i=0; i < dataset.importfiles.length; i++){ var importfile = dataset.importfiles[i]; if (importfile.source_type === "Assessed Raw") { return false; } } return true; }; /** * missing_pm_files: true if the dataset has no Portfolio Manager files */ $scope.missing_pm_files = function(dataset) { for (var i=0; i < dataset.importfiles.length; i++){ var importfile = dataset.importfiles[i]; if (importfile.source_type === "Portfolio Raw") { return false; } } return true; }; /** * event brocasted from menu controller when a new dataset is added */ $scope.$on('datasets_updated', function(){ init(); }); /** * init: refreshes dataset list */ var init = function(){ dataset_service.get_datasets().then(function(data){ // resolve promise $scope.datasets = data.datasets; }); }; } ]);
buildingenergy/buildingenergy-platform
seed/static/seed/js/controllers/dataset_list_controller.js
JavaScript
apache-2.0
5,009
using PeNet.FileParser; namespace PeNet.Header.Pe { /// <summary> /// The export directory contains all exported function, symbols etc. /// which can be used by other module. /// </summary> public class ImageExportDirectory : AbstractStructure { /// <summary> /// Create a new ImageExportDirectory object. /// </summary> /// <param name="peFile">A PE file.</param> /// <param name="offset">Raw offset of the export directory in the PE file.</param> public ImageExportDirectory(IRawFile peFile, long offset) : base(peFile, offset) { } /// <summary> /// The characteristics of the export directory. /// </summary> public uint Characteristics { get => PeFile.ReadUInt(Offset); set => PeFile.WriteUInt(Offset, value); } /// <summary> /// Time and date stamp. /// </summary> public uint TimeDateStamp { get => PeFile.ReadUInt(Offset + 0x4); set => PeFile.WriteUInt(Offset + 0x4, value); } /// <summary> /// Major Version. /// </summary> public ushort MajorVersion { get => PeFile.ReadUShort(Offset + 0x8); set => PeFile.WriteUShort(Offset + 0x8, value); } /// <summary> /// Minor Version. /// </summary> public ushort MinorVersion { get => PeFile.ReadUShort(Offset + 0xA); set => PeFile.WriteUShort(Offset + 0xA, value); } /// <summary> /// Name. /// </summary> public uint Name { get => PeFile.ReadUInt(Offset + 0xC); set => PeFile.WriteUInt(Offset + 0xC, value); } /// <summary> /// Base. /// </summary> public uint Base { get => PeFile.ReadUInt(Offset + 0x10); set => PeFile.WriteUInt(Offset + 0x10, value); } /// <summary> /// Number of exported functions. /// </summary> public uint NumberOfFunctions { get => PeFile.ReadUInt(Offset + 0x14); set => PeFile.WriteUInt(Offset + 0x14, value); } /// <summary> /// Number of exported names. /// </summary> public uint NumberOfNames { get => PeFile.ReadUInt(Offset + 0x18); set => PeFile.WriteUInt(Offset + 0x18, value); } /// <summary> /// RVA to the addresses of the functions. /// </summary> public uint AddressOfFunctions { get => PeFile.ReadUInt(Offset + 0x1C); set => PeFile.WriteUInt(Offset + 0x1C, value); } /// <summary> /// RVA to the addresses of the names. /// </summary> public uint AddressOfNames { get => PeFile.ReadUInt(Offset + 0x20); set => PeFile.WriteUInt(Offset + 0x20, value); } /// <summary> /// RVA to the name ordinals. /// </summary> public uint AddressOfNameOrdinals { get => PeFile.ReadUInt(Offset + 0x24); set => PeFile.WriteUInt(Offset + 0x24, value); } } }
secana/PeNet
src/PeNet/Header/Pe/ImageExportDirectory.cs
C#
apache-2.0
3,397
package jeffaschenk.commons.standards.statecodes; import jeffaschenk.commons.standards.CountryCode; /** * Official ISO-3166 State/Province Codes * <p/> * Country: Lao Peoples Democratic Republic * * @author jeffaschenk@gmail.com * Date: May 19, 2010 * Time: 12:12:11 PM */ @SuppressWarnings("unused") public enum StateCodes_LA { /** * State Code Enumerator */ LA_AT("Attapu [Attopeu]","LA-AT","province","15080", CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_BK("Bok\u0232o","LA-BK","province","15081",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_BL("Bolikhamxai [Borikhane]","LA-BL","province","15089",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_CH("Champasak [Champassak]","LA-CH","province","15082",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_HO("Houaphan","LA-HO","province","15093",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_KH("Khammouan","LA-KH","province","15094",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_LM("Louang Namtha","LA-LM","province","15083",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_LP("Louangphabang [Louang Prabang]","LA-LP","province","15092",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_OU("Oud\u0244mxai [Oudomsai]","LA-OU","province","15084",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_PH("Ph\u0244ngsali [Phong Saly]","LA-PH","province","15085",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_SL("Salavan [Saravane]","LA-SL","province","15091",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_SV("Savannakh\u0233t","LA-SV","province","15086",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_VI("Vientiane","LA-VI","province","15095",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_VT("Vientiane Prefecture","LA-VT","prefecture","15087",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_XA("Xaignabouli [Sayaboury]","LA-XA","province","15088",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_XN("Xais\u0244mboun","LA-XN","special zone","15096",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_XI("Xiangkhoang [Xieng Khouang]","LA-XI","province","15079",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC), LA_XE("X\u0233kong [S\u0233kong]","LA-XE","province","15090",CountryCode.LAO_PEOPLES_DEMOCRATIC_REPUBLIC); // ************************************* // Common Enum Structure for all // States of the World private final String stateProvinceName; private final String stateCode; private final String stateProvinceType; private final String stateNumericCode; private final CountryCode countryCode; StateCodes_LA(String stateProvinceName, String stateCode, String stateProvinceType, String stateNumericCode, CountryCode countryCode) { this.stateProvinceName = stateProvinceName; this.stateCode = stateCode; this.stateProvinceType = stateProvinceType; this.stateNumericCode = stateNumericCode; this.countryCode = countryCode; } public String stateProvinceName() { return this.stateProvinceName; } public String stateCode() { return this.stateCode; } public String stateProvinceType() { return this.stateProvinceType; } public String stateNumericCode() { return this.stateNumericCode; } public CountryCode countryCode() { return this.countryCode; } }
jaschenk/jeffaschenk-commons
src/main/java/jeffaschenk/commons/standards/statecodes/StateCodes_LA.java
Java
apache-2.0
3,468
/* * 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.servicecomb.demo.springmvc.server; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import javax.validation.constraints.Min; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response.Status; import org.apache.servicecomb.demo.controller.Person; import org.apache.servicecomb.provider.rest.common.RestSchema; import org.apache.servicecomb.swagger.invocation.exception.InvocationException; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; // This class tests "contract first", the controller.yaml will override annotations defined in class. @RestSchema(schemaId = "controller") @RequestMapping(path = "/springmvc/controller", produces = MediaType.APPLICATION_JSON) public class ControllerImpl { @GetMapping(path = "/add") public int add(@Min(1) @RequestParam("a") int a, @Min(1) @RequestParam("b") int b) { return a + b; } @PostMapping(path = "/sayhello/{name}") public String sayHello(@PathVariable("name") String name) { if ("exception".equals(name)) { throw new InvocationException(Status.SERVICE_UNAVAILABLE, ""); } return "hello " + name; } @RequestMapping(path = "/saysomething", method = RequestMethod.POST) public String saySomething(String prefix, @RequestBody Person user) { return prefix + " " + user.getName(); } // Parameters defined in controller.yaml. The code definition do not have any parameters. @RequestMapping(path = "/sayhi", method = RequestMethod.GET) public String sayHi(HttpServletRequest request) throws Exception { String addr = request.getRemoteAddr(); if (addr == null || addr.isEmpty()) { throw new Exception("Can't get remote addr!"); } String[] values = request.getParameterValues("name"); if (values != null && values.length > 0 && values[0].equals("throwexception")) { throw new RuntimeException(); } return "hi " + request.getParameter("name") + " " + Arrays.toString(values); } @RequestMapping(path = "/sayhei", method = RequestMethod.GET) public String sayHei(@RequestHeader("name") String name) { return "hei " + name; } }
ServiceComb/java-chassis
demo/demo-springmvc/springmvc-server/src/main/java/org/apache/servicecomb/demo/springmvc/server/ControllerImpl.java
Java
apache-2.0
3,364
# EarthquakeEvent ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **dateTime** | [**DateTimeEarthQuake**](DateTimeEarthQuake.md) | | [optional] **seismicRegionNumber** | **Integer** | | [optional] **depth** | [**Depth**](Depth.md) | | [optional] **magnitude** | [**Magnitude**](Magnitude.md) | | [optional] **cause** | **String** | | [optional] **culturalEffect** | **String** | | [optional] **intensity** | **Integer** | | [optional] **diastrophism** | **String** | | [optional] **miscPhenomena** | **String** | | [optional] **location** | [**EarthquakeLocation**](EarthquakeLocation.md) | | [optional]
PitneyBowes/LocationIntelligenceSDK-Java
docs/EarthquakeEvent.md
Markdown
apache-2.0
690
/* * 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.hyracks.control.common.ipc; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.net.URL; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.hyracks.api.client.NodeControllerInfo; import org.apache.hyracks.api.comm.NetworkAddress; import org.apache.hyracks.api.dataflow.ActivityId; import org.apache.hyracks.api.dataflow.ConnectorDescriptorId; import org.apache.hyracks.api.dataflow.OperatorDescriptorId; import org.apache.hyracks.api.dataflow.TaskAttemptId; import org.apache.hyracks.api.dataflow.TaskId; import org.apache.hyracks.api.dataflow.connectors.ConnectorPolicyFactory; import org.apache.hyracks.api.dataflow.connectors.IConnectorPolicy; import org.apache.hyracks.api.dataset.ResultSetId; import org.apache.hyracks.api.deployment.DeploymentId; import org.apache.hyracks.api.job.JobFlag; import org.apache.hyracks.api.job.JobId; import org.apache.hyracks.api.job.JobStatus; import org.apache.hyracks.api.partitions.PartitionId; import org.apache.hyracks.control.common.controllers.NodeParameters; import org.apache.hyracks.control.common.controllers.NodeRegistration; import org.apache.hyracks.control.common.deployment.DeploymentStatus; import org.apache.hyracks.control.common.heartbeat.HeartbeatData; import org.apache.hyracks.control.common.job.PartitionDescriptor; import org.apache.hyracks.control.common.job.PartitionRequest; import org.apache.hyracks.control.common.job.PartitionState; import org.apache.hyracks.control.common.job.TaskAttemptDescriptor; import org.apache.hyracks.control.common.job.profiling.om.JobProfile; import org.apache.hyracks.control.common.job.profiling.om.TaskProfile; import org.apache.hyracks.ipc.api.IPayloadSerializerDeserializer; import org.apache.hyracks.ipc.impl.JavaSerializationBasedPayloadSerializerDeserializer; public class CCNCFunctions { private static final Logger LOGGER = Logger.getLogger(CCNCFunctions.class.getName()); private static final int FID_CODE_SIZE = 1; public enum FunctionId { REGISTER_NODE, UNREGISTER_NODE, NOTIFY_JOBLET_CLEANUP, NOTIFY_TASK_COMPLETE, NOTIFY_TASK_FAILURE, NODE_HEARTBEAT, REPORT_PROFILE, REGISTER_PARTITION_PROVIDER, REGISTER_PARTITION_REQUEST, REGISTER_RESULT_PARTITION_LOCATION, REPORT_RESULT_PARTITION_WRITE_COMPLETION, REPORT_RESULT_PARTITION_FAILURE, NODE_REGISTRATION_RESULT, START_TASKS, ABORT_TASKS, CLEANUP_JOBLET, REPORT_PARTITION_AVAILABILITY, SEND_APPLICATION_MESSAGE, GET_NODE_CONTROLLERS_INFO, GET_NODE_CONTROLLERS_INFO_RESPONSE, DEPLOY_BINARY, NOTIFY_DEPLOY_BINARY, UNDEPLOY_BINARY, SHUTDOWN_REQUEST, SHUTDOWN_RESPONSE, DISTRIBUTE_JOB, DESTROY_JOB, DISTRIBUTED_JOB_FAILURE, STATE_DUMP_REQUEST, STATE_DUMP_RESPONSE, THREAD_DUMP_REQUEST, THREAD_DUMP_RESPONSE, OTHER } public static class SendApplicationMessageFunction extends Function { private static final long serialVersionUID = 1L; private byte[] serializedMessage; private DeploymentId deploymentId; private String nodeId; public DeploymentId getDeploymentId() { return deploymentId; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public byte[] getMessage() { return serializedMessage; } public SendApplicationMessageFunction(byte[] data, DeploymentId deploymentId, String nodeId) { this.serializedMessage = data; this.deploymentId = deploymentId; this.nodeId = nodeId; } @Override public FunctionId getFunctionId() { return FunctionId.SEND_APPLICATION_MESSAGE; } } public static abstract class Function implements Serializable { private static final long serialVersionUID = 1L; public abstract FunctionId getFunctionId(); } public static class RegisterNodeFunction extends Function { private static final long serialVersionUID = 1L; private final NodeRegistration reg; public RegisterNodeFunction(NodeRegistration reg) { this.reg = reg; } @Override public FunctionId getFunctionId() { return FunctionId.REGISTER_NODE; } public NodeRegistration getNodeRegistration() { return reg; } } public static class UnregisterNodeFunction extends Function { private static final long serialVersionUID = 1L; private final String nodeId; public UnregisterNodeFunction(String nodeId) { this.nodeId = nodeId; } @Override public FunctionId getFunctionId() { return FunctionId.UNREGISTER_NODE; } public String getNodeId() { return nodeId; } } public static class NotifyTaskCompleteFunction extends Function { private static final long serialVersionUID = 1L; private JobId jobId; private TaskAttemptId taskId; private String nodeId; private TaskProfile statistics; public NotifyTaskCompleteFunction(JobId jobId, TaskAttemptId taskId, String nodeId, TaskProfile statistics) { this.jobId = jobId; this.taskId = taskId; this.nodeId = nodeId; this.statistics = statistics; } @Override public FunctionId getFunctionId() { return FunctionId.NOTIFY_TASK_COMPLETE; } public JobId getJobId() { return jobId; } public TaskAttemptId getTaskId() { return taskId; } public String getNodeId() { return nodeId; } public TaskProfile getStatistics() { return statistics; } public static Object deserialize(ByteBuffer buffer, int length) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), length); DataInputStream dis = new DataInputStream(bais); JobId jobId = JobId.create(dis); String nodeId = dis.readUTF(); TaskAttemptId taskId = TaskAttemptId.create(dis); TaskProfile statistics = TaskProfile.create(dis); return new NotifyTaskCompleteFunction(jobId, taskId, nodeId, statistics); } public static void serialize(OutputStream out, Object object) throws Exception { NotifyTaskCompleteFunction fn = (NotifyTaskCompleteFunction) object; DataOutputStream dos = new DataOutputStream(out); fn.jobId.writeFields(dos); dos.writeUTF(fn.nodeId); fn.taskId.writeFields(dos); fn.statistics.writeFields(dos); } } public static class NotifyTaskFailureFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final TaskAttemptId taskId; private final String nodeId; private final List<Exception> exceptions; public NotifyTaskFailureFunction(JobId jobId, TaskAttemptId taskId, String nodeId, List<Exception> exceptions) { this.jobId = jobId; this.taskId = taskId; this.nodeId = nodeId; this.exceptions = exceptions; } @Override public FunctionId getFunctionId() { return FunctionId.NOTIFY_TASK_FAILURE; } public JobId getJobId() { return jobId; } public TaskAttemptId getTaskId() { return taskId; } public String getNodeId() { return nodeId; } public List<Exception> getExceptions() { return exceptions; } } public static class ReportDistributedJobFailureFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final String nodeId; public ReportDistributedJobFailureFunction(JobId jobId, String nodeId) { this.jobId = jobId; this.nodeId = nodeId; } @Override public FunctionId getFunctionId() { return FunctionId.DISTRIBUTED_JOB_FAILURE; } public JobId getJobId() { return jobId; } public String getNodeId() { return nodeId; } } public static class NotifyJobletCleanupFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final String nodeId; public NotifyJobletCleanupFunction(JobId jobId, String nodeId) { this.jobId = jobId; this.nodeId = nodeId; } @Override public FunctionId getFunctionId() { return FunctionId.NOTIFY_JOBLET_CLEANUP; } public JobId getJobId() { return jobId; } public String getNodeId() { return nodeId; } public static Object deserialize(ByteBuffer buffer, int length) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), length); DataInputStream dis = new DataInputStream(bais); JobId jobId = JobId.create(dis); String nodeId = dis.readUTF(); return new NotifyJobletCleanupFunction(jobId, nodeId); } public static void serialize(OutputStream out, Object object) throws Exception { NotifyJobletCleanupFunction fn = (NotifyJobletCleanupFunction) object; DataOutputStream dos = new DataOutputStream(out); fn.jobId.writeFields(dos); dos.writeUTF(fn.nodeId); } } public static class NodeHeartbeatFunction extends Function { private static final long serialVersionUID = 1L; private final String nodeId; private final HeartbeatData hbData; public NodeHeartbeatFunction(String nodeId, HeartbeatData hbData) { this.nodeId = nodeId; this.hbData = hbData; } @Override public FunctionId getFunctionId() { return FunctionId.NODE_HEARTBEAT; } public String getNodeId() { return nodeId; } public HeartbeatData getHeartbeatData() { return hbData; } public static Object deserialize(ByteBuffer buffer, int length) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), length); DataInputStream dis = new DataInputStream(bais); String nodeId = dis.readUTF(); HeartbeatData hbData = new HeartbeatData(); hbData.readFields(dis); return new NodeHeartbeatFunction(nodeId, hbData); } public static void serialize(OutputStream out, Object object) throws Exception { NodeHeartbeatFunction fn = (NodeHeartbeatFunction) object; DataOutputStream dos = new DataOutputStream(out); dos.writeUTF(fn.nodeId); fn.hbData.write(dos); } } public static class ReportProfileFunction extends Function { private static final long serialVersionUID = 1L; private final String nodeId; private final List<JobProfile> profiles; public ReportProfileFunction(String nodeId, List<JobProfile> profiles) { this.nodeId = nodeId; this.profiles = profiles; } @Override public FunctionId getFunctionId() { return FunctionId.REPORT_PROFILE; } public String getNodeId() { return nodeId; } public List<JobProfile> getProfiles() { return profiles; } } public static class RegisterPartitionProviderFunction extends Function { private static final long serialVersionUID = 1L; private final PartitionDescriptor partitionDescriptor; public RegisterPartitionProviderFunction(PartitionDescriptor partitionDescriptor) { this.partitionDescriptor = partitionDescriptor; } @Override public FunctionId getFunctionId() { return FunctionId.REGISTER_PARTITION_PROVIDER; } public PartitionDescriptor getPartitionDescriptor() { return partitionDescriptor; } public static Object deserialize(ByteBuffer buffer, int length) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), length); DataInputStream dis = new DataInputStream(bais); // Read PartitionId PartitionId pid = readPartitionId(dis); // Read nodeId String nodeId = dis.readUTF(); // Read TaskAttemptId TaskAttemptId taId = readTaskAttemptId(dis); // Read reusable flag boolean reusable = dis.readBoolean(); // Read Partition State PartitionState state = readPartitionState(dis); PartitionDescriptor pd = new PartitionDescriptor(pid, nodeId, taId, reusable); pd.setState(state); return new RegisterPartitionProviderFunction(pd); } public static void serialize(OutputStream out, Object object) throws Exception { RegisterPartitionProviderFunction fn = (RegisterPartitionProviderFunction) object; DataOutputStream dos = new DataOutputStream(out); PartitionDescriptor pd = fn.getPartitionDescriptor(); // Write PartitionId writePartitionId(dos, pd.getPartitionId()); // Write nodeId dos.writeUTF(pd.getNodeId()); // Write TaskAttemptId writeTaskAttemptId(dos, pd.getProducingTaskAttemptId()); // Write reusable flag dos.writeBoolean(pd.isReusable()); // Write Partition State writePartitionState(dos, pd.getState()); } } public static class RegisterPartitionRequestFunction extends Function { private static final long serialVersionUID = 1L; private final PartitionRequest partitionRequest; public RegisterPartitionRequestFunction(PartitionRequest partitionRequest) { this.partitionRequest = partitionRequest; } @Override public FunctionId getFunctionId() { return FunctionId.REGISTER_PARTITION_REQUEST; } public PartitionRequest getPartitionRequest() { return partitionRequest; } public static Object deserialize(ByteBuffer buffer, int length) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), length); DataInputStream dis = new DataInputStream(bais); // Read PartitionId PartitionId pid = readPartitionId(dis); // Read nodeId String nodeId = dis.readUTF(); // Read TaskAttemptId TaskAttemptId taId = readTaskAttemptId(dis); // Read Partition State PartitionState state = readPartitionState(dis); PartitionRequest pr = new PartitionRequest(pid, nodeId, taId, state); return new RegisterPartitionRequestFunction(pr); } public static void serialize(OutputStream out, Object object) throws Exception { RegisterPartitionRequestFunction fn = (RegisterPartitionRequestFunction) object; DataOutputStream dos = new DataOutputStream(out); PartitionRequest pr = fn.getPartitionRequest(); // Write PartitionId writePartitionId(dos, pr.getPartitionId()); // Write nodeId dos.writeUTF(pr.getNodeId()); // Write TaskAttemptId writeTaskAttemptId(dos, pr.getRequestingTaskAttemptId()); // Write Partition State writePartitionState(dos, pr.getMinimumState()); } } public static class RegisterResultPartitionLocationFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final ResultSetId rsId; private final boolean orderedResult; private final boolean emptyResult; private final int partition; private final int nPartitions; private NetworkAddress networkAddress; public RegisterResultPartitionLocationFunction(JobId jobId, ResultSetId rsId, boolean orderedResult, boolean emptyResult, int partition, int nPartitions, NetworkAddress networkAddress) { this.jobId = jobId; this.rsId = rsId; this.orderedResult = orderedResult; this.emptyResult = emptyResult; this.partition = partition; this.nPartitions = nPartitions; this.networkAddress = networkAddress; } @Override public FunctionId getFunctionId() { return FunctionId.REGISTER_RESULT_PARTITION_LOCATION; } public JobId getJobId() { return jobId; } public ResultSetId getResultSetId() { return rsId; } public boolean getOrderedResult() { return orderedResult; } public boolean getEmptyResult() { return emptyResult; } public int getPartition() { return partition; } public int getNPartitions() { return nPartitions; } public NetworkAddress getNetworkAddress() { return networkAddress; } } public static class ReportResultPartitionWriteCompletionFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final ResultSetId rsId; private final int partition; public ReportResultPartitionWriteCompletionFunction(JobId jobId, ResultSetId rsId, int partition) { this.jobId = jobId; this.rsId = rsId; this.partition = partition; } @Override public FunctionId getFunctionId() { return FunctionId.REPORT_RESULT_PARTITION_WRITE_COMPLETION; } public JobId getJobId() { return jobId; } public ResultSetId getResultSetId() { return rsId; } public int getPartition() { return partition; } } public static class ReportResultPartitionFailureFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final ResultSetId rsId; private final int partition; public ReportResultPartitionFailureFunction(JobId jobId, ResultSetId rsId, int partition) { this.jobId = jobId; this.rsId = rsId; this.partition = partition; } @Override public FunctionId getFunctionId() { return FunctionId.REPORT_RESULT_PARTITION_FAILURE; } public JobId getJobId() { return jobId; } public ResultSetId getResultSetId() { return rsId; } public int getPartition() { return partition; } } public static class NodeRegistrationResult extends Function { private static final long serialVersionUID = 1L; private final NodeParameters params; private final Exception exception; public NodeRegistrationResult(NodeParameters params, Exception exception) { this.params = params; this.exception = exception; } @Override public FunctionId getFunctionId() { return FunctionId.NODE_REGISTRATION_RESULT; } public NodeParameters getNodeParameters() { return params; } public Exception getException() { return exception; } } public static class DistributeJobFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final byte[] acgBytes; public DistributeJobFunction(JobId jobId, byte[] acgBytes) { this.jobId = jobId; this.acgBytes = acgBytes; } @Override public FunctionId getFunctionId() { return FunctionId.DISTRIBUTE_JOB; } public JobId getJobId() { return jobId; } public byte[] getacgBytes() { return acgBytes; } } public static class DestroyJobFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; public DestroyJobFunction(JobId jobId) { this.jobId = jobId; } @Override public FunctionId getFunctionId() { return FunctionId.DESTROY_JOB; } public JobId getJobId() { return jobId; } } public static class StartTasksFunction extends Function { private static final long serialVersionUID = 1L; private final DeploymentId deploymentId; private final JobId jobId; private final byte[] planBytes; private final List<TaskAttemptDescriptor> taskDescriptors; private final Map<ConnectorDescriptorId, IConnectorPolicy> connectorPolicies; private final Set<JobFlag> flags; public StartTasksFunction(DeploymentId deploymentId, JobId jobId, byte[] planBytes, List<TaskAttemptDescriptor> taskDescriptors, Map<ConnectorDescriptorId, IConnectorPolicy> connectorPolicies, Set<JobFlag> flags) { this.deploymentId = deploymentId; this.jobId = jobId; this.planBytes = planBytes; this.taskDescriptors = taskDescriptors; this.connectorPolicies = connectorPolicies; this.flags = flags; } @Override public FunctionId getFunctionId() { return FunctionId.START_TASKS; } public DeploymentId getDeploymentId() { return deploymentId; } public JobId getJobId() { return jobId; } public byte[] getPlanBytes() { return planBytes; } public List<TaskAttemptDescriptor> getTaskDescriptors() { return taskDescriptors; } public Map<ConnectorDescriptorId, IConnectorPolicy> getConnectorPolicies() { return connectorPolicies; } public Set<JobFlag> getFlags() { return flags; } public static Object deserialize(ByteBuffer buffer, int length) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), length); DataInputStream dis = new DataInputStream(bais); //read jobId and taskId JobId jobId = JobId.create(dis); DeploymentId deploymentId = null; boolean hasDeployed = dis.readBoolean(); if (hasDeployed) { deploymentId = DeploymentId.create(dis); } // read plan bytes int planBytesSize = dis.readInt(); byte[] planBytes = null; if (planBytesSize >= 0) { planBytes = new byte[planBytesSize]; dis.read(planBytes, 0, planBytesSize); } // read task attempt descriptors int tadSize = dis.readInt(); List<TaskAttemptDescriptor> taskDescriptors = new ArrayList<TaskAttemptDescriptor>(); for (int i = 0; i < tadSize; i++) { TaskAttemptDescriptor tad = TaskAttemptDescriptor.create(dis); taskDescriptors.add(tad); } //read connector policies int cpSize = dis.readInt(); Map<ConnectorDescriptorId, IConnectorPolicy> connectorPolicies = new HashMap<ConnectorDescriptorId, IConnectorPolicy>(); for (int i = 0; i < cpSize; i++) { ConnectorDescriptorId cid = ConnectorDescriptorId.create(dis); IConnectorPolicy policy = ConnectorPolicyFactory.INSTANCE.getConnectorPolicy(dis); connectorPolicies.put(cid, policy); } // read flags int flagSize = dis.readInt(); EnumSet<JobFlag> flags = EnumSet.noneOf(JobFlag.class); for (int i = 0; i < flagSize; i++) { flags.add(JobFlag.values()[(dis.readInt())]); } return new StartTasksFunction(deploymentId, jobId, planBytes, taskDescriptors, connectorPolicies, flags); } public static void serialize(OutputStream out, Object object) throws Exception { StartTasksFunction fn = (StartTasksFunction) object; DataOutputStream dos = new DataOutputStream(out); //write jobId and deploymentId fn.jobId.writeFields(dos); dos.writeBoolean(fn.deploymentId == null ? false : true); if (fn.deploymentId != null) { fn.deploymentId.writeFields(dos); } //write plan bytes dos.writeInt(fn.planBytes == null ? -1 : fn.planBytes.length); if (fn.planBytes != null) { dos.write(fn.planBytes, 0, fn.planBytes.length); } //write task descriptors dos.writeInt(fn.taskDescriptors.size()); for (int i = 0; i < fn.taskDescriptors.size(); i++) { fn.taskDescriptors.get(i).writeFields(dos); } //write connector policies dos.writeInt(fn.connectorPolicies.size()); for (Entry<ConnectorDescriptorId, IConnectorPolicy> entry : fn.connectorPolicies.entrySet()) { entry.getKey().writeFields(dos); ConnectorPolicyFactory.INSTANCE.writeConnectorPolicy(entry.getValue(), dos); } //write flags dos.writeInt(fn.flags.size()); for (JobFlag flag : fn.flags) { dos.writeInt(flag.ordinal()); } } } public static class AbortTasksFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final List<TaskAttemptId> tasks; public AbortTasksFunction(JobId jobId, List<TaskAttemptId> tasks) { this.jobId = jobId; this.tasks = tasks; } @Override public FunctionId getFunctionId() { return FunctionId.ABORT_TASKS; } public JobId getJobId() { return jobId; } public List<TaskAttemptId> getTasks() { return tasks; } } public static class CleanupJobletFunction extends Function { private static final long serialVersionUID = 1L; private final JobId jobId; private final JobStatus status; public CleanupJobletFunction(JobId jobId, JobStatus status) { this.jobId = jobId; this.status = status; } @Override public FunctionId getFunctionId() { return FunctionId.CLEANUP_JOBLET; } public JobId getJobId() { return jobId; } public JobStatus getStatus() { return status; } public static Object deserialize(ByteBuffer buffer, int length) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), length); DataInputStream dis = new DataInputStream(bais); JobId jobId = JobId.create(dis); JobStatus status = JobStatus.values()[dis.readInt()]; return new CleanupJobletFunction(jobId, status); } public static void serialize(OutputStream out, Object object) throws Exception { CleanupJobletFunction fn = (CleanupJobletFunction) object; DataOutputStream dos = new DataOutputStream(out); fn.jobId.writeFields(dos); dos.writeInt(fn.status.ordinal()); } } public static class GetNodeControllersInfoFunction extends Function { private static final long serialVersionUID = 1L; @Override public FunctionId getFunctionId() { return FunctionId.GET_NODE_CONTROLLERS_INFO; } } public static class GetNodeControllersInfoResponseFunction extends Function { private static final long serialVersionUID = 1L; private final Map<String, NodeControllerInfo> ncInfos; public GetNodeControllersInfoResponseFunction(Map<String, NodeControllerInfo> ncInfos) { this.ncInfos = ncInfos; } @Override public FunctionId getFunctionId() { return FunctionId.GET_NODE_CONTROLLERS_INFO_RESPONSE; } public Map<String, NodeControllerInfo> getNodeControllerInfos() { return ncInfos; } } public static class ThreadDumpRequestFunction extends Function { private static final long serialVersionUID = 1L; private final String requestId; public ThreadDumpRequestFunction(String requestId) { this.requestId = requestId; } @Override public FunctionId getFunctionId() { return FunctionId.THREAD_DUMP_REQUEST; } public String getRequestId() { return requestId; } } public static class ThreadDumpResponseFunction extends Function { private static final long serialVersionUID = 1L; private final String nodeId; private final String requestId; private final String threadDumpJSON; public ThreadDumpResponseFunction(String nodeId, String requestId, String threadDumpJSON) { this.nodeId = nodeId; this.requestId = requestId; this.threadDumpJSON = threadDumpJSON; } @Override public FunctionId getFunctionId() { return FunctionId.THREAD_DUMP_RESPONSE; } public String getNodeId() { return nodeId; } public String getRequestId() { return requestId; } public String getThreadDumpJSON() { return threadDumpJSON; } } public static class ReportPartitionAvailabilityFunction extends Function { private static final long serialVersionUID = 1L; private final PartitionId pid; private final NetworkAddress networkAddress; public ReportPartitionAvailabilityFunction(PartitionId pid, NetworkAddress networkAddress) { this.pid = pid; this.networkAddress = networkAddress; } @Override public FunctionId getFunctionId() { return FunctionId.REPORT_PARTITION_AVAILABILITY; } public PartitionId getPartitionId() { return pid; } public NetworkAddress getNetworkAddress() { return networkAddress; } public static Object deserialize(ByteBuffer buffer, int length) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), length); DataInputStream dis = new DataInputStream(bais); // Read PartitionId PartitionId pid = readPartitionId(dis); // Read NetworkAddress NetworkAddress networkAddress = readNetworkAddress(dis); return new ReportPartitionAvailabilityFunction(pid, networkAddress); } public static void serialize(OutputStream out, Object object) throws Exception { ReportPartitionAvailabilityFunction fn = (ReportPartitionAvailabilityFunction) object; DataOutputStream dos = new DataOutputStream(out); // Write PartitionId writePartitionId(dos, fn.getPartitionId()); // Write NetworkAddress writeNetworkAddress(dos, fn.getNetworkAddress()); } } public static class DeployBinaryFunction extends Function { private static final long serialVersionUID = 1L; private final List<URL> binaryURLs; private final DeploymentId deploymentId; public DeployBinaryFunction(DeploymentId deploymentId, List<URL> binaryURLs) { this.binaryURLs = binaryURLs; this.deploymentId = deploymentId; } @Override public FunctionId getFunctionId() { return FunctionId.DEPLOY_BINARY; } public List<URL> getBinaryURLs() { return binaryURLs; } public DeploymentId getDeploymentId() { return deploymentId; } } public static class UnDeployBinaryFunction extends Function { private static final long serialVersionUID = 1L; private final DeploymentId deploymentId; public UnDeployBinaryFunction(DeploymentId deploymentId) { this.deploymentId = deploymentId; } @Override public FunctionId getFunctionId() { return FunctionId.UNDEPLOY_BINARY; } public DeploymentId getDeploymentId() { return deploymentId; } } public static class RequestShutdownFunction extends Function { private static final long serialVersionUID = 1L; @Override public FunctionId getFunctionId() { return FunctionId.SHUTDOWN_REQUEST; } } public static class NotifyShutdownFunction extends Function { private static final long serialVersionUID = 1L; private final String nodeId; public NotifyShutdownFunction(String nodeId) { this.nodeId = nodeId; } @Override public FunctionId getFunctionId() { return FunctionId.SHUTDOWN_RESPONSE; } public String getNodeId() { return nodeId; } } public static class NotifyDeployBinaryFunction extends Function { private static final long serialVersionUID = 1L; private final String nodeId; private final DeploymentId deploymentId; private final DeploymentStatus deploymentStatus; public NotifyDeployBinaryFunction(DeploymentId deploymentId, String nodeId, DeploymentStatus deploymentStatus) { this.nodeId = nodeId; this.deploymentId = deploymentId; this.deploymentStatus = deploymentStatus; } @Override public FunctionId getFunctionId() { return FunctionId.NOTIFY_DEPLOY_BINARY; } public String getNodeId() { return nodeId; } public DeploymentId getDeploymentId() { return deploymentId; } public DeploymentStatus getDeploymentStatus() { return deploymentStatus; } } public static class StateDumpRequestFunction extends Function { private static final long serialVersionUID = 1L; private final String stateDumpId; public StateDumpRequestFunction(String stateDumpId) { this.stateDumpId = stateDumpId; } public String getStateDumpId() { return stateDumpId; } @Override public FunctionId getFunctionId() { return FunctionId.STATE_DUMP_REQUEST; } } public static class StateDumpResponseFunction extends Function { private static final long serialVersionUID = 1L; private final String nodeId; private final String stateDumpId; private final String state; public StateDumpResponseFunction(String nodeId, String stateDumpId, String state) { this.nodeId = nodeId; this.stateDumpId = stateDumpId; this.state = state; } public String getNodeId() { return nodeId; } public String getStateDumpId() { return stateDumpId; } public String getState() { return state; } @Override public FunctionId getFunctionId() { return FunctionId.STATE_DUMP_RESPONSE; } } public static class ShutdownRequestFunction extends Function { private static final long serialVersionUID = 1L; private final boolean terminateNCService; public ShutdownRequestFunction(boolean terminateNCService) { this.terminateNCService = terminateNCService; } @Override public FunctionId getFunctionId() { return FunctionId.SHUTDOWN_REQUEST; } public boolean isTerminateNCService() { return terminateNCService; } } public static class ShutdownResponseFunction extends Function { private final String nodeId; public ShutdownResponseFunction(String nodeId) { this.nodeId = nodeId; } public String getNodeId() { return nodeId; } @Override public FunctionId getFunctionId() { return FunctionId.SHUTDOWN_RESPONSE; } } public static class SerializerDeserializer implements IPayloadSerializerDeserializer { private final JavaSerializationBasedPayloadSerializerDeserializer javaSerde; public SerializerDeserializer() { javaSerde = new JavaSerializationBasedPayloadSerializerDeserializer(); } @Override public Object deserializeObject(ByteBuffer buffer, int length) throws Exception { if (length < FID_CODE_SIZE) { throw new IllegalStateException("Message size too small: " + length); } byte fid = buffer.get(); return deserialize(fid, buffer, length - FID_CODE_SIZE); } @Override public Exception deserializeException(ByteBuffer buffer, int length) throws Exception { if (length < FID_CODE_SIZE) { throw new IllegalStateException("Message size too small: " + length); } byte fid = buffer.get(); if (fid != FunctionId.OTHER.ordinal()) { throw new IllegalStateException("Expected FID for OTHER, found: " + fid); } return (Exception) deserialize(fid, buffer, length - FID_CODE_SIZE); } @Override public byte[] serializeObject(Object object) throws Exception { if (object instanceof Function) { Function fn = (Function) object; return serialize(object, (byte) fn.getFunctionId().ordinal()); } else { return serialize(object, (byte) FunctionId.OTHER.ordinal()); } } @Override public byte[] serializeException(Exception object) throws Exception { return serialize(object, (byte) FunctionId.OTHER.ordinal()); } private byte[] serialize(Object object, byte fid) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(fid); try { serialize(baos, object, fid); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error serializing " + object, e); throw e; } baos.close(); return baos.toByteArray(); } private void serialize(OutputStream out, Object object, byte fid) throws Exception { switch (FunctionId.values()[fid]) { case REGISTER_PARTITION_PROVIDER: RegisterPartitionProviderFunction.serialize(out, object); return; case REGISTER_PARTITION_REQUEST: RegisterPartitionRequestFunction.serialize(out, object); return; case REPORT_PARTITION_AVAILABILITY: ReportPartitionAvailabilityFunction.serialize(out, object); return; case NODE_HEARTBEAT: NodeHeartbeatFunction.serialize(out, object); return; case START_TASKS: StartTasksFunction.serialize(out, object); return; case NOTIFY_TASK_COMPLETE: NotifyTaskCompleteFunction.serialize(out, object); return; case NOTIFY_JOBLET_CLEANUP: NotifyJobletCleanupFunction.serialize(out, object); return; case CLEANUP_JOBLET: CleanupJobletFunction.serialize(out, object); return; } JavaSerializationBasedPayloadSerializerDeserializer.serialize(out, object); } private Object deserialize(byte fid, ByteBuffer buffer, int length) throws Exception { switch (FunctionId.values()[fid]) { case REGISTER_PARTITION_PROVIDER: return RegisterPartitionProviderFunction.deserialize(buffer, length); case REGISTER_PARTITION_REQUEST: return RegisterPartitionRequestFunction.deserialize(buffer, length); case REPORT_PARTITION_AVAILABILITY: return ReportPartitionAvailabilityFunction.deserialize(buffer, length); case NODE_HEARTBEAT: return NodeHeartbeatFunction.deserialize(buffer, length); case START_TASKS: return StartTasksFunction.deserialize(buffer, length); case NOTIFY_TASK_COMPLETE: return NotifyTaskCompleteFunction.deserialize(buffer, length); case NOTIFY_JOBLET_CLEANUP: return NotifyJobletCleanupFunction.deserialize(buffer, length); case CLEANUP_JOBLET: return CleanupJobletFunction.deserialize(buffer, length); } return javaSerde.deserializeObject(buffer, length); } } private static PartitionId readPartitionId(DataInputStream dis) throws IOException { long jobId = dis.readLong(); int cdid = dis.readInt(); int senderIndex = dis.readInt(); int receiverIndex = dis.readInt(); PartitionId pid = new PartitionId(new JobId(jobId), new ConnectorDescriptorId(cdid), senderIndex, receiverIndex); return pid; } private static void writePartitionId(DataOutputStream dos, PartitionId pid) throws IOException { dos.writeLong(pid.getJobId().getId()); dos.writeInt(pid.getConnectorDescriptorId().getId()); dos.writeInt(pid.getSenderIndex()); dos.writeInt(pid.getReceiverIndex()); } private static TaskAttemptId readTaskAttemptId(DataInputStream dis) throws IOException { int odid = dis.readInt(); int aid = dis.readInt(); int partition = dis.readInt(); int attempt = dis.readInt(); TaskAttemptId taId = new TaskAttemptId( new TaskId(new ActivityId(new OperatorDescriptorId(odid), aid), partition), attempt); return taId; } private static void writeTaskAttemptId(DataOutputStream dos, TaskAttemptId taId) throws IOException { TaskId tid = taId.getTaskId(); ActivityId aid = tid.getActivityId(); OperatorDescriptorId odId = aid.getOperatorDescriptorId(); dos.writeInt(odId.getId()); dos.writeInt(aid.getLocalId()); dos.writeInt(tid.getPartition()); dos.writeInt(taId.getAttempt()); } private static PartitionState readPartitionState(DataInputStream dis) throws IOException { PartitionState state = PartitionState.values()[dis.readInt()]; return state; } private static void writePartitionState(DataOutputStream dos, PartitionState state) throws IOException { dos.writeInt(state.ordinal()); } private static NetworkAddress readNetworkAddress(DataInputStream dis) throws IOException { String address = dis.readUTF(); int port = dis.readInt(); NetworkAddress networkAddress = new NetworkAddress(address, port); return networkAddress; } private static void writeNetworkAddress(DataOutputStream dos, NetworkAddress networkAddress) throws IOException { dos.writeUTF(networkAddress.getAddress()); dos.writeInt(networkAddress.getPort()); } }
heriram/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-control/hyracks-control-common/src/main/java/org/apache/hyracks/control/common/ipc/CCNCFunctions.java
Java
apache-2.0
46,469
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is "SMS Library for the Java platform". * * The Initial Developer of the Original Code is Markus Eriksson. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.marre.sms; import com.zx.sms.common.GlobalConstance; /** * * @author Markus Eriksson * @version $Id$ */ public class SmsUserData { /** The actual user data. */ protected final byte[] data_; /** Length of data, in octets or septets depending on the dcs. */ protected final int length_; /** Data Coding Scheme for this user data. */ protected final AbstractSmsDcs dcs_; public SmsUserData(byte[] userData, int userDataLength, AbstractSmsDcs dataCodingScheme) { data_ = userData; length_ = userDataLength; dcs_ = dataCodingScheme; } public SmsUserData(byte[] userData, AbstractSmsDcs dataCodingScheme) { data_ = userData; length_ = userData.length; dcs_ = dataCodingScheme; } public SmsUserData(byte[] userData) { data_ = userData; length_ = userData.length; dcs_ = GlobalConstance.defaultmsgfmt; } public byte[] getData() { return data_; } /** * Returns the length of the user data field. * * This can be in characters or byte depending on the message (DCS). If * message is 7 bit coded the length is given in septets. If 8bit or UCS2 * the length is in octets. * * @return The length */ public int getLength() { return length_; } /** * Returns the data coding scheme. * * @return The dcs */ public AbstractSmsDcs getDcs() { return dcs_; } }
Lihuanghe/CMPPGate
src/main/java/org/marre/sms/SmsUserData.java
Java
apache-2.0
3,257
# -*- coding: utf-8 -*- __author__ = 'eveliotc' __license__ = 'See LICENSE' import alfred from alfred import Item import sys from subprocess import Popen, PIPE def json_to_obj(x): if isinstance(x, dict): return type('X', (), {k: json_to_obj(v) for k, v in x.iteritems()}) else: return x def join_query(dic): return ' '.join(dic) def le_result(r, exit = True): alfred.write(r) if exit: sys.exit() def xml_result(r, exit = True): if len(r) < 1: empty_result(exit) else: le_result(alfred.xml(r), exit) def empty_result(exit = True): empty = Item( attributes={'uid': alfred.uid('empty'), 'arg': ''}, title='Gradle Please', subtitle=u':( Nothing found.', icon=u'icon.png') xml_result([empty], exit) def apple_script(scpt, args=[]): p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(scpt) return stdout def tell_alfred(what): apple_script('tell application "Alfred 2" to search "%s"' % what) # TODO refactor gp.py to use this instead of dynamic obj class Pom(object): a = '' g = '' p = '' latestVersion = '' source = '' @property def id(self): return self.g + ':' + self.a def __repr__(self): #notjson #justdebugginthings return '{id:%s a:%s g:%s p:%s v:%s}' % (self.id, self.a, self.g, self.p, self.latestVersion)
eveliotc/gradleplease-workflow
common.py
Python
apache-2.0
1,475
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import { useCallback, useEffect, useState } from '@googleforcreators/react'; /** * This hook creates a handler to use for double click listening * on a node, where single clicks are also relevant. Default timeout * is 200 ms. If no subsequent click has been recorded in the given * time, single click will be assumed. * * This hook returns a handler retrieval function, not the handler * itself. This allows the component to use the same hook for multiple * children listening for events. * * For example: * ``` * function SomeComponent() { * const handleSingle = useCallback( ( evt, item ) => { * // Handle single click on `item` * }, [] ); * const handleDouble = useCallback( ( evt, item ) => { * // Handle double click on `item` * }, [] ); * const getHandler = useDoubleClick( handleSingle, handleDouble ); * const items = [ * // Some objects with `id` and `name` attributes. * ]; * return items.map( ( item} ) => ( * <button key={ item.id } onClick={ getHandler( item ) }> * { item.name } * </button> * ) ); * } * ``` * * @param {Function} onSingleClick Handler to activate on single click. * @param {Function} onDoubleClick Handler to activate on double click. * @param {number} ms Timeout in ms to wait - defaults to 200. * @return {Function} Handler retrieval function to get an onClick listener (invoke with unique value). */ const useDoubleClick = (onSingleClick, onDoubleClick, ms = null) => { const [target, setTarget] = useState(null); const [lastEvent, setLastEvent] = useState(null); const getHandler = useCallback( (newTarget) => (evt) => { evt.stopPropagation(); if (target !== newTarget) { if (target) { onSingleClick(evt, target); } setTarget(newTarget); setLastEvent(evt); return; } onDoubleClick(evt, target); setTarget(null); }, [onSingleClick, onDoubleClick, target] ); useEffect(() => { if (!target) { return undefined; } const int = setTimeout(() => { setTarget(null); onSingleClick(lastEvent, target); }, ms || DEFAULT_MS); return () => { clearTimeout(int); }; }, [target, lastEvent, onSingleClick, ms]); return getHandler; }; export default useDoubleClick; const DEFAULT_MS = 200;
GoogleForCreators/web-stories-wp
packages/story-editor/src/utils/useDoubleClick.js
JavaScript
apache-2.0
2,991
# AUTOGENERATED FILE FROM balenalib/am571x-evm-alpine:3.13-run # remove several traces of python RUN apk del python* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apk add --no-cache ca-certificates libffi \ && apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 # point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED. # https://www.python.org/dev/peps/pep-0476/#trust-database ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt ENV PYTHON_VERSION 3.9.4 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ gnupg \ ' \ && apk add --no-cache --virtual .build-deps $buildDeps \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" \ && echo "ed043a94289b6553f5dde55c8b8b36a67b811c510cf56909621ea165c1f5f554 Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.13 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.4, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && ln -f /bin/sh /bin/sh.real \ && ln -f /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/python/am571x-evm/alpine/3.13/3.9.4/run/Dockerfile
Dockerfile
apache-2.0
4,130
// Copyright 2014 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 storage import ( "encoding/gob" "errors" "fmt" "io/ioutil" "os" "path" "sort" "strings" "sync" "time" "github.com/go-kit/log" "github.com/go-kit/log/level" //nolint:staticcheck // Ignore SA1019. Dependencies use the deprecated package, so we have to, too. "github.com/golang/protobuf/proto" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" dto "github.com/prometheus/client_model/go" ) const ( pushMetricName = "push_time_seconds" pushMetricHelp = "Last Unix time when changing this group in the Pushgateway succeeded." pushFailedMetricName = "push_failure_time_seconds" pushFailedMetricHelp = "Last Unix time when changing this group in the Pushgateway failed." writeQueueCapacity = 1000 ) var errTimestamp = errors.New("pushed metrics must not have timestamps") // DiskMetricStore is an implementation of MetricStore that persists metrics to // disk. type DiskMetricStore struct { lock sync.RWMutex // Protects metricFamilies. writeQueue chan WriteRequest drain chan struct{} done chan error metricGroups GroupingKeyToMetricGroup persistenceFile string predefinedHelp map[string]string logger log.Logger } type mfStat struct { pos int // Where in the result slice is the MetricFamily? copied bool // Has the MetricFamily already been copied? } // NewDiskMetricStore returns a DiskMetricStore ready to use. To cleanly shut it // down and free resources, the Shutdown() method has to be called. // // If persistenceFile is the empty string, no persisting to disk will // happen. Otherwise, a file of that name is used for persisting metrics to // disk. If the file already exists, metrics are read from it as part of the // start-up. Persisting is happening upon shutdown and after every write action, // but the latter will only happen persistenceDuration after the previous // persisting. // // If a non-nil Gatherer is provided, the help strings of metrics gathered by it // will be used as standard. Pushed metrics with deviating help strings will be // adjusted to avoid inconsistent expositions. func NewDiskMetricStore( persistenceFile string, persistenceInterval time.Duration, gatherPredefinedHelpFrom prometheus.Gatherer, logger log.Logger, ) *DiskMetricStore { // TODO: Do that outside of the constructor to allow the HTTP server to // serve /-/healthy and /-/ready earlier. dms := &DiskMetricStore{ writeQueue: make(chan WriteRequest, writeQueueCapacity), drain: make(chan struct{}), done: make(chan error), metricGroups: GroupingKeyToMetricGroup{}, persistenceFile: persistenceFile, logger: logger, } if err := dms.restore(); err != nil { level.Error(logger).Log("msg", "could not load persisted metrics", "err", err) } if helpStrings, err := extractPredefinedHelpStrings(gatherPredefinedHelpFrom); err == nil { dms.predefinedHelp = helpStrings } else { level.Error(logger).Log("msg", "could not gather metrics for predefined help strings", "err", err) } go dms.loop(persistenceInterval) return dms } // SubmitWriteRequest implements the MetricStore interface. func (dms *DiskMetricStore) SubmitWriteRequest(req WriteRequest) { dms.writeQueue <- req } // Shutdown implements the MetricStore interface. func (dms *DiskMetricStore) Shutdown() error { close(dms.drain) return <-dms.done } // Healthy implements the MetricStore interface. func (dms *DiskMetricStore) Healthy() error { // By taking the lock we check that there is no deadlock. dms.lock.Lock() defer dms.lock.Unlock() // A pushgateway that cannot be written to should not be // considered as healthy. if len(dms.writeQueue) == cap(dms.writeQueue) { return fmt.Errorf("write queue is full") } return nil } // Ready implements the MetricStore interface. func (dms *DiskMetricStore) Ready() error { return dms.Healthy() } // GetMetricFamilies implements the MetricStore interface. func (dms *DiskMetricStore) GetMetricFamilies() []*dto.MetricFamily { dms.lock.RLock() defer dms.lock.RUnlock() result := []*dto.MetricFamily{} mfStatByName := map[string]mfStat{} for _, group := range dms.metricGroups { for name, tmf := range group.Metrics { mf := tmf.GetMetricFamily() if mf == nil { level.Warn(dms.logger).Log("msg", "storage corruption detected, consider wiping the persistence file") continue } stat, exists := mfStatByName[name] if exists { existingMF := result[stat.pos] if !stat.copied { mfStatByName[name] = mfStat{ pos: stat.pos, copied: true, } existingMF = copyMetricFamily(existingMF) result[stat.pos] = existingMF } if mf.GetHelp() != existingMF.GetHelp() { level.Info(dms.logger).Log("msg", "metric families inconsistent help strings", "err", "Metric families have inconsistent help strings. The latter will have priority. This is bad. Fix your pushed metrics!", "new", mf, "old", existingMF) } // Type inconsistency cannot be fixed here. We will detect it during // gathering anyway, so no reason to log anything here. existingMF.Metric = append(existingMF.Metric, mf.Metric...) } else { copied := false if help, ok := dms.predefinedHelp[name]; ok && mf.GetHelp() != help { level.Info(dms.logger).Log("msg", "metric families overlap", "err", "Metric family has the same name as a metric family used by the Pushgateway itself but it has a different help string. Changing it to the standard help string. This is bad. Fix your pushed metrics!", "metric_family", mf, "standard_help", help) mf = copyMetricFamily(mf) copied = true mf.Help = proto.String(help) } mfStatByName[name] = mfStat{ pos: len(result), copied: copied, } result = append(result, mf) } } } return result } // GetMetricFamiliesMap implements the MetricStore interface. func (dms *DiskMetricStore) GetMetricFamiliesMap() GroupingKeyToMetricGroup { dms.lock.RLock() defer dms.lock.RUnlock() groupsCopy := make(GroupingKeyToMetricGroup, len(dms.metricGroups)) for k, g := range dms.metricGroups { metricsCopy := make(NameToTimestampedMetricFamilyMap, len(g.Metrics)) groupsCopy[k] = MetricGroup{Labels: g.Labels, Metrics: metricsCopy} for n, tmf := range g.Metrics { metricsCopy[n] = tmf } } return groupsCopy } func (dms *DiskMetricStore) loop(persistenceInterval time.Duration) { lastPersist := time.Now() persistScheduled := false lastWrite := time.Time{} persistDone := make(chan time.Time) var persistTimer *time.Timer checkPersist := func() { if dms.persistenceFile != "" && !persistScheduled && lastWrite.After(lastPersist) { persistTimer = time.AfterFunc( persistenceInterval-lastWrite.Sub(lastPersist), func() { persistStarted := time.Now() if err := dms.persist(); err != nil { level.Error(dms.logger).Log("msg", "error persisting metrics", "err", err) } else { level.Info(dms.logger).Log("msg", "metrics persisted", "file", dms.persistenceFile) } persistDone <- persistStarted }, ) persistScheduled = true } } for { select { case wr := <-dms.writeQueue: lastWrite = time.Now() if dms.checkWriteRequest(wr) { dms.processWriteRequest(wr) } else { dms.setPushFailedTimestamp(wr) } if wr.Done != nil { close(wr.Done) } checkPersist() case lastPersist = <-persistDone: persistScheduled = false checkPersist() // In case something has been written in the meantime. case <-dms.drain: // Prevent a scheduled persist from firing later. if persistTimer != nil { persistTimer.Stop() } // Now draining... for { select { case wr := <-dms.writeQueue: if dms.checkWriteRequest(wr) { dms.processWriteRequest(wr) } else { dms.setPushFailedTimestamp(wr) } default: dms.done <- dms.persist() return } } } } } func (dms *DiskMetricStore) processWriteRequest(wr WriteRequest) { dms.lock.Lock() defer dms.lock.Unlock() key := groupingKeyFor(wr.Labels) if wr.MetricFamilies == nil { // No MetricFamilies means delete request. Delete the whole // metric group, and we are done here. delete(dms.metricGroups, key) return } // Otherwise, it's an update. group, ok := dms.metricGroups[key] if !ok { group = MetricGroup{ Labels: wr.Labels, Metrics: NameToTimestampedMetricFamilyMap{}, } dms.metricGroups[key] = group } else if wr.Replace { // For replace, we have to delete all metric families in the // group except pre-existing push timestamps. for name := range group.Metrics { if name != pushMetricName && name != pushFailedMetricName { delete(group.Metrics, name) } } } wr.MetricFamilies[pushMetricName] = newPushTimestampGauge(wr.Labels, wr.Timestamp) // Only add a zero push-failed metric if none is there yet, so that a // previously added fail timestamp is retained. if _, ok := group.Metrics[pushFailedMetricName]; !ok { wr.MetricFamilies[pushFailedMetricName] = newPushFailedTimestampGauge(wr.Labels, time.Time{}) } for name, mf := range wr.MetricFamilies { group.Metrics[name] = TimestampedMetricFamily{ Timestamp: wr.Timestamp, GobbableMetricFamily: (*GobbableMetricFamily)(mf), } } } func (dms *DiskMetricStore) setPushFailedTimestamp(wr WriteRequest) { dms.lock.Lock() defer dms.lock.Unlock() key := groupingKeyFor(wr.Labels) group, ok := dms.metricGroups[key] if !ok { group = MetricGroup{ Labels: wr.Labels, Metrics: NameToTimestampedMetricFamilyMap{}, } dms.metricGroups[key] = group } group.Metrics[pushFailedMetricName] = TimestampedMetricFamily{ Timestamp: wr.Timestamp, GobbableMetricFamily: (*GobbableMetricFamily)(newPushFailedTimestampGauge(wr.Labels, wr.Timestamp)), } // Only add a zero push metric if none is there yet, so that a // previously added push timestamp is retained. if _, ok := group.Metrics[pushMetricName]; !ok { group.Metrics[pushMetricName] = TimestampedMetricFamily{ Timestamp: wr.Timestamp, GobbableMetricFamily: (*GobbableMetricFamily)(newPushTimestampGauge(wr.Labels, time.Time{})), } } } // checkWriteRequest return if applying the provided WriteRequest will result in // a consistent state of metrics. The dms is not modified by the check. However, // the WriteRequest _will_ be sanitized: the MetricFamilies are ensured to // contain the grouping Labels after the check. If false is returned, the // causing error is written to the Done channel of the WriteRequest. // // Special case: If the WriteRequest has no Done channel set, the (expensive) // consistency check is skipped. The WriteRequest is still sanitized, and the // presence of timestamps still results in returning false. func (dms *DiskMetricStore) checkWriteRequest(wr WriteRequest) bool { if wr.MetricFamilies == nil { // Delete request cannot create inconsistencies, and nothing has // to be sanitized. return true } var err error defer func() { if err != nil && wr.Done != nil { wr.Done <- err } }() if timestampsPresent(wr.MetricFamilies) { err = errTimestamp return false } for _, mf := range wr.MetricFamilies { sanitizeLabels(mf, wr.Labels) } // Without Done channel, don't do the expensive consistency check. if wr.Done == nil { return true } // Construct a test dms, acting on a copy of the metrics, to test the // WriteRequest with. tdms := &DiskMetricStore{ metricGroups: dms.GetMetricFamiliesMap(), predefinedHelp: dms.predefinedHelp, logger: log.NewNopLogger(), } tdms.processWriteRequest(wr) // Construct a test Gatherer to check if consistent gathering is possible. tg := prometheus.Gatherers{ prometheus.DefaultGatherer, prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) { return tdms.GetMetricFamilies(), nil }), } if _, err = tg.Gather(); err != nil { return false } return true } func (dms *DiskMetricStore) persist() error { // Check (again) if persistence is configured because some code paths // will call this method even if it is not. if dms.persistenceFile == "" { return nil } f, err := ioutil.TempFile( path.Dir(dms.persistenceFile), path.Base(dms.persistenceFile)+".in_progress.", ) if err != nil { return err } inProgressFileName := f.Name() e := gob.NewEncoder(f) dms.lock.RLock() err = e.Encode(dms.metricGroups) dms.lock.RUnlock() if err != nil { f.Close() os.Remove(inProgressFileName) return err } if err := f.Close(); err != nil { os.Remove(inProgressFileName) return err } return os.Rename(inProgressFileName, dms.persistenceFile) } func (dms *DiskMetricStore) restore() error { if dms.persistenceFile == "" { return nil } f, err := os.Open(dms.persistenceFile) if os.IsNotExist(err) { return nil } if err != nil { return err } defer f.Close() d := gob.NewDecoder(f) if err := d.Decode(&dms.metricGroups); err != nil { return err } return nil } func copyMetricFamily(mf *dto.MetricFamily) *dto.MetricFamily { return &dto.MetricFamily{ Name: mf.Name, Help: mf.Help, Type: mf.Type, Metric: append([]*dto.Metric{}, mf.Metric...), } } // groupingKeyFor creates a grouping key from the provided map of grouping // labels. The grouping key is created by joining all label names and values // together with model.SeparatorByte as a separator. The label names are sorted // lexicographically before joining. In that way, the grouping key is both // reproducible and unique. func groupingKeyFor(labels map[string]string) string { if len(labels) == 0 { // Super fast path. return "" } labelNames := make([]string, 0, len(labels)) for labelName := range labels { labelNames = append(labelNames, labelName) } sort.Strings(labelNames) sb := strings.Builder{} for i, labelName := range labelNames { sb.WriteString(labelName) sb.WriteByte(model.SeparatorByte) sb.WriteString(labels[labelName]) if i+1 < len(labels) { // No separator at the end. sb.WriteByte(model.SeparatorByte) } } return sb.String() } // extractPredefinedHelpStrings extracts all the HELP strings from the provided // gatherer so that the DiskMetricStore can fix deviations in pushed metrics. func extractPredefinedHelpStrings(g prometheus.Gatherer) (map[string]string, error) { if g == nil { return nil, nil } mfs, err := g.Gather() if err != nil { return nil, err } result := map[string]string{} for _, mf := range mfs { result[mf.GetName()] = mf.GetHelp() } return result, nil } func newPushTimestampGauge(groupingLabels map[string]string, t time.Time) *dto.MetricFamily { return newTimestampGauge(pushMetricName, pushMetricHelp, groupingLabels, t) } func newPushFailedTimestampGauge(groupingLabels map[string]string, t time.Time) *dto.MetricFamily { return newTimestampGauge(pushFailedMetricName, pushFailedMetricHelp, groupingLabels, t) } func newTimestampGauge(name, help string, groupingLabels map[string]string, t time.Time) *dto.MetricFamily { var ts float64 if !t.IsZero() { ts = float64(t.UnixNano()) / 1e9 } mf := &dto.MetricFamily{ Name: proto.String(name), Help: proto.String(help), Type: dto.MetricType_GAUGE.Enum(), Metric: []*dto.Metric{ { Gauge: &dto.Gauge{ Value: proto.Float64(ts), }, }, }, } sanitizeLabels(mf, groupingLabels) return mf } // sanitizeLabels ensures that all the labels in groupingLabels and the // `instance` label are present in the MetricFamily. The label values from // groupingLabels are set in each Metric, no matter what. After that, if the // 'instance' label is not present at all in a Metric, it will be created (with // an empty string as value). // // Finally, sanitizeLabels sorts the label pairs of all metrics. func sanitizeLabels(mf *dto.MetricFamily, groupingLabels map[string]string) { gLabelsNotYetDone := make(map[string]string, len(groupingLabels)) metric: for _, m := range mf.GetMetric() { for ln, lv := range groupingLabels { gLabelsNotYetDone[ln] = lv } hasInstanceLabel := false for _, lp := range m.GetLabel() { ln := lp.GetName() if lv, ok := gLabelsNotYetDone[ln]; ok { lp.Value = proto.String(lv) delete(gLabelsNotYetDone, ln) } if ln == string(model.InstanceLabel) { hasInstanceLabel = true } if len(gLabelsNotYetDone) == 0 && hasInstanceLabel { sort.Sort(labelPairs(m.Label)) continue metric } } for ln, lv := range gLabelsNotYetDone { m.Label = append(m.Label, &dto.LabelPair{ Name: proto.String(ln), Value: proto.String(lv), }) if ln == string(model.InstanceLabel) { hasInstanceLabel = true } delete(gLabelsNotYetDone, ln) // To prepare map for next metric. } if !hasInstanceLabel { m.Label = append(m.Label, &dto.LabelPair{ Name: proto.String(string(model.InstanceLabel)), Value: proto.String(""), }) } sort.Sort(labelPairs(m.Label)) } } // Checks if any timestamps have been specified. func timestampsPresent(metricFamilies map[string]*dto.MetricFamily) bool { for _, mf := range metricFamilies { for _, m := range mf.GetMetric() { if m.TimestampMs != nil { return true } } } return false } // labelPairs implements sort.Interface. It provides a sortable version of a // slice of dto.LabelPair pointers. type labelPairs []*dto.LabelPair func (s labelPairs) Len() int { return len(s) } func (s labelPairs) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s labelPairs) Less(i, j int) bool { return s[i].GetName() < s[j].GetName() }
prometheus/pushgateway
storage/diskmetricstore.go
GO
apache-2.0
18,203
// // MRDPCursor.h // MacFreeRDP // // Created by Laxmikant Rashinkar // Copyright (c) 2012 FreeRDP.org All rights reserved. // #import <Cocoa/Cocoa.h> #include "freerdp/graphics.h" @interface MRDPCursor : NSObject { @public rdpPointer *pointer; uint8 *cursor_data; // bitmapped pixel data NSBitmapImageRep *bmiRep; NSCursor *nsCursor; NSImage *nsImage; } @end
awakecoding/WinPR-msasn1
client/Mac/MRDPCursor.h
C
apache-2.0
425
import mx from '../../multiplex'; import * as mocks from './_mocks'; import { qmodule, qtest } from '../../qunit'; qmodule('linq-first'); function simpleNumericPredicate(t) { return t > 3; } qtest('basic "first" test', function (assert) { assert.equal(mx(mocks.array).first(), 1, 'first of an array of numbers'); assert.equal(mx(mocks.array).first(simpleNumericPredicate), 4, 'first of an array of numbers with predicate'); assert.equal(mx('test').first(), 't', 'first of an string'); }); qtest('collections "first" method tests', function (assert) { assert.equal(mocks.enumerable.first(), 1, 'Test "first" in an enumerable'); assert.equal(mocks.enumerable.first(simpleNumericPredicate), 4, 'Test "first" in an enumerable with predicate'); assert.equal(mocks.collection.first(), 1, 'Test "first" in a Collection'); assert.equal(mocks.collection.first(simpleNumericPredicate), 4, 'Test "first" in a Collection with predicate'); assert.equal(mocks.list.first(), 1, 'Test "first" in a List'); assert.equal(mocks.list.first(simpleNumericPredicate), 4, 'Test "first" in a List with predicate'); assert.equal(mocks.readOnlyCollection.first(), 1, 'Test "first" in a ReadOnlyCollection'); assert.equal(mocks.readOnlyCollection.first(simpleNumericPredicate), 4, 'Test "first" in a ReadOnlyCollection with predicate'); assert.equal(mocks.linkedList.first(), 1, 'Test "first" in a LinkedList'); assert.equal(mocks.linkedList.first(simpleNumericPredicate), 4, 'Test "first" in a LinkedList with predicate'); assert.equal(mocks.hashSet.first(), 1, 'Test "first" in a HashSet'); assert.equal(mocks.hashSet.first(simpleNumericPredicate), 4, 'Test "first" in a HashSet with predicate'); assert.equal(mocks.stack.first(), 1, 'Test "first" in a Stack'); assert.equal(mocks.stack.first(simpleNumericPredicate), 4, 'Test "first" in a Stack with predicate'); assert.equal(mocks.queue.first(), 1, 'Test "first" in a Queue'); assert.equal(mocks.queue.first(simpleNumericPredicate), 4, 'Test "first" in a Queue with predicate'); assert.equal(mocks.set.first(), 1, 'Test "first" in a Set'); assert.equal(mocks.set.first(simpleNumericPredicate), 4, 'Test "first" in a Set with predicate'); assert.equal(mocks.map.first()[0], 1, 'Test "first" in a Map'); assert.equal(mocks.map.first(function (t) { return t[0] > 3; })[0], 4, 'Test "first" in a Map with predicate'); assert.equal(mocks.dictionary.first().key, 1, 'Test "first" in a Dictionary'); assert.equal(mocks.dictionary.first(function (t) { return t.key > 3; }).key, 4, 'Test "first" in a Dictionary with predicate'); assert.equal(mocks.lookup.first().key, 1, 'Test "first" in a Lookup'); assert.equal(mocks.lookup.first(function (t) { return t.key > 3; }).key, 4, 'Test "first" in a Lookup with predicate'); assert.equal(mocks.sortedList.first().key, 1, 'Test "first" in a SortedList'); assert.equal(mocks.sortedList.first(function (t) { return t.key > 3; }).key, 4, 'Test "first" in a SortedList with predicate'); }); qtest('first method validations', function (assert) { assert.throws(function () { mx([]).first(); }, 'empty collection'); assert.throws(function () { mx([1]).first(1); }, 'non-function predicate'); assert.throws(function () { mx([1]).first(simpleNumericPredicate); }, 'no match'); });
multiplex/multiplex.js
test/unit/linq/first.js
JavaScript
apache-2.0
3,479
/* * Updater.java * * Copyright 2006 The Apache Software Foundation * * 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.apache.hadoop.metrics; /** * Call-back interface. See <code>MetricsContext.registerUpdater()</code>. */ public interface Updater { /** * Timer-based call-back from the metric library. */ public abstract void doUpdates(MetricsContext context); }
moreus/hadoop
hadoop-0.2.0/src/java/org/apache/hadoop/metrics/Updater.java
Java
apache-2.0
920
/* * 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.apm.collector.storage.h2.define.appcomp; import org.apache.skywalking.apm.collector.core.storage.TimePyramid; import org.apache.skywalking.apm.collector.core.util.Const; import org.apache.skywalking.apm.collector.storage.table.application.ApplicationComponentTable; /** * @author peng-yongsheng */ public class ApplicationComponentDayH2TableDefine extends AbstractApplicationComponentH2TableDefine { public ApplicationComponentDayH2TableDefine() { super(ApplicationComponentTable.TABLE + Const.ID_SPLIT + TimePyramid.Day.getName()); } }
hanahmily/sky-walking
apm-collector/apm-collector-storage/collector-storage-h2-provider/src/main/java/org/apache/skywalking/apm/collector/storage/h2/define/appcomp/ApplicationComponentDayH2TableDefine.java
Java
apache-2.0
1,394
package org.http4s package client package jetty import cats.effect._ import cats.effect.concurrent.Semaphore import cats.effect.implicits._ import cats.implicits.{catsSyntaxEither => _, _} import fs2._ import org.eclipse.jetty.client.util.DeferredContentProvider import org.eclipse.jetty.util.{Callback => JettyCallback} import org.http4s.internal.loggingAsyncCallback import org.log4s.getLogger private[jetty] final case class StreamRequestContentProvider[F[_]](s: Semaphore[F])( implicit F: Effect[F]) extends DeferredContentProvider { import StreamRequestContentProvider.logger def write(req: Request[F]): F[Unit] = req.body.chunks .through(pipe) .compile .drain .onError { case t => F.delay(logger.error(t)("Unable to write to Jetty sink")) } private val pipe: Pipe[F, Chunk[Byte], Unit] = _.evalMap { c => write(c) .ensure(new Exception("something terrible has happened"))(res => res) .map(_ => ()) } private def write(chunk: Chunk[Byte]): F[Boolean] = s.acquire .map(_ => super.offer(chunk.toByteBuffer, callback)) private val callback: JettyCallback = new JettyCallback { override def succeeded(): Unit = s.release.runAsync(loggingAsyncCallback(logger)).unsafeRunSync() } } private[jetty] object StreamRequestContentProvider { private val logger = getLogger def apply[F[_]]()(implicit F: ConcurrentEffect[F]): F[StreamRequestContentProvider[F]] = Semaphore[F](1).map(StreamRequestContentProvider(_)) }
aeons/http4s
jetty-client/src/main/scala/org/http4s/client/jetty/StreamRequestContentProvider.scala
Scala
apache-2.0
1,525
# Solanum ochoanum Lechn. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Solanum/Solanum tuberosum/ Syn. Solanum ochoanum/README.md
Markdown
apache-2.0
180
# Cortinarius cristatosporus Reumaux SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in in Bidaud, Carteret, Eyssartier, Moënne-Loccoz & Reumaux, Atlas des Cortinaires (Meyzieu) 14: 905 (2004) #### Original name Cortinarius cristatosporus Reumaux ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius cristatosporus/README.md
Markdown
apache-2.0
298
# Podocarpus aspleniifolia Labill. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Pinophyta/Pinopsida/Pinales/Podocarpaceae/Podocarpus/Podocarpus aspleniifolia/README.md
Markdown
apache-2.0
182
# Roegneria macroura (Turcz.) Nevski SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Elymus/Elymus macrourus/ Syn. Roegneria macroura/README.md
Markdown
apache-2.0
191
# Heterobasidion annosum f. incrustans (Bourdot & Galzin) Domanski, Orlos & Skirg. FORM #### Status ACCEPTED #### According to Index Fungorum #### Published in Flora Polska. Grzyby (Mycota). Podstawczaki (Basidiomycetes), Bezblaszkowce (Aphyllophorales), Skórnikowate (Stereaceae), Pucharkowate (Podoscyphaceae) (Kraków) 183 (1967) #### Original name Ungulina annosa f. incrustans Bourdot & Galzin ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Russulales/Bondarzewiaceae/Heterobasidion/Heterobasidion annosum/Heterobasidion annosum incrustans/README.md
Markdown
apache-2.0
421
# Baccharis tola var. lejia (Phil.) Reiche VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Baccharis/Baccharis tola/Baccharis tola lejia/README.md
Markdown
apache-2.0
190
# Polyporus pubescens var. grayi Cooke & Ellis VARIETY #### Status ACCEPTED #### According to Index Fungorum #### Published in in Ellis, N. Amer. Fung. , Ser. 2 (1888) #### Original name Polyporus pubescens var. grayi Cooke & Ellis ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Polyporaceae/Trametes/Trametes pubescens/Polyporus pubescens grayi/README.md
Markdown
apache-2.0
253
# Spermacoce remota Lam. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Tabl. encycl. 1:273. 1792 #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Spermacoce/Spermacoce remota/README.md
Markdown
apache-2.0
201
# Diacheopsis laxifila Nann.-Bremek. & Hoof, 1996 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in in Hooff & Nannenga-Bremekamp, Proc. K. Ned. Akad. Wet. 99(1-2): 47 (1996) #### Original name Diacheopsis laxifila Nann.-Bremek. & Hoof, 1996 ### Remarks null
mdoering/backbone
life/Protozoa/Mycetozoa/Myxomycetes/Stemonitales/Stemonitidaceae/Diacheopsis/Diacheopsis laxifila/README.md
Markdown
apache-2.0
318
# Idanothekion M.A. Millay & D.A. Eggert, 1970 GENUS #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in American Journal of Botany 57: -. [50-61] #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Lyginopteridaceae/Idanothekion/README.md
Markdown
apache-2.0
245
# Oreocarya confertiflora var. confertiflora VARIETY #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Cryptantha/Cryptantha confertiflora/Oreocarya confertiflora confertiflora/README.md
Markdown
apache-2.0
184
# Oncidium hians Lindl. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Grandiphyllum/Grandiphyllum hians/ Syn. Oncidium hians/README.md
Markdown
apache-2.0
178
# Bryum dunense A. J. E. Smith & H. Whitehouse, 1978 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Bryophyta/Bryopsida/Bryales/Bryaceae/Bryum/Bryum dunense/README.md
Markdown
apache-2.0
208
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #include <helpers/ArrayUtils.h> namespace nd4j { namespace ArrayUtils { void toIntPtr(std::initializer_list<int> list, int* target) { std::vector<int> vec(list); toIntPtr(vec, target); } void toIntPtr(std::vector<int>& list, int* target) { memcpy(target, list.data(), list.size() * sizeof(int)); } void toLongPtr(std::initializer_list<Nd4jLong> list, Nd4jLong* target) { std::vector<Nd4jLong> vec(list); toLongPtr(vec, target); } void toLongPtr(std::vector<Nd4jLong>& list, Nd4jLong* target) { memcpy(target, list.data(), list.size() * sizeof(Nd4jLong)); } std::vector<Nd4jLong> toLongVector(std::vector<int> vec) { std::vector<Nd4jLong> result(vec.size()); Nd4jLong vecSize = vec.size(); for (Nd4jLong e = 0; e < vecSize; e++) result[e] = vec[e]; return result; } std::vector<Nd4jLong> toLongVector(std::vector<Nd4jLong> vec) { return vec; } } }
RobAltena/deeplearning4j
libnd4j/include/helpers/impl/ArrayUtils.cpp
C++
apache-2.0
1,907
--- layout: page title: Seattle Police Officer 5326 Von B. Levandowski permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/5326/ --- **Age as of Feb. 24, 2016:** 55
seattlepublicrecords/seattlepublicrecords.github.io
information/agencies/city_of_seattle/seattle_police_department/copbook/5326/index.md
Markdown
apache-2.0
197
package eu.claudiumihaila.nlp.uima; import java.util.Iterator; import org.apache.uima.aae.client.UimaAsBaseCallbackListener; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.CASRuntimeException; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.collection.EntityProcessStatus; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; public class Application { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // prepares a listener for when the analysis engine is complete UimaAsBaseCallbackListener asyncListener = new UimaAsBaseCallbackListener() { /** * This will be called once the text is processed. */ @Override public void entityProcessComplete(CAS output, EntityProcessStatus aStatus) { try { final JCas jcas = output.getJCas(); AnnotationIndex<Annotation> annIndex = jcas .getAnnotationIndex(Annotation.type); Iterator<Annotation> annIt = annIndex.iterator(); Annotation ann = null; System.out.println(jcas.getDocumentText()); while (annIt.hasNext()) { ann = (Annotation) annIt.next(); System.out.println(ann.getType()); } } catch (CASRuntimeException e) { e.printStackTrace(); } catch (CASException e) { e.printStackTrace(); } } }; // constructs a class to create and run a UIMA pipeline Pipeline uimaPipeline = new Pipeline(asyncListener); for (int i = 0; i < 100; i++) { uimaPipeline.process("This is text number " + i + "."); } } }
claudiu-mihaila/uima-as-skeleton
src/main/java/eu/claudiumihaila/nlp/uima/Application.java
Java
apache-2.0
1,631
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited 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. """ from flash_kinetis import Flash_Kinetis flash_algo = { 'load_address' : 0x20000000, 'instructions' : [ 0xE00ABE00, 0x062D780D, 0x24084068, 0xD3000040, 0x1E644058, 0x1C49D1FA, 0x2A001E52, 0x4770D1F2, 0x4831b510, 0x6041492f, 0x60814930, 0x22806801, 0x22204391, 0x60014311, 0x4448482d, 0xf8cef000, 0xd0002800, 0xbd102001, 0x47702000, 0xb5104828, 0x44484928, 0xf8aef000, 0xd1050004, 0x21004824, 0xf0004448, 0x4604f983, 0xf835f000, 0xbd104620, 0x4d1fb570, 0x444d4606, 0x4b1e4601, 0x68ea4628, 0xf85ef000, 0xd1060004, 0x46312300, 0x68ea4628, 0xf934f000, 0xf0004604, 0x4620f81e, 0xb5febd70, 0x460b460d, 0x46014607, 0x46164811, 0xf0004448, 0x0004f8f5, 0x9001d10b, 0x21019002, 0x9100480c, 0x462a4633, 0x44484639, 0xf95ef000, 0xf0004604, 0x4620f802, 0x4808bdfe, 0x220168c1, 0x43110292, 0x477060c1, 0xd928c520, 0x40076000, 0x0000ffff, 0x00000004, 0x6b65666b, 0xf0003000, 0x2800b500, 0x2a00d009, 0x000bd007, 0xfa35f000, 0x0b0b0708, 0x13110f0d, 0x20041715, 0x68c0bd00, 0x20006010, 0x6840bd00, 0x6880e7fa, 0x6800e7f8, 0x2001e7f6, 0x6900e7f4, 0x6940e7f2, 0x206ae7f0, 0x0000bd00, 0x4607b5f8, 0x460d4614, 0xf0004618, 0x2800f889, 0x2308d12a, 0x46294622, 0xf0004638, 0x0006f867, 0x192cd122, 0x68f91e64, 0x91004620, 0xf956f000, 0xd0162900, 0x1c409c00, 0x1e644344, 0x480be011, 0x68004478, 0x490a6005, 0x71c82009, 0xf92ef000, 0x69b84606, 0xd0002800, 0x2e004780, 0x68f8d103, 0x42a51945, 0x4630d9eb, 0x0000bdf8, 0x0000042c, 0x40020000, 0x4604b510, 0xf0004608, 0x2800f851, 0x2c00d106, 0x4904d005, 0x71c82044, 0xf90ef000, 0x2004bd10, 0x0000bd10, 0x40020000, 0x2800b510, 0x492ad019, 0x4a2a68c9, 0x00490e09, 0x5a51447a, 0xd0120309, 0x60022200, 0x21026041, 0x02896081, 0x492460c1, 0x158b7a0c, 0x610340a3, 0x61827ac9, 0x46106141, 0x2004bd10, 0x2064bd10, 0x2800bd10, 0x6181d002, 0x47702000, 0x47702004, 0x2800b510, 0x1e5bd004, 0x421c460c, 0xe001d104, 0xbd102004, 0xd001421a, 0xbd102065, 0x428b6803, 0x6840d804, 0x18181889, 0xd2014288, 0xbd102066, 0xbd102000, 0x4288490d, 0x206bd001, 0x20004770, 0x28004770, 0x290fd008, 0x2a04d802, 0xe005d104, 0xd8012913, 0xd0012a08, 0x47702004, 0x47702000, 0x40075040, 0x000003a0, 0x40020020, 0x6b65666b, 0xb081b5ff, 0x0015461e, 0xd007460f, 0x46322304, 0xf7ff9801, 0x0004ffbd, 0xe018d101, 0xb0052004, 0x480dbdf0, 0x68014478, 0xcd02600f, 0x60416800, 0x2006490a, 0xf00071c8, 0x4604f88b, 0x69809801, 0xd0002800, 0x2c004780, 0x1d3fd103, 0x2e001f36, 0x4620d1e7, 0x0000e7e3, 0x000002ec, 0x40020000, 0xb081b5ff, 0x460e4614, 0x23084605, 0xff90f7ff, 0xd1272800, 0x686868a9, 0xf882f000, 0x42719000, 0x40014240, 0x42b5424d, 0x9800d101, 0x2c00182d, 0x1bafd017, 0xd90042a7, 0x480b4627, 0x447808f9, 0x60066800, 0x22014809, 0x0a0a71c2, 0x728172c2, 0x72419904, 0xf84cf000, 0xd1032800, 0x19f61be4, 0x2000e7e3, 0xbdf0b005, 0x00000272, 0x40020000, 0x2800b510, 0x4804d006, 0x71c22240, 0xf0007181, 0xbd10f837, 0xbd102004, 0x40020000, 0x9f08b5f8, 0x4616001c, 0xd005460d, 0xf7ff2304, 0x2800ff49, 0xe01dd101, 0xbdf82004, 0x4478480f, 0x600d6801, 0x2202490e, 0x9a0671ca, 0x680072ca, 0x60816821, 0xf816f000, 0xd0082800, 0x29009907, 0x600dd000, 0xd0e82f00, 0x60392100, 0x1f36bdf8, 0x1d2d1d24, 0xd1e12e00, 0x0000bdf8, 0x00000206, 0x40020000, 0x2170480a, 0x21807001, 0x78017001, 0xd5fc0609, 0x06817800, 0x2067d501, 0x06c14770, 0x2068d501, 0x07c04770, 0x2069d0fc, 0x00004770, 0x40020000, 0x09032200, 0xd32c428b, 0x428b0a03, 0x2300d311, 0xe04e469c, 0x430b4603, 0x2200d43c, 0x428b0843, 0x0903d331, 0xd31c428b, 0x428b0a03, 0x4694d301, 0x09c3e03f, 0xd301428b, 0x1ac001cb, 0x09834152, 0xd301428b, 0x1ac0018b, 0x09434152, 0xd301428b, 0x1ac0014b, 0x09034152, 0xd301428b, 0x1ac0010b, 0x08c34152, 0xd301428b, 0x1ac000cb, 0x08834152, 0xd301428b, 0x1ac0008b, 0x08434152, 0xd301428b, 0x1ac0004b, 0x1a414152, 0x4601d200, 0x46104152, 0xe05d4770, 0xd0000fca, 0x10034249, 0x4240d300, 0x22004053, 0x0903469c, 0xd32d428b, 0x428b0a03, 0x22fcd312, 0xba120189, 0x428b0a03, 0x0189d30c, 0x428b1192, 0x0189d308, 0x428b1192, 0x0189d304, 0x1192d03a, 0x0989e000, 0x428b09c3, 0x01cbd301, 0x41521ac0, 0x428b0983, 0x018bd301, 0x41521ac0, 0x428b0943, 0x014bd301, 0x41521ac0, 0x428b0903, 0x010bd301, 0x41521ac0, 0x428b08c3, 0x00cbd301, 0x41521ac0, 0x428b0883, 0x008bd301, 0x41521ac0, 0x0843d2d9, 0xd301428b, 0x1ac0004b, 0x1a414152, 0x4601d200, 0x41524663, 0x4610105b, 0x4240d301, 0xd5002b00, 0x47704249, 0x105b4663, 0x4240d300, 0x2000b501, 0x46c046c0, 0xb430bd02, 0x1e644674, 0x1c647825, 0xd20042ab, 0x5d63461d, 0x18e3005b, 0x4718bc30, 0x00040002, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00000080, 0x00000000, 0x00800000, 0x40020004, 0x00000000, ], 'pc_init' : 0x20000021, 'pc_eraseAll' : 0x2000004D, 'pc_erase_sector' : 0x20000071, 'pc_program_page' : 0x2000009F, 'begin_stack' : 0x20000800, 'begin_data' : 0x20000a00, # Analyzer uses a max of 2 KB data (512 pages * 4 bytes / page) 'page_buffers' : [0x20000a00, 0x20001200], # Enable double buffering 'static_base' : 0x20000000 + 0x20 + 0x594, 'page_size' : 2048, 'analyzer_supported' : True, 'analyzer_address' : 0x1fffa000 }; # @brief Flash algorithm for Kinetis L-series devices. class Flash_kl28z(Flash_Kinetis): def __init__(self, target): super(Flash_kl28z, self).__init__(target, flash_algo)
geky/pyOCD
pyOCD/flash/flash_kl28z.py
Python
apache-2.0
6,139
/* * Copyright 2011 Edmunds.com, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edmunds.etm.common.api; /** * @author Ryan Holmes */ public enum UrlTokenType { FIXED, REGEX }
edmunds/etm-api
etm-common/src/main/java/com/edmunds/etm/common/api/UrlTokenType.java
Java
apache-2.0
721
/* * 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 net.firejack.platform.api.process.domain; import net.firejack.platform.api.directory.domain.User; import net.firejack.platform.core.annotation.Property; import net.firejack.platform.core.domain.BaseEntity; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; import java.util.List; @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Case extends BaseEntity { private static final long serialVersionUID = 6097356968389773543L; private boolean hasPreviousTask; private boolean userCanPerform; @Property private Process process; @Property private Status status; @Property private User assignee; @Property private List<CaseObject> caseObjects; @Property private String description; @Property private String data; @Property private Boolean active; @Property private Date startDate; @Property private Date updateDate; @Property private Date completeDate; @Property(name = "processFieldCaseValues") private List<ProcessFieldCaseValue> customFields; public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public User getAssignee() { return assignee; } public void setAssignee(User assignee) { this.assignee = assignee; } public List<CaseObject> getCaseObjects() { return caseObjects; } public void setCaseObjects(List<CaseObject> caseObjects) { this.caseObjects = caseObjects; } public Date getCompleteDate() { return completeDate; } public void setCompleteDate(Date completeDate) { this.completeDate = completeDate; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isHasPreviousTask() { return hasPreviousTask; } public void setHasPreviousTask(boolean hasPreviousTask) { this.hasPreviousTask = hasPreviousTask; } public Process getProcess() { return process; } public void setProcess(Process process) { this.process = process; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public boolean isUserCanPerform() { return userCanPerform; } public void setUserCanPerform(boolean userCanPerform) { this.userCanPerform = userCanPerform; } public List<ProcessFieldCaseValue> getCustomFields() { return customFields; } public void setCustomFields(List<ProcessFieldCaseValue> customFields) { this.customFields = customFields; } }
firejack-open/Firejack-Platform
integration/src/main/java/net/firejack/platform/api/process/domain/Case.java
Java
apache-2.0
4,564
package com.u2ware.springfield.controller; import org.springframework.data.domain.Pageable; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; public interface EntityController<T,Q> { public final static String COMMAND_ID_PATH = "command_id_path"; public final static String COMMAND_METHOD = "command_method"; public final static String COMMAND_EXTENSION = "command_extension"; public final static String COMMAND_VIEW = "command_view"; public final static String MODEL_INFORMATION = "model_information"; public final static String MODEL_ENTITY = "model_entity"; public final static String MODEL_QUERY = "model_query"; public final static String MODEL_QUERY_PAGEABLE = "model_query_pageable"; public final static String MODEL_QUERY_RESULT = "model_query_result"; public static final String PAGE_PARAMETER_NAME = "model_query_pageable.pageNumber"; public static final String SIZE_PARAMETER_NAME = "model_query_pageable.pageSize"; public static final String SORT_PARAMETER_NAME = "model_query_pageable.pageSort"; public static final String ENABLE_PARAMETER_NAME = "model_query_pageable.pageEnable"; public String find(Boolean pageEnable, Model model, Pageable pageable, Q query, BindingResult errors) throws Exception; public String read(Model model, T entity, BindingResult errors) throws Exception; public String createForm(Model model, T entity, BindingResult errors) throws Exception; public String create(Model model, T entity, BindingResult errors) throws Exception; public String updateForm(Model model, T entity, BindingResult errors) throws Exception; public String update(Model model, T entity, BindingResult errors) throws Exception; public String delete(Model model, T entity, BindingResult errors) throws Exception; }
u2ware/springfield
src/main/java/com/u2ware/springfield/controller/EntityController.java
Java
apache-2.0
1,860
# Cirsium komarovii Schischk. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Cirsium komarovii/README.md
Markdown
apache-2.0
177
# Tyson & Letha's Wedding Site ## Visit the Site Visit the site [here.](http://www.tysonandletha.us) ## About This Site This site uses [Start Bootstrap](http://startbootstrap.com/) - [Agency](http://startbootstrap.com/template-overviews/agency/) as a base theme, with many modifications made. ## Creator Start Bootstrap was created by and is maintained by **David Miller**, Managing Partner at [Iron Summit Media Strategies](http://www.ironsummitmedia.com/). * https://twitter.com/davidmillerskt * https://github.com/davidtmiller ## Copyright and License Copyright 2013-2015 Iron Summit Media Strategies, LLC. Code released under the [Apache 2.0](https://github.com/IronSummitMedia/startbootstrap-agency/blob/gh-pages/LICENSE) license.
kdmcclin/wedding-site
README.md
Markdown
apache-2.0
743
/* * Copyright 2015-2019 The OpenZipkin 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 zipkin2.storage.cassandra; import com.datastax.driver.core.Host; import com.datastax.driver.core.KeyspaceMetadata; import com.datastax.driver.core.Session; import com.google.common.collect.Lists; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.RegisterExtension; import zipkin2.Endpoint; import zipkin2.Span; import zipkin2.TestObjects; import zipkin2.storage.QueryRequest; import zipkin2.storage.StorageComponent; import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static zipkin2.TestObjects.DAY; import static zipkin2.TestObjects.TODAY; import static zipkin2.storage.cassandra.InternalForTests.writeDependencyLinks; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ITCassandraStorage { @RegisterExtension CassandraStorageExtension backend = new CassandraStorageExtension( "openzipkin/zipkin-cassandra:2.16.0"); @Nested class ITSpanStore extends zipkin2.storage.ITSpanStore<CassandraStorage> { @Override protected boolean initializeStoragePerTest() { return true; } @Override protected StorageComponent.Builder newStorageBuilder(TestInfo testInfo) { return backend.computeStorageBuilder().keyspace(InternalForTests.keyspace(testInfo)); } @Override public void clear() { // Just let the data pile up to prevent warnings and slowness. } @Test void overFetchesToCompensateForDuplicateIndexData() throws IOException { int traceCount = 2000; List<Span> spans = new ArrayList<>(); for (int i = 0; i < traceCount; i++) { final long delta = i * 1000; // all timestamps happen a millisecond later for (Span s : TestObjects.TRACE) { Span.Builder builder = s.toBuilder() .traceId(Long.toHexString((i + 1) * 10L)) .timestamp(s.timestampAsLong() + delta); s.annotations().forEach(a -> builder.addAnnotation(a.timestamp() + delta, a.value())); spans.add(builder.build()); } } accept(spans.toArray(new Span[0])); // Index ends up containing more rows than services * trace count, and cannot be de-duped // in a server-side query. int localServiceCount = storage.serviceAndSpanNames().getServiceNames().execute().size(); assertThat(storage .session() .execute("SELECT COUNT(*) from trace_by_service_span") .one() .getLong(0)) .isGreaterThan(traceCount * localServiceCount); // Implementation over-fetches on the index to allow the user to receive unsurprising results. QueryRequest request = requestBuilder() .serviceName("frontend") // Ensure we use serviceName so that trace_by_service_span is used .lookback(DAY).limit(traceCount).build(); assertThat(store().getTraces(request).execute()) .hasSize(traceCount); } @Test void searchingByAnnotationShouldFilterBeforeLimiting() throws IOException { int queryLimit = 2; int nbTraceFetched = queryLimit * storage.indexFetchMultiplier(); for (int i = 0; i < nbTraceFetched; i++) { accept(TestObjects.LOTS_OF_SPANS[i++].toBuilder().timestamp((TODAY - i) * 1000L).build()); } // Add two traces with the tag we're looking for before the preceding ones Endpoint endpoint = TestObjects.LOTS_OF_SPANS[0].localEndpoint(); for (int i = 0; i < 2; i++) { int j = nbTraceFetched + i; accept(TestObjects.LOTS_OF_SPANS[j].toBuilder() .timestamp((TODAY - j) * 1000L) .localEndpoint(endpoint) .putTag("host.name", "host1") .build()); } QueryRequest queryRequest = requestBuilder() .parseAnnotationQuery("host.name=host1") .serviceName(endpoint.serviceName()) .limit(queryLimit) .build(); assertThat(store().getTraces(queryRequest).execute()).hasSize(queryLimit); } /** Makes sure the test cluster doesn't fall over on BusyPoolException */ @Override protected void accept(Span... spans) throws IOException { // TODO: this avoids overrunning the cluster with BusyPoolException for (List<Span> nextChunk : Lists.partition(asList(spans), 100)) { super.accept(nextChunk.toArray(new Span[0])); // Now, block until writes complete, notably so we can read them. blockWhileInFlight(storage); } } @Override @Test @Disabled("No consumer-side span deduplication") public void deduplicates() { } } @Nested class ITSearchEnabledFalse extends zipkin2.storage.ITSearchEnabledFalse<CassandraStorage> { @Override protected boolean initializeStoragePerTest() { return true; } @Override protected StorageComponent.Builder newStorageBuilder(TestInfo testInfo) { return backend.computeStorageBuilder().keyspace(InternalForTests.keyspace(testInfo)); } @Override public void clear() { // Just let the data pile up to prevent warnings and slowness. } @Test void doesntCreateIndexes() { KeyspaceMetadata metadata = storage.session().getCluster().getMetadata().getKeyspace(storage.keyspace()); assertThat(metadata.getTable("trace_by_service_span")).isNull(); assertThat(metadata.getTable("span_by_service")).isNull(); } } @Nested class ITStrictTraceIdFalse extends zipkin2.storage.ITStrictTraceIdFalse<CassandraStorage> { CassandraStorage storageBeforeSwitch; @BeforeEach void initializeStorageBeforeSwitch() { storageBeforeSwitch = backend.computeStorageBuilder().keyspace(storage.keyspace()).build(); } @AfterEach void closeStorageBeforeSwitch() { storageBeforeSwitch.close(); storageBeforeSwitch = null; } @Override protected boolean initializeStoragePerTest() { return true; } @Override protected StorageComponent.Builder newStorageBuilder(TestInfo testInfo) { return backend.computeStorageBuilder().keyspace(InternalForTests.keyspace(testInfo)); } @Override public void clear() { // Just let the data pile up to prevent warnings and slowness. } /** Ensures we can still lookup fully 128-bit traces when strict trace ID id disabled */ @Test public void getTraces_128BitTraceId() throws IOException { getTraces_128BitTraceId(accept128BitTrace(storageBeforeSwitch)); } /** Ensures data written before strict trace ID was enabled can be read */ @Test public void getTrace_retrievesBy128BitTraceId_afterSwitch() throws IOException { List<Span> trace = accept128BitTrace(storageBeforeSwitch); assertThat(store().getTrace(trace.get(0).traceId()).execute()) .containsOnlyElementsOf(trace); } } @Nested class ITServiceAndSpanNames extends zipkin2.storage.ITServiceAndSpanNames<CassandraStorage> { @Override protected boolean initializeStoragePerTest() { return true; } @Override protected StorageComponent.Builder newStorageBuilder(TestInfo testInfo) { return backend.computeStorageBuilder().keyspace(InternalForTests.keyspace(testInfo)); } @Override public void clear() { // Just let the data pile up to prevent warnings and slowness. } } @Nested class ITAutocompleteTags extends zipkin2.storage.ITAutocompleteTags<CassandraStorage> { @Override protected boolean initializeStoragePerTest() { return true; } @Override protected StorageComponent.Builder newStorageBuilder(TestInfo testInfo) { return backend.computeStorageBuilder().keyspace(InternalForTests.keyspace(testInfo)); } @Override public void clear() { // Just let the data pile up to prevent warnings and slowness. } } @Nested class ITDependencies extends zipkin2.storage.ITDependencies<CassandraStorage> { @Override protected boolean initializeStoragePerTest() { return true; } @Override protected StorageComponent.Builder newStorageBuilder(TestInfo testInfo) { return backend.computeStorageBuilder().keyspace(InternalForTests.keyspace(testInfo)); } @Override public void clear() { // Just let the data pile up to prevent warnings and slowness. } /** * The current implementation does not include dependency aggregation. It includes retrieval of * pre-aggregated links, usually made via zipkin-dependencies */ @Override protected void processDependencies(List<Span> spans) throws Exception { aggregateLinks(spans).forEach( (midnight, links) -> writeDependencyLinks(storage, links, midnight)); } } @Nested class ITEnsureSchema extends zipkin2.storage.cassandra.ITEnsureSchema { TestInfo testInfo; @BeforeEach void setTestInfo(TestInfo testInfo) { this.testInfo = testInfo; } @Override protected String keyspace() { return InternalForTests.keyspace(testInfo); } @Override protected Session session() { return backend.session; } @Override protected InetSocketAddress contactPoint() { return backend.contactPoint(); } } @Nested class ITSpanConsumer extends zipkin2.storage.cassandra.ITSpanConsumer { @Override CassandraStorage.Builder storageBuilder() { return backend.computeStorageBuilder(); } } static void blockWhileInFlight(CassandraStorage storage) { // Now, block until writes complete, notably so we can read them. Session.State state = storage.session().getState(); refresh: while (true) { for (Host host : state.getConnectedHosts()) { if (state.getInFlightQueries(host) > 0) { sleepUninterruptibly(100, TimeUnit.MILLISECONDS); state = storage.session().getState(); continue refresh; } } break; } } }
abesto/zipkin
zipkin-storage/cassandra/src/test/java/zipkin2/storage/cassandra/ITCassandraStorage.java
Java
apache-2.0
10,867
.zwartopwit { background: #fff; color: #000; }
wesleyvano/KW1C_Javascript-L1P3
Hoofdstuk 5/512/css/StyleSheet.css
CSS
apache-2.0
54
package org.genericConfig.admin.shared.configTree /** * Copyright (C) 2016 Gennadi Heimann genaheimann@gmail.com * * Created by Gennadi Heimann 02.06.2020 */ case class ConfigTreeItemConfigPropDTO ( kind : String, id : String, items : Option[List[ConfigTreeItemDTO]] )
gennadij/admin
shared/src/main/scala/org/genericConfig/admin/shared/configTree/ConfigTreeItemConfigPropDTO.scala
Scala
apache-2.0
430
sap.ui.define(["sap/ui/core/UIComponent", "sap/ui/core/mvc/XMLView"], function(UIComponent, XMLView) { 'use strict'; var Component = UIComponent.extend("sap.tnt.sample.InfoLabelInTable.Component", { metadata : { publicMethods : [ "getTable" ], dependencies : { libs : [ "sap.tnt", "sap.m", "sap.ui.layout" ] }, config : { sample : { files : [ "V.view.xml", "V.controller.js", "Formatter.js" ] } } }, getTable : function () { return this._rootView.getContent()[0]; } }); Component.prototype.createContent = function () { this._rootView = sap.ui.xmlview({ viewName : "sap.tnt.sample.InfoLabelInTable.V" }); return this._rootView; }; return Component; });
cschuff/openui5
src/sap.tnt/test/sap/tnt/demokit/sample/InfoLabelInTable/Component.js
JavaScript
apache-2.0
768
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.test.context.junit4; import java.util.Arrays; import java.util.Collection; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runner.notification.RunNotifier; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestContext; import org.springframework.test.context.TestExecutionListener; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.support.AbstractTestExecutionListener; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; import static org.junit.Assert.*; /** * <p> * JUnit 4 based integration test for verifying that '<i>before</i>' and '<i>after</i>' * methods of {@link TestExecutionListener TestExecutionListeners} as well as * {@link BeforeTransaction &#064;BeforeTransaction} and * {@link AfterTransaction &#064;AfterTransaction} methods can fail a test in a * JUnit 4.4 environment, as requested in <a * href="http://opensource.atlassian.com/projects/spring/browse/SPR-3960" * target="_blank">SPR-3960</a>. * </p> * <p> * Indirectly, this class also verifies that all {@link TestExecutionListener} * lifecycle callbacks are called. * </p> * <p> * As of Spring 3.0, this class also tests support for the new * {@link TestExecutionListener#beforeTestClass(TestContext) beforeTestClass()} * and {@link TestExecutionListener#afterTestClass(TestContext) * afterTestClass()} lifecycle callback methods. * </p> * * @author Sam Brannen * @since 2.5 */ @RunWith(Parameterized.class) public class FailingBeforeAndAfterMethodsJUnitTests { protected final Class<?> clazz; public FailingBeforeAndAfterMethodsJUnitTests(final Class<?> clazz) { this.clazz = clazz; } @Parameters public static Collection<Object[]> testData() { return Arrays.asList(new Object[][] {// // { AlwaysFailingBeforeTestClassTestCase.class },// { AlwaysFailingAfterTestClassTestCase.class },// { AlwaysFailingPrepareTestInstanceTestCase.class },// { AlwaysFailingBeforeTestMethodTestCase.class },// { AlwaysFailingAfterTestMethodTestCase.class },// { FailingBeforeTransactionTestCase.class },// { FailingAfterTransactionTestCase.class } // }); } @Test public void runTestAndAssertCounters() throws Exception { final TrackingRunListener listener = new TrackingRunListener(); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); new SpringJUnit4ClassRunner(this.clazz).run(notifier); assertEquals("Verifying number of failures for test class [" + this.clazz + "].", 1, listener.getTestFailureCount()); } // ------------------------------------------------------------------- static class AlwaysFailingBeforeTestClassTestExecutionListener extends AbstractTestExecutionListener { @Override public void beforeTestClass(TestContext testContext) { fail("always failing beforeTestClass()"); } } static class AlwaysFailingAfterTestClassTestExecutionListener extends AbstractTestExecutionListener { @Override public void afterTestClass(TestContext testContext) { fail("always failing afterTestClass()"); } } static class AlwaysFailingPrepareTestInstanceTestExecutionListener extends AbstractTestExecutionListener { @Override public void prepareTestInstance(TestContext testContext) throws Exception { fail("always failing prepareTestInstance()"); } } static class AlwaysFailingBeforeTestMethodTestExecutionListener extends AbstractTestExecutionListener { @Override public void beforeTestMethod(TestContext testContext) { fail("always failing beforeTestMethod()"); } } static class AlwaysFailingAfterTestMethodTestExecutionListener extends AbstractTestExecutionListener { @Override public void afterTestMethod(TestContext testContext) { fail("always failing afterTestMethod()"); } } @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({}) public static abstract class BaseTestCase { @Test public void testNothing() { } } @Ignore("TestCase classes are run manually by the enclosing test class") @TestExecutionListeners(AlwaysFailingBeforeTestClassTestExecutionListener.class) public static class AlwaysFailingBeforeTestClassTestCase extends BaseTestCase { } @Ignore("TestCase classes are run manually by the enclosing test class") @TestExecutionListeners(AlwaysFailingAfterTestClassTestExecutionListener.class) public static class AlwaysFailingAfterTestClassTestCase extends BaseTestCase { } @Ignore("TestCase classes are run manually by the enclosing test class") @TestExecutionListeners(AlwaysFailingPrepareTestInstanceTestExecutionListener.class) public static class AlwaysFailingPrepareTestInstanceTestCase extends BaseTestCase { } @Ignore("TestCase classes are run manually by the enclosing test class") @TestExecutionListeners(AlwaysFailingBeforeTestMethodTestExecutionListener.class) public static class AlwaysFailingBeforeTestMethodTestCase extends BaseTestCase { } @Ignore("TestCase classes are run manually by the enclosing test class") @TestExecutionListeners(AlwaysFailingAfterTestMethodTestExecutionListener.class) public static class AlwaysFailingAfterTestMethodTestCase extends BaseTestCase { } @Ignore("TestCase classes are run manually by the enclosing test class") @ContextConfiguration("FailingBeforeAndAfterMethodsTests-context.xml") public static class FailingBeforeTransactionTestCase extends AbstractTransactionalJUnit4SpringContextTests { @Test public void testNothing() { } @BeforeTransaction public void beforeTransaction() { fail("always failing beforeTransaction()"); } } @Ignore("TestCase classes are run manually by the enclosing test class") @ContextConfiguration("FailingBeforeAndAfterMethodsTests-context.xml") public static class FailingAfterTransactionTestCase extends AbstractTransactionalJUnit4SpringContextTests { @Test public void testNothing() { } @AfterTransaction public void afterTransaction() { fail("always failing afterTransaction()"); } } }
qobel/esoguproject
spring-framework/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsJUnitTests.java
Java
apache-2.0
6,904
from nativedroid.protobuf.java_signatures_pb2 import * __author__ = "Fengguo Wei" __copyright__ = "Copyright 2018, The Argus-SAF Project" __license__ = "Apache v2.0" def java_package_str(java_package_pb, delimiter): """ Return full string of a java package proto. :param JavaPackage java_package_pb: java_signatures_pb2.JavaPackage :param str delimiter: :return: str """ pkg_str = java_package_pb.name tmp = java_package_pb while tmp.HasField('parent'): tmp = tmp.parent pkg_str = tmp.name + delimiter + pkg_str return pkg_str def primitive_type_str(primitive_type_pb, is_signature): """ Return full string of a primitive type proto. :param PrimitiveType primitive_type_pb: java_signatures_pb2.PrimitiveType :param bool is_signature: normal form int, signature form I :return: str """ if primitive_type_pb.type == PrimitiveType.BYTE: if is_signature: return 'B' else: return 'byte' elif primitive_type_pb.type == PrimitiveType.SHORT: if is_signature: return 'S' else: return 'short' elif primitive_type_pb.type == PrimitiveType.INT: if is_signature: return 'I' else: return 'int' elif primitive_type_pb.type == PrimitiveType.FLOAT: if is_signature: return 'F' else: return 'float' elif primitive_type_pb.type == PrimitiveType.BOOLEAN: if is_signature: return 'Z' else: return 'boolean' elif primitive_type_pb.type == PrimitiveType.CHAR: if is_signature: return 'C' else: return 'char' elif primitive_type_pb.type == PrimitiveType.LONG: if is_signature: return 'L' else: return 'long' elif primitive_type_pb.type == PrimitiveType.DOUBLE: if is_signature: return 'D' else: return 'double' def class_type_str(class_type_pb, is_signature): """ Return full string of a class type proto. :param ClassType class_type_pb: java_signatures_pb2.ClassType :param bool is_signature: normal form java.lang.Object, signature form Ljava/lang/Object; :return: str """ type_str = class_type_pb.name if is_signature: delimiter = '/' else: delimiter = '.' if class_type_pb.HasField('package'): type_str = java_package_str(class_type_pb.package, delimiter) + delimiter + type_str if class_type_pb.unknown: type_str += '?' if is_signature: type_str = 'L' + type_str + ';' return type_str def java_type_str(java_type_pb, is_signature): """ Return full string of a java type proto. :param JavaType java_type_pb: java_signatures_pb2.JavaType :param bool is_signature: normal form java.lang.Object[], signature form [Ljava/lang/Object; :return: str """ if java_type_pb.HasField('primitive_type'): type_str = primitive_type_str(java_type_pb.primitive_type, is_signature) else: type_str = class_type_str(java_type_pb.class_type, is_signature) dimension = java_type_pb.dimension while dimension > 0: if is_signature: type_str = '[' + type_str else: type_str += '[]' dimension -= 1 return type_str def method_proto_str(method_proto_pb): """ Return full string of a method proto proto. :param MethodProto method_proto_pb: java_signatures_pb2.MethodProto :return: str """ proto = '(' for param in method_proto_pb.param_types: proto += java_type_str(param, True) proto += ')' if method_proto_pb.HasField('return_java_type'): proto += java_type_str(method_proto_pb.return_java_type, True) else: proto += 'V' return proto def method_signature_str(method_signature_pb): """ Return full string of a method signature proto. :param MethodSignature method_signature_pb: java_signatures_pb2.MethodSignature :return: str """ owner_str = java_type_str(method_signature_pb.owner, is_signature=True) proto_str = method_proto_str(method_signature_pb.proto) return owner_str + '.' + method_signature_pb.name + ':' + proto_str def get_params_from_method_signature(method_signature_pb, is_static): """ Get parameter types from method signature. :param MethodSignature method_signature_pb: java_signatures_pb2.MethodSignature :param bool is_static: is static method :return: list of JavaType """ param_types = [] if not is_static: param_types.append(method_signature_pb.owner) param_types.extend(method_signature_pb.proto.param_types) return param_types
arguslab/Argus-SAF
nativedroid/nativedroid/jawa/utils.py
Python
apache-2.0
4,799
// PatternDlg.cpp : implementation file // #include "stdafx.h" #include "ColorEyeI.h" #include "PatternDlg.h" #include <cstdlib> #include <ctime> // #include "xMsrPoint.h" #include "EnterValueDlg.h" #include "ReadBarCodeDialog.h" #include "TranScripter.h" #include "MainFrm.h" #include "ColorEyeIDoc.h" #include "OmdHead.h" #include "MsrTableDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef _DEBUG #define DebugCode( code_fragment ) { code_fragment } #else #define DebugCode( code_fragment ) #endif ///////////////////////////////////////////////////////////////////////////// // CPatternDlg dialog CPatternDlg::CPatternDlg(const initType& it, CWnd* pParent /*=NULL*/) : CDialog(CPatternDlg::IDD, pParent), InitDataType(it) { //{{AFX_DATA_INIT(CPatternDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT initCa210(); initDataDlgType(); TranScripter Ts; m_Goal.SetRadius(Ts.Cm2pixel(2.25)); } void CPatternDlg::initCa210() { CMainFrame* pMainFrm = dynamic_cast<CMainFrame*>(AfxGetMainWnd()); ASSERT_VALID(pMainFrm); m_pCA210 = pMainFrm->m_pCa210; m_pCA210->SetOnline(TRUE); m_pCA210->LinkMemory(); initLCMSize(); } void CPatternDlg::initDataDlgType() const { CDialog *dlgData = 0; switch(InitDataType) { case MsrForItem: dlgData = new CMsrItemDlg(); break; case MsrForTable: dlgData = new CMsrTableDlg(); break; default: CString str("Pattern Dialogªì©l¤Æ¶q´ú¸ê®Æ¥X°ÝÃD"); AfxMessageBox(str); } ASSERT(dlgData); dlgData->DoModal(); delete dlgData; } void CPatternDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPatternDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPatternDlg, CDialog) //{{AFX_MSG_MAP(CPatternDlg) ON_WM_CTLCOLOR() ON_WM_PAINT() ON_WM_TIMER() ON_WM_SHOWWINDOW() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPatternDlg message handlers BOOL CPatternDlg::OnInitDialog() { // TODO: Add extra initialization here c_bStatusBar = TRUE; c_bMsrBegin = FALSE; c_bMsrEnd = FALSE; c_bMsrEndnMsred = FALSE; c_bRunMsrAI = TRUE; c_bUnCntCA210 = FALSE; ColorRef tempClr(255, 0, 127); //²`¬õ¦â m_Goal.SetArcColor(tempClr.Shift(5)); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } HBRUSH CPatternDlg::OnCtlColor(CDC* , CWnd* , UINT ) { //¥Ã»·³£¤£»Ý­n­×§ï m_BkBrush.DeleteObject(); m_BkBrush.CreateSolidBrush(m_BkColor.oRGB()); return m_BkBrush; } void CPatternDlg::OnPaint() { /* NextGoal ¹B§@°Ñ¼Æ Goal°T®§ NextGoal°T®§ iteratorªº°T®§ ø¹Ï°Ñ¼Æ ª¬ºA¦C ¾Þ§@»¡©ú ª¬ºA ¥D­n¶q´ú«ü¥Ü ¦Ê¤À¤ñÅã¥Ü Goal ¶q´ú¥Ø¼Ð«ü¥Ü ¼Æ¾ÚÅã¥Ü zero calªº¦r endªº¦r */ const int wordHight(18); CPaintDC dc(this); // device context for painting CString temp; dc.SetBkMode(OPAQUE); dc.SetBkColor(m_BkColor.oRGB()); if (m_itor->m_pBackGorund != 0) m_itor->m_pBackGorund->Draw(dc); //DrawCrsTlkRect(dc); DebugCode( dc.SetTextColor(m_BkColor.Shift()); int lineIndex(0); //Pattern¹B§@°Ñ¼Æ //Goal°T®§ temp.Format(" Goal%s", m_Goal.showMe()); TextOut(dc, 0, wordHight*lineIndex++, temp, temp.GetLength()); //Áä½L°T®§ // KeyMessage.Format("nChar = %d, nRepCnt = %d, nFlags = %d", key1, key2, key3); // TextOut(dc, 0, wordHight*lineIndex++, KeyMessage, 40); //iteratorªº°T®§ CString IsEndstr ( m_itor == m_RNA.Begin()? "Begin" : m_itor == m_RNA.End() ? "End" : "Other" ); temp.Format("­¡¥N¾¹¸ê°T: itor.begin = 0x%x, itor.end = 0x%x, itor(¦ì§} / ¦ì¸m) = 0x%x / %s", \ m_RNA.Begin(), m_RNA.End(), m_itor, IsEndstr); TextOut(dc, 0, wordHight*lineIndex++, temp, temp.GetLength()); temp.Format("PatternDlgºX¼Ð: IsShowGoal: %d, IsShowStateBar: %d, ²Ä¤@ÂI = %d, ³Ì«á¤@ÂI = %d, ³Ì«á¤@ÂI¶q§¹ = %d, ¦Û°Ê¶q´ú¼Ò¦¡ = %d, ³sµ²CA-210 = %d", \ m_Goal.isVisible(), c_bStatusBar, c_bMsrBegin, c_bMsrEnd, c_bMsrEndnMsred, !c_bRunMsrAI, c_bUnCntCA210); TextOut(dc, 0, wordHight*lineIndex++, temp, temp.GetLength()); temp.Format("³o¤@ÂIªº¸ê°T: %s", m_itor->ShowMe()); TextOut(dc, 0, wordHight*lineIndex++, temp, temp.GetLength()); ) //ª¬ºA¦C if (c_bStatusBar) { dc.SetTextColor(m_BkColor.Shift()); //¾Þ§@»¡©ú¡]¥ª¡^ temp.Format("¤W¤@ÂI: ¡ö, ¤U¤@ÂI: ¡÷, §ì­È+¤U¤@ÂI: Enter, ¦Û°Ê¶q´ú: ¡õ"); TextOut(dc, 0, GetSystemMetrics(SM_CYSCREEN) - wordHight*1, temp, temp.GetLength()); //ª¬ºA¡]¥k¡^ temp.Format("³s½uª¬ºA: %s, ¥Ø«e¶q´ú: %s, ¸ÑªR«×: %d¡Ñ%d, Channel: %s, LCM size: %2.1f inch", \ m_pCA210->isOnline() ? "³s½u" : "Â÷½u" , m_itor->GetDescrip(), GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), m_pCA210->GetChData(), m_pCA210->GetLcmSize());//LCM Size³o¼Ë§ì·|¦³°ÝÃD TextOut(dc, GetSystemMetrics(SM_CXSCREEN) - (int)(temp.GetLength()*6.7), GetSystemMetrics(SM_CYSCREEN) - wordHight*1, temp, temp.GetLength()); } //¥D­n¶q´ú«ü¥Ü m_Goal.Draw(dc);//¶q´ú¥Ø¼Ð if (c_bMsrEnd && c_bRunMsrAI && c_bMsrEndnMsred) { temp.Format("«öESCÂ÷¶}¡C"); dc.SetTextColor(m_BkColor.Invrt()); if ((m_Goal.GetCenter().x == GetSystemMetrics(SM_CXSCREEN)/2) && (m_Goal.GetCenter().y == GetSystemMetrics(SM_CYSCREEN)/2)) TextOut(dc, GetSystemMetrics(SM_CXSCREEN)/2 - 75, GetSystemMetrics(SM_CYSCREEN)/2-8-m_Goal.GetRadius()*2, temp, temp.GetLength()); else TextOut(dc, GetSystemMetrics(SM_CXSCREEN)/2 - 75, GetSystemMetrics(SM_CYSCREEN)/2-8, temp, temp.GetLength()); } if (c_bUnCntCA210) temp.Format("¥¼³s±µCA-210¡C"); else temp.Format(""); dc.SetTextColor(m_BkColor.Invrt()); TextOut(dc, GetSystemMetrics(SM_CXSCREEN)/2 - 75, GetSystemMetrics(SM_CYSCREEN)/2-8, temp, temp.GetLength()); // TODO: Add your message handler code here // Do not call CDialog::OnPaint() for painting messages } void CPatternDlg::initLCMSize() const { if (atoi(m_pCA210->GetLcmSize()) == 0) { CEnterValueDlg dlgEnterValue("µLªk§P§OLCM Size", "LCM Size"); do{ dlgEnterValue.DoModal(); m_pCA210->SetLcmSize(dlgEnterValue.m_strValue); }while (dlgEnterValue.m_strValue.IsEmpty()); //¤ÏÂЬd¬O¤£¬OªÅ¦r¦ê } } void CPatternDlg::initDocument() { CMainFrame* pMainFrm = dynamic_cast<CMainFrame*>(AfxGetMainWnd()); ASSERT_VALID(pMainFrm); CColorEyeIDoc* pDoc = dynamic_cast<CColorEyeIDoc*>(pMainFrm->GetActiveDocument()); ASSERT_VALID(pDoc); pDoc->GetFileHead().iCHID ( pMainFrm->m_pCa210->GetChStrNo() ); pDoc->GetFileHead().iPrb ( pMainFrm->m_pCa210->GetProb() ); pDoc->GetFileHead().iMsrDvc( pMainFrm->m_pCa210->GetDeviceType() ); pDoc->GetFileHead().iInch ( pMainFrm->m_pCa210->GetLcmSize() ); m_RNA = pDoc->GetMsrRNA(); m_itor = m_RNA.Begin(); //SetPanelID if (m_RNA.Size()) { CReadBarCodeDialog dlgReadBarCode; dlgReadBarCode.DoModal(); } } void CPatternDlg::LoadedCartridge() { // TODO: Add extra validation here m_Goal.SetWnd(GetActiveWindow()); //GetActiveWindow()»Ýµ¥«Øºc¦¡§¹¦¨¤~¥i¥H§ì¨ú initDocument(); //MsrItem«ö¤U¡u½T©w¡vÁÙ¬O¡u¨ú®ø¡v if (m_RNA.IsEmpty()) ShowWindow(SW_HIDE); else { //++BeginItor; trigger(); ShowWindow(SW_MAXIMIZE); SetFocus(); } checkMsrLimit(); } void CPatternDlg::trigger() { m_itor->m_pBackGorund->NT_SetWnd(GetActiveWindow()); m_itor->m_pBackGorund->NT_SetCa(m_pCA210); setBkColor(m_itor->GetBkColor()); m_Goal.SetData(m_itor->GetBullet()); m_Goal.SetPrcntColor(m_BkColor.Shift()); m_Goal.SetCenter(m_itor->GetPointPosi()); //¹v¦ì¸m m_Goal.SetPercent(0); m_Goal.Animation(); } void CPatternDlg::checkMsrLimit() { c_bMsrBegin = ( m_itor == m_RNA.Begin()) ? TRUE : FALSE; c_bMsrEnd = ( m_itor+1 == m_RNA.End() ) ? TRUE : FALSE; c_bMsrEndnMsred = ( c_bMsrEnd && !m_itor->GetBullet().IsEmpty() ) ? TRUE : FALSE;//­Y²{¦b¬O³Ì«á¤@ÂI¡A¨Ã¥B³Ì«á¤@ÂI¤w¸g¶q¤F } BOOL CPatternDlg::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class if (pMsg->message == WM_KEYDOWN) { switch(pMsg->wParam) { case VK_SPACE: eventSwCntCa210(); break;//ªÅ¥ÕÁä¡G¤Á´«³s½u case VK_DOWN: eventRunMsrAi(); break;//¤U ¡G¦Û°Ê¶q´ú¼Ò¦¡ case VK_RIGHT: eventGoNextGoal(); break;//¥k ¡G¸õ¤U¤@­ÓÂI case VK_LEFT: eventGoPrvsGoal(); break;//¥ª ¡G¤W¤@­ÓÂI case VK_RETURN: eventCatchMsrValue(); break;//Enter¡G§ì­È§ì§ì§ì!!!! case VK_ESCAPE: eventExitDialog(); break;//ESC ¡G¸õÂ÷Patten Dialog } return TRUE; } return CDialog::PreTranslateMessage(pMsg); } const CaState CPatternDlg::recoil() { //¼È¦s¥Ø«eªº¿Ã¹õÅã¥Ü/ÁôÂꬺA BOOL OldDrawGold = m_Goal.isVisible(); BOOL OldStatusBar = c_bStatusBar; //©T©wÃö±¼©Ò¦³¿Ã¹õÅã¥Ü/ÁôÂꬺA c_bStatusBar = FALSE; m_Goal.Visible(FALSE); Invalidate(); UpdateWindow(); Sleep(70); const CaState camsrResult(m_pCA210->Measure()); m_itor->SetBullet(m_pCA210->GetMsrData()); m_Goal.SetData(m_itor->GetBullet()); //«ì´_¥Ø«eªº¿Ã¹õÅã¥Ü/ÁôÂꬺA m_Goal.Visible(OldDrawGold); c_bStatusBar = OldStatusBar; Invalidate(); UpdateWindow(); return camsrResult; } void CPatternDlg::OnTimer(UINT nIDEvent) { //Àˬd³s½u // c_bUnCntCA210 = FALSE; /* ¨â­ÓªùÂe 1. ¶q´úªùÂe­È 0 «G«×0¡A¥Ø«e0-Cal 1 ¼Ð·ÇªùÂe­È¤º¡GÄ~Äò¶q´ú+¦Ê¤À¤ñ¡÷ 2. 2 ¼Ð·ÇªùÂe­È¥~¡GÄ~Äò¶q´ú-¦Ê¤À¤ñ 3 ¥¼³s½u 2. ¦Ê¤À¤ñ 0 ¤p©ó0 1 ¼Ð·Ç½d³ò ¡÷2. 2 ¤j©ó100 */ if (m_pCA210->isOnline()) { srand(time(NULL)); switch( m_pCA210->MsrAI( (float)0.005 ) ) //check isRemote, isZeroCal, isRightPosition, and //return a status to say is MsrAiValue in spec. { case MA_InDeviation://¼Ð·ÇªùÂe­È¤º¡GÄ~Äò¶q´ú+¦Ê¤À¤ñ msrKernel(); break; case MA_OutDeviation://¼Ð·ÇªùÂe­È¥~¡GÄ~Äò¶q´ú-¦Ê¤À¤ñ m_Goal.SetPercent(m_Goal.GetPercent() - rand()%25+rand()%25+1); //m_Percent -= rand()%25+rand()%25+1; break; case MA_nonMsr: eventRunMsrAi(FALSE); AfxMessageBox("Àˬd±´ÀY¡G­nÂà¨ìMEAS\nÀˬd¥D¾÷¡GREMOTE¿O­n«G\n¥i¥H¶¶§Q¦Û°Ê¶q´ú¡I"); break; } Invalidate(); UpdateWindow(); } else c_bUnCntCA210 = TRUE; CDialog::OnTimer(nIDEvent); } void CPatternDlg::msrKernel() { int percent(m_Goal.GetPercent()); if (percent < 0) { m_Goal.SetPercent(rand()%20+10); } else if (percent >= 0 && percent <100) { percent = m_Goal.GetPercent() + rand()%50+rand()%50+1; m_Goal.SetPercent(( percent > 100 ) ? 100 : percent); } else if (percent >= 100) { eventRunMsrAi(FALSE); if ((eventCatchMsrValue() == 1) //³Ì½ÆÂøªº¨BÆJ || (c_bMsrEndnMsred == FALSE)) eventRunMsrAi(TRUE); } else ASSERT(0); } void CPatternDlg::eventGoPrvsGoal() { //¤W¤@­ÓÂI if (!c_bMsrBegin) { ++m_itor; if (m_itor != m_RNA.Begin()) m_itor--; if (m_itor != m_RNA.Begin()) m_itor--; trigger(); //¥¦·|µ¥©ó0¡A´N¬O±q³Ì«á¤@¦^ªð¦^¤@¦¸ Invalidate(); } checkMsrLimit(); m_Goal.ShowLabel(TRUE); } BOOL CPatternDlg::eventGoNextGoal() { //¤U¤@­ÓÂI if (!c_bMsrEnd) { //­pºâ¤U¤@Áû ++m_itor; if (m_itor == m_RNA.End()) m_itor--; if (m_itor == m_RNA.End()) m_itor--; //­«·sµe°é°é+°Êµe trigger(); Invalidate(); } checkMsrLimit(); m_Goal.ShowLabel(c_bMsrEndnMsred); return !c_bMsrEnd; } UINT CPatternDlg::eventCatchMsrValue() { //§ì­È§ì§ì§ì!!!! //³Ì«á¤@ÂIªº¸Ü´N°±¤î¦Û°Ê //¤£µM´N¬O¤U¤@ÂI m_Goal.ShowLabel(FALSE); if (m_itor->GetBkStatus() == BGS_NitsNeg || m_itor->GetBkStatus() == BGS_NitsPos) { m_itor->m_pBackGorund->NT_colorReviseByNits(m_BkColor); m_NitsLv.Format("%d", m_BkColor.R()); } /* recoil() 0 ¨S³s½u 1 ³s½u 2 ©|¥¼Zero Cal 3 Àɦ줣¦bMEAS 4 ¶q´ú¥¿±` ·í§@1 ³Ì«á¤@ÂI 5 */ switch(recoil()) { case CA_Offline: MessageBox("¨S³s½u¡AµLªk¶q´ú"); return 0; case CA_ZeroCalMode: MessageBox("Àɦ줣¦bMEAS"); return 3; case CA_MsrMode: default: if (!eventGoNextGoal()) return 5;//¬O§_¬°³Ì«á¤@ÂI else return 1; } } void CPatternDlg::eventRunMsrAi(int isRun) { //¤£­nÀH·N§ó°Ê¡I= =+ //Ãö´Nµ¹¥¦¶}¡A¶}´Nµ¹¥¦Ãö //«ü©w±±¨î TRUE FALSE // 2 : Switch Mode // 1 : Assign Run Mode // 0 : Assign Off Mode c_bRunMsrAI = (isRun == 2) ? c_bRunMsrAI ? FALSE : TRUE : !isRun; switch(isRun) { default: if (!c_bRunMsrAI) { case 1://¦Û°Ê¶q´ú±Ò©lÂI SetTimer(1, 180, NULL); if (isRun) break; } else { case 0: KillTimer(1); m_Goal.SetPercent(0); if (!isRun) break; } } } void CPatternDlg::eventSwCntCa210() { //¤Á´«³s½u m_pCA210->SetOnline(m_pCA210->isOnline() ? FALSE : TRUE); Invalidate(); } void CPatternDlg::eventExitDialog() { if(c_bRunMsrAI) KillTimer(1); ShowWindow(SW_HIDE); CMainFrame* pMainFrm = dynamic_cast<CMainFrame*>(AfxGetMainWnd()); ASSERT_VALID(pMainFrm); CColorEyeIDoc* pDoc = dynamic_cast<CColorEyeIDoc*>(pMainFrm->GetActiveDocument()); ASSERT_VALID(pDoc); pDoc->UpdateDocRNA(m_RNA); pDoc->GetFileHead().iNitsLv(m_NitsLv); pDoc->UpdateAllViews(NULL); } void CPatternDlg::setBkColor(const ColorRef& clr) { m_BkColor = clr; Invalidate(); UpdateWindow(); } void CPatternDlg::OnShowWindow(BOOL bShow, UINT nStatus) { CDialog::OnShowWindow(bShow, nStatus); m_pCA210->SetOnline(bShow); }
dwatow/ColorEyeI
PatternDlg.cpp
C++
apache-2.0
14,619
'use strict'; const Q = require("q"); const util = require("util"); const https = require("https"); const http = require("http"); const fs = require("fs"); const xml2js = require("xml2js"); const paths = { "inchikey" : "inchikey", "name" : "name/startswith", "rn" : "rn" }; function ChemIDDB () { var database = {}; } module.exports.DB = ChemIDDB; ChemIDDB.prototype.load = function( filename ) { var parser = new xml2js.Parser(); if (verbose) console.log("loading: ", filename); fs.readFile(filename, function( err, data ){ parser.parseString(data, function(err, results) { if(err) { console.log("error", err); process.exit(); } if (verbose) console.log("results:", util.inspect(results[0], false, null)); // database = results; }).then(function(){ console.log("db loaded"); }) }) } function query( params, verbose, callback ) { if (!Array.isArray(params)) { params = [params]; } var promises = []; params.forEach(function(param) { var options = { query : param.query || null, type : param.type || 'name', match : param.match || 'first' } promises.push( retrieve( options.query, options.type, options.match, verbose)) }); Q.allSettled(promises).then( function( values ) { callback(null, values); }, function ( err ) { callback(err); } ) } function retrieve( query, type, match, verbose ) { var deferred = Q.defer(); var url = [host, paths[type],query].join("/"); if (!query) { deferred.reject("NA"); } if (verbose) { console.log("ChemID url: " + url); } var result = ""; var req = https.get(url, function( res ) { if (verbose) { console.log("Status: ", res.statusCode); console.log("Headers: ", res.headers); } if (res.statusCode < 200 || res.statusCode > 399) { deferred.reject( res.statusCode ); } res.on("data", function( chunk ) { result += chunk; }); res.on("end", function( ) { deferred.resolve( result ); }) }); req.on("error", function(err) { deferred.reject(err); }) return deferred.promise; } module.exports.query = query;
timdockins/webchemjs
lib/chemid.js
JavaScript
apache-2.0
2,485
/* * (c) the authors Licensed under the Apache License, Version 2.0. */ package org.roaringbitmap; import org.roaringbitmap.buffer.MappeableBitmapContainer; import org.roaringbitmap.buffer.MappeableContainer; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.LongBuffer; import java.util.Arrays; import java.util.Iterator; import static java.lang.Long.bitCount; import static java.lang.Long.numberOfTrailingZeros; /** * Simple bitset-like container. */ public final class BitmapContainer extends Container implements Cloneable { public static final int MAX_CAPACITY = 1 << 16; private static final long serialVersionUID = 2L; // bail out early when the number of runs is excessive, without // an exact count (just a decent lower bound) private static final int BLOCKSIZE = 128; // 64 words can have max 32 runs per word, max 2k runs /** * optimization flag: whether the cardinality of the bitmaps is maintained through branchless * operations */ private static final boolean USE_BRANCHLESS = true; /** * Return a bitmap iterator over this array * * @param bitmap array to be iterated over * @return an iterator */ public static CharIterator getReverseShortIterator(long[] bitmap) { return new ReverseBitmapContainerCharIterator(bitmap); } /** * Return a bitmap iterator over this array * * @param bitmap array to be iterated over * @return an iterator */ public static PeekableCharIterator getShortIterator(long[] bitmap) { return new BitmapContainerCharIterator(bitmap); } // the parameter is for overloading and symmetry with ArrayContainer protected static int serializedSizeInBytes(int unusedCardinality) { return MAX_CAPACITY / 8; } final long[] bitmap; int cardinality; // nruns value for which RunContainer.serializedSizeInBytes == // BitmapContainer.getArraySizeInBytes() private final int MAXRUNS = (getArraySizeInBytes() - 2) / 4; /** * Create a bitmap container with all bits set to false */ public BitmapContainer() { this.cardinality = 0; this.bitmap = new long[MAX_CAPACITY / 64]; } /** * Create a bitmap container with a run of ones from firstOfRun to lastOfRun. Caller must ensure * that the range isn't so small that an ArrayContainer should have been created instead * * @param firstOfRun first index * @param lastOfRun last index (range is exclusive) */ public BitmapContainer(final int firstOfRun, final int lastOfRun) { this.cardinality = lastOfRun - firstOfRun; this.bitmap = new long[MAX_CAPACITY / 64]; Util.setBitmapRange(bitmap, firstOfRun, lastOfRun); } private BitmapContainer(int newCardinality, long[] newBitmap) { this.cardinality = newCardinality; this.bitmap = Arrays.copyOf(newBitmap, newBitmap.length); } /** * Create a new container, no copy is made. * * @param newBitmap content * @param newCardinality desired cardinality. */ public BitmapContainer(long[] newBitmap, int newCardinality) { this.cardinality = newCardinality; this.bitmap = newBitmap; } /** * Creates a new non-mappeable container from a mappeable one. This copies the data. * * @param bc the original container */ public BitmapContainer(MappeableBitmapContainer bc) { this.cardinality = bc.getCardinality(); this.bitmap = bc.toLongArray(); } @Override public Container add(int begin, int end) { // TODO: may need to convert to a RunContainer if (end == begin) { return clone(); } if ((begin > end) || (end > (1 << 16))) { throw new IllegalArgumentException("Invalid range [" + begin + "," + end + ")"); } BitmapContainer answer = clone(); int prevOnesInRange = answer.cardinalityInRange(begin, end); Util.setBitmapRange(answer.bitmap, begin, end); answer.updateCardinality(prevOnesInRange, end - begin); return answer; } @Override public Container add(final char i) { final long previous = bitmap[i >>> 6]; long newval = previous | (1L << i); bitmap[i >>> 6] = newval; if (USE_BRANCHLESS) { cardinality += (int)((previous ^ newval) >>> i); } else if (previous != newval) { ++cardinality; } return this; } @Override public ArrayContainer and(final ArrayContainer value2) { final ArrayContainer answer = new ArrayContainer(value2.content.length); int c = value2.cardinality; for (int k = 0; k < c; ++k) { char v = value2.content[k]; answer.content[answer.cardinality] = v; answer.cardinality += (int)this.bitValue(v); } return answer; } @Override public Container and(final BitmapContainer value2) { int newCardinality = 0; for (int k = 0; k < this.bitmap.length; ++k) { newCardinality += Long.bitCount(this.bitmap[k] & value2.bitmap[k]); } if (newCardinality > ArrayContainer.DEFAULT_MAX_SIZE) { final BitmapContainer answer = new BitmapContainer(); for (int k = 0; k < answer.bitmap.length; ++k) { answer.bitmap[k] = this.bitmap[k] & value2.bitmap[k]; } answer.cardinality = newCardinality; return answer; } ArrayContainer ac = new ArrayContainer(newCardinality); Util.fillArrayAND(ac.content, this.bitmap, value2.bitmap); ac.cardinality = newCardinality; return ac; } @Override public Container and(RunContainer x) { return x.and(this); } @Override public int andCardinality(final ArrayContainer value2) { int answer = 0; int c = value2.cardinality; for (int k = 0; k < c; ++k) { char v = value2.content[k]; answer += (int)this.bitValue(v); } return answer; } @Override public int andCardinality(final BitmapContainer value2) { int newCardinality = 0; for (int k = 0; k < this.bitmap.length; ++k) { newCardinality += Long.bitCount(this.bitmap[k] & value2.bitmap[k]); } return newCardinality; } @Override public int andCardinality(RunContainer x) { return x.andCardinality(this); } @Override public Container andNot(final ArrayContainer value2) { final BitmapContainer answer = clone(); int c = value2.cardinality; for (int k = 0; k < c; ++k) { char v = value2.content[k]; final int i = (v) >>> 6; long w = answer.bitmap[i]; long aft = w & (~(1L << v)); answer.bitmap[i] = aft; answer.cardinality -= (w ^ aft) >>> v; } if (answer.cardinality <= ArrayContainer.DEFAULT_MAX_SIZE) { return answer.toArrayContainer(); } return answer; } @Override public Container andNot(final BitmapContainer value2) { int newCardinality = 0; for (int k = 0; k < this.bitmap.length; ++k) { newCardinality += Long.bitCount(this.bitmap[k] & (~value2.bitmap[k])); } if (newCardinality > ArrayContainer.DEFAULT_MAX_SIZE) { final BitmapContainer answer = new BitmapContainer(); for (int k = 0; k < answer.bitmap.length; ++k) { answer.bitmap[k] = this.bitmap[k] & (~value2.bitmap[k]); } answer.cardinality = newCardinality; return answer; } ArrayContainer ac = new ArrayContainer(newCardinality); Util.fillArrayANDNOT(ac.content, this.bitmap, value2.bitmap); ac.cardinality = newCardinality; return ac; } @Override public Container andNot(RunContainer x) { // could be rewritten as return andNot(x.toBitmapOrArrayContainer()); BitmapContainer answer = this.clone(); for (int rlepos = 0; rlepos < x.nbrruns; ++rlepos) { int start = (x.getValue(rlepos)); int end = start + (x.getLength(rlepos)) + 1; int prevOnesInRange = answer.cardinalityInRange(start, end); Util.resetBitmapRange(answer.bitmap, start, end); answer.updateCardinality(prevOnesInRange, 0); } if (answer.getCardinality() > ArrayContainer.DEFAULT_MAX_SIZE) { return answer; } else { return answer.toArrayContainer(); } } @Override public void clear() { if (cardinality != 0) { cardinality = 0; Arrays.fill(bitmap, 0); } } @Override public BitmapContainer clone() { return new BitmapContainer(this.cardinality, this.bitmap); } @Override public boolean isEmpty() { return cardinality == 0; } /** * Recomputes the cardinality of the bitmap. */ void computeCardinality() { this.cardinality = 0; for (int k = 0; k < this.bitmap.length; k++) { this.cardinality += Long.bitCount(this.bitmap[k]); } } int cardinalityInRange(int start, int end) { assert (cardinality != -1); if (end - start > MAX_CAPACITY / 2) { int before = Util.cardinalityInBitmapRange(bitmap, 0, start); int after = Util.cardinalityInBitmapRange(bitmap, end, MAX_CAPACITY); return cardinality - before - after; } return Util.cardinalityInBitmapRange(bitmap, start, end); } void updateCardinality(int prevOnes, int newOnes) { int oldCardinality = this.cardinality; this.cardinality = oldCardinality - prevOnes + newOnes; } @Override public boolean contains(final char i) { return (bitmap[i >>> 6] & (1L << i)) != 0; } @Override public boolean contains(int minimum, int supremum) { int start = minimum >>> 6; int end = supremum >>> 6; long first = -(1L << minimum); long last = ((1L << supremum) - 1); if (start == end) { return ((bitmap[end] & first & last) == (first & last)); } if ((bitmap[start] & first) != first) { return false; } if (end < bitmap.length && (bitmap[end] & last) != last) { return false; } for (int i = start + 1; i < bitmap.length && i < end; ++i) { if (bitmap[i] != -1L) { return false; } } return true; } @Override protected boolean contains(BitmapContainer bitmapContainer) { if((cardinality != -1) && (bitmapContainer.cardinality != -1)) { if(cardinality < bitmapContainer.cardinality) { return false; } } for(int i = 0; i < bitmapContainer.bitmap.length; ++i ) { if((this.bitmap[i] & bitmapContainer.bitmap[i]) != bitmapContainer.bitmap[i]) { return false; } } return true; } @Override protected boolean contains(RunContainer runContainer) { final int runCardinality = runContainer.getCardinality(); if (cardinality != -1) { if (cardinality < runCardinality) { return false; } } else { int card = cardinality; if (card < runCardinality) { return false; } } for (int i = 0; i < runContainer.numberOfRuns(); ++i) { int start = (runContainer.getValue(i)); int length = (runContainer.getLength(i)); if (!contains(start, start + length)) { return false; } } return true; } @Override protected boolean contains(ArrayContainer arrayContainer) { if (arrayContainer.cardinality != -1) { if (cardinality < arrayContainer.cardinality) { return false; } } for (int i = 0; i < arrayContainer.cardinality; ++i) { if(!contains(arrayContainer.content[i])) { return false; } } return true; } int bitValue(final char i) { return (int)(bitmap[i >>> 6] >>> i ) & 1; } @Override public void deserialize(DataInput in) throws IOException { // little endian this.cardinality = 0; for (int k = 0; k < bitmap.length; ++k) { long w = Long.reverseBytes(in.readLong()); bitmap[k] = w; this.cardinality += Long.bitCount(w); } } @Override public boolean equals(Object o) { if (o instanceof BitmapContainer) { BitmapContainer srb = (BitmapContainer) o; if (srb.cardinality != this.cardinality) { return false; } return Arrays.equals(this.bitmap, srb.bitmap); } else if (o instanceof RunContainer) { return o.equals(this); } return false; } /** * Fill the array with set bits * * @param array container (should be sufficiently large) */ void fillArray(final char[] array) { int pos = 0; int base = 0; for (int k = 0; k < bitmap.length; ++k) { long bitset = bitmap[k]; while (bitset != 0) { array[pos++] = (char) (base + numberOfTrailingZeros(bitset)); bitset &= (bitset - 1); } base += 64; } } @Override public void fillLeastSignificant16bits(int[] x, int i, int mask) { int pos = i; int base = mask; for (int k = 0; k < bitmap.length; ++k) { long bitset = bitmap[k]; while (bitset != 0) { x[pos++] = base + numberOfTrailingZeros(bitset); bitset &= (bitset - 1); } base += 64; } } @Override public Container flip(char i) { int index = i >>> 6; long bef = bitmap[index]; long mask = 1L << i; if (cardinality == ArrayContainer.DEFAULT_MAX_SIZE + 1) {// this is // the // uncommon // path if ((bef & mask) != 0) { --cardinality; bitmap[index] &= ~mask; return this.toArrayContainer(); } } // TODO: check whether a branchy version could be faster cardinality += 1 - 2 * (int)((bef & mask) >>> i); bitmap[index] ^= mask; return this; } @Override public int getArraySizeInBytes() { return MAX_CAPACITY / 8; } @Override public int getCardinality() { return cardinality; } @Override public PeekableCharIterator getReverseCharIterator() { return new ReverseBitmapContainerCharIterator(this.bitmap); } @Override public PeekableCharIterator getCharIterator() { return new BitmapContainerCharIterator(this.bitmap); } @Override public PeekableCharRankIterator getCharRankIterator() { return new BitmapContainerCharRankIterator(this.bitmap); } @Override public ContainerBatchIterator getBatchIterator() { return new BitmapBatchIterator(this); } @Override public int getSizeInBytes() { return this.bitmap.length * 8; } @Override public int hashCode() { return Arrays.hashCode(this.bitmap); } @Override public Container iadd(int begin, int end) { // TODO: may need to convert to a RunContainer if (end == begin) { return this; } if ((begin > end) || (end > (1 << 16))) { throw new IllegalArgumentException("Invalid range [" + begin + "," + end + ")"); } int prevOnesInRange = cardinalityInRange(begin, end); Util.setBitmapRange(bitmap, begin, end); updateCardinality(prevOnesInRange, end - begin); return this; } @Override public Container iand(final ArrayContainer b2) { if (-1 == cardinality) { // actually we can avoid allocating in lazy mode Util.intersectArrayIntoBitmap(bitmap, b2.content, b2.cardinality); return this; } else { return b2.and(this); } } @Override public Container iand(final BitmapContainer b2) { if (-1 == cardinality) { // in lazy mode, just intersect the bitmaps, can repair afterwards for (int i = 0; i < bitmap.length; ++i) { bitmap[i] &= b2.bitmap[i]; } return this; } else { int newCardinality = 0; for (int k = 0; k < this.bitmap.length; ++k) { newCardinality += Long.bitCount(this.bitmap[k] & b2.bitmap[k]); } if (newCardinality > ArrayContainer.DEFAULT_MAX_SIZE) { for (int k = 0; k < this.bitmap.length; ++k) { this.bitmap[k] = this.bitmap[k] & b2.bitmap[k]; } this.cardinality = newCardinality; return this; } ArrayContainer ac = new ArrayContainer(newCardinality); Util.fillArrayAND(ac.content, this.bitmap, b2.bitmap); ac.cardinality = newCardinality; return ac; } } @Override public Container iand(RunContainer x) { // could probably be replaced with return iand(x.toBitmapOrArrayContainer()); final int card = x.getCardinality(); if (-1 != cardinality && card <= ArrayContainer.DEFAULT_MAX_SIZE) { // no point in doing it in-place, unless it's a lazy operation ArrayContainer answer = new ArrayContainer(card); answer.cardinality = 0; for (int rlepos = 0; rlepos < x.nbrruns; ++rlepos) { int runStart = (x.getValue(rlepos)); int runEnd = runStart + (x.getLength(rlepos)); for (int runValue = runStart; runValue <= runEnd; ++runValue) { answer.content[answer.cardinality] = (char) runValue; answer.cardinality += (int)this.bitValue((char) runValue); } } return answer; } int start = 0; for (int rlepos = 0; rlepos < x.nbrruns; ++rlepos) { int end = x.getValue(rlepos); if (-1 == cardinality) { Util.resetBitmapRange(this.bitmap, start, end); } else { int prevOnes = cardinalityInRange(start, end); Util.resetBitmapRange(this.bitmap, start, end); updateCardinality(prevOnes, 0); } start = end + x.getLength(rlepos) + 1; } if (-1 == cardinality) { // in lazy mode don't try to trim Util.resetBitmapRange(this.bitmap, start, MAX_CAPACITY); } else { int ones = cardinalityInRange(start, MAX_CAPACITY); Util.resetBitmapRange(this.bitmap, start, MAX_CAPACITY); updateCardinality(ones, 0); if (getCardinality() <= ArrayContainer.DEFAULT_MAX_SIZE) { return toArrayContainer(); } } return this; } @Override public Container iandNot(final ArrayContainer b2) { for (int k = 0; k < b2.cardinality; ++k) { this.remove(b2.content[k]); } if (cardinality <= ArrayContainer.DEFAULT_MAX_SIZE) { return this.toArrayContainer(); } return this; } @Override public Container iandNot(final BitmapContainer b2) { int newCardinality = 0; for (int k = 0; k < this.bitmap.length; ++k) { newCardinality += Long.bitCount(this.bitmap[k] & (~b2.bitmap[k])); } if (newCardinality > ArrayContainer.DEFAULT_MAX_SIZE) { for (int k = 0; k < this.bitmap.length; ++k) { this.bitmap[k] = this.bitmap[k] & (~b2.bitmap[k]); } this.cardinality = newCardinality; return this; } ArrayContainer ac = new ArrayContainer(newCardinality); Util.fillArrayANDNOT(ac.content, this.bitmap, b2.bitmap); ac.cardinality = newCardinality; return ac; } @Override public Container iandNot(RunContainer x) { // could probably be replaced with return iandNot(x.toBitmapOrArrayContainer()); for (int rlepos = 0; rlepos < x.nbrruns; ++rlepos) { int start = (x.getValue(rlepos)); int end = start + (x.getLength(rlepos)) + 1; int prevOnesInRange = cardinalityInRange(start, end); Util.resetBitmapRange(this.bitmap, start, end); updateCardinality(prevOnesInRange, 0); } if (getCardinality() > ArrayContainer.DEFAULT_MAX_SIZE) { return this; } else { return toArrayContainer(); } } Container ilazyor(ArrayContainer value2) { this.cardinality = -1;// invalid int c = value2.cardinality; for (int k = 0; k < c; ++k) { char v = value2.content[k]; final int i = (v) >>> 6; this.bitmap[i] |= (1L << v); } return this; } Container ilazyor(BitmapContainer x) { this.cardinality = -1;// invalid for (int k = 0; k < this.bitmap.length; k++) { this.bitmap[k] |= x.bitmap[k]; } return this; } Container ilazyor(RunContainer x) { // could be implemented as return ilazyor(x.toTemporaryBitmap()); cardinality = -1; // invalid for (int rlepos = 0; rlepos < x.nbrruns; ++rlepos) { int start = (x.getValue(rlepos)); int end = start + (x.getLength(rlepos)) + 1; Util.setBitmapRange(this.bitmap, start, end); } return this; } @Override public Container inot(final int firstOfRange, final int lastOfRange) { int prevOnes = cardinalityInRange(firstOfRange, lastOfRange); Util.flipBitmapRange(bitmap, firstOfRange, lastOfRange); updateCardinality(prevOnes, lastOfRange - firstOfRange - prevOnes); if (cardinality <= ArrayContainer.DEFAULT_MAX_SIZE) { return toArrayContainer(); } return this; } @Override public boolean intersects(ArrayContainer value2) { int c = value2.cardinality; for (int k = 0; k < c; ++k) { if (this.contains(value2.content[k])) { return true; } } return false; } @Override public boolean intersects(BitmapContainer value2) { for (int k = 0; k < this.bitmap.length; ++k) { if ((this.bitmap[k] & value2.bitmap[k]) != 0) { return true; } } return false; } @Override public boolean intersects(RunContainer x) { return x.intersects(this); } @Override public boolean intersects(int minimum, int supremum) { if((minimum < 0) || (supremum < minimum) || (supremum > (1<<16))) { throw new RuntimeException("This should never happen (bug)."); } int start = minimum >>> 6; int end = supremum >>> 6; if (start == end) { return ((bitmap[end] & (-(1L << minimum) & ((1L << supremum) - 1))) != 0); } if ((bitmap[start] & -(1L << minimum)) != 0) { return true; } if (end < bitmap.length && (bitmap[end] & ((1L << supremum) - 1)) != 0) { return true; } for (int i = 1 + start; i < end && i < bitmap.length; ++i) { if (bitmap[i] != 0) { return true; } } return false; } @Override public BitmapContainer ior(final ArrayContainer value2) { int c = value2.cardinality; for (int k = 0; k < c; ++k) { final int i = (value2.content[k]) >>> 6; long bef = this.bitmap[i]; long aft = bef | (1L << value2.content[k]); this.bitmap[i] = aft; if (USE_BRANCHLESS) { cardinality += (int)((bef - aft) >>> 63); } else { if (bef != aft) { cardinality++; } } } return this; } @Override public Container ior(final BitmapContainer b2) { for (int k = 0; k < this.bitmap.length & k < b2.bitmap.length; k++) { this.bitmap[k] |= b2.bitmap[k]; } computeCardinality(); if (isFull()) { return RunContainer.full(); } return this; } @Override public Container ior(RunContainer x) { // could probably be replaced with return ior(x.toBitmapOrArrayContainer()); for (int rlepos = 0; rlepos < x.nbrruns; ++rlepos) { int start = (x.getValue(rlepos)); int end = start + (x.getLength(rlepos)) + 1; int prevOnesInRange = cardinalityInRange(start, end); Util.setBitmapRange(this.bitmap, start, end); updateCardinality(prevOnesInRange, end - start); } if (isFull()) { return RunContainer.full(); } return this; } @Override public Container iremove(int begin, int end) { if (end == begin) { return this; } if ((begin > end) || (end > (1 << 16))) { throw new IllegalArgumentException("Invalid range [" + begin + "," + end + ")"); } int prevOnesInRange = cardinalityInRange(begin, end); Util.resetBitmapRange(bitmap, begin, end); updateCardinality(prevOnesInRange, 0); if (getCardinality() <= ArrayContainer.DEFAULT_MAX_SIZE) { return toArrayContainer(); } return this; } @Override public Iterator<Character> iterator() { return new Iterator<Character>() { final CharIterator si = BitmapContainer.this.getCharIterator(); @Override public boolean hasNext() { return si.hasNext(); } @Override public Character next() { return si.next(); } @Override public void remove() { // TODO: implement throw new RuntimeException("unsupported operation: remove"); } }; } @Override public Container ixor(final ArrayContainer value2) { int c = value2.cardinality; for (int k = 0; k < c; ++k) { char vc = value2.content[k]; long mask = 1L << vc; final int index = (vc) >>> 6; long ba = this.bitmap[index]; // TODO: check whether a branchy version could be faster this.cardinality += 1 - 2 * (int)((ba & mask) >>> vc); this.bitmap[index] = ba ^ mask; } if (this.cardinality <= ArrayContainer.DEFAULT_MAX_SIZE) { return this.toArrayContainer(); } return this; } @Override public Container ixor(BitmapContainer b2) { // do this first because we have to compute the xor no matter what, and this loop gets // vectorized and is faster than computing the cardinality or filling the array for (int k = 0; k < this.bitmap.length & k < b2.bitmap.length; ++k) { this.bitmap[k] ^= b2.bitmap[k]; } // now count the bits computeCardinality(); if (cardinality > ArrayContainer.DEFAULT_MAX_SIZE) { return this; } return toArrayContainer(); } @Override public Container ixor(RunContainer x) { // could probably be replaced with return ixor(x.toBitmapOrArrayContainer()); for (int rlepos = 0; rlepos < x.nbrruns; ++rlepos) { int start = x.getValue(rlepos); int end = start + x.getLength(rlepos) + 1; int prevOnes = cardinalityInRange(start, end); Util.flipBitmapRange(this.bitmap, start, end); updateCardinality(prevOnes, end - start - prevOnes); } if (this.getCardinality() > ArrayContainer.DEFAULT_MAX_SIZE) { return this; } else { return toArrayContainer(); } } protected Container lazyor(ArrayContainer value2) { BitmapContainer answer = this.clone(); answer.cardinality = -1;// invalid int c = value2.cardinality; for (int k = 0; k < c; ++k) { char v = value2.content[k]; final int i = (v) >>> 6; answer.bitmap[i] |= (1L << v); } return answer; } protected Container lazyor(BitmapContainer x) { BitmapContainer answer = new BitmapContainer(); answer.cardinality = -1;// invalid for (int k = 0; k < this.bitmap.length; k++) { answer.bitmap[k] = this.bitmap[k] | x.bitmap[k]; } return answer; } protected Container lazyor(RunContainer x) { BitmapContainer bc = clone(); bc.cardinality = -1; // invalid for (int rlepos = 0; rlepos < x.nbrruns; ++rlepos) { int start = (x.getValue(rlepos)); int end = start + (x.getLength(rlepos)) + 1; Util.setBitmapRange(bc.bitmap, start, end); } return bc; } @Override public Container limit(int maxcardinality) { if (maxcardinality >= this.cardinality) { return clone(); } if (maxcardinality <= ArrayContainer.DEFAULT_MAX_SIZE) { ArrayContainer ac = new ArrayContainer(maxcardinality); int pos = 0; for (int k = 0; (ac.cardinality < maxcardinality) && (k < bitmap.length); ++k) { long bitset = bitmap[k]; while ((ac.cardinality < maxcardinality) && (bitset != 0)) { ac.content[pos++] = (char) (k * 64 + numberOfTrailingZeros(bitset)); ac.cardinality++; bitset &= (bitset - 1); } } return ac; } BitmapContainer bc = new BitmapContainer(maxcardinality, this.bitmap); int s = (select(maxcardinality)); int usedwords = (s + 63) / 64; int todelete = this.bitmap.length - usedwords; for (int k = 0; k < todelete; ++k) { bc.bitmap[bc.bitmap.length - 1 - k] = 0; } int lastword = s % 64; if (lastword != 0) { bc.bitmap[s / 64] &= (0xFFFFFFFFFFFFFFFFL >>> (64 - lastword)); } return bc; } void loadData(final ArrayContainer arrayContainer) { this.cardinality = arrayContainer.cardinality; for (int k = 0; k < arrayContainer.cardinality; ++k) { final char x = arrayContainer.content[k]; bitmap[(x) / 64] |= (1L << x); } } /** * Find the index of the next set bit greater or equal to i, returns -1 if none found. * * @param i starting index * @return index of the next set bit */ public int nextSetBit(final int i) { int x = i >> 6; long w = bitmap[x]; w >>>= i; if (w != 0) { return i + numberOfTrailingZeros(w); } for (++x; x < bitmap.length; ++x) { if (bitmap[x] != 0) { return x * 64 + numberOfTrailingZeros(bitmap[x]); } } return -1; } /** * Find the index of the next clear bit greater or equal to i. * * @param i starting index * @return index of the next clear bit */ private int nextClearBit(final int i) { int x = i >> 6; long w = ~bitmap[x]; w >>>= i; if (w != 0) { return i + numberOfTrailingZeros(w); } for (++x; x < bitmap.length; ++x) { long map = ~bitmap[x]; if (map != 0) { return x * 64 + numberOfTrailingZeros(map); } } return MAX_CAPACITY; } @Override public Container not(final int firstOfRange, final int lastOfRange) { BitmapContainer answer = clone(); return answer.inot(firstOfRange, lastOfRange); } @Override int numberOfRuns() { int numRuns = 0; long nextWord = bitmap[0]; for (int i = 0; i < bitmap.length - 1; i++) { long word = nextWord; nextWord = bitmap[i + 1]; numRuns += Long.bitCount((~word) & (word << 1)) + (int)((word >>> 63) & ~nextWord); } long word = nextWord; numRuns += Long.bitCount((~word) & (word << 1)); if ((word & 0x8000000000000000L) != 0) { numRuns++; } return numRuns; } /** * Computes the number of runs * * @return the number of runs */ public int numberOfRunsAdjustment() { int ans = 0; long nextWord = bitmap[0]; for (int i = 0; i < bitmap.length - 1; i++) { final long word = nextWord; nextWord = bitmap[i + 1]; ans += (int)((word >>> 63) & ~nextWord); } final long word = nextWord; if ((word & 0x8000000000000000L) != 0) { ans++; } return ans; } /** * Counts how many runs there is in the bitmap, up to a maximum * * @param mustNotExceed maximum of runs beyond which counting is pointless * @return estimated number of courses */ public int numberOfRunsLowerBound(int mustNotExceed) { int numRuns = 0; for (int blockOffset = 0; blockOffset + BLOCKSIZE <= bitmap.length; blockOffset += BLOCKSIZE) { for (int i = blockOffset; i < blockOffset + BLOCKSIZE; i++) { long word = bitmap[i]; numRuns += Long.bitCount((~word) & (word << 1)); } if (numRuns > mustNotExceed) { return numRuns; } } return numRuns; } @Override public Container or(final ArrayContainer value2) { final BitmapContainer answer = clone(); int c = value2.cardinality; for (int k = 0; k < c; ++k) { char v = value2.content[k]; final int i = (v) >>> 6; long w = answer.bitmap[i]; long aft = w | (1L << v); answer.bitmap[i] = aft; if (USE_BRANCHLESS) { answer.cardinality += (int)((w - aft) >>> 63); } else { if (w != aft) { answer.cardinality++; } } } if (answer.isFull()) { return RunContainer.full(); } return answer; } @Override public boolean isFull() { return cardinality == MAX_CAPACITY; } @Override public Container or(final BitmapContainer value2) { BitmapContainer value1 = this.clone(); return value1.ior(value2); } @Override public Container or(RunContainer x) { return x.or(this); } /** * Find the index of the previous set bit less than or equal to i, returns -1 if none found. * * @param i starting index * @return index of the previous set bit */ int prevSetBit(final int i) { int x = i >> 6; // i / 64 with sign extension long w = bitmap[x]; w <<= 64 - i - 1; if (w != 0) { return i - Long.numberOfLeadingZeros(w); } for (--x; x >= 0; --x) { if (bitmap[x] != 0) { return x * 64 + 63 - Long.numberOfLeadingZeros(bitmap[x]); } } return -1; } /** * Find the index of the previous clear bit less than or equal to i. * * @param i starting index * @return index of the previous clear bit */ private int prevClearBit(final int i) { int x = i >> 6; // i / 64 with sign extension long w = ~bitmap[x]; w <<= 64 - (i + 1); if (w != 0) { return i - Long.numberOfLeadingZeros(w); } for (--x; x >= 0; --x) { long map = ~bitmap[x]; if (map != 0) { return x * 64 + 63 - Long.numberOfLeadingZeros(map); } } return -1; } @Override public int rank(char lowbits) { int leftover = (lowbits + 1) & 63; int answer = 0; for (int k = 0; k < (lowbits + 1) >>> 6; ++k) { answer += Long.bitCount(bitmap[k]); } if (leftover != 0) { answer += Long.bitCount(bitmap[(lowbits + 1) >>> 6] << (64 - leftover)); } return answer; } @Override public void readExternal(ObjectInput in) throws IOException { deserialize(in); } @Override public Container remove(int begin, int end) { if (end == begin) { return clone(); } if ((begin > end) || (end > (1 << 16))) { throw new IllegalArgumentException("Invalid range [" + begin + "," + end + ")"); } BitmapContainer answer = clone(); int prevOnesInRange = answer.cardinalityInRange(begin, end); Util.resetBitmapRange(answer.bitmap, begin, end); answer.updateCardinality(prevOnesInRange, 0); if (answer.getCardinality() <= ArrayContainer.DEFAULT_MAX_SIZE) { return answer.toArrayContainer(); } return answer; } @Override public Container remove(final char i) { int index = i >>> 6; long bef = bitmap[index]; long mask = 1L << i; if (cardinality == ArrayContainer.DEFAULT_MAX_SIZE + 1) {// this is // the // uncommon // path if ((bef & mask) != 0) { --cardinality; bitmap[i >>> 6] = bef & ~mask; return this.toArrayContainer(); } } long aft = bef & ~mask; cardinality -= (aft - bef) >>> 63; bitmap[index] = aft; return this; } @Override public Container repairAfterLazy() { if (getCardinality() < 0) { computeCardinality(); if(getCardinality() <= ArrayContainer.DEFAULT_MAX_SIZE) { return this.toArrayContainer(); } else if (isFull()) { return RunContainer.full(); } } return this; } @Override public Container runOptimize() { int numRuns = numberOfRunsLowerBound(MAXRUNS); // decent choice int sizeAsRunContainerLowerBound = RunContainer.serializedSizeInBytes(numRuns); if (sizeAsRunContainerLowerBound >= getArraySizeInBytes()) { return this; } // else numRuns is a relatively tight bound that needs to be exact // in some cases (or if we need to make the runContainer the right // size) numRuns += numberOfRunsAdjustment(); int sizeAsRunContainer = RunContainer.serializedSizeInBytes(numRuns); if (getArraySizeInBytes() > sizeAsRunContainer) { return new RunContainer(this, numRuns); } else { return this; } } @Override public char select(int j) { int leftover = j; for (int k = 0; k < bitmap.length; ++k) { int w = Long.bitCount(bitmap[k]); if (w > leftover) { return (char) (k * 64 + Util.select(bitmap[k], leftover)); } leftover -= w; } throw new IllegalArgumentException("Insufficient cardinality."); } @Override public void serialize(DataOutput out) throws IOException { // little endian for (long w : bitmap) { out.writeLong(Long.reverseBytes(w)); } } @Override public int serializedSizeInBytes() { return serializedSizeInBytes(0); } /** * Copies the data to an array container * * @return the array container */ ArrayContainer toArrayContainer() { ArrayContainer ac = new ArrayContainer(cardinality); if (cardinality != 0) { ac.loadData(this); } if (ac.getCardinality() != cardinality) { throw new RuntimeException("Internal error."); } return ac; } /** * Return the content of this container as a LongBuffer. This creates a copy and might be * relatively slow. * * @return the LongBuffer */ public LongBuffer toLongBuffer() { LongBuffer lb = LongBuffer.allocate(bitmap.length); lb.put(bitmap); return lb; } @Override public MappeableContainer toMappeableContainer() { return new MappeableBitmapContainer(this); } @Override public String toString() { StringBuilder sb = new StringBuilder(); final CharIterator i = this.getCharIterator(); sb.append("{"); while (i.hasNext()) { sb.append((int)(i.next())); if (i.hasNext()) { sb.append(","); } } sb.append("}"); return sb.toString(); } @Override public void trim() { } @Override public void writeArray(DataOutput out) throws IOException { serialize(out); } @Override public void writeArray(ByteBuffer buffer) { assert buffer.order() == ByteOrder.LITTLE_ENDIAN; LongBuffer buf = buffer.asLongBuffer(); buf.put(bitmap); int bytesWritten = bitmap.length * 8; buffer.position(buffer.position() + bytesWritten); } @Override public void writeExternal(ObjectOutput out) throws IOException { serialize(out); } @Override public Container xor(final ArrayContainer value2) { final BitmapContainer answer = clone(); int c = value2.cardinality; for (int k = 0; k < c; ++k) { char vc = value2.content[k]; final int index = vc >>> 6; final long mask = 1L << vc; final long val = answer.bitmap[index]; // TODO: check whether a branchy version could be faster answer.cardinality += (int)(1 - 2 * ((val & mask) >>> vc)); answer.bitmap[index] = val ^ mask; } if (answer.cardinality <= ArrayContainer.DEFAULT_MAX_SIZE) { return answer.toArrayContainer(); } return answer; } @Override public Container xor(BitmapContainer value2) { int newCardinality = 0; for (int k = 0; k < this.bitmap.length; ++k) { newCardinality += Long.bitCount(this.bitmap[k] ^ value2.bitmap[k]); } if (newCardinality > ArrayContainer.DEFAULT_MAX_SIZE) { final BitmapContainer answer = new BitmapContainer(); for (int k = 0; k < answer.bitmap.length; ++k) { answer.bitmap[k] = this.bitmap[k] ^ value2.bitmap[k]; } answer.cardinality = newCardinality; return answer; } ArrayContainer ac = new ArrayContainer(newCardinality); Util.fillArrayXOR(ac.content, this.bitmap, value2.bitmap); ac.cardinality = newCardinality; return ac; } @Override public Container xor(RunContainer x) { return x.xor(this); } @Override public void forEach(char msb, IntConsumer ic) { int high = msb << 16; for (int x = 0; x < bitmap.length; ++x) { long w = bitmap[x]; while (w != 0) { ic.accept(((x << 6) + numberOfTrailingZeros(w)) | high); w &= (w - 1); } } } @Override public void forAll(int offset, final RelativeRangeConsumer rrc) { for (int wordIndex = 0; wordIndex < bitmap.length; wordIndex++) { long word = bitmap[wordIndex]; int bufferWordStart = offset + (wordIndex << 6); int bufferWordEnd = bufferWordStart + 64; addWholeWordToRangeConsumer(word, bufferWordStart, bufferWordEnd, rrc); } } @Override public void forAllFrom(char startValue, final RelativeRangeConsumer rrc) { int startIndex = startValue >>> 6; for (int wordIndex = startIndex; wordIndex < bitmap.length; wordIndex++) { long word = bitmap[wordIndex]; int wordStart = wordIndex << 6; int wordEnd = wordStart + 64; if (wordStart < startValue) { // startValue is in the middle of the word // some special cases for efficiency if (word == 0) { rrc.acceptAllAbsent(0, wordEnd - startValue); } else if (word == -1) { // all 1s rrc.acceptAllPresent(0, wordEnd - startValue); } else { int nextPos = startValue; while (word != 0) { int pos = wordStart + numberOfTrailingZeros(word); if (nextPos < pos) { rrc.acceptAllAbsent(nextPos - startValue, pos - startValue); rrc.acceptPresent(pos - startValue); nextPos = pos + 1; } else if (nextPos == pos) { rrc.acceptPresent(pos - startValue); nextPos++; } // else just we out before startValue, so ignore word &= (word - 1); } if (nextPos < wordEnd) { rrc.acceptAllAbsent(nextPos - startValue, wordEnd - startValue); } } } else { // startValue is aligned with word addWholeWordToRangeConsumer(word, wordStart - startValue, wordEnd - startValue, rrc); } } } @Override public void forAllUntil(int offset, char endValue, final RelativeRangeConsumer rrc) { int bufferEndPos = offset + endValue; for (int wordIndex = 0; wordIndex < bitmap.length; wordIndex++) { long word = bitmap[wordIndex]; int bufferWordStart = offset + (wordIndex << 6); int bufferWordEnd = bufferWordStart + 64; if (bufferWordStart >= bufferEndPos) { return; } if (bufferEndPos < bufferWordEnd) { // we end on this word // some special cases for efficiency if (word == 0) { rrc.acceptAllAbsent(bufferWordStart, bufferEndPos); } else if (word == -1) { // all 1s rrc.acceptAllPresent(bufferWordStart, bufferEndPos); } else { int nextPos = bufferWordStart; while (word != 0) { int pos = bufferWordStart + numberOfTrailingZeros(word); if (bufferEndPos <= pos) { // we've moved past the end if (nextPos < bufferEndPos) { rrc.acceptAllAbsent(nextPos, bufferEndPos); } return; } if (nextPos < pos) { rrc.acceptAllAbsent(nextPos, pos); nextPos = pos; } rrc.acceptPresent(pos); nextPos++; word &= (word - 1); } if (nextPos < bufferEndPos) { rrc.acceptAllAbsent(nextPos, bufferEndPos); } return; } } else { addWholeWordToRangeConsumer(word, bufferWordStart, bufferWordEnd, rrc); } } } @Override public void forAllInRange(char startValue, char endValue, final RelativeRangeConsumer rrc) { if (endValue <= startValue) { throw new IllegalArgumentException( "startValue (" + startValue + ") must be less than endValue (" + endValue + ")"); } int startIndex = startValue >>> 6; for (int wordIndex = startIndex; wordIndex < bitmap.length; wordIndex++) { long word = bitmap[wordIndex]; int wordStart = wordIndex << 6; int wordEnd = wordStart + 64; if (wordStart >= endValue) { return; } boolean startInWord = wordStart < startValue; boolean endInWord = endValue < wordEnd; boolean wordAllZeroes = word == 0; boolean wordAllOnes = word == -1; if (startInWord && endInWord) { if (wordAllZeroes) { rrc.acceptAllAbsent(0, endValue - startValue); } else if (wordAllOnes) { rrc.acceptAllPresent(0, endValue - startValue); } else { int nextPos = startValue; while (word != 0) { int pos = wordStart + numberOfTrailingZeros(word); if (endValue < pos) { // we've moved past the end if (nextPos < endValue) { rrc.acceptAllAbsent(nextPos - startValue, endValue - startValue); } return; } if (nextPos < pos) { rrc.acceptAllAbsent(nextPos - startValue, pos - startValue); rrc.acceptPresent(pos - startValue); nextPos = pos + 1; } else if (nextPos == pos) { rrc.acceptPresent(pos - startValue); nextPos++; } word &= (word - 1); } if (nextPos < endValue) { rrc.acceptAllAbsent(nextPos - startValue, endValue - startValue); } } return; } else if (startInWord) { if (wordAllZeroes) { rrc.acceptAllAbsent(0, 64 - startValue); } else if (wordAllOnes) { rrc.acceptAllPresent(0, 64 - startValue); } else { int nextPos = startValue; while (word != 0) { int pos = wordStart + numberOfTrailingZeros(word); if (nextPos < pos) { rrc.acceptAllAbsent(nextPos - startValue, pos - startValue); rrc.acceptPresent(pos - startValue); nextPos = pos + 1; } else if (nextPos == pos) { rrc.acceptPresent(pos - startValue); nextPos++; } word &= (word - 1); } if (nextPos < wordEnd) { rrc.acceptAllAbsent(nextPos - startValue, wordEnd - startValue); } } } else if (endInWord) { if (wordAllZeroes) { rrc.acceptAllAbsent(wordStart - startValue, endValue - startValue); } else if (wordAllOnes) { rrc.acceptAllPresent(wordStart - startValue, endValue - startValue); } else { int nextPos = wordStart; while (word != 0) { int pos = wordStart + numberOfTrailingZeros(word); if (endValue <= pos) { // we've moved past the end if (nextPos < endValue) { rrc.acceptAllAbsent(nextPos - startValue, endValue - startValue); } return; } if (nextPos < pos) { rrc.acceptAllAbsent(nextPos - startValue, pos - startValue); nextPos = pos; } rrc.acceptPresent(pos - startValue); nextPos++; word &= (word - 1); } if (nextPos < endValue) { rrc.acceptAllAbsent(nextPos - startValue, endValue - startValue); } } return; } else { addWholeWordToRangeConsumer(word, wordStart - startValue, wordEnd - startValue, rrc); } } } private void addWholeWordToRangeConsumer( long word, int bufferWordStart, int bufferWordEnd, final RelativeRangeConsumer rrc) { // some special cases for efficiency if (word == 0) { rrc.acceptAllAbsent(bufferWordStart, bufferWordEnd); } else if (word == -1) { // all 1s rrc.acceptAllPresent(bufferWordStart, bufferWordEnd); } else { int nextPos = bufferWordStart; while (word != 0) { int pos = bufferWordStart + numberOfTrailingZeros(word); if (nextPos < pos) { rrc.acceptAllAbsent(nextPos, pos); nextPos = pos; } rrc.acceptPresent(pos); nextPos++; word &= (word - 1); } if (nextPos < bufferWordEnd) { rrc.acceptAllAbsent(nextPos, bufferWordEnd); } } } @Override public BitmapContainer toBitmapContainer() { return this; } @Override public int nextValue(char fromValue) { return nextSetBit((fromValue)); } @Override public int previousValue(char fromValue) { return prevSetBit((fromValue)); } @Override public int nextAbsentValue(char fromValue) { return nextClearBit((fromValue)); } @Override public int previousAbsentValue(char fromValue) { return prevClearBit((fromValue)); } @Override public int first() { assertNonEmpty(cardinality == 0); int i = 0; while(i < bitmap.length - 1 && bitmap[i] == 0) { ++i; // seek forward } // sizeof(long) * #empty words at start + number of bits preceding the first bit set return i * 64 + numberOfTrailingZeros(bitmap[i]); } @Override public int last() { assertNonEmpty(cardinality == 0); int i = bitmap.length - 1; while(i > 0 && bitmap[i] == 0) { --i; // seek backward } // sizeof(long) * #words from start - number of bits after the last bit set return (i + 1) * 64 - Long.numberOfLeadingZeros(bitmap[i]) - 1; } } class BitmapContainerCharIterator implements PeekableCharIterator { long w; int x; long[] bitmap; BitmapContainerCharIterator() { } BitmapContainerCharIterator(long[] p) { wrap(p); } @Override public PeekableCharIterator clone() { try { return (PeekableCharIterator) super.clone(); } catch (CloneNotSupportedException e) { return null;// will not happen } } @Override public boolean hasNext() { return x < bitmap.length; } @Override public char next() { char answer = (char) (x * 64 + numberOfTrailingZeros(w)); w &= (w - 1); while (w == 0) { ++x; if (x == bitmap.length) { break; } w = bitmap[x]; } return answer; } @Override public int nextAsInt() { return (next()); } @Override public void remove() { // TODO: implement throw new RuntimeException("unsupported operation: remove"); } public void wrap(long[] b) { bitmap = b; for (x = 0; x < bitmap.length; ++x) { if ((w = bitmap[x]) != 0) { break; } } } @Override public void advanceIfNeeded(char minval) { if ((minval) >= (x + 1) * 64) { x = (minval) / 64; w = bitmap[x]; while (w == 0) { ++x; if (x == bitmap.length) { return; } w = bitmap[x]; } } while (hasNext() && ((peekNext()) < (minval))) { next(); // could be optimized } } @Override public char peekNext() { return (char) (x * 64 + numberOfTrailingZeros(w)); } } final class BitmapContainerCharRankIterator extends BitmapContainerCharIterator implements PeekableCharRankIterator { private int nextRank = 1; BitmapContainerCharRankIterator(long[] p) { super(p); } @Override public int peekNextRank() { return nextRank; } @Override public char next() { ++nextRank; return super.next(); } @Override public void advanceIfNeeded(char minval) { if ((minval) >= (x + 1) * 64) { int nextX = (minval) / 64; nextRank += bitCount(w); for(x = x + 1; x < nextX; ++x) { w = bitmap[x]; nextRank += bitCount(w); } x = nextX; w = bitmap[x]; while (w == 0) { ++x; if (x == bitmap.length) { return; } w = bitmap[x]; } } while (hasNext() && ((peekNext()) < (minval))) { next(); // could be optimized } } @Override public PeekableCharRankIterator clone() { return (PeekableCharRankIterator) super.clone(); } } final class ReverseBitmapContainerCharIterator implements PeekableCharIterator { long word; int position; long[] bitmap; ReverseBitmapContainerCharIterator() { } ReverseBitmapContainerCharIterator(long[] bitmap) { wrap(bitmap); } @Override public PeekableCharIterator clone() { try { return (PeekableCharIterator) super.clone(); } catch (CloneNotSupportedException e) { return null; } } @Override public boolean hasNext() { return position >= 0; } @Override public char next() { int shift = Long.numberOfLeadingZeros(word) + 1; char answer = (char)((position + 1) * 64 - shift); word &= (0xFFFFFFFFFFFFFFFEL >>> shift); while (word == 0) { --position; if (position < 0) { break; } word = bitmap[position]; } return answer; } @Override public int nextAsInt() { return next(); } @Override public void advanceIfNeeded(char maxval) { if ((maxval) <= (position - 1) * 64) { position = (maxval) / 64; word = bitmap[position]; while (word == 0) { --position; if (position == 0) { break; } word = bitmap[position]; } } while (hasNext() && ((peekNext()) > (maxval))) { next(); // could be optimized } } @Override public char peekNext() { int shift = Long.numberOfLeadingZeros(word) + 1; return (char) ((position + 1) * 64 - shift); } @Override public void remove() { // TODO: implement throw new RuntimeException("unsupported operation: remove"); } void wrap(long[] b) { bitmap = b; for (position = bitmap.length - 1; position >= 0; --position) { if ((word = bitmap[position]) != 0) { break; } } } }
RoaringBitmap/RoaringBitmap
RoaringBitmap/src/main/java/org/roaringbitmap/BitmapContainer.java
Java
apache-2.0
52,906
<?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title><?php if(!empty($seo_title)): echo ($seo_title); ?>_<?php endif; echo ($CONFIG["site"]["sitename"]); ?>会员中心</title> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"> <?php if($CONFIG[site][concat] != 1): ?><link rel="stylesheet" href="/static/default/wap/css/base.css"> <link rel="stylesheet" href="/static/default/wap/css/mcenter.css"/> <script src="/static/default/wap/js/jquery.js"></script> <script src="/static/default/wap/js/base.js"></script> <script src="/static/default/wap/other/layer.js"></script> <script src="/static/default/wap/other/roll.js"></script> <script src="/static/default/wap/js/public.js"></script> <?php else: ?> <link rel="stylesheet" href="/static/default/wap/css/??base.css,mcenter.css" /> <script src="/static/default/wap/js/??jquery.js,base.js,roll.js,layer.js,public.js"></script><?php endif; ?> </head> <body> <header class="top-fixed bg-yellow bg-inverse"> <div class="top-back"> <a class="top-addr" href="<?php echo U('information/index');?>"><i class="icon-angle-left"></i></a> </div> <div class="top-title"> 修改密码 </div> <div class="top-signed"> <?php if($msg_day > 0): ?><a href="<?php echo U('mcenter/message/index');?>"> <i class="icon-envelope"></i> <span class="badge bg-red jiaofei"><?php echo ($msg_day); ?></span> </a> <?php else: ?> <?php if(empty($sign_day)): ?><a href="<?php echo U('mobile/sign/signed');?>" class="top-addr icon-plus"> 签到</a> <?php else: ?> <a href="<?php echo U('mobile/passport/logout');?>" class="top-addr icon-sign-out"></a><?php endif; endif; ?> </div> </header> <style> .line {padding:0 10px;} .line .x2{height:40px;line-height:40px;color:#999;} .line .x10{position:relative;height:40px;} .line .x10 input{border:none;padding:10px;position:absolute;bottom:0;} </style> <form action="<?php echo U('info/password');?>" method="post" target="x-frame"> <div class="line border-bottom"> <span class="x2">新设密码</span> <span class="x10"><input name="newpwd" type="password" placeholder=""></span> </div> <div class="line border-bottom"> <span class="x2">确认密码</span> <span class="x10"><input name="pwd2" type="password" placeholder=""></span> </div> <div class="blank-30"></div> <div class="container"> <button class="button button-block button-big bg-dot" type="submit">立刻修改</button> </div> </form> <div class="blank-20"></div> <!--<?php if($CONFIG[other][footer] == 1): ?>--> <!----> <!--<footer class="foot-fixed">--> <!----> <!--<a class="foot-item <?php if(($ctl == 'index') AND ($act != 'more')): ?>active<?php endif; ?>" href="<?php echo u('mobile/index/index');?>"> --> <!--<span class="icon icon-home"></span>--> <!--<span class="foot-label">首页</span>--> <!--</a>--> <!----> <!----> <!--<a class="foot-item <?php if(($ctl == 'tuan') || ($ctl == 'goods') || ($ctl == 'eleorder') || ($ctl == 'ding') ): ?>active<?php endif; ?>" href=" <?php echo LinkTo('tuan/index');?>"> --> <!--<span class="icon icon-cart-plus"></span><span class="foot-label">订单</span></a>--> <!----> <!--<a class="foot-item <?php if(($ctl == 'tuancode')): ?>active<?php endif; ?>" href="<?php echo u('mcenter/tuancode/index');?>"> --> <!--<span class="icon icon-tags"></span><span class="foot-label">抢购劵</span></a>--> <!----> <!----> <!----> <!--<a class="foot-item <?php if(($ctl == 'message') ||($act == 'xiaoxizhongxin')): ?>active<?php endif; ?>" href="<?php echo u('mcenter/message/someone');?>"> --> <!--<span class="icon icon-volume-up"></span><span class="foot-label">消息</span></a>--> <!----> <!--<a class="foot-item <?php if(($ctl == 'member') || ($ctl == 'logs') || ($ctl == 'cash') ||($act == 'zijinguanli')): ?>active<?php endif; ?>" href="<?php echo u('mcenter/member/index');?>">--> <!--<span class="icon icon-user"></span><span class="foot-label">会员中心</span></a>--> <!----> <!----> <!--</footer>--> <!--<?php endif; ?>--> <footer class="foot-fixed"> <a class="foot-item <?php if(($ctl == 'mall') AND ($act != 'more')): ?>active<?php endif; ?>" href="<?php echo u('mobile/mall/index');?>"> <span class="icon icon-home"></span> <span class="foot-label">首页</span> </a> <a class="foot-item <?php if(($ctl == 'tuan') || ($ctl == 'goods') || ($ctl == 'eleorder') || ($ctl == 'ding') ): ?>active<?php endif; ?>" href="<?php echo LinkTo('goods/index');?>"> <span class="icon icon-cart-plus"></span><span class="foot-label">我的订单</span></a> <a class="foot-item <?php if(($ctl == 'pay')): ?>active<?php endif; ?>" href="<?php echo U('pay/index');?>"> <span class="icon icon-tags"></span><span class="foot-label">优惠买单</span></a> <a class="foot-item <?php if(($ctl == 'message') ||($act == 'xiaoxizhongxin')): ?>active<?php endif; ?>" href="<?php echo u('mcenter/message/someone');?>"> <span class="icon icon-volume-up"></span><span class="foot-label">消息</span></a> <a class="foot-item <?php if(($ctl == 'member') || ($ctl == 'logs') || ($ctl == 'cash') ||($act == 'zijinguanli')): ?>active<?php endif; ?>" href="<?php echo u('mcenter/member/index');?>"> <span class="icon icon-user"></span><span class="foot-label">会员中心</span></a> </footer> <iframe id="x-frame" name="x-frame" style="display:none;"> </iframe> </body> </html>
ksyydream/api_llx
Baocms/Runtime/Cache/Mcenter/6f31a81f4b54ec97d29bba4ec2dc7136.php
PHP
apache-2.0
5,602
using System; using System.Collections.Generic; using System.Text; namespace P2PCLIENT { //class Program //{ // static void Main(string[] args) // { // LogOut.Action += new ActionOutHandler(LogOut_Action); // ClientInfo client = new ClientInfo(Config.Default.ServerIP, Config.Default.ServerPort, Config.Default.ServerRegPort, Config.Default.MinPort, Config.Default.MaxPort,Config.Default.ResCount); // client.ConToServer(); // client.ClientDataIn += new ClientDataInHandler(client_ClientDataIn); // client.ClientConnToMe += new ClientConnToHandler(client_ClientConnToMe); // client.ClientDiscon += new ClientDisconHandler(client_ClientDiscon); // while (true) // { // byte[] data = Encoding.Default.GetBytes(Console.ReadLine()); // foreach (KeyValuePair<string, ConClient> keyv in client.ConnUserList) // { // keyv.Value.SendData(data); // } // } // } // static void client_ClientDiscon(ConClient client, string message) // { // Console.WriteLine(client.Host + ":" + client.Port + "-" + client.Key + " ->"+message); // } // static void client_ClientConnToMe(ConClient client) // { // Console.WriteLine(client.Host + ":" + client.Port + "-" + client.Key + " 连接"); // } // static void client_ClientDataIn(ConClient client, byte[] data) // { // Console.WriteLine(Encoding.Default.GetString(data)); // } // static void LogOut_Action(string message, ActionType type) // { // Console.WriteLine(message); // } //} }
luyikk/ZYSOCKET
TCPP2P/P2PCLIENT/P2PCLIENT/Program.cs
C#
apache-2.0
1,764
// -*- coding: utf-8 -*- // Copyright (C) 2019 Nippon Telegraph and Telephone Corporation. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. // See the License for the specific language governing permissions and // limitations under the License. package mkpb import ( log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) const ( GobgpConfFile = "gobgp.conf" GobgpdConfFile = "gobgpd.conf" ) type GobgpCmd struct { *Command gobgpConfFile string gobgpdConfFile string } func NewGobgpCmd() *GobgpCmd { return &GobgpCmd{ Command: NewCommand(), gobgpConfFile: GobgpConfFile, gobgpdConfFile: GobgpdConfFile, } } func (c *GobgpCmd) setConfigFlags(cmd *cobra.Command) *cobra.Command { cmd.Flags().StringVarP(&c.gobgpConfFile, "gobgp-conf", "", GobgpConfFile, "gobgpd service config") cmd.Flags().StringVarP(&c.gobgpdConfFile, "gobgpd-conf", "", GobgpdConfFile, "gobgpd config") return c.Command.setConfigFlags(cmd) } func (c *GobgpCmd) createConf(playbookName string) error { if err := c.mkDirAll(playbookName); err != nil { return err } if err := c.createGoBGPdConf(playbookName); err != nil { return err } return c.createGoBGPConf(playbookName) } func (c *GobgpCmd) createGoBGPConf(playbookName string) error { opt := c.optionConfig() path := c.filesPath(playbookName, c.gobgpConfFile) f, err := createFile(path, c.overwrite, func(backup string) { log.Debugf("%s backup", backup) }) if err != nil { return err } defer f.Close() log.Debugf("%s created.", path) t := NewPlaybookGoBGPConf() t.APIAddr = opt.GoBGPAPIAddr t.APIPort = opt.GoBGPAPIPort return t.Execute(f) } func (c *GobgpCmd) createGoBGPdConf(playbookName string) error { opt := c.optionConfig() g := c.globalConfig() r, err := c.routerConfig(playbookName) if err != nil { return err } path := c.filesPath(playbookName, c.gobgpdConfFile) f, err := createFile(path, c.overwrite, func(backup string) { log.Debugf("%s backup", backup) }) if err != nil { return err } defer f.Close() log.Debugf("%s created.", path) zapiEnabled := func() bool { if g.Vpn { return r.NodeID != 0 // VPN-MIC => false, VPN-RIC => true } return opt.GoBGPZAPIEnable }() t := NewPlaybookGoBGPdConf() t.RouterID = g.ReID t.AS = opt.GoBGPAs t.ZAPIVersion = opt.GoBGPZAPIVersion t.ZAPIEnable = zapiEnabled return t.Execute(f) } func NewGoBGPCommand() *cobra.Command { rootCmd := &cobra.Command{ Use: "gobgp", Short: "gobgp command.", } gobgp := NewGobgpCmd() rootCmd.AddCommand(gobgp.setConfigFlags( &cobra.Command{ Use: "create <playbook name>", Short: "Crate new gobgp config file.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if err := gobgp.readConfig(); err != nil { return err } return gobgp.createConf(args[0]) }, }, )) return rootCmd }
beluganos/beluganos
src/fabricflow/ffctl/mkpb/gobgp.go
GO
apache-2.0
3,274
<!doctype html> <html lang="en" class="fullscreen-bg"> <head> <title>登录页面</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <!-- VENDOR CSS --> <link rel="stylesheet" href="../../assets/css/bootstrap.min.css"> <link rel="stylesheet" href="../../assets/source/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="../../assets/source/linearicons/style.css"> <!-- MAIN CSS --> <link rel="stylesheet" href="../../assets/css/main.css"> <!-- FOR DEMO PURPOSES ONLY. You should remove this in your project --> <link rel="stylesheet" href="../../assets/css/demo.css"> <!-- GOOGLE FONTS --> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700" rel="stylesheet"> <!-- ICONS --> <link rel="apple-touch-icon" sizes="76x76" href="../../assets/img/apple-icon.png"> <link rel="icon" type="image/png" sizes="96x96" href="../../assets/img/favicon.png"> </head> <body> <!-- WRAPPER --> <div id="wrapper"> <div class="vertical-align-wrap"> <div class="vertical-align-middle"> <div class="auth-box "> <div class="left"> <div class="content"> <div class="header"> <!--<div class="logo text-center"><img src="assets/img/logo-dark.png" alt="Klorofil Logo"></div> --><p class="lead">登录账号</p> </div> <form class="form-auth-small" action="http://localhost:8080/login" method="post"> <div class="form-group"> <input type="text" class="form-control" id="signin-user" value="" placeholder="用户名" name="name"> </div> <div class="form-group"> <input type="password" class="form-control" id="signin-password" value="" placeholder="密码" name="password"> </div> <div class="form-group clearfix"> <label class="fancy-checkbox element-left"> <input type="checkbox"> <span>记住密码</span> </label> </div> <button type="submit" class="btn btn-primary btn-lg btn-block">登录密码</button> <div class="bottom"> <span class="helper-text"><i class="fa fa-lock"></i> <a href="#">忘记密码?</a></span> </div> </form> </div> </div> <div class="right"> <div class="overlay"></div> <div class="content text"> <h1 class="heading">开元数据集</h1> <p>欢迎你</p> </div> </div> <div class="clearfix"></div> </div> </div> </div> </div> <!-- END WRAPPER --> </body> </html>
brainysoon/repdata
RepData/src/main/webapp/WEB-INF/templates/login.html
HTML
apache-2.0
3,462
/* * Copyright (c) 2005-2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.core.session; import org.apache.axis2.context.ConfigurationContext; import org.apache.catalina.Manager; import org.apache.catalina.ha.ClusterManager; import org.apache.catalina.ha.tcp.SimpleTcpCluster; import org.wso2.carbon.core.internal.CarbonCoreDataHolder; /** * The class extends tomcat's SimpleTcpCluster. The main use of this class is to have our * implementation of DeltaManger(ClusterManager) to be used when standardContext class creates * managers for contexts */ public class CarbonTomcatSimpleTcpCluster extends SimpleTcpCluster{ protected ClusterManager managerTemplate = new CarbonTomcatClusterableSessionManager(); @Override public void setManagerTemplate(ClusterManager managerTemplate) { this.managerTemplate = managerTemplate; } @Override public ClusterManager getManagerTemplate() { return managerTemplate; } /** * Create new Manager without add to cluster (comes with start the manager) * * @param name * Context Name of this manager * @see org.apache.catalina.Cluster#createManager(java.lang.String) * @see org.apache.catalina.ha.session.DeltaManager#start() */ @Override public synchronized Manager createManager(String name) { if (log.isDebugEnabled()) { log.debug("Creating ClusterManager for context " + name + " using class " + getManagerTemplate().getClass().getName()); } Manager manager = null; try { manager = managerTemplate.cloneFromTemplate(); ((ClusterManager)manager).setName(name); // TODO The following is the correct place to set sessionReplication is enabled, but CC is not yet ready /*ConfigurationContext configurationContext = CarbonCoreDataHolder.getInstance().getMainServerConfigContext(); if (configurationContext != null) { configurationContext.setProperty(SessionConstants.SESSION_REPLICATION_INITIALIZED, true); }*/ } catch (Exception x) { log.error("Unable to clone cluster manager, " + "defaulting to org.apache.catalina.ha.session.DeltaManager", x); manager = new org.apache.catalina.ha.session.DeltaManager(); } finally { if ( manager != null && (manager instanceof ClusterManager)) ((ClusterManager)manager).setCluster(this); } return manager; } }
maheshika/carbon4-kernel
core/org.wso2.carbon.core/src/main/java/org/wso2/carbon/core/session/CarbonTomcatSimpleTcpCluster.java
Java
apache-2.0
3,176
<HTML> <HEAD> <meta charset="UTF-8"> <title>NicotineMethodPhrases - biomedicus-core</title> <link rel="stylesheet" href="../../../style.css"> </HEAD> <BODY> <a href="../../index.html">biomedicus-core</a>&nbsp;/&nbsp;<a href="../index.html">edu.umn.biomedicus.sh</a>&nbsp;/&nbsp;<a href="./index.html">NicotineMethodPhrases</a><br/> <br/> <h1>NicotineMethodPhrases</h1> <code><span class="identifier">@Singleton</span> <span class="keyword">class </span><span class="identifier">NicotineMethodPhrases</span></code> <p>Nicotine methods model.</p> <h3>Constructors</h3> <table> <tbody> <tr> <td> <p><a href="-init-.html">&lt;init&gt;</a></p> </td> <td> <code><span class="identifier">NicotineMethodPhrases</span><span class="symbol">(</span><span class="identifier" id="edu.umn.biomedicus.sh.NicotineMethodPhrases$<init>(edu.umn.biomedicus.common.SequenceDetector((kotlin.String, edu.umn.biomedicus.tokenization.ParseToken)))/detector">detector</span><span class="symbol">:</span>&nbsp;<a href="../../edu.umn.biomedicus.common/-sequence-detector/index.html"><span class="identifier">SequenceDetector</span></a><span class="symbol">&lt;</span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html"><span class="identifier">String</span></a><span class="symbol">,</span>&nbsp;<a href="../../edu.umn.biomedicus.tokenization/-parse-token/index.html"><span class="identifier">ParseToken</span></a><span class="symbol">&gt;</span><span class="symbol">)</span></code> <p>Nicotine methods model.</p> </td> </tr> </tbody> </table> <h3>Properties</h3> <table> <tbody> <tr> <td> <p><a href="detector.html">detector</a></p> </td> <td> <code><span class="keyword">val </span><span class="identifier">detector</span><span class="symbol">: </span><a href="../../edu.umn.biomedicus.common/-sequence-detector/index.html"><span class="identifier">SequenceDetector</span></a><span class="symbol">&lt;</span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html"><span class="identifier">String</span></a><span class="symbol">,</span>&nbsp;<a href="../../edu.umn.biomedicus.tokenization/-parse-token/index.html"><span class="identifier">ParseToken</span></a><span class="symbol">&gt;</span></code></td> </tr> </tbody> </table> </BODY> </HTML>
NLPIE/BioMedICUS
doc/dokka/biomedicus-core/edu.umn.biomedicus.sh/-nicotine-method-phrases/index.html
HTML
apache-2.0
2,272
/*! * express * Copyright(c) 2009-2013 TJ Holowaychuk * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module dependencies. * @private */ var contentDisposition = require('content-disposition'); var deprecate = require('depd')('express'); var encodeUrl = require('encodeurl'); var escapeHtml = require('escape-html'); var http = require('http'); var onFinished = require('on-finished'); var path = require('path'); var pathIsAbsolute = require('path-is-absolute'); var statuses = require('statuses') var merge = require('utils-merge'); var sign = require('cookie-signature').sign; var normalizeType = require('./utils').normalizeType; var normalizeTypes = require('./utils').normalizeTypes; var setCharset = require('./utils').setCharset; var cookie = require('cookie'); var send = require('send'); var extname = path.extname; var mime = send.mime; var resolve = path.resolve; var vary = require('vary'); /** * Response prototype. * @public */ var res = Object.create(http.ServerResponse.prototype) /** * Module exports. * @public */ module.exports = res /** * Module variables. * @private */ var charsetRegExp = /;\s*charset\s*=/; /** * Set status `code`. * * @param {Number} code * @return {ServerResponse} * @public */ res.status = function status(code) { this.statusCode = code; return this; }; /** * Set Link header field with the given `links`. * * Examples: * * res.links({ * next: 'http://api.example.com/users?page=2', * last: 'http://api.example.com/users?page=5' * }); * * @param {Object} links * @return {ServerResponse} * @public */ res.links = function(links){ var link = this.get('Link') || ''; if (link) link += ', '; return this.set('Link', link + Object.keys(links).map(function(rel){ return '<' + links[rel] + '>; rel="' + rel + '"'; }).join(', ')); }; /** * Send a response. * * Examples: * * res.send(new Buffer('wahoo')); * res.send({ some: 'json' }); * res.send('<p>some html</p>'); * * @param {string|number|boolean|object|Buffer} body * @public */ res.send = function send(body) { var chunk = body; var encoding; var len; var req = this.req; var type; // settings var app = this.app; // support res.send(status, body) if (arguments.length === 2) { deprecate('res.send(status, body): Use res.status(status).send(body) instead'); this.statusCode = arguments[0]; chunk = arguments[1]; } switch (typeof chunk) { // string defaulting to html case 'string': if (!this.get('Content-Type')) { this.type('html'); } break; case 'boolean': case 'number': case 'object': if (chunk === null) { chunk = ''; } else if (Buffer.isBuffer(chunk)) { if (!this.get('Content-Type')) { this.type('bin'); } } else { return this.json(chunk); } break; } // write strings in utf-8 if (typeof chunk === 'string') { encoding = 'utf8'; type = this.get('Content-Type'); // reflect this in content-type if (typeof type === 'string') { this.set('Content-Type', setCharset(type, 'utf-8')); } } // populate Content-Length if (chunk !== undefined) { if (!Buffer.isBuffer(chunk)) { // convert chunk to Buffer; saves later double conversions chunk = new Buffer(chunk, encoding); encoding = undefined; } len = chunk.length; this.set('Content-Length', len); } // populate ETag var etag; var generateETag = len !== undefined && app.get('etag fn'); if (typeof generateETag === 'function' && !this.get('ETag')) { if ((etag = generateETag(chunk, encoding))) { this.set('ETag', etag); } } // freshness if (req.fresh) this.statusCode = 304; // strip irrelevant headers if (204 === this.statusCode || 304 === this.statusCode) { this.removeHeader('Content-Type'); this.removeHeader('Content-Length'); this.removeHeader('Transfer-Encoding'); chunk = ''; } if (req.method === 'HEAD') { // skip body for HEAD this.end(); } else { // respond this.end(chunk, encoding); } return this; }; /** * Send JSON response. * * Examples: * * res.json(null); * res.json({ user: 'tj' }); * * @param {string|number|boolean|object} obj * @public */ res.json = function json(obj) { // settings var app = this.app; var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); var body = stringify(obj, replacer, spaces); // content-type if (!this.get('Content-Type')) { this.set('Content-Type', 'application/json'); } return this.send(body); }; /** * Send JSON response with JSONP callback support. * * Examples: * * res.jsonp(null); * res.jsonp({ user: 'tj' }); * * @param {string|number|boolean|object} obj * @public */ res.jsonp = function jsonp(obj) { // settings var app = this.app; var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); var body = stringify(obj, replacer, spaces); var callback = this.req.query[app.get('jsonp callback name')]; // content-type if (!this.get('Content-Type')) { this.set('X-Content-Type-Options', 'nosniff'); this.set('Content-Type', 'application/json'); } // fixup callback if (Array.isArray(callback)) { callback = callback[0]; } // jsonp if (typeof callback === 'string' && callback.length !== 0) { this.charset = 'utf-8'; this.set('X-Content-Type-Options', 'nosniff'); this.set('Content-Type', 'text/javascript'); // restrict callback charset callback = callback.replace(/[^\[\]\w$.]/g, ''); // replace chars not allowed in JavaScript that are in JSON body = body .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029'); // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" // the typeof check is just to reduce client error noise body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; } return this.send(body); }; /** * Send given HTTP status code. * * Sets the response status to `statusCode` and the body of the * response to the standard description from node's http.STATUS_CODES * or the statusCode number if no description. * * Examples: * * res.sendStatus(200); * * @param {number} statusCode * @public */ res.sendStatus = function sendStatus(statusCode) { var body = statuses[statusCode] || String(statusCode) this.statusCode = statusCode; this.type('txt'); return this.send(body); }; /** * Transfer the file at the given `path`. * * Automatically sets the _Content-Type_ response header field. * The callback `callback(err)` is invoked when the transfer is complete * or when an error occurs. Be sure to check `res.sentHeader` * if you wish to attempt responding, as the header and some data * may have already been transferred. * * Options: * * - `maxAge` defaulting to 0 (can be string converted by `ms`) * - `root` root directory for relative filenames * - `headers` object of headers to serve with file * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them * * Other options are passed along to `send`. * * Examples: * * The following example illustrates how `res.sendFile()` may * be used as an alternative for the `static()` middleware for * dynamic situations. The code backing `res.sendFile()` is actually * the same code, so HTTP cache support etc is identical. * * app.get('/user/:uid/photos/:file', function(req, res){ * var uid = req.params.uid * , file = req.params.file; * * req.user.mayViewFilesFrom(uid, function(yes){ * if (yes) { * res.sendFile('/uploads/' + uid + '/' + file); * } else { * res.send(403, 'Sorry! you cant see that.'); * } * }); * }); * * @public */ res.sendFile = function sendFile(path, options, callback) { var done = callback; var req = this.req; var res = this; var next = req.next; var opts = options || {}; if (!path) { throw new TypeError('path argument is required to res.sendFile'); } // support function as second arg if (typeof options === 'function') { done = options; opts = {}; } if (!opts.root && !pathIsAbsolute(path)) { throw new TypeError('path must be absolute or specify root to res.sendFile'); } // create file stream var pathname = encodeURI(path); var file = send(req, pathname, opts); // transfer sendfile(res, file, opts, function (err) { if (done) return done(err); if (err && err.code === 'EISDIR') return next(); // next() all but write errors if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { next(err); } }); }; /** * Transfer the file at the given `path` as an attachment. * * Optionally providing an alternate attachment `filename`, * and optional callback `callback(err)`. The callback is invoked * when the data transfer is complete, or when an error has * ocurred. Be sure to check `res.headersSent` if you plan to respond. * * This method uses `res.sendFile()`. * * @public */ res.download = function download(path, filename, callback) { var done = callback; var name = filename; // support function as second arg if (typeof filename === 'function') { done = filename; name = null; } // set Content-Disposition when file is sent var headers = { 'Content-Disposition': contentDisposition(name || path) }; // Resolve the full path for sendFile var fullPath = resolve(path); return this.sendFile(fullPath, { headers: headers }, done); }; /** * Set _Content-Type_ response header with `type` through `mime.lookup()` * when it does not contain "/", or set the Content-Type to `type` otherwise. * * Examples: * * res.type('.html'); * res.type('html'); * res.type('json'); * res.type('application/json'); * res.type('png'); * * @param {String} type * @return {ServerResponse} for chaining * @public */ res.contentType = res.type = function contentType(type) { var ct = type.indexOf('/') === -1 ? mime.lookup(type) : type; return this.set('Content-Type', ct); }; /** * Respond to the Acceptable formats using an `obj` * of mime-type callbacks. * * This method uses `req.accepted`, an array of * acceptable types ordered by their quality values. * When "Accept" is not present the _first_ callback * is invoked, otherwise the first match is used. When * no match is performed the server responds with * 406 "Not Acceptable". * * Content-Type is set for you, however if you choose * you may alter this within the callback using `res.type()` * or `res.set('Content-Type', ...)`. * * res.format({ * 'text/plain': function(){ * res.send('hey'); * }, * * 'text/html': function(){ * res.send('<p>hey</p>'); * }, * * 'appliation/json': function(){ * res.send({ message: 'hey' }); * } * }); * * In addition to canonicalized MIME types you may * also use extnames mapped to these types: * * res.format({ * text: function(){ * res.send('hey'); * }, * * html: function(){ * res.send('<p>hey</p>'); * }, * * json: function(){ * res.send({ message: 'hey' }); * } * }); * * By default Express passes an `Error` * with a `.status` of 406 to `next(err)` * if a match is not made. If you provide * a `.default` callback it will be invoked * instead. * * @param {Object} obj * @return {ServerResponse} for chaining * @public */ res.format = function(obj){ var req = this.req; var next = req.next; var fn = obj.default; if (fn) delete obj.default; var keys = Object.keys(obj); var key = keys.length > 0 ? req.accepts(keys) : false; this.vary("Accept"); if (key) { this.set('Content-Type', normalizeType(key).value); obj[key](req, this, next); } else if (fn) { fn(); } else { var err = new Error('Not Acceptable'); err.status = err.statusCode = 406; err.types = normalizeTypes(keys).map(function(o){ return o.value }); next(err); } return this; }; /** * Set _Content-Disposition_ header to _attachment_ with optional `filename`. * * @param {String} filename * @return {ServerResponse} * @public */ res.attachment = function attachment(filename) { if (filename) { this.type(extname(filename)); } this.set('Content-Disposition', contentDisposition(filename)); return this; }; /** * Append additional header `field` with value `val`. * * Example: * * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']); * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); * res.append('Warning', '199 Miscellaneous warning'); * * @param {String} field * @param {String|Array} val * @return {ServerResponse} for chaining * @public */ res.append = function append(field, val) { var prev = this.get(field); var value = val; if (prev) { // concat the new and prev vals value = Array.isArray(prev) ? prev.concat(val) : Array.isArray(val) ? [prev].concat(val) : [prev, val]; } return this.set(field, value); }; /** * Set header `field` to `val`, or pass * an object of header fields. * * Examples: * * res.set('Foo', ['bar', 'baz']); * res.set('Accept', 'application/json'); * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); * * Aliased as `res.header()`. * * @param {String|Object} field * @param {String|Array} val * @return {ServerResponse} for chaining * @public */ res.set = res.header = function header(field, val) { if (arguments.length === 2) { var value = Array.isArray(val) ? val.map(String) : String(val); // add charset to content-type if (field.toLowerCase() === 'content-type' && !charsetRegExp.test(value)) { var charset = mime.charsets.lookup(value.split(';')[0]); if (charset) value += '; charset=' + charset.toLowerCase(); } this.setHeader(field, value); } else { for (var key in field) { this.set(key, field[key]); } } return this; }; /** * Get value for header `field`. * * @param {String} field * @return {String} * @public */ res.get = function(field){ return this.getHeader(field); }; /** * Clear cookie `name`. * * @param {String} name * @param {Object} [options] * @return {ServerResponse} for chaining * @public */ res.clearCookie = function clearCookie(name, options) { var opts = merge({ expires: new Date(1), path: '/' }, options); return this.cookie(name, '', opts); }; /** * Set cookie `name` to `value`, with the given `options`. * * Options: * * - `maxAge` max-age in milliseconds, converted to `expires` * - `signed` sign the cookie * - `path` defaults to "/" * * Examples: * * // "Remember Me" for 15 minutes * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); * * // save as above * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) * * @param {String} name * @param {String|Object} value * @param {Options} options * @return {ServerResponse} for chaining * @public */ res.cookie = function (name, value, options) { var opts = merge({}, options); var secret = this.req.secret; var signed = opts.signed; if (signed && !secret) { throw new Error('cookieParser("secret") required for signed cookies'); } var val = typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value); if (signed) { val = 's:' + sign(val, secret); } if ('maxAge' in opts) { opts.expires = new Date(Date.now() + opts.maxAge); opts.maxAge /= 1000; } if (opts.path == null) { opts.path = '/'; } this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); return this; }; /** * Set the location header to `url`. * * The given `url` can also be "back", which redirects * to the _Referrer_ or _Referer_ headers or "/". * * Examples: * * res.location('/foo/bar').; * res.location('http://example.com'); * res.location('../login'); * * @param {String} url * @return {ServerResponse} for chaining * @public */ res.location = function location(url) { var loc = url; // "back" is an alias for the referrer if (url === 'back') { loc = this.req.get('Referrer') || '/'; } // set location return this.set('Location', encodeUrl(loc)); }; /** * Redirect to the given `url` with optional response `status` * defaulting to 302. * * The resulting `url` is determined by `res.location()`, so * it will play nicely with mounted apps, relative paths, * `"back"` etc. * * Examples: * * res.redirect('/foo/bar'); * res.redirect('http://example.com'); * res.redirect(301, 'http://example.com'); * res.redirect('../login'); // /blog/post/1 -> /blog/login * * @public */ res.redirect = function redirect(url) { var address = url; var body; var status = 302; // allow status / url if (arguments.length === 2) { if (typeof arguments[0] === 'number') { status = arguments[0]; address = arguments[1]; } else { deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); status = arguments[1]; } } // Set location header address = this.location(address).get('Location'); // Support text/{plain,html} by default this.format({ text: function(){ body = statuses[status] + '. Redirecting to ' + address }, html: function(){ var u = escapeHtml(address); body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>' }, default: function(){ body = ''; } }); // Respond this.statusCode = status; this.set('Content-Length', Buffer.byteLength(body)); if (this.req.method === 'HEAD') { this.end(); } else { this.end(body); } }; /** * Add `field` to Vary. If already present in the Vary set, then * this call is simply ignored. * * @param {Array|String} field * @return {ServerResponse} for chaining * @public */ res.vary = function(field){ vary(this, field); return this; }; /** * Render `view` with the given `options` and optional callback `fn`. * When a callback function is given a response will _not_ be made * automatically, otherwise a response of _200_ and _text/html_ is given. * * Options: * * - `cache` boolean hinting to the engine it should cache * - `filename` filename of the view being rendered * * @public */ res.render = function render(view, options, callback) { var app = this.req.app; var done = callback; var opts = options || {}; var req = this.req; var self = this; // support callback function as second arg if (typeof options === 'function') { done = options; opts = {}; } // merge res.locals opts._locals = self.locals; // default callback to respond done = done || function (err, str) { if (err) return req.next(err); self.send(str); }; // render app.render(view, opts, done); }; // pipe the send file stream function sendfile(res, file, options, callback) { var done = false; var streaming; // request aborted function onaborted() { if (done) return; done = true; var err = new Error('Request aborted'); err.code = 'ECONNABORTED'; callback(err); } // directory function ondirectory() { if (done) return; done = true; var err = new Error('EISDIR, read'); err.code = 'EISDIR'; callback(err); } // errors function onerror(err) { if (done) return; done = true; callback(err); } // ended function onend() { if (done) return; done = true; callback(); } // file function onfile() { streaming = false; } // finished function onfinish(err) { if (err && err.code === 'ECONNRESET') return onaborted(); if (err) return onerror(err); if (done) return; setImmediate(function () { if (streaming !== false && !done) { onaborted(); return; } if (done) return; done = true; callback(); }); } // streaming function onstream() { streaming = true; } file.on('directory', ondirectory); file.on('end', onend); file.on('error', onerror); file.on('file', onfile); file.on('stream', onstream); onFinished(res, onfinish); if (options.headers) { // set headers on successful transfer file.on('headers', function headers(res) { var obj = options.headers; var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var k = keys[i]; res.setHeader(k, obj[k]); } }); } // pipe file.pipe(res); } /** * Stringify JSON, like JSON.stringify, but v8 optimized. * @private */ function stringify(value, replacer, spaces) { // v8 checks arguments.length for optimizing simple call // https://bugs.chromium.org/p/v8/issues/detail?id=4730 return replacer || spaces ? JSON.stringify(value, replacer, spaces) : JSON.stringify(value); }
wangweiyan0901/practiceCode
express_wwy/node_modules/express/lib/response.js
JavaScript
apache-2.0
21,341
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60-ea) on Fri Nov 04 13:24:42 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrustSupplier (Public javadocs 2016.11.0 API)</title> <meta name="date" content="2016-11-04"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrustSupplier (Public javadocs 2016.11.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrustSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2016.11.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/wildfly/swarm/config/security/security_domain/class-use/ClassicIdentityTrustSupplier.html" target="_top">Frames</a></li> <li><a href="ClassicIdentityTrustSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrustSupplier" class="title">Uses of Interface<br>org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrustSupplier</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrustSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain">ClassicIdentityTrustSupplier</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.security">org.wildfly.swarm.config.security</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.security"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrustSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain">ClassicIdentityTrustSupplier</a> in <a href="../../../../../../../org/wildfly/swarm/config/security/package-summary.html">org.wildfly.swarm.config.security</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/security/package-summary.html">org.wildfly.swarm.config.security</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrustSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain">ClassicIdentityTrustSupplier</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/security/SecurityDomain.html" title="type parameter in SecurityDomain">T</a></code></td> <td class="colLast"><span class="typeNameLabel">SecurityDomain.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/security/SecurityDomain.html#classicIdentityTrust-org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrustSupplier-">classicIdentityTrust</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrustSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain">ClassicIdentityTrustSupplier</a>&nbsp;supplier)</code> <div class="block">Identity trust configuration.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrustSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2016.11.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/wildfly/swarm/config/security/security_domain/class-use/ClassicIdentityTrustSupplier.html" target="_top">Frames</a></li> <li><a href="ClassicIdentityTrustSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2016.11.0/apidocs/org/wildfly/swarm/config/security/security_domain/class-use/ClassicIdentityTrustSupplier.html
HTML
apache-2.0
8,130
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60-ea) on Tue Sep 06 12:41:43 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.config.management.access.syslog_handler.protocol (Public javadocs 2016.9 API)</title> <meta name="date" content="2016-09-06"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/protocol/package-summary.html" target="classFrame">org.wildfly.swarm.config.management.access.syslog_handler.protocol</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="ClientCertificateStoreAuthenticationConsumer.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler.protocol" target="classFrame"><span class="interfaceName">ClientCertificateStoreAuthenticationConsumer</span></a></li> <li><a href="ClientCertificateStoreAuthenticationSupplier.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler.protocol" target="classFrame"><span class="interfaceName">ClientCertificateStoreAuthenticationSupplier</span></a></li> <li><a href="TruststoreAuthenticationConsumer.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler.protocol" target="classFrame"><span class="interfaceName">TruststoreAuthenticationConsumer</span></a></li> <li><a href="TruststoreAuthenticationSupplier.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler.protocol" target="classFrame"><span class="interfaceName">TruststoreAuthenticationSupplier</span></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="ClientCertificateStoreAuthentication.html" title="class in org.wildfly.swarm.config.management.access.syslog_handler.protocol" target="classFrame">ClientCertificateStoreAuthentication</a></li> <li><a href="TruststoreAuthentication.html" title="class in org.wildfly.swarm.config.management.access.syslog_handler.protocol" target="classFrame">TruststoreAuthentication</a></li> </ul> </div> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2016.9/apidocs/org/wildfly/swarm/config/management/access/syslog_handler/protocol/package-frame.html
HTML
apache-2.0
2,434
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Tue Oct 30 00:53:03 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface org.wildfly.swarm.config.WeldSupplier (BOM: * : All 2.2.1.Final API)</title> <meta name="date" content="2018-10-30"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.wildfly.swarm.config.WeldSupplier (BOM: * : All 2.2.1.Final API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/wildfly/swarm/config/WeldSupplier.html" title="interface in org.wildfly.swarm.config">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.2.1.Final</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/class-use/WeldSupplier.html" target="_top">Frames</a></li> <li><a href="WeldSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.wildfly.swarm.config.WeldSupplier" class="title">Uses of Interface<br>org.wildfly.swarm.config.WeldSupplier</h2> </div> <div class="classUseContainer">No usage of org.wildfly.swarm.config.WeldSupplier</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/wildfly/swarm/config/WeldSupplier.html" title="interface in org.wildfly.swarm.config">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.2.1.Final</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/class-use/WeldSupplier.html" target="_top">Frames</a></li> <li><a href="WeldSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2.2.1.Final/apidocs/org/wildfly/swarm/config/class-use/WeldSupplier.html
HTML
apache-2.0
4,806
/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ package de.dfki.asr.atlas.cdi.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface AtlasExporter { public String contentType(); public String fileExtension(); public String[] folderTypes(); }
dfki-asr/atlas-server
src/main/java/de/dfki/asr/atlas/cdi/annotations/AtlasExporter.java
Java
apache-2.0
689
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <phosphor/phosphor.h> /** \file * This program generates some interesting statistics about Phosphor's internal * representations, e.g. object sizes etc. */ phosphor::tracepoint_info tpi = { "category", "name", {{"arg1", "arg2"}} }; int main(int argc, char** argv) { using namespace phosphor; std::cout << "\nStructure Sizes\n"; std::cout << "===================\n"; std::cout << "ChunkLock: " << sizeof(ChunkLock) << " bytes\n"; std::cout << "TraceArgument: " << sizeof(TraceArgument) << " bytes\n"; std::cout << "TraceEvent: " << sizeof(TraceEvent) << " bytes\n"; std::cout << "TraceChunk: " << sizeof(TraceChunk) << " bytes\n"; std::cout << "CategoryRegistry: " << sizeof(CategoryRegistry) << " bytes\n"; std::cout << "TraceLog: " << sizeof(TraceLog) << " bytes\n"; TraceLog log; log.start(TraceConfig(BufferMode::fixed, 100 * 1024 * 1024)); while(log.isEnabled()) { log.logEvent(&tpi, TraceEvent::Type::Instant); } auto buffer = log.getBuffer(); std::cout << "\nCapacities\n"; std::cout << "===================\n"; std::cout << "TraceChunk: " << TraceChunk::chunk_size << " trace events\n"; std::cout << "100MiB TraceBuffer: " << buffer->chunk_count() << " trace chunks\n"; int n = 0; for(const auto& event : *buffer) { n++; } std::cout << "100MiB TraceBuffer: " << n << " trace events\n"; }
Chippiewill/phosphor
examples/statistics.cc
C++
apache-2.0
2,155
// ParkitectNexus.AssetMagic // Copyright 2016 Tim Potze // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices.ComTypes; using ParkitectNexus.AssetMagic.Converters; using ParkitectNexus.AssetMagic.Data; using ParkitectNexus.AssetMagic.Data.Coasters; namespace ParkitectNexus.AssetMagic.Debug { internal class Program { private static string Join(params string[] values) { if (values == null) return string.Empty; return string.Join(", ", values); } private static void Main(string[] args) { Console.WriteLine("\n\nBLUEPRINTS:"); var path = @"..\..\..\..\tests\blueprints\shipwreck-cove.png"; var bp = BlueprintConverter.DeserializeFromFile(path); var str =BlueprintConverter.SerializeToString(bp); Console.WriteLine(str); var coaster = bp.Coasters.FirstOrDefault(); var h = bp.Header; Console.WriteLine(h.GameVersion); Console.WriteLine(h.GameVersionName); var stats = coaster?.Stats; Console.WriteLine(stats?.MaxLatG); Console.WriteLine(stats?.MaxLongG); Console.WriteLine(coaster?.TrainCount); // Console.WriteLine(BlueprintConverter.ReadFromImage(Image.FromFile(path))); // Console.ReadLine(); // Console.WriteLine("Rewriting to same content? {0}", // BlueprintConverter.SerializeToString(bp) == BlueprintConverter.ReadFromImage(Image.FromFile(path))); // PrintUnmappedProperties(bp.Header); // Console.WriteLine($"Blueprint: {bp.Header.Name}"); // Console.WriteLine($"Date: {bp.Header.Date}"); // Console.WriteLine($"GameVersion: {bp.Header.GameVersion}"); // Console.WriteLine($"GameVersionName: {bp.Header.GameVersionName}"); // Console.WriteLine($"SavegameVersion: {bp.Header.SavegameVersion}"); // Console.WriteLine($"Type: {bp.Header.Type}"); // Console.WriteLine($"ApproximateCost: {bp.Header.ApproximateCost}"); // Console.WriteLine($"Types: [{Join(bp.Header.Types)}]"); // Console.WriteLine($"DecoTypes: [{Join(bp.Header.DecoTypes)}]"); // Console.WriteLine($"FlatRideTypes: [{Join( bp.Header.FlatRideTypes)}]"); // Console.WriteLine($"TrackedRideTypes: [{Join(bp.Header.TrackedRideTypes)}]"); //Console.WriteLine($"Coaster.Type: {bp.GetElement<Coaster>()?.Type}"); // Console.WriteLine("\n\nSAVEGAMES:"); //var path2 = @"..\..\..\..\tests\parks\compressed.park"; // var path2 = @"..\..\..\..\tests\parks\unnamed-park.txt"; // var sg = SavegameConverter.DeserializeFromFile(path2); // byte[] bytes; // using (var ms = new MemoryStream()) // { // SavegameConverter.SerializeToStream(sg, ms); // bytes = ms.ToArray(); // } // //// SavegameConverter.SerializeToFile(sg, path2.Replace(".park", "back.park")); // Console.WriteLine("Rewriting to same content? {0}", bytes.SequenceEqual(File.ReadAllBytes(path2))); // PrintUnmappedProperties(sg.Header); // PrintUnmappedProperties(sg.Park); Console.ReadLine(); } private static void PrintUnmappedProperties(DataWrapper wrapper) { // var u = wrapper.GetUnmappedProperties(); // // if (u.Any()) // { // Console.WriteLine($"UNMAPPED PROPERTIES IN {wrapper.GetType()}"); // // foreach (var p in u) // Console.WriteLine($">>> {p} ({wrapper[p].GetType()})"); // // Console.WriteLine(); // } } } }
ParkitectNexus/AssetMagic
src/ParkitectNexus.AssetMagic.Debug/Program.cs
C#
apache-2.0
4,586
class Solution: def uniquePathsIII(self, grid: 'List[List[int]]') -> 'int': self.res = 0 R, C, E = len(grid), len(grid[0]), 1 for i in range(R): for j in range(C): if grid[i][j] == 1: x,y = (i, j) elif grid[i][j] == 2: end = (i, j) elif grid[i][j] == 0: E += 1 def dfs(x, y, E): if not (0 <= x < R and 0 <= y < C and grid[x][y] >= 0): return if (x,y) == end and E == 0: self.res += 1 return grid[x][y] = -2 dfs(x+1, y, E-1) dfs(x-1, y, E-1) dfs(x, y+1, E-1) dfs(x, y-1, E-1) grid[x][y] = 0 dfs(x, y, E) return self.res s = Solution() print(s.uniquePathsIII([[1,0,0,0],[0,0,0,0],[0,0,2,-1]])) print(s.uniquePathsIII([[1,0,0,0],[0,0,0,0],[0,0,0,2]])) print(s.uniquePathsIII([[0,1],[2,0]]))
zuun77/givemegoogletshirts
leetcode/python/980_unique_paths_III.py
Python
apache-2.0
938
package com.zblog.core.lucene; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 查询构建器 * * @author zhou * */ public class QueryBuilder{ private static final Logger logger = LoggerFactory.getLogger(QueryBuilder.class); private static int MAX_QUERY_TOKENS = 5; /* 最长查询字符串 */ private static int MAX_QUERY_LENGTH = 20; private Analyzer analyzer; private List<Term> must; private List<Term> should; private List<String> lighters; private Set<SortField> sorts; private Filter filter; public QueryBuilder(Analyzer analyzer){ this.analyzer = analyzer; must = new LinkedList<Term>(); should = new LinkedList<Term>(); lighters = new ArrayList<String>(); } public QueryBuilder addMust(String field, String value){ String[] tokens = token(value); if(tokens != null && tokens.length > 0){ for(String token : tokens){ must.add(new Term(field, token)); } }else{ logger.warn("must query field word can't analyzer -->" + value); } return this; } public QueryBuilder addShould(String field, String value){ String[] tokens = token(value); if(tokens != null && tokens.length > 0){ for(String token : tokens){ should.add(new Term(field, token)); } }else{ logger.warn("should query field word can't analyzer -->" + value); } return this; } /** * 添加高亮字段 * * @param fields * @return */ public QueryBuilder addLighter(String... fields){ lighters.addAll(Arrays.asList(fields)); return this; } public List<String> getHighlighter(){ return lighters; } public QueryBuilder sortBy(SortField field){ if(sorts == null) sorts = new HashSet<SortField>(); sorts.add(field); return this; } public QueryBuilder filter(Filter filter){ this.filter = filter; return this; } public Query getQuery(){ BooleanQuery query = new BooleanQuery(); for(Term term : must){ query.add(new TermQuery(term), Occur.MUST); } for(Term term : should){ query.add(new TermQuery(term), Occur.SHOULD); } return query; } public Filter getFilter(){ return filter; } public Sort getSort(){ return null; } /** * 看新版本文档,tokenStream之后必须reset * * @param str * @return */ public String[] token(String str){ str = str.length() > MAX_QUERY_LENGTH ? str.substring(0, MAX_QUERY_LENGTH) : str; TokenStream stream = null; try{ List<String> list = new ArrayList<String>(); /* tokenStream的fieldName随意 */ stream = analyzer.tokenStream("any", new StringReader(str)); CharTermAttribute cta = stream.addAttribute(CharTermAttribute.class); stream.reset(); while(stream.incrementToken() && list.size() <= MAX_QUERY_TOKENS){ list.add(cta.toString()); } stream.end(); /* 当没有分词结果时(如停用词,量词等),直接返回null */ if(list.isEmpty()){ return null; } list = reSubset(list); String[] result = new String[list.size()]; return list.toArray(result); }catch(IOException e){ logger.error("analyer " + str + " error", e); }finally{ LuceneUtils.closeQuietly(stream); } return null; } /** * 剔除子集(例:[视频网站、视频、网站、购物]剔除后变为[视频网站、购物])<br> * 其实和最大匹配分词效果一样(IKAnalyzer.setUseSmart(true)),但在添加文档必须使用最细粒度分词 * * @param source * @return */ private List<String> reSubset(List<String> source){ List<String> result = new ArrayList<String>(source.size()); for(int i = 0; i < source.size() - 1; i++){ buildMinHeap(source, source.size() - i - 1); Collections.swap(source, 0, source.size() - i - 1); } result.add(source.get(0)); for(int i = 1; i < source.size(); i++){ String item = source.get(i); boolean hasSub = false; for(String temp : result){ if(temp.indexOf(item) != -1){ hasSub = true; break; } } if(!hasSub) result.add(item); } return result; } // 建小顶堆 private void buildMinHeap(List<String> list, int last){ // 从最后一个非叶子节点起 for(int i = (last - 1) / 2; i >= 0; i--){ int current = i; // 当前非叶节点 while((2 * current + 1) <= last){ // 如果current存在子节点 int big = 2 * current + 1; if(big < last){ // 如果current节点右子节点存在 if(list.get(big).length() > list.get(big + 1).length()) big++; } if(list.get(current).length() > list.get(big).length()){ // 如果current节点小于它的最大子节点 Collections.swap(list, current, big); // 将big赋值给current,因为修改了big节点值,开始下一层循环 current = big; }else break; } } } }
hawklithm/zblog
src/main/java/com/zblog/core/lucene/QueryBuilder.java
Java
apache-2.0
5,810
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="my opinion, my code, my life"> <meta name="author" content="Saquib Hafiz"> <title>Saquib Hafiz</title> <!-- Bootstrap Core CSS --> <link href="../css/bootstrap.min.css" rel="stylesheet"> <!-- Clean Blog CSS --> <link href="../css/clean-blog.min.css" rel="stylesheet"> <!-- Prettify CSS --> <link href="../css/prettify.css" rel="stylesheet"> <!-- Hemisu Light CSS --> <link href="../css/tomorrow-night-bright.css" rel="stylesheet"> <!-- Custom CSS --> <link href="../css/custom.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Navigation --> <nav class="navbar navbar-default navbar-custom navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html">Saquib Hafiz</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a href="../Resume.pdf"><span class="glyphicon glyphicon-file" aria-hidden="true"></span></a> </li> <li> <a href="../about.html">About</a> </li> <li> <a href="../archive.html">Archive</a> </li> <li> <a href="../contact.html">Contact</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('https://farm5.staticflickr.com/4124/5068845349_4af970eaac_o.jpg')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="post-heading"> <h1>Base Negative Two (BNT): Part 1 - A Simple Understanding</h1> <h2 class="subheading">Number systems and the power of negative based number systems</h2> <span class="meta">Posted on November 7th 2014</span> <div class="meta">Background image by <a href="https://www.flickr.com/photos/mcclanahoochie/5068845349/">Chris McClanahan (mcclanahoochie)</a> <a href="http://creativecommons.org/licenses/by-sa/4.0/legalcode">&#0169;</a></div> </div> </div> </div> </div> </header> <!-- Post Content --> <article> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <p> The most common numerical system is the decimal system. This just means that we use base 10 when defining numbers. Other commonly known/used numerical systems include binary (base 2) and hexadecimal (base 16). Every numerical system can be read once you understand how they are defined. Each digit, in any numerical system, represents a quantity of a certain magnitude. Lets explore this with a simple example: if we have a decimal number 23, this means that there are 2 units of magnitude \(10^1\) and 3 units of magnitude \(10^0\). This is a very abstract understanding that helps us easily understand how other numerical systems work. So 1101 in binary is 1 unit of \(2^0\), 0 units of \(2^1\), 1 unit of \(2^2\) and 1 unit of \(2^3\); which simply translates to 13. </p> <p> So far we have explored how to represent numbers in different numerical systems however we have only shown examples with positive numbers. What about negative numbers? Well in most cases we use a signal of some kind to signify negation. In decimal we use a '\(-\)' sign to mean negative. In binary it is common practice for the most significant is 1 if its negative and 0 otherwise. </p> <p> Now let us discuss negative bases, this refers to bases that are \(&lt; 0\). This seems like an unusual topic but it helps us perform some interesting magic. From now on I will mainly discuss base negative two as an example but the topics covered can be abstracted over all negative bases. </p> <p> Reading a number is the same process so 1101 in base negative is&nbsp;\(1*-2^0 + 0*-2^1 + 1*-2^2 + 1*-2^3 = -3\). Similarly 101 in bnt is 5. Notice how we cannot represent both positive and negative numbers in in this numerical system without the need of a signal. This is the power of negative bases. </p> <p> I am going to be representing bnt numbers in an array where the index represents the significance of the digit, as in array[0] is the least significant digit and array[array.length-1] is the most significant digit; Let's define a few utility functions that we can use in the future. The obvious one is converting bnt numbers into decimal: </p> <pre class="prettyprint"><code class="language-js">function bntToDec(n) { var current = 1, result = 0; for (var i = 0; i &lt; n.length; i++) { result += current * n[i]; current *= -2; } return result; } </code></pre> <p> Converting from decimal to bnt is a slightly different different problem but still simple: </p> <pre class="prettyprint"><code class="language-js">function decToBNT(n) { var arr = [], i = 0; while (n != 0) { arr.push(Math.abs(n % -2)); n = Math.ceil(n / -2); } return arr; }</code></pre> <p> In the next part I will discuss bnt arithmetic such as negation, addition, subtraction and much more. </p> </div> </div> </div> </article> <hr> <!-- Footer --> <footer> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <ul class="list-inline text-center"> <li> <a href="https://twitter.com/saquibhafizz"> <span class="fa-stack fa-lg" target="_blank"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-twitter fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="https://www.linkedin.com/in/saquibhafiz"> <span class="fa-stack fa-lg" target="_blank"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="https://github.com/saquibhafiz" target="_blank"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> <p class="copyright text-muted">Copyright &copy; Saquib Hafiz 2014</p> </div> </div> </div> </footer> <!-- jQuery --> <script src="../js/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="../js/bootstrap.min.js"></script> <!-- Clean Blog Theme JavaScript --> <script src="../js/clean-blog.min.js"></script> <!-- Prettify JavaScript --> <script src="../js/google-code-prettify/prettify.js"></script> <script type="text/javascript"> $( document ).ready(function() { ! function ($) { $(function () { window.prettyPrint && prettyPrint() }) }(window.jQuery) }); </script> <!-- Handlebars JavaScript --> <script src="../js/handlebars.js"></script> <!-- Custom JavaScript --> <script src="../js/posts.js"></script> <script src="../js/custom.js"></script> <!-- MathJax JavaScript --> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> </body> </html>
saquibhafiz/personalwebsite
public_html/blog/bnt_part_1.html
HTML
apache-2.0
9,713
/* * Copyright (c) 2018 Arm Limited * * 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. */ /** * \file gfc100_process_specific_api.h * * \brief Header file for the process specific part of the * GFC100 flash controller */ #ifndef __GFC100_PROCESS_SPEC_API_H__ #define __GFC100_PROCESS_SPEC_API_H__ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> /** * \brief Sets timing parameters on the process specific part * * \param[in] reg_map_base Process specific register map base * \param[in] sys_clk System clock in Hz */ void gfc100_proc_spec_set_eflash_timing(uint32_t reg_map_base, uint32_t sys_clk); /** * \brief Gets flash memory size * * \param[in] reg_map_base Process specific register map base * * \return Returns the size of the flash memory */ uint32_t gfc100_proc_spec_get_eflash_size(uint32_t reg_map_base); /** * \brief Gets flash page size * * \param[in] reg_map_base Process specific register map base * * \return Returns the page size of the flash memory */ uint32_t gfc100_proc_spec_get_eflash_page_size(uint32_t reg_map_base); /** * \brief Gets word width of the process specific part * * \param[in] reg_map_base Process specific register map base * * \return Returns word width of the process specific part */ uint32_t gfc100_proc_spec_get_eflash_word_width(uint32_t reg_map_base); /** * \brief Gets number of info pages * * \param[in] reg_map_base Process specific register map base * * \return Returns the number of info pages from the extended area */ uint32_t gfc100_proc_spec_get_num_of_info_pages(uint32_t reg_map_base); /** * \brief Gets process specific error bits * * \param[in] reg_map_base Process specific register map base * * \return Returns the error bits specified by the process specific part * of the controller. */ uint32_t gfc100_proc_spec_get_error_cause(uint32_t reg_map_base); #ifdef __cplusplus } #endif #endif /* __GFC100_PROCESS_SPEC_API_H__ */
mbedmicro/FlashAlgo
source/arm/gfc100/Native_Driver/gfc100_process_spec_api.h
C
apache-2.0
2,521
var current_iframe; /** * 切换子系统界面 * @param moduleid * (1)传字符串表示子系统第一级菜单的menuid或moduleid * (2)传数字表示切换第几个子系统,从0开始 */ DM.index.module = function(moduleid){ var $a; if(typeof moduleid=='number'){ $a = $('div.menu-root li.item').eq(moduleid).children('a'); }else{ $a = $('div.menu-root li.item').find('a[data-menuid="'+moduleid+'"],[data-moduleid="'+moduleid+'"]'); } if($a.length==0){ return null; } var menuid = $a.attr('data-menuid'); //转换显示content var $content = $('#content-'+menuid); if($content.length==0){ return null; } if(!$a.hasClass('active')){ //设置当前菜单选中样式 $a.addClass('active') //恢复原选中菜单样式 .parent().addClass('active').siblings('.active').removeClass('active') .children('.active').removeClass('active'); $content.addClass('iactive') //隐藏原来显示的content .siblings().removeClass('iactive'); $('div.menu-root div.selected').html($a.html()+"<img src='kstrap/images/triangle_down_17.gif'/>"); $('div.menu-root div.sidebar div').click(); } return $content; }; /** * 一级菜单点击事件 */ DM.index.menuSubSysClick = function(a){ DM.index.module($(a).attr('data-menuid')); var $content = $(a).parents('div.content'); //判断有没有打开的子菜单页面,如果没有自动打开首页 if($content.find('.dm-tab').children('iframe').length==0){ DM.index.home($(a).attr('data-menuid')); } }; //用于方格布局菜单打开使用 DM.index.menuSubItemClick2 = function(a){ var jq = $(a); var argsJson={}; argsJson.menuid=jq.attr('data-menuid'); argsJson.title=jq.attr('data-title'); argsJson.find_menu=false; argsJson.url=jq.attr('data-url'); DM.index.openPage(argsJson); }; /** * 用于打开子页面的API */ DM.index.openPage = function(argsJson, params){ if(typeof argsJson=='string'){ //直接传string认为它是menuid argsJson = {menuid: argsJson}; } var menuid = argsJson.menuid; if(menuid==null || menuid==''){ DM.logerror('DM.index.openPage[0]:必须指定menuid值'); return; } var url = Tools.trim(argsJson.url); var icon = argsJson.icon; var title = argsJson.title; var find_menu = argsJson.find_menu; var closeable = argsJson.closeable; if(closeable==null){ closeable = true; } //找到当前激活的子系统content div var $cont = $('div.main-cloud').children('.content.iactive'); //当前显示的子系统操作区tab对象 var $tab = $cont.children('.dm-tab'); //所有子系统content div var $contents = $('div.main-cloud').children('.content'), tab_title_ul = $tab.find('div.dm-tab-title > ul');//当前显示的tab导航栏ul对象 //在所有子系统的左侧菜单中查找输入的menuid var $menu_a = null;//用于保存找到的menuid的菜单节点 //可以通过传find_menu=false来阻止查找菜单节点,供home函数使用,节省遍历菜单节点的处理 if(find_menu!==false){ $contents.each(function(){//遍历子系统工作区 var $ct = $(this); //遍历子系统左侧菜单节点 $ct.find('ul.sub-menu-ul').find('a').each(function(){ var $this = $(this); if($this.attr('data-menuid') == menuid){ $menu_a = $this; return false; } }); //找到对应的菜单节点就退出遍历了 if($menu_a!=null){ //保存一下菜单节点所在的子系统工作区的tab面板引用 $menu_a.data('k-tab', $ct.children('.dm-tab')); return false; } }); } //接下来需要查找一下需要打开的menuid对应的页面是否已被找到,如果是,则激活(按钮调用还得刷新),如果不是就需要创建新的子页面了 var $search_title_lis = null; var $search_tab = null; if($menu_a==null){//找不到菜单节点 //找不到菜单节点,就一定不是菜单点击调用的,只能是页面上的按钮点击调用的,只在当前激活页面中查找是否已打开 $search_tab = $tab; $search_title_lis = tab_title_ul.children('li:not(.dropdown)'); }else{ //找到了菜单节点,就在找到的节点所在的工作区的tab面板查找 $search_tab = $menu_a.data('k-tab'); $search_title_lis = $search_tab.find('div.dm-tab-title > ul > li:not(.dropdown)'); //激活显示目标子系统工作区 DM.index.module($menu_a.attr('data-moduleid')); } var active_panel = null; //开始查找menuid的页面是否已打开(在tab-title里找到) $search_title_lis.each(function(n){ var $this = $(this); if($this.attr('data-tab-menuid')==menuid){ active_panel = DM.tab.active($search_tab, n); return false; } }); if($menu_a){//有找到菜单节点 var moduleid = $menu_a.attr('data-moduleid'); menuid = menuid || $menu_a.attr('data-menuid'); url = url || Tools.trim($menu_a.attr('data-url')) || 'page/M'+moduleid.toUpperCase()+'/'+$menu_a.attr('data-menuid')+'.jsp'; title = title || $menu_a.attr('data-menuname'); icon = icon || $menu_a.attr('data-icon'); } if(!$menu_a){ $menu_a = $(".sub-menu").find('ul li a.home-con'); url = url || Tools.trim($menu_a.attr('data-url')); title = title || $menu_a.attr('data-menuname'); } if(url==null || url==''){ DM.logerror('DM.index.openPage[1]:没有指定要页面的url地址'); return; } var open_url; if(url.indexOf('?')==-1){ open_url = url + '?'; }else{ open_url = url + '&'; } open_url = open_url + Tools.json2get({moduleid: moduleid, menuid: menuid}); if(active_panel==null){//页面没打开,需要创建 var add_iframe = $('<div data-closeable="'+closeable+'" data-menuid="'+menuid+'" data-moduleid="'+moduleid+'" data-title="'+title+'" class="panel"><iframe id="iframe-'+menuid+'" name="iframe-'+menuid+'" frameBorder="0" marginWidth="0" marginHeight="0"></iframe></div>'); $search_tab.append(add_iframe); DM.tab.add($search_tab, add_iframe); var add_tab_li = add_iframe.data('tab_title'); add_tab_li.attr('data-tab-menuid',menuid);//如果存在menuid则存放menuid为引用 Tools.submit2BlankWindow(open_url, params, "iframe-"+menuid); current_iframe = "iframe-"+menuid; }else{//找到已打开页面 if($menu_a!=null){//如果是找到的菜单节点页面 //要打开的url与已打开的页面相同,并且没有传参数,则判断为不需要刷新已打开页面 if(argsJson.url==null || url==argsJson.url && params==null){ return; }; } Tools.submit2BlankWindow(open_url, params, "iframe-"+menuid); current_iframe = "iframe-"+menuid; } }; /** * 获取子页面(是个在index.jsp里的iframe的DOM对象 */ DM.index.getPage = function(menuid){ var $menuid; //找到当前激活的子系统content div var $cont = $('div.main-cloud').children('.content.iactive'); var $tab_lis = $cont.find("div.dm-tab-title > ul > li:not(.dropdown)"); $tab_lis.each(function(i){ var $this = $(this); if($this.hasClass('active')&&menuid==null){ $menuid = $(this); return false; }else if($this.attr('data-tab-menuid') == menuid){ $menuid = $(this); return false; } }); var the_iframe = $menuid.data('tab_panel').children('iframe'); return the_iframe; }; DM.index.getPageK = function(menuid){ return $(DM.index.getPage(menuid)).data('child-K'); }; /** * menuid,可选参数,如果不传menuid参数则关闭当前激活页面,传menuid则关闭,指定菜单页面 * */ DM.index.closePage = function(menuid){ var index; //找到当前激活的子系统content div var $cont = $('div.main-cloud').children('.content.iactive'); var $tab_lis = $cont.find("div.dm-tab-title > ul > li:not(.dropdown)"); $tab_lis.each(function(i){ var $this = $(this); if($this.hasClass('active')&&menuid==null){ index = i; return false; }else if($this.attr('data-tab-menuid') == menuid){ index = i; return false; } }); DM.tab.remove($cont,index); }; /** * 左侧二级以下分支节点菜单的点击事件 */ DM.index.menuSubClick = function(a){ var jq = $(a); var spancon = jq.children('span.branch-con'); //设置左边的小箭头图标 spancon.toggleClass('branch-open').toggleClass('branch-close'); //设置下级菜单显示或隐藏 jq.parent().children('ul').toggle(); jq.siblings('ul').find('a').each(function(){ if($(this).hasClass('active')){ if(spancon.hasClass('branch-open')){ jq.removeClass('active'); }else{ jq.addClass('active'); } return false; } }); }; /** * 返回主页的方法 */ DM.index.home = function(moduleid){ var $content = DM.index.module(moduleid); if($content==null){ return; } var homeMenuid = $content.attr('data-home-menuid'), homeUrl = $content.attr('data-home-url'), homeIcon = $content.attr('data-home-icon'), homeName = $content.attr('data-home-menuname'); if(homeMenuid==null || homeMenuid=='' || homeUrl==null || homeUrl==''){ return; } DM.index.openPage({url: homeUrl, menuid: homeMenuid, icon: homeIcon, title: homeName, closable: false, find_menu: false}); }; DM.index.expandAll = function(a){ $this = $(a); var sub_menu_ul = $this.parents('div.sub-menu-top').siblings('div.sub-menu-div').children('ul.sub-menu-ul'); sub_menu_ul.find('span.branch-close').each(function(){ $this = $(this); $this.parent('a').click(); }); }; DM.index.collapseAll = function(a){ $this = $(a); var sub_menu_ul = $this.parents('div.sub-menu-top').siblings('div.sub-menu-div').children('ul.sub-menu-ul'); sub_menu_ul.find('span.branch-open').each(function(){ $this = $(this); $this.parent('a').click(); }); }; DM.index.menuSubItemClick = function(a){ var jq = $(a); jq.parents('ul.sub-menu-ul').find('a.active').removeClass('active');//还原被选中状态样式 jq.addClass('active');//添加选中状态样式 DM.index.openPage(jq.attr('data-menuid')); }; /** * 定义在每个子系统工作区的k-tab的data-on-active方法, * 用于在点击k-tab的title标签切换页面时,选中相应的左侧菜单 */ DM.index.subPageOnActive = function(panel){ var $panel = $(panel), menuid = $panel.attr('data-menuid'), $ul = $(this).prev('.sub-menu').find('ul.sub-menu-ul'), $a = $ul.find('a[data-menuid="'+menuid+'"]'); if($a.length==0){ return; } if($a.hasClass('active')){ return; } $ul.find('a.active').removeClass('active'); $a.addClass('active'); }; $(function(){ //初始激活第一个子系统和首页 DM.index.home(0); //给menu-root-ul绑定鼠标事件 var SPACE = 4, ANIMATE_TIME = 150, $div = $('div.menu-root'), $ul = $div.children('ul'), $selected = $div.children('div.selected') ; var $mainBoard; var fn_show = function(){ if($div.hasClass('show')){ return; } $div.attr('data-showing',true); if(navigator.userAgent.indexOf("MSIE 7.0")>0){ //因为IE7下切换菜单会导致定位错误,所以去除IE7下滑动的特性 $ul.css({"width":"202px"}); $div.attr('data-showing',false); if(!$div.hasClass('hover')){ fn_hide(); }else{ $div.addClass('show'); } }else{ $ul.animate({ width: "202px" },ANIMATE_TIME,function(){ $div.attr('data-showing',false); if(!$div.hasClass('hover')){ fn_hide(); }else{ $div.addClass('show'); } }); } }, fn_hide = function(force){ if($div.attr('data-showing')=='true'){ return; } if($div.hasClass('hover') && force!==true){ return; } if(navigator.userAgent.indexOf("MSIE 7.0")>0){ //因为IE7下切换菜单会导致定位错误,所以去除IE7下滑动的特性 $ul.css({"width":"0px"}); }else{ $ul.animate({ width: "0px" },ANIMATE_TIME); } }; $ul.children('li').click(function(){ if($div.hasClass('show')){ $div.removeClass('hover'); $div.removeClass('show'); fn_hide(); }else{ $div.addClass('hover'); fn_show(); } }); $selected.click(function(){ if($div.hasClass('show')){ $div.removeClass('hover'); $div.removeClass('show'); fn_hide(); $('div.menu-root div.selected').html($mainBoard+"<img src='kstrap/images/triangle_down_17.gif'/>"); }else{ $div.addClass('hover'); fn_show(); $mainBoard=$('div.menu-root div.selected').text(); $('div.menu-root div.selected').html($mainBoard+"<img src='kstrap/images/triangle_up_17.gif'/>"); } $(window).resize(); }); $("span.branch-close").parent("a").find("span.icon-add ").removeClass("tree-node-tool icon-add last"); $("span.branch-open").parent("a").find("span.icon-add").removeClass("tree-node-tool icon-add last"); if(navigator.userAgent.indexOf("MSIE 7.0")>0){ //因为IE7下切换菜单会导致定位错误,所以去除IE7下滑动的特性 window.setInterval("reinitIframe()", 500); } }); function reinitIframe(){ var iframe = document.getElementById(current_iframe); try{ if(iframe){ var height = $(".content.iactive .dm-tab.dm-tab-primary.last").height(); $(iframe).css({"height":height+"px"}); } }catch (ex){} }
wlzjdm/wolf
wolf-sys-manager/src/main/webapp/frame/component/js/dm-index3.js
JavaScript
apache-2.0
13,417
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id: ChunkServer.h 385 2010-05-27 15:58:30Z sriramsrao $ // // Created 2006/03/16 // // Copyright 2008 Quantcast Corp. // Copyright 2006-2008 Kosmix Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // //---------------------------------------------------------------------------- #ifndef _CHUNKSERVER_H #define _CHUNKSERVER_H #include "libkfsIO/TelemetryClient.h" #include "ChunkManager.h" #include "ClientManager.h" #include "ClientSM.h" #include "MetaServerSM.h" #include "RemoteSyncSM.h" namespace KFS { class ChunkServer { public: ChunkServer() : mOpCount(0), mKickNetThread(false) { }; void Init(); void MainLoop(int clientAcceptPort, const std::string & serverHostname); bool IsLocalServer(const ServerLocation &location) const { return mLocation == location; } RemoteSyncSMPtr FindServer(const ServerLocation &location, bool connect = true); void RemoveServer(RemoteSyncSM *target); std::string GetMyLocation() const { return mLocation.ToString(); } void ToggleNetThreadKicking (bool v) { mKickNetThread = v; } bool NeedToKickNetThread() { return mKickNetThread; } void OpInserted() { mOpCount++; } void OpFinished() { mOpCount--; if (mOpCount < 0) mOpCount = 0; } int GetNumOps() const { return mOpCount; } void SendTelemetryReport(KfsOp_t op, double timeSpent); private: int mClientAcceptPort; // # of ops in the system int mOpCount; bool mKickNetThread; ServerLocation mLocation; std::list<RemoteSyncSMPtr> mRemoteSyncers; // telemetry reporter...used for notifying slow writes thru this node TelemetryClient mTelemetryReporter; }; extern void verifyExecutingOnNetProcessor(); extern void verifyExecutingOnEventProcessor(); extern void StopNetProcessor(int status); extern ChunkServer gChunkServer; } #endif // _CHUNKSERVER_H
sumedhsakdeo/zynx
src/cc/chunk/ChunkServer.h
C
apache-2.0
2,630
#include "StdAfx.h" #include <gtest/gtest.h> class PlayFabApiTestTest : public ::testing::Test { protected: void SetUp() override { } void TearDown() override { } }; TEST_F(PlayFabApiTestTest, ExampleTest) { ASSERT_TRUE(true); } GEM_IMPLEMENT_TEST_RUNNER
JoshuaStrunk/SDKGenerator
targets/LumberyardSdk/testing/TestGem/Code/Tests/PlayFabApiTestTest.cpp
C++
apache-2.0
291
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Text; namespace Gallio.Common.Reflection.Impl { /// <summary> /// Represents a code element that could not be resolved to a native reflection type. /// </summary> /// <remarks> /// <para> /// The <see cref="UnresolvedCodeElementFactory"/> produces reflection objects that /// implement this interface. /// </para> /// </remarks> public interface IUnresolvedCodeElement { /// <summary> /// Gets the underlying reflection adapter. /// </summary> ICodeElementInfo Adapter { get; } } }
citizenmatt/gallio
src/Gallio/Gallio/Common/Reflection/Impl/IUnresolvedCodeElement.cs
C#
apache-2.0
1,301
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Thu Dec 05 05:02:03 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>LdapRealmConsumer (BOM: * : All 2.6.0.Final API)</title> <meta name="date" content="2019-12-05"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="LdapRealmConsumer (BOM: * : All 2.6.0.Final API)"; } } catch(err) { } //--> var methods = {"i0":6,"i1":18}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/LdapRealmConsumer.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.6.0.Final</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealm.html" title="class in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" target="_top">Frames</a></li> <li><a href="LdapRealmConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.wildfly.swarm.config.elytron</div> <h2 title="Interface LdapRealmConsumer" class="title">Interface LdapRealmConsumer&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealm.html" title="class in org.wildfly.swarm.config.elytron">LdapRealm</a>&lt;T&gt;&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Functional Interface:</dt> <dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd> </dl> <hr> <br> <pre><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a> public interface <span class="typeNameLabel">LdapRealmConsumer&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealm.html" title="class in org.wildfly.swarm.config.elytron">LdapRealm</a>&lt;T&gt;&gt;</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html#accept-T-">accept</a></span>(<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="type parameter in LdapRealmConsumer">T</a>&nbsp;value)</code> <div class="block">Configure a pre-constructed instance of LdapRealm resource</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>default <a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="interface in org.wildfly.swarm.config.elytron">LdapRealmConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="type parameter in LdapRealmConsumer">T</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html#andThen-org.wildfly.swarm.config.elytron.LdapRealmConsumer-">andThen</a></span>(<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="interface in org.wildfly.swarm.config.elytron">LdapRealmConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="type parameter in LdapRealmConsumer">T</a>&gt;&nbsp;after)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="accept-org.wildfly.swarm.config.elytron.LdapRealm-"> <!-- --> </a><a name="accept-T-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>accept</h4> <pre>void&nbsp;accept(<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="type parameter in LdapRealmConsumer">T</a>&nbsp;value)</pre> <div class="block">Configure a pre-constructed instance of LdapRealm resource</div> </li> </ul> <a name="andThen-org.wildfly.swarm.config.elytron.LdapRealmConsumer-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>andThen</h4> <pre>default&nbsp;<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="interface in org.wildfly.swarm.config.elytron">LdapRealmConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="type parameter in LdapRealmConsumer">T</a>&gt;&nbsp;andThen(<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="interface in org.wildfly.swarm.config.elytron">LdapRealmConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" title="type parameter in LdapRealmConsumer">T</a>&gt;&nbsp;after)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/LdapRealmConsumer.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.6.0.Final</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealm.html" title="class in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/LdapRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/LdapRealmConsumer.html" target="_top">Frames</a></li> <li><a href="LdapRealmConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2.6.0.Final/apidocs/org/wildfly/swarm/config/elytron/LdapRealmConsumer.html
HTML
apache-2.0
11,131
package com.example.mobilesafe.db; /** * Created by 若兰 on 2015/12/25. * 一个懂得了编程乐趣的小白,希望自己 * 能够在这个道路上走的很远,也希望自己学习到的 * 知识可以帮助更多的人,分享就是学习的一种乐趣 * QQ:1069584784 * csdn:http://blog.csdn.net/wuyinlei */ import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; /** * 归属地查询数据库 */ public class AddressDao { //该路径必须是一下的这个目录 public static final String PATH = "data/data/com.example.mobilesafe/files/address.db"; public static String getAddress(String number) { String address = "未知号码"; //拿到数据库对象 /** * openDatabase()这个api只支持从他默认的路径下打开数据库文件,不支持直接打开assets目录下的文件 * 所以我们通过流的复制,把这个assets目录下的文件复制到了"data/data/com.example.mobilesafe/files" * 这个目录下,以达到我们可以读取数据库文件 */ SQLiteDatabase db = SQLiteDatabase.openDatabase(PATH, null, SQLiteDatabase.OPEN_READONLY); //分析输入的是否是手机号码,也就是用到了正则表达式 //手机号码特点 1(345678) (9位数字) //手机号码的正则表达式 //^1[3-8]\d{9}$ if (number.matches("^1[3-8]\\d{9}$")) { //匹配手机号码 String sql = "select location from data2 where id=(select outkey from data1 where id=?)"; Cursor cursor = db.rawQuery(sql, new String[]{number.substring(0, 7)}); if (cursor.moveToNext()) { address = cursor.getString(0); } cursor.close(); } else if (number.matches("^\\d+$")) { //匹配数字 switch (number.length()) { case 3: address = "报警电话"; break; case 4: address = "模拟器"; break; case 5: address = "客服电话"; break; //判断本地电话 case 7: case 8: address = "本地电话"; break; //0102225125 default: if (number.startsWith("0") && number.length() > 10) { //有可能是长途电话 //有些区号是4位,有些区号是3位(包括0) // 先查询4位区号 Cursor cursor = db.rawQuery( "select location from data2 where area =?", new String[]{number.substring(1, 4)}); if (cursor.moveToNext()) { address = cursor.getString(0); } else { cursor.close(); // 查询3位区号 cursor = db.rawQuery( "select location from data2 where area =?", new String[]{number.substring(1, 3)}); if (cursor.moveToNext()) { address = cursor.getString(0); } cursor.close(); } } address = ""; break; } } //关闭数据库 db.close(); return address; } }
wuyinlei/MobileSafe
src/main/java/com/example/mobilesafe/db/AddressDao.java
Java
apache-2.0
3,661
// Copyright 2012 Paolo Severini // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "stdafx.h" #include "CppUnitTest.h" #include "testUtils.h" #include "throwingEnumerable.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTest { TEST_CLASS(SelectTest) { public: static void test() { fprintf(stdout, "select\n"); SelectTest selectTest; selectTest.Select_EmptySource(); selectTest.Select_ExecutionIsDeferred(); selectTest.Select_SimpleProjection(); selectTest.Select_SimpleProjectionToDifferentType(); selectTest.Select_SimpleProjectionWithQueryExpression(); selectTest.Select_WithIndexEmptySource(); selectTest.Select_WithIndexExecutionIsDeferred(); selectTest.Select_WithIndexSimpleProjection(); selectTest.Select_SideEffectsInProjection(); } //TEST_METHOD(Select_NullProjectionThrowsNullArgumentException) //{ // int v[] = { 1, 3, 7, 9, 10 }; // std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, ARRAYSIZE(v))); // std::function<int(int)> projection = nullptr; // Assert::ExpectException<ArgumentNullException&>([source, &projection]() { // source->Select<int>(projection); // }); //} //TEST_METHOD(Select_WithIndexNullPredicateThrowsNullArgumentException) //{ // int v[] = { 1, 3, 7, 9, 10 }; // std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, ARRAYSIZE(v))); // std::function<int(int, int)> projection = nullptr; // Assert::ExpectException<ArgumentNullException&>([source, &projection]() { // source->SelectIndex<int>(projection); // }); //} TEST_METHOD(Select_SimpleProjection) { int v[] = { 1, 5, 2 }; std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, ARRAYSIZE(v))); auto result = source->Select<int>([](int x) { return x * 2; }); int exp[] = { 2, 10, 4 }; Assert::IsTrue(result->SequenceEqual<int>(exp, ARRAYSIZE(exp))); } TEST_METHOD(Select_SimpleProjectionWithQueryExpression) { int v[] = { 1, 5, 2 }; std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, ARRAYSIZE(v))); auto result = source->Select<int>([](int x) { return x * 2; }); int exp[] = { 2, 10, 4 }; Assert::IsTrue(result->SequenceEqual<int>(exp, ARRAYSIZE(exp))); } TEST_METHOD(Select_SimpleProjectionToDifferentType) { int v[] = { 1, 5, 2 }; std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, ARRAYSIZE(v))); auto result = source->Select<std::string>([](int x) { return IntToString(x); }); std::string exp[] = { "1", "5", "2" }; Assert::IsTrue(result->SequenceEqual<std::string>(exp, ARRAYSIZE(exp))); } TEST_METHOD(Select_EmptySource) { int* v = new int[0]; std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, 0)); auto result = source->Select<int>([](int x) { return x * 2; }); Assert::IsTrue(result->SequenceEqual<int>(v, 0)); delete [] v; } TEST_METHOD(Select_ExecutionIsDeferred) { ThrowingEnumerable::AssertDeferred([](std::shared_ptr<IEnumerable<int>> src) { return src->Select<int>([=](int x) { return x * 2; } ); }); } TEST_METHOD(Select_WithIndexSimpleProjection) { int v[] = { 1, 5, 2 }; std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, ARRAYSIZE(v))); auto result = source->SelectIndex<int>([](int x, int index) { return x + index * 10; }); int exp[] = { 1, 15, 22 }; Assert::IsTrue(result->SequenceEqual<int>(exp, ARRAYSIZE(exp))); } TEST_METHOD(Select_WithIndexEmptySource) { int* v = new int[0]; std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, 0)); auto result = source->SelectIndex<int>([](int x, int index) { return x + index; }); Assert::IsTrue(result->SequenceEqual<int>(v, 0)); delete [] v; } TEST_METHOD(Select_WithIndexExecutionIsDeferred) { ThrowingEnumerable::AssertDeferred([](std::shared_ptr<IEnumerable<int>> src) { return src->SelectIndex<int>([=](int x, int index) { return x + index; } ); }); } TEST_METHOD(Select_SideEffectsInProjection) { int v[3] = { 0, 0, 0 }; // Actual values won't be relevant std::shared_ptr<IEnumerable<int>> source(new Vector<int>(v, ARRAYSIZE(v))); int count = 0; auto query = source->Select<int>([&count](int x) { return count++; }); int exp1[] = { 0, 1, 2 }; Assert::IsTrue(query->SequenceEqual<int>(exp1, ARRAYSIZE(exp1))); int exp2[] = { 3, 4, 5 }; Assert::IsTrue(query->SequenceEqual<int>(exp2, ARRAYSIZE(exp2))); count = 10; int exp3[] = { 10, 11, 12 }; Assert::IsTrue(query->SequenceEqual<int>(exp3, ARRAYSIZE(exp3))); } }; }
paolosev/cpplinq
src/cppLinqUnitTest/selectTest.cpp
C++
apache-2.0
6,181