repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
splicemachine/splice-community-sample-code
|
spark-streaming-splice-adapter/src/main/resources/scripts/run-kafka-spark-streaming.sh
|
745
|
#!/usr/bin/env bash
export CLASS_NAME="com.splicemachine.tutorials.spark.SparkStreamingKafka"
export APPLICATION_JAR="splice-tutorial-file-spark-2.6.1.1736.jar"
export SPARK_JARS_DIR="${SPARK_HOME}/jars"
CURRENT_IP=$(ifconfig eth0 | grep inet | awk '{print $2}')
SPARK_IMAGE=${SPARK_IMAGE:-"splicemachine/tutorial-spark-kafka-consumer:2.0.3"}
echo "spark.driver.host $CURRENT_IP" >> $SPARK_HOME/conf/spark-defaults.conf
echo "spark.mesos.executor.docker.image $SPARK_IMAGE" >> $SPARK_HOME/conf/spark-defaults.conf
exec "${SPARK_HOME}"/bin/spark-submit \
--class ${CLASS_NAME} \
--files ${SPARK_HOME}/conf/hbase-site.xml,${SPARK_HOME}/conf/core-site.xml,${SPARK_HOME}/conf/hdfs-site.xml \
"${APPLICATION_JAR}" \
"$@"
|
apache-2.0
|
Abnaxos/guards
|
annotations/src/main/java/ch/raffael/guards/Pure.java
|
1167
|
/*
* Copyright 2015 Raffael Herzog
*
* 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 ch.raffael.guards;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies that this method does not change the state of the object in any ways.
*
* It's the same as `@Contract(pure=true)` using IDEA annotations.
*
* @author <a href="mailto:[email protected]">Raffael Herzog</a>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Pure {
}
|
apache-2.0
|
ckeita/training-java
|
computer-database/core/src/main/java/fr/ebiz/computer_database/model/Role.java
|
457
|
package fr.ebiz.computer_database.model;
import javax.persistence.*;
/**
* Created by ebiz on 31/05/17.
*/
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String role;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
apache-2.0
|
svn2github/hwmail-mirror
|
hedwig-server/src/test/java/com/hs/mail/smtp/processor/hook/DNSRBLHandlerTest.java
|
640
|
package com.hs.mail.smtp.processor.hook;
import java.util.StringTokenizer;
import org.junit.AfterClass;
import org.junit.Test;
public class DNSRBLHandlerTest {
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test() {
String ipAddress = "1.2.3.4";
StringBuffer sb = new StringBuffer();
StringTokenizer st = new StringTokenizer(ipAddress, " .", false);
while (st.hasMoreTokens()) {
sb.insert(0, st.nextToken() + ".");
}
String reversedOctets = sb.toString();
System.out.println(reversedOctets);
}
}
|
apache-2.0
|
nghiant2710/base-images
|
balena-base-images/node/jetson-nano/debian/sid/15.6.0/run/Dockerfile
|
2931
|
# AUTOGENERATED FILE
FROM balenalib/jetson-nano-debian:sid-run
ENV NODE_VERSION 15.6.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& echo "b0660398fe590f8588431a787e9b032c7271a2fa88306c7a26e751571df998e4 node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
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/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
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 v8 \nOS: Debian Sid \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.6.0, Yarn v1.22.4 \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/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
apache-2.0
|
arnaud71/webso-db
|
docs/solr-core/org/apache/solr/util/ConcurrentLFUCache.EvictionListener.html
|
8905
|
<!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 (version 1.6.0_27) on Thu Jan 23 20:22:09 EST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>ConcurrentLFUCache.EvictionListener (Solr 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ConcurrentLFUCache.EvictionListener (Solr 4.6.1 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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/ConcurrentLFUCache.EvictionListener.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="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/solr/util/ConcurrentLFUCache.html" title="class in org.apache.solr.util"><span class="strong">PREV CLASS</span></a></li>
<li><a href="../../../../org/apache/solr/util/ConcurrentLFUCache.Stats.html" title="class in org.apache.solr.util"><span class="strong">NEXT CLASS</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/solr/util/ConcurrentLFUCache.EvictionListener.html" target="_top">FRAMES</a></li>
<li><a href="ConcurrentLFUCache.EvictionListener.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All 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: </li>
<li>NESTED | </li>
<li>FIELD | </li>
<li>CONSTR | </li>
<li><a href="#method_summary">METHOD</a></li>
</ul>
<ul class="subNavList">
<li>DETAIL: </li>
<li>FIELD | </li>
<li>CONSTR | </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">
<p class="subTitle">org.apache.solr.util</p>
<h2 title="Interface ConcurrentLFUCache.EvictionListener" class="title">Interface ConcurrentLFUCache.EvictionListener<K,V></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../org/apache/solr/util/ConcurrentLFUCache.html" title="class in org.apache.solr.util">ConcurrentLFUCache</a><<a href="../../../../org/apache/solr/util/ConcurrentLFUCache.html" title="type parameter in ConcurrentLFUCache">K</a>,<a href="../../../../org/apache/solr/util/ConcurrentLFUCache.html" title="type parameter in ConcurrentLFUCache">V</a>></dd>
</dl>
<hr>
<br>
<pre>public static interface <strong>ConcurrentLFUCache.EvictionListener<K,V></strong></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="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/solr/util/ConcurrentLFUCache.EvictionListener.html#evictedEntry(K, V)">evictedEntry</a></strong>(<a href="../../../../org/apache/solr/util/ConcurrentLFUCache.EvictionListener.html" title="type parameter in ConcurrentLFUCache.EvictionListener">K</a> key,
<a href="../../../../org/apache/solr/util/ConcurrentLFUCache.EvictionListener.html" title="type parameter in ConcurrentLFUCache.EvictionListener">V</a> value)</code> </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="evictedEntry(java.lang.Object,java.lang.Object)">
<!-- -->
</a><a name="evictedEntry(K, V)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>evictedEntry</h4>
<pre>void evictedEntry(<a href="../../../../org/apache/solr/util/ConcurrentLFUCache.EvictionListener.html" title="type parameter in ConcurrentLFUCache.EvictionListener">K</a> key,
<a href="../../../../org/apache/solr/util/ConcurrentLFUCache.EvictionListener.html" title="type parameter in ConcurrentLFUCache.EvictionListener">V</a> value)</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><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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/ConcurrentLFUCache.EvictionListener.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="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/solr/util/ConcurrentLFUCache.html" title="class in org.apache.solr.util"><span class="strong">PREV CLASS</span></a></li>
<li><a href="../../../../org/apache/solr/util/ConcurrentLFUCache.Stats.html" title="class in org.apache.solr.util"><span class="strong">NEXT CLASS</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/solr/util/ConcurrentLFUCache.EvictionListener.html" target="_top">FRAMES</a></li>
<li><a href="ConcurrentLFUCache.EvictionListener.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All 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: </li>
<li>NESTED | </li>
<li>FIELD | </li>
<li>CONSTR | </li>
<li><a href="#method_summary">METHOD</a></li>
</ul>
<ul class="subNavList">
<li>DETAIL: </li>
<li>FIELD | </li>
<li>CONSTR | </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>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
|
apache-2.0
|
newmana/rtree
|
lib/rtree/bounding_box.rb
|
1520
|
module Rtree
class BoundingBox < Struct.new(:top_left, :bottom_right)
def self.from_points(points)
x0 = points.min { |a,b| a.x <=> b.x }.x
y0 = points.min { |a,b| a.y <=> b.y }.y
x1 = points.max { |a,b| a.x <=> b.x }.x
y1 = points.max { |a,b| a.y <=> b.y }.y
BoundingBox.new(Point.new(x0, y0), Point.new(x1, y1))
end
def self.merged_bound_box(shapes)
self.minimum_bounding_rectangle(shapes.map { |s| s.bounding_box })
end
def self.minimum_bounding_rectangle(bounding_boxes)
x0 = bounding_boxes.min { |a,b| a.top_left.x <=> b.top_left.x }.top_left.x
y0 = bounding_boxes.min { |a,b| a.top_left.y <=> b.top_left.y }.top_left.y
x1 = bounding_boxes.max { |a,b| a.bottom_right.x <=> b.bottom_right.x }.bottom_right.x
y1 = bounding_boxes.max { |a,b| a.bottom_right.y <=> b.bottom_right.y }.bottom_right.y
BoundingBox.new(Point.new(x0, y0), Point.new(x1, y1))
end
def overlap(other_bounding_box)
x0, y0 = self.top_left.x, self.top_left.y
x1, y1 = self.bottom_right.x, self.bottom_right.y
x2, y2 = other_bounding_box.top_left.x, other_bounding_box.top_left.y
x3, y3 = other_bounding_box.bottom_right.x, other_bounding_box.bottom_right.y
half_w0, half_h0 = (x1-x0)/2, (y1-y0)/2
half_w1, half_h1 = (x3-x2)/2, (y3-y2)/2
within_x = ((x1+x0)/2 - (x3+x2)/2).abs <= half_w0 + half_w1
within_y = ((y1+y0)/2 - (y3+y2)/2).abs <= half_h0 + half_h1
within_x && within_y
end
end
end
|
apache-2.0
|
jbload/Muscularity
|
Muscularity.Web/Infrastructure/JwtTokenServiceOptions.cs
|
444
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;
namespace Muscularity.Web.Infrastructure
{
public class JwtTokenServiceOptions
{
public TimeSpan TimeToLive { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public SecurityKey SigningKey { get; set; }
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-greengrassv2/src/main/java/com/amazonaws/services/greengrassv2/model/transform/EffectiveDeploymentMarshaller.java
|
5040
|
/*
* Copyright 2017-2022 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.greengrassv2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.greengrassv2.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* EffectiveDeploymentMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class EffectiveDeploymentMarshaller {
private static final MarshallingInfo<String> DEPLOYMENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentId").build();
private static final MarshallingInfo<String> DEPLOYMENTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentName").build();
private static final MarshallingInfo<String> IOTJOBID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("iotJobId").build();
private static final MarshallingInfo<String> IOTJOBARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("iotJobArn").build();
private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build();
private static final MarshallingInfo<String> TARGETARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("targetArn").build();
private static final MarshallingInfo<String> COREDEVICEEXECUTIONSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("coreDeviceExecutionStatus").build();
private static final MarshallingInfo<String> REASON_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("reason").build();
private static final MarshallingInfo<java.util.Date> CREATIONTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("creationTimestamp").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<java.util.Date> MODIFIEDTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("modifiedTimestamp").timestampFormat("unixTimestamp").build();
private static final EffectiveDeploymentMarshaller instance = new EffectiveDeploymentMarshaller();
public static EffectiveDeploymentMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(EffectiveDeployment effectiveDeployment, ProtocolMarshaller protocolMarshaller) {
if (effectiveDeployment == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(effectiveDeployment.getDeploymentId(), DEPLOYMENTID_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getDeploymentName(), DEPLOYMENTNAME_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getIotJobId(), IOTJOBID_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getIotJobArn(), IOTJOBARN_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getTargetArn(), TARGETARN_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getCoreDeviceExecutionStatus(), COREDEVICEEXECUTIONSTATUS_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getReason(), REASON_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getCreationTimestamp(), CREATIONTIMESTAMP_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getModifiedTimestamp(), MODIFIEDTIMESTAMP_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
apache-2.0
|
jentfoo/aws-sdk-java
|
aws-java-sdk-mediatailor/src/main/java/com/amazonaws/services/mediatailor/model/ListTagsForResourceResult.java
|
4860
|
/*
* 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.mediatailor.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mediatailor-2018-04-23/ListTagsForResource" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListTagsForResourceResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* </p>
*/
private java.util.Map<String, String> tags;
/**
* <p>
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* </p>
*
* @return A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
*/
public java.util.Map<String, String> getTags() {
return tags;
}
/**
* <p>
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* </p>
*
* @param tags
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
*/
public void setTags(java.util.Map<String, String> tags) {
this.tags = tags;
}
/**
* <p>
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* </p>
*
* @param tags
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTagsForResourceResult withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
}
public ListTagsForResourceResult addTagsEntry(String key, String value) {
if (null == this.tags) {
this.tags = new java.util.HashMap<String, String>();
}
if (this.tags.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.tags.put(key, value);
return this;
}
/**
* Removes all the entries added into Tags.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTagsForResourceResult clearTagsEntries() {
this.tags = null;
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListTagsForResourceResult == false)
return false;
ListTagsForResourceResult other = (ListTagsForResourceResult) obj;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public ListTagsForResourceResult clone() {
try {
return (ListTagsForResourceResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
apache-2.0
|
NewpTone/stacklab-nova
|
debian/nova-doc/usr/share/doc/nova-doc/html/api/nova.virt.connection.html
|
7536
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The nova.virt.connection Module — nova 2012.2.1 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/tweaks.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '2012.2.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/jquery.tweet.js"></script>
<link rel="top" title="nova 2012.2.1 documentation" href="../index.html" />
<link rel="up" title="<no title>" href="autoindex.html" />
<link rel="next" title="The nova.virt.disk.api Module" href="nova.virt.disk.api.html" />
<link rel="prev" title="The nova.virt.configdrive Module" href="nova.virt.configdrive.html" />
</head>
<body>
<div id="header">
<h1 id="logo"><a href="http://www.openstack.org/">OpenStack</a></h1>
<ul id="navigation">
<li><a href="http://www.openstack.org/" title="Go to the Home page" class="link">Home</a></li>
<li><a href="http://www.openstack.org/projects/" title="Go to the OpenStack Projects page">Projects</a></li>
<li><a href="http://www.openstack.org/user-stories/" title="Go to the User Stories page" class="link">User Stories</a></li>
<li><a href="http://www.openstack.org/community/" title="Go to the Community page" class="link">Community</a></li>
<li><a href="http://www.openstack.org/blog/" title="Go to the OpenStack Blog">Blog</a></li>
<li><a href="http://wiki.openstack.org/" title="Go to the OpenStack Wiki">Wiki</a></li>
<li><a href="http://docs.openstack.org/" title="Go to OpenStack Documentation" class="current">Documentation</a></li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="module-nova.virt.connection">
<span id="the-nova-virt-connection-module"></span><h1>The <a class="reference internal" href="#module-nova.virt.connection" title="nova.virt.connection"><tt class="xref py py-mod docutils literal"><span class="pre">nova.virt.connection</span></tt></a> Module<a class="headerlink" href="#module-nova.virt.connection" title="Permalink to this headline">¶</a></h1>
<p>Abstraction of the underlying virtualization API.</p>
<dl class="function">
<dt id="nova.virt.connection.get_connection">
<tt class="descname">get_connection</tt><big>(</big><em>read_only=False</em><big>)</big><a class="headerlink" href="#nova.virt.connection.get_connection" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an object representing the connection to a virtualization
platform, or to an on-demand bare-metal provisioning platform.</p>
<p>This could be <tt class="xref py py-mod docutils literal"><span class="pre">nova.virt.fake.FakeConnection</span></tt> in test mode,
a connection to KVM, QEMU, or UML via <tt class="xref py py-mod docutils literal"><span class="pre">libvirt_conn</span></tt>, or a connection
to XenServer or Xen Cloud Platform via <tt class="xref py py-mod docutils literal"><span class="pre">xenapi</span></tt>. Other platforms are
also supported.</p>
<p>Any object returned here must conform to the interface documented by
<tt class="xref py py-mod docutils literal"><span class="pre">FakeConnection</span></tt>.</p>
<p><strong>Related flags</strong></p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name" colspan="2">Connection_type :</th></tr>
<tr class="field-odd field"><td> </td><td class="field-body"><p class="first">A string literal that falls through an if/elif structure
to determine what virtualization mechanism to use.
Values may be</p>
<blockquote class="last">
<div><ul class="simple">
<li>fake</li>
<li>libvirt</li>
<li>xenapi</li>
<li>vmwareapi</li>
<li>baremetal</li>
</ul>
</div></blockquote>
</td>
</tr>
</tbody>
</table>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="nova.virt.configdrive.html"
title="previous chapter">The <tt class="docutils literal docutils literal docutils literal"><span class="pre">nova.virt.configdrive</span></tt> Module</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="nova.virt.disk.api.html"
title="next chapter">The <tt class="docutils literal"><span class="pre">nova.virt.disk.api</span></tt> Module</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/api/nova.virt.connection.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" size="18" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="nova.virt.disk.api.html" title="The nova.virt.disk.api Module"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="nova.virt.configdrive.html" title="The nova.virt.configdrive Module"
accesskey="P">previous</a> |</li>
<li><a href="../index.html">nova 2012.2.1 documentation</a> »</li>
<li><a href="../devref/index.html" >Developer Guide</a> »</li>
<li><a href="autoindex.html" accesskey="U"><no title></a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2010-present, OpenStack, LLC.
Last updated on Thu Nov 1 16:11:51 2012, commit 4ed8d3e.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html>
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Genipa/Genipa americana/ Syn. Genipa americana jörgensenii/README.md
|
186
|
# Genipa americana f. jörgensenii FORM
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
jatin9896/incubator-carbondata
|
processing/src/main/java/org/apache/carbondata/processing/loading/sort/unsafe/holder/UnsafeSortTempFileChunkHolder.java
|
10153
|
/*
* 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.carbondata.processing.loading.sort.unsafe.holder;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Comparator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datastore.impl.FileFactory;
import org.apache.carbondata.core.util.CarbonProperties;
import org.apache.carbondata.core.util.CarbonUtil;
import org.apache.carbondata.processing.loading.row.IntermediateSortTempRow;
import org.apache.carbondata.processing.loading.sort.SortStepRowHandler;
import org.apache.carbondata.processing.sort.exception.CarbonSortKeyAndGroupByException;
import org.apache.carbondata.processing.sort.sortdata.IntermediateSortTempRowComparator;
import org.apache.carbondata.processing.sort.sortdata.SortParameters;
import org.apache.carbondata.processing.sort.sortdata.TableFieldStat;
public class UnsafeSortTempFileChunkHolder implements SortTempChunkHolder {
/**
* LOGGER
*/
private static final LogService LOGGER =
LogServiceFactory.getLogService(UnsafeSortTempFileChunkHolder.class.getName());
/**
* temp file
*/
private File tempFile;
/**
* read stream
*/
private DataInputStream stream;
/**
* entry count
*/
private int entryCount;
/**
* return row
*/
private IntermediateSortTempRow returnRow;
private int readBufferSize;
private String compressorName;
private IntermediateSortTempRow[] currentBuffer;
private IntermediateSortTempRow[] backupBuffer;
private boolean isBackupFilled;
private boolean prefetch;
private int bufferSize;
private int bufferRowCounter;
private ExecutorService executorService;
private Future<Void> submit;
private int prefetchRecordsProceesed;
/**
* totalRecordFetch
*/
private int totalRecordFetch;
private int numberOfObjectRead;
private TableFieldStat tableFieldStat;
private SortStepRowHandler sortStepRowHandler;
private Comparator<IntermediateSortTempRow> comparator;
/**
* Constructor to initialize
*/
public UnsafeSortTempFileChunkHolder(File tempFile, SortParameters parameters) {
// set temp file
this.tempFile = tempFile;
this.readBufferSize = parameters.getBufferSize();
this.compressorName = parameters.getSortTempCompressorName();
this.tableFieldStat = new TableFieldStat(parameters);
this.sortStepRowHandler = new SortStepRowHandler(tableFieldStat);
this.executorService = Executors.newFixedThreadPool(1);
comparator = new IntermediateSortTempRowComparator(parameters.getNoDictionarySortColumn());
initialize();
}
/**
* This method will be used to initialize
*
* @throws CarbonSortKeyAndGroupByException problem while initializing
*/
public void initialize() {
prefetch = Boolean.parseBoolean(CarbonProperties.getInstance()
.getProperty(CarbonCommonConstants.CARBON_MERGE_SORT_PREFETCH,
CarbonCommonConstants.CARBON_MERGE_SORT_PREFETCH_DEFAULT));
bufferSize = Integer.parseInt(CarbonProperties.getInstance()
.getProperty(CarbonCommonConstants.CARBON_PREFETCH_BUFFERSIZE,
CarbonCommonConstants.CARBON_PREFETCH_BUFFERSIZE_DEFAULT));
initialise();
}
private void initialise() {
try {
stream = FileFactory.getDataInputStream(tempFile.getPath(), FileFactory.FileType.LOCAL,
readBufferSize, compressorName);
this.entryCount = stream.readInt();
LOGGER.info("Processing unsafe mode file rows with size : " + entryCount);
if (prefetch) {
new DataFetcher(false).call();
totalRecordFetch += currentBuffer.length;
if (totalRecordFetch < this.entryCount) {
submit = executorService.submit(new DataFetcher(true));
}
}
} catch (FileNotFoundException e) {
LOGGER.error(e);
throw new RuntimeException(tempFile + " No Found", e);
} catch (IOException e) {
LOGGER.error(e);
throw new RuntimeException(tempFile + " No Found", e);
} catch (Exception e) {
LOGGER.error(e);
throw new RuntimeException(tempFile + " Problem while reading", e);
}
}
/**
* This method will be used to read new row from file
*
* @throws CarbonSortKeyAndGroupByException problem while reading
*/
@Override
public void readRow() throws CarbonSortKeyAndGroupByException {
if (prefetch) {
fillDataForPrefetch();
} else {
try {
this.returnRow = sortStepRowHandler.readIntermediateSortTempRowFromInputStream(stream);
this.numberOfObjectRead++;
} catch (IOException e) {
throw new CarbonSortKeyAndGroupByException("Problems while reading row", e);
}
}
}
private void fillDataForPrefetch() {
if (bufferRowCounter >= bufferSize) {
if (isBackupFilled) {
bufferRowCounter = 0;
currentBuffer = backupBuffer;
totalRecordFetch += currentBuffer.length;
isBackupFilled = false;
if (totalRecordFetch < this.entryCount) {
submit = executorService.submit(new DataFetcher(true));
}
} else {
try {
submit.get();
} catch (Exception e) {
LOGGER.error(e);
}
bufferRowCounter = 0;
currentBuffer = backupBuffer;
isBackupFilled = false;
totalRecordFetch += currentBuffer.length;
if (totalRecordFetch < this.entryCount) {
submit = executorService.submit(new DataFetcher(true));
}
}
}
prefetchRecordsProceesed++;
returnRow = currentBuffer[bufferRowCounter++];
}
/**
* get a batch of row, this interface is used in reading compressed sort temp files
*
* @param expected expected number in a batch
* @return a batch of row
* @throws IOException if error occurs while reading from stream
*/
private IntermediateSortTempRow[] readBatchedRowFromStream(int expected)
throws IOException {
IntermediateSortTempRow[] holders = new IntermediateSortTempRow[expected];
for (int i = 0; i < expected; i++) {
IntermediateSortTempRow holder
= sortStepRowHandler.readIntermediateSortTempRowFromInputStream(stream);
holders[i] = holder;
}
this.numberOfObjectRead += expected;
return holders;
}
/**
* below method will be used to get the row
*
* @return row
*/
public IntermediateSortTempRow getRow() {
return this.returnRow;
}
/**
* below method will be used to check whether any more records are present
* in file or not
*
* @return more row present in file
*/
public boolean hasNext() {
if (prefetch) {
return this.prefetchRecordsProceesed < this.entryCount;
}
return this.numberOfObjectRead < this.entryCount;
}
/**
* Below method will be used to close streams
*/
public void close() {
CarbonUtil.closeStreams(stream);
if (null != executorService && !executorService.isShutdown()) {
executorService.shutdownNow();
}
}
/**
* This method will number of entries
*
* @return entryCount
*/
public int numberOfRows() {
return entryCount;
}
@Override public int compareTo(SortTempChunkHolder other) {
return comparator.compare(returnRow, other.getRow());
}
@Override public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof UnsafeSortTempFileChunkHolder)) {
return false;
}
UnsafeSortTempFileChunkHolder o = (UnsafeSortTempFileChunkHolder) obj;
return this == o;
}
@Override public int hashCode() {
int hash = 0;
hash += tableFieldStat.hashCode();
hash += tempFile.hashCode();
return hash;
}
private final class DataFetcher implements Callable<Void> {
private boolean isBackUpFilling;
private int numberOfRecords;
private DataFetcher(boolean backUp) {
isBackUpFilling = backUp;
calculateNumberOfRecordsToBeFetched();
}
private void calculateNumberOfRecordsToBeFetched() {
int numberOfRecordsLeftToBeRead = entryCount - totalRecordFetch;
numberOfRecords =
bufferSize < numberOfRecordsLeftToBeRead ? bufferSize : numberOfRecordsLeftToBeRead;
}
@Override public Void call() throws Exception {
try {
if (isBackUpFilling) {
backupBuffer = prefetchRecordsFromFile(numberOfRecords);
isBackupFilled = true;
} else {
currentBuffer = prefetchRecordsFromFile(numberOfRecords);
}
} catch (Exception e) {
LOGGER.error(e);
}
return null;
}
}
/**
* This method will read the records from sort temp file and keep it in a buffer
*
* @param numberOfRecords number of records to be read
* @return batch of intermediate sort temp row
* @throws IOException if error occurs reading records from file
*/
private IntermediateSortTempRow[] prefetchRecordsFromFile(int numberOfRecords)
throws IOException {
return readBatchedRowFromStream(numberOfRecords);
}
}
|
apache-2.0
|
LQJJ/demo
|
126-go-common-master/app/service/main/feed/service/article.go
|
2972
|
package service
import (
"context"
"sync"
artmdl "go-common/app/interface/openplatform/article/model"
accmdl "go-common/app/service/main/account/model"
"go-common/app/service/main/feed/dao"
"go-common/library/log"
"go-common/library/sync/errgroup"
)
const _upsArtBulkSize = 50
// attenUpArticles get new articles of attention uppers.
func (s *Service) attenUpArticles(c context.Context, minTotalCount int, mid int64, ip string) (res map[int64][]*artmdl.Meta, err error) {
var mids []int64
arg := &accmdl.ArgMid{Mid: mid}
if mids, err = s.accRPC.Attentions3(c, arg); err != nil {
dao.PromError("关注rpc接口:Attentions", "s.accRPC.Attentions(%d) error(%v)", mid, err)
return
}
if len(mids) == 0 {
return
}
count := minTotalCount/len(mids) + s.c.Feed.MinUpCnt
return s.upsArticle(c, count, ip, mids...)
}
func (s *Service) upsArticle(c context.Context, count int, ip string, mids ...int64) (res map[int64][]*artmdl.Meta, err error) {
dao.MissedCount.Add("upArt", int64(len(mids)))
var (
group *errgroup.Group
errCtx context.Context
midsLen, i int
mutex = sync.Mutex{}
)
res = make(map[int64][]*artmdl.Meta)
group, errCtx = errgroup.WithContext(c)
midsLen = len(mids)
for ; i < midsLen; i += _upsArtBulkSize {
var partMids []int64
if i+_upsArcBulkSize > midsLen {
partMids = mids[i:]
} else {
partMids = mids[i : i+_upsArtBulkSize]
}
group.Go(func() (err error) {
var tmpRes map[int64][]*artmdl.Meta
arg := &artmdl.ArgUpsArts{Mids: partMids, Pn: 1, Ps: count, RealIP: ip}
if tmpRes, err = s.artRPC.UpsArtMetas(errCtx, arg); err != nil {
log.Error("s.artRPC.UpsArtMetas(%+v) error(%v)", arg, err)
err = nil
return
}
mutex.Lock()
for mid, arcs := range tmpRes {
for _, arc := range arcs {
if arc.AttrVal(artmdl.AttrBitNoDistribute) {
continue
}
res[mid] = append(res[mid], arc)
}
}
mutex.Unlock()
return
})
}
group.Wait()
return
}
func (s *Service) articles(c context.Context, ip string, aids ...int64) (res map[int64]*artmdl.Meta, err error) {
var (
mutex = sync.Mutex{}
bulkSize = s.c.Feed.BulkSize
)
res = make(map[int64]*artmdl.Meta, len(aids))
group, errCtx := errgroup.WithContext(c)
aidsLen := len(aids)
for i := 0; i < aidsLen; i += bulkSize {
var partAids []int64
if i+bulkSize < aidsLen {
partAids = aids[i : i+bulkSize]
} else {
partAids = aids[i:aidsLen]
}
group.Go(func() error {
var (
tmpRes map[int64]*artmdl.Meta
artErr error
arg *artmdl.ArgAids
)
arg = &artmdl.ArgAids{Aids: partAids, RealIP: ip}
if tmpRes, artErr = s.artRPC.ArticleMetas(errCtx, arg); artErr != nil {
log.Error("s.artRPC.ArticleMetas() error(%v)", artErr)
return nil
}
mutex.Lock()
for aid, arc := range tmpRes {
if arc.AttrVal(artmdl.AttrBitNoDistribute) {
continue
}
res[aid] = arc
}
mutex.Unlock()
return nil
})
}
group.Wait()
return
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Rhodophyta/Florideophyceae/Batrachospermales/Batrachospermaceae/Batrachospermum/Batrachospermum fluitans/README.md
|
189
|
# Batrachospermum fluitans Kerner SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
midonet/orizuru
|
lib/orizuru/operations.py
|
17776
|
#!/usr/bin/python -Werror
#
# Copyright (c) 2015 Midokura SARL, 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.
#
import sys
import os
import os.path
import yaml
from fabric.api import *
from netaddr import IPNetwork as CIDR
from fabric.colors import yellow, blue, green
from fabric.utils import puts
import cuisine
class Check(object):
def __init__(self, metadata):
self._metadata = metadata
def check_broken_cuisine(self):
run("rm -f /tmp/check_broken_cuisine.txt")
cuisine.file_write("/tmp/check_broken_cuisine.txt", "WORKING")
run("grep WORKING /tmp/check_broken_cuisine.txt")
class Configure(object):
def __init__(self, metadata):
self._metadata = metadata
def configure(self):
self.localegen()
self.name_resolution()
self.os_release()
self.datastax()
self.midonet()
def localegen(self):
if env.host_string in self._metadata.roles["all_containers"]:
run("locale-gen de_DE.UTF-8")
def name_resolution(self):
if env.host_string not in self._metadata.roles["all_containers"]:
run("hostname %s" % env.host_string.split(".")[0])
run("ip address add %s/32 dev lo || echo" % self._metadata.servers[env.host_string]["ip"])
cuisine.file_write("/etc/hostname", env.host_string.split(".")[0])
cuisine.file_write("/etc/resolv.conf", """
nameserver %s
options single-request
""" % self._metadata.config["nameserver"])
local_ip = self._metadata.servers[env.host_string]["ip"]
cuisine.file_write("/etc/hosts", """
127.0.0.1 localhost.localdomain localhost
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
%s %s.%s # %s
%s
""" % (
local_ip,
env.host_string,
self._metadata.config["domain"],
env.host_string.split(".")[0],
open("%s/etc/hosts" % os.environ["TMPDIR"]).read()
))
@classmethod
def repokey(cls, url):
run("""
URL="%s"
wget -SO- "${URL}" | apt-key add -
""" % url)
def datastax(self):
if env.host_string in self._metadata.containers:
run("""
apt-key add - <<EOF
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1
mQENBExkbXsBCACgUAbMWASAz/fmnMoWE4yJ/YHeuFHTK8zloJ/mApwizlQXTIVp
U4UV8nbLJrbkFY92VTcC2/IBtvnHpZl8eVm/JSI7nojXc5Kmm4Ek/cY7uW2KKPr4
cuka/5cNsOg2vsgTIMOZT6vWAbag2BGHtEJbriMLhT3v1tlu9caJfybu3QFWpahC
wRYtG3B4tkypt21ssWwNnmp2bjFRGpLssc5HCCxUCBFLYoIkAGAFRZ6ymglsLDBn
SCEzCkn9zQfmyqs0lZk4odBx6rzE350xgEnzFktT2uekFYqRqPQY8f7AhVfj2DJF
gVM4wXbSoVrTnDiFsaJt/Ea4OJ263jRUHeIRABEBAAG0LVJpcHRhbm8gUGFja2Fn
ZSBSZXBvc2l0b3J5IDxwYXVsQHJpcHRhbm8uY29tPokBPgQTAQIAKAIbAwYLCQgH
AwIGFQgCCQoLBBYCAwECHgECF4AFAlW/zKMFCRLBYKQACgkQNQIA8rmZo3LebAgA
gAwWkvBrPaD5Kf8H4uw9rXtHnHYxX5G6cOVJ3vuWCs1ov7m3JWq918q00hWfLtOs
zb15kFcjcEJ7kiRFJmAXZhcX2I0DHTmTZSl9orKzoUlXQqAANJGdek8pzdTDUQfz
V26k63d6eLqjXotrb0hFzg7B8VSolxRE44S5k1xhzUCedOqYYsWVv3xnRIP6UBPt
WLvzrLa0o9x/hT4w81dOP4rzZMuq2RApnenoz9AZwJrmZ14QW2ncy4RbqK6pKdRJ
y57vBv8F0LkGlLwBd/JYWwQ85lUTkNG5wCWdj0IEYTO3+fGyO1LHU6bVZCrNtkUE
ahSZUiRdidiktIkbtNXImYkCHAQQAQgABgUCTGRt2QAKCRATbpzxe100LaUfD/9D
q84HarIQMEoUiRBklg+afgTMaNNdvhU3V59KoMja2vMeE4JjE3SvNoKCHjPZj6Ti
720KL6V5O/Uo1VjtSXzAPRJywcE9aS5HRjM2Dr1mp5GnmpvbiKBdl91G9aPc3D2Z
LpG7vZr8E/vYLc5h1DMz2XDqi6gAqW2yxb2vnmHL4FiAdoXfpZimC9KZpUdTsGPO
VbXEDEn3y/AiIC35Bq66Sp3W4gVNakV7Y5RUPPDDBIsTZEOhzd9nl5FXOnPtONp5
dtp5NoWl6q3BjYe2P52TloCp+BJ62donfFTRSGfqyvtaRgmnHHEIWgypMghW6wSb
O/BxFpdggHTItMfBg2a8tWDFjYmBoFd3iP9SfcmBb/7zB5YXC5b1/s3RNCtR76hf
+iXjm/zy22tb6qy5XJsnCoORjEoFaWNH6ckgACK7HQyJZ2Lo2MuCYYaQLs6gTd6a
zMEQHT08cPF+I5It9mOzAtUOkCcVK8dIXRFETXFVdQqFMTmZmuK1Iv1CFBeUIHnM
iyoYv1bzNsUg/hJpW8ximVmBg5Apza2K0p3XKHkw9MPBqnQ4PbBM1nqb/+o56p+o
8mVZmjn4bdraB8c0Br15Mi19Zne7b65OZ5k+SVripUk5/XeJD9M9U6+DG+/uxemD
Fzp9XjnnAe8T/u8JpqHYQ2mRONFM7ZMOAFeEe4yIEIkBPgQTAQIAKAUCTGRtewIb
AwUJA8JnAAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQNQIA8rmZo3K3HAf/
V+6OSdt/Zwdsk+WsUwi75ndOIz60TN8Wg16WOMq5KOBuYIneG2+CEFJHTppNLc2j
r/ugTjTPeS/DAo5MtnK+zzHxT7JmMKypb23t6MaahSlER4THbYvWUwsw5mm2LsTe
PTlb5mkvQnXkt6pN2UzZVyIdNFXRv1YZLdTcf4aJ0pZySvCdYoE9RaoP4/JI9GfS
NXH7oOxI8YaxRGK5i6w/LZyhxkfbkPX+pbbe1Ept+SZCcwWVc/S6veGZWQ1pNHR2
RW6F3WE0Mle6xWtvW1NlMs4ATEqS13GS4RVlgE07KTe/oBRkd+4NwXAQoEzUvoRr
j5Ad7LVKeygeUUyaWP+qN7kBDQRMZG17AQgAypZBEfm9pM8Tr4ktsHp1xThYHvzT
OScLPZcCaF1Gjg8em0cQI4z4yN+yffsmUD4/dGcRxZgVms/jTexKQ8Z/Ps3e4vRG
b4RCFaY0KhW4t+TTJJ9I5wvFzXZj7zNFxiQWpueiq/cDiBY+Liv3zMSOBaXzxR6L
7igNPKi/0ELLyCIU/okUwqc0O/4r5PgFANkMyvvVNqzxjC5s8MXbGivJXiML67/Y
0M/siNqDSia/TGItpXjvi7v1zulbiIV0iSBkO3vsxNE0xXGBXY/UztAShN3FTbx9
CZDupi35wgqK7McJ3WSjEDzwkElmwkmh7JdLziyH09kS1wRqiLcB+wSTywARAQAB
iQElBBgBAgAPAhsMBQJVv8zOBQkSwWDOAAoJEDUCAPK5maNyLl4H/3n/+xZsuKia
fHtBUMh44YRabEX1Bd10LAfxGlOZtKV/Dr1RaKetci6RRa5sJj0wKra6FhIryuqS
jFTalPF3o8WjVEA5AjJ3ddSgAwX5gGJ3u+C0XMI0E6h/vAXh6meFxHtGinYr1Gcp
P1/S3/Jy+0cmTt3FvqBtXtU3VIyb/4vUNZ+dY+jcw/gs/yS+s+jtR8hWUDbSrbU9
pja+p1icNwU5pMbEfx1HYB7JCKuE0iJNbAFagRtPCOKq4vUTPDUQUB5MjWV+89+f
cizh+doQR9z8e+/02drCCMWiUf4iiFs2dNHwaIPDOJ8Xn9xcxiUaKk32sjT3sict
XO5tB2KhE3A=
=YO7C
-----END PGP PUBLIC KEY BLOCK-----
EOF
""")
cuisine.file_write("/etc/apt/sources.list.d/datastax.list", """
deb [arch=amd64] http://debian.datastax.com/community 2.0 main
""")
#self.repokey("https://debian.datastax.com/debian/repo_key")
def midonet(self):
# Install(self._metadata).apt_get_update()
if "OS_MIDOKURA_REPOSITORY_USER" in os.environ:
username = os.environ["OS_MIDOKURA_REPOSITORY_USER"]
else:
username = ""
if "OS_MIDOKURA_REPOSITORY_PASS" in os.environ:
password = os.environ["OS_MIDOKURA_REPOSITORY_PASS"]
else:
password = ""
if "midonet_repo" in self._metadata.config:
repo_flavor = self._metadata.config["midonet_repo"]
else:
repo_flavor = "OSS"
if "midonet_manager" in self._metadata.roles:
if env.host_string in self._metadata.roles["container_midonet_manager"]:
if username <> "":
if password <> "":
repo_flavor = "MEM"
if "OS_MIDOKURA_URL_OVERRIDE" in os.environ:
url_override = os.environ["OS_MIDOKURA_URL_OVERRIDE"]
else:
url_override = ""
if "OS_MIDOKURA_PLUGIN_URL_OVERRIDE" in os.environ:
plugin_url_override = os.environ["OS_MIDOKURA_PLUGIN_URL_OVERRIDE"]
else:
plugin_url_override = ""
puts(blue("setting up Midokura repos"))
run("""
if [[ "%s" == "True" ]] ; then set -x; fi
#
# initialize the password cache
#
%s
USERNAME="%s"
PASSWORD="%s"
MIDONET_VERSION="%s"
OPENSTACK_PLUGIN_VERSION="%s"
REPO_FLAVOR="%s"
URL_OVERRIDE="%s"
PLUGIN_URL_OVERRIDE="%s"
rm -fv -- /etc/apt/sources.list.d/midonet*
rm -fv -- /etc/apt/sources.list.d/midokura*
if [[ "${REPO_FLAVOR}" == "MEM" ]]; then
FILENAME="/etc/apt/sources.list.d/midokura.list"
wget -SO- "http://${USERNAME}:${PASSWORD}@apt.midokura.com/packages.midokura.key" | apt-key add -
if [[ "${URL_OVERRIDE}" == "" && "${PLUGIN_URL_OVERRIDE}" == "" ]]; then
cat>"${FILENAME}"<<EOF
#
# MEM midolman
#
deb [arch=amd64] http://${USERNAME}:${PASSWORD}@apt.midokura.com/midonet/v${MIDONET_VERSION}/stable trusty main non-free
#
# MEM midonet neutron plugin
#
deb [arch=amd64] http://${USERNAME}:${PASSWORD}@apt.midokura.com/openstack/${OPENSTACK_PLUGIN_VERSION}/stable trusty main
EOF
else
cat>"${FILENAME}"<<EOF
#
# MEM midolman (url override)
#
${URL_OVERRIDE}
#
# MEM midonet neutron plugin (plugin url override)
#
${PLUGIN_URL_OVERRIDE}
EOF
fi
fi
if [[ "${REPO_FLAVOR}" == "OSS" ]]; then
FILENAME="/etc/apt/sources.list.d/midonet.list"
wget -SO- http://repo.midonet.org/packages.midokura.key | apt-key add -
cat>"${FILENAME}"<<EOF
# OSS MidoNet
deb http://repo.midonet.org/midonet/v${MIDONET_VERSION} stable main
# OSS MidoNet OpenStack Integration
deb http://repo.midonet.org/openstack-${OPENSTACK_PLUGIN_VERSION} stable main
# OSS MidoNet 3rd Party Tools and Libraries
deb http://repo.midonet.org/misc stable main
EOF
fi
""" % (
self._metadata.config["debug"],
open(os.environ["PASSWORDCACHE"]).read(),
username,
password,
self._metadata.config["midonet_%s_version" % repo_flavor.lower()],
self._metadata.config["midonet_%s_openstack_plugin_version" % repo_flavor.lower()],
repo_flavor.upper(),
url_override,
plugin_url_override
))
def os_release(self):
if env.host_string in self._metadata.containers:
self.__lib_orizuru_operations_ubuntu_repo(self._metadata.config["container_os_release_codename"])
else:
self.__lib_orizuru_operations_ubuntu_repo(self._metadata.config["os_release_codename"])
def __lib_orizuru_operations_ubuntu_repo(self, codename):
archive_country = self._metadata.config["archive_country"]
apt_cacher = self._metadata.config["apt-cacher"]
run("""
if [[ "%s" == "True" ]] ; then set -x; fi
XC="%s" # ubuntu release
XD="%s" # country code
XX="%s" # apt-cacher
cat>/etc/apt/sources.list<<EOF
#
# autogenerated file - do not modify - modify %s instead
#
EOF
for TYPE in 'deb' 'deb-src'; do
for realm in "main restricted" "universe" "multiverse"; do
echo "${TYPE} ${XX}/${XD}.archive.ubuntu.com/ubuntu/ ${XC} ${realm}"
echo "${TYPE} ${XX}/${XD}.archive.ubuntu.com/ubuntu/ ${XC}-updates ${realm}"
echo "${TYPE} ${XX}/security.archive.ubuntu.com/ubuntu/ ${XC}-security ${realm}"
done
echo "${TYPE} ${XX}/${XD}.archive.ubuntu.com/ubuntu/ ${XC}-backports main restricted universe multiverse"
done | tee -a /etc/apt/sources.list
""" % (self._metadata.config["debug"], codename, archive_country, apt_cacher, sys._getframe().f_code.co_name))
class Install(object):
def __init__(self, metadata):
self._metadata = metadata
def install(self):
self.rsyslog()
self.screen()
self.login_stuff()
self.apt_get_update()
self.common_packages()
self.rp_filter()
self.cloud_repository()
self.apt_get_update()
self.ntp()
self.dist_upgrade()
self.constrictor()
self.kmod("openvswitch")
self.kmod("nbd")
self.kmod("kvm")
self.kmod("vhost_net")
self.lldpd()
def lldpd(self):
cuisine.package_ensure("lldpd")
def kmod(self, module_name):
if env.host_string not in self._metadata.roles["all_containers"]:
run("modprobe %s || true" % module_name)
def constrictor(self):
constrictor_bin = self._metadata.config["constrictor"]
run("mkdir -pv $(dirname %s)" % constrictor_bin)
cuisine.file_write(constrictor_bin, """#!/usr/bin/python -Werror
import sys
import ConfigParser
def add_section(configuration, section):
if not(section == 'DEFAULT' or configuration.has_section(section)):
configuration.add_section(section)
def set_option(configfile, configuration, section, option, value):
configuration.set(section, option, value)
cfgfile = open(configfile, "w")
configuration.write(cfgfile)
cfgfile.close()
def get_option(configuration, section, option):
print configuration.get(section, option)
def handle_command(args):
command = args[1]
configfile = args[2]
section = args[3]
option = args[4]
configuration = ConfigParser.RawConfigParser()
configuration.read(configfile)
if command == 'set':
value = args[5]
add_section(configuration, section)
set_option(configfile, configuration, section, option, value)
if command == 'get':
get_option(configuration, section, option)
return 0
if __name__ == "__main__":
sys.exit(handle_command(sys.argv))
""")
run("chmod 0755 %s" % constrictor_bin)
def screen(self):
screenrc_string = "%s.%s" % (env.host_string, self._metadata.config["domain"])
cuisine.package_ensure("screen")
run("""
mkdir -pv /var/run/screen
chmod 0755 /usr/bin/screen
chmod 0777 /var/run/screen
""")
cuisine.file_write("/root/.screenrc", """
hardstatus alwayslastline
hardstatus string '%%{= kG} %s [%%= %%{= kw}%%?%%-Lw%%?%%{r}[%%{W}%%n*%%f %%t%%?{%%u}%%?%%{r}]%%{w}%%?%%+Lw%%?%%?%%= %%{g}] %%{W}%%{g}%%{.w} screen %%{.c} [%%H]'
""" % screenrc_string)
@classmethod
def login_stuff(cls):
run("""
chmod 0755 /usr/bin/sudo
chmod u+s /usr/bin/sudo
""")
@classmethod
def apt_get_update(cls):
puts(yellow("updating repositories, this may take a long time."))
run("""
#
# Round 1: try to apt-get update without purging the cache
#
apt-get update 1>/dev/null
#
# Round 2: clean cache and update again
#
if [[ ! "${?}" == "0" ]]; then
rm -rf /var/lib/apt/lists/*
rm -f /etc/apt/apt.conf
sync
apt-get update 2>&1
fi
""")
def common_packages(self):
cuisine.package_ensure(self._metadata.config["common_packages"])
def rsyslog(self):
cuisine.package_ensure("rsyslog")
controller_name = self._metadata.roles["openstack_controller"][0]
controller_ip_suffix = self._metadata.config["idx"][controller_name]
controller_ip = "%s.%s" % (self._metadata.config["vpn_base"], controller_ip_suffix)
if env.host_string <> controller_name:
cuisine.file_write("/etc/rsyslog.conf", """
$KLogPermitNonKernelFacility on
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
$RepeatedMsgReduction on
$FileOwner syslog
$FileGroup adm
$FileCreateMode 0640
$DirCreateMode 0755
$Umask 0022
$PrivDropToUser syslog
$PrivDropToGroup syslog
$WorkDirectory /var/spool/rsyslog
$IncludeConfig /etc/rsyslog.d/*.conf
$ModLoad imuxsock
$ModLoad imklog
*.* @%s:514
*.* @@%s:514
""" % (controller_ip, controller_ip))
else:
cuisine.file_write("/etc/rsyslog.conf", """
$ModLoad imuxsock # provides support for local system logging
$ModLoad imklog # provides kernel logging support
$KLogPermitNonKernelFacility on
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
$RepeatedMsgReduction on
$FileOwner syslog
$FileGroup adm
$FileCreateMode 0640
$DirCreateMode 0755
$Umask 0022
$PrivDropToUser syslog
$PrivDropToGroup syslog
$WorkDirectory /var/spool/rsyslog
$IncludeConfig /etc/rsyslog.d/*.conf
$ModLoad imudp
$UDPServerRun 514
$template FILENAME,"/var/log/%fromhost-ip%/syslog.log"
*.* ?FILENAME
""")
run("service rsyslog restart")
run("logger ping")
def rp_filter(self):
#
# async routing traffic floating from neutron metadata/dhcp midonet agent to hypervisors and gateways
#
if 'physical_midonet_gateway' in self._metadata.roles or 'physical_openstack_compute' in self._metadata.roles:
if env.host_string not in self._metadata.containers:
run("""
for RP in /proc/sys/net/ipv4/conf/*/rp_filter; do
echo 0 > "${RP}"
done
""")
def cloud_repository(self):
run("rm -rf /etc/apt/sources.list.d/cloudarchive-*")
cuisine.package_ensure(["python-software-properties", "software-properties-common", "ubuntu-cloud-keyring"])
self.dist_upgrade()
if self._metadata.config["container_os_release_codename"] == "precise":
if self._metadata.config["openstack_release"] in ["icehouse", "juno"]:
run("add-apt-repository --yes cloud-archive:%s" % self._metadata.config["openstack_release"])
if self._metadata.config["container_os_release_codename"] == "trusty":
if self._metadata.config["openstack_release"] in ["juno", "kilo"]:
run("add-apt-repository --yes cloud-archive:%s" % self._metadata.config["openstack_release"])
run("""
OPENSTACK_RELEASE="%s"
APT_CACHER="%s"
SOURCES_LIST="/etc/apt/sources.list.d/cloudarchive-${OPENSTACK_RELEASE}.list"
test -f "${SOURCES_LIST}" && \
sed -i 's,http://ubuntu-cloud.archive.canonical.com,'"${APT_CACHER}"'/ubuntu-cloud.archive.canonical.com,g;' "${SOURCES_LIST}"
exit 0
""" % (
self._metadata.config["openstack_release"],
self._metadata.config["apt-cacher"]
))
self.dist_upgrade()
@classmethod
def dist_upgrade(cls):
run("""
export DEBIAN_FRONTEND=noninteractive
debconf-set-selections <<EOF
grub grub/update_grub_changeprompt_threeway select install_new
grub-legacy-ec2 grub/update_grub_changeprompt_threeway select install_new
EOF
yes | dpkg --configure -a
apt-get -y -u --force-yes install
apt-get -y -u --force-yes dist-upgrade 1>/dev/null
""")
run("apt-get clean")
run("""
export DEBIAN_FRONTEND=noninteractive
apt-get -y autoremove
""")
def ntp(self):
if env.host_string not in self._metadata.containers:
cuisine.package_ensure("ntpdate")
cuisine.package_ensure("ntp")
run("""
/etc/init.d/ntp stop || true
ln -sfv "/usr/share/zoneinfo/%s" /etc/localtime
ntpdate zeit.fu-berlin.de || true
/etc/init.d/ntp start || true
""" % self._metadata.config["timezone"])
|
apache-2.0
|
MattHubble/carbon
|
Source/Test/Xdt/Merge.cs
|
1981
|
// Copyright 2012 Aaron Jensen
//
// 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 Microsoft.Web.XmlTransform;
using System.Linq;
using System.Xml;
namespace Carbon.Test.Xdt
{
/// <summary>
/// https://github.com/appharbor/appharbor-transformtester/blob/master/AppHarbor.TransformTester/Transforms/Merge.cs
/// </summary>
public class Merge : Transform
{
public Merge() : base(TransformFlags.UseParentAsTargetNode)
{
}
protected override void Apply()
{
Apply((XmlElement)TargetNode, (XmlElement)TransformNode);
}
public void Apply(XmlElement targetElement, XmlElement transformElement)
{
var targetChildElement = targetElement.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.LocalName == transformElement.LocalName);
if (targetChildElement == null)
{
InsertTransformElement(targetElement, transformElement);
return;
}
foreach (var transformChildElement in transformElement.ChildNodes.OfType<XmlElement>())
{
Apply(targetChildElement, transformChildElement);
}
}
protected virtual void InsertTransformElement(XmlElement targetElement, XmlElement transformElement)
{
targetElement.AppendChild(transformElement);
}
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-redshiftdataapi/src/main/java/com/amazonaws/services/redshiftdataapi/model/transform/BatchExecuteStatementResultJsonUnmarshaller.java
|
4194
|
/*
* Copyright 2017-2022 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.redshiftdataapi.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.redshiftdataapi.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* BatchExecuteStatementResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BatchExecuteStatementResultJsonUnmarshaller implements Unmarshaller<BatchExecuteStatementResult, JsonUnmarshallerContext> {
public BatchExecuteStatementResult unmarshall(JsonUnmarshallerContext context) throws Exception {
BatchExecuteStatementResult batchExecuteStatementResult = new BatchExecuteStatementResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return batchExecuteStatementResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("ClusterIdentifier", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setClusterIdentifier(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("CreatedAt", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setCreatedAt(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("Database", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setDatabase(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DbUser", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setDbUser(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Id", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("SecretArn", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setSecretArn(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return batchExecuteStatementResult;
}
private static BatchExecuteStatementResultJsonUnmarshaller instance;
public static BatchExecuteStatementResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new BatchExecuteStatementResultJsonUnmarshaller();
return instance;
}
}
|
apache-2.0
|
PENGUINLIONG/GaLiong
|
GaLiong/Bmp.cpp
|
2500
|
//
// Bitmap.hpp
// GaLiong
//
// Created by Liong on ??/??/??.
//
#include "Include/Bmp.hpp"
_L_BEGIN
namespace Media
{
// Public
Bmp::Bmp(Image& instance)
{
}
Bmp::~Bmp()
{
}
bool Bmp::InitHeader()
{
FileHeader f;
InfoHeader i;
stream.read((char *)&f, sizeof(FileHeader));
if (f.Type != 0x4D42)
return false;
stream.read((char *)&i, sizeof(InfoHeader));
if (i.BitCount != 24)
return false;
size = { i.Width, i.Height };
length = i.Width * i.Height * 3;
stream.seekg(f.OffBits, stream.beg);
return true;
}
Buffer Bmp::ReadData(BufferLength length)
{
Buffer data = new Byte[length]; // NEED TO BE DELETED.
stream.read((char *)data, length);
return data;
}
TextureRef Bmp::ToTexture(wchar_t *path, Flag option)
{
Log << L"Bmp: Try loading " << path << L"...";
if (stream.is_open())
stream.close();
stream.open(path, stream.in | stream.binary | stream._Nocreate);
TextureRef ref;
Size size;
BufferLength dataLength;
if (InitHeader(size, dataLength))
{
Buffer data = ReadData(dataLength);
if (!data)
return TextureRef();
ref = TextureManager.NewTexture(dataLength, data, size, Texture::PixelFormat::BGR, Texture::ByteSize::UByte);
if ((option & FileReadOption::NoGenerate) == FileReadOption::None)
ref.lock()->Generate();
}
else
{
Log.Log((L"Bmp: Failed in loading " + wstring(path) + L"!").c_str(), Logger::WarningLevel::Warn);
return TextureRef();
}
if ((option & FileReadOption::NoClose) == FileReadOption::None)
stream.close();
Log << L"Bmp: Succeeded!";
return ref;
}
// Derived from [LiongFramework::Media::Image]
Buffer Bmp::GetChunk(Point position, Size size)
{
return _Bitmap::GetChunk(position, size);
}
BufferLength Bmp::GetInterpretedLength(PixelType pixelType)
{
return _Bitmap.GetInterpretedLength(pixelType);
}
Byte* Bmp::GetPixel(Point position)
{
return _Bitmap.GetPixel(position);
}
Size Bmp::GetSize()
{
return _Bitmap.GetSize();
}
bool Bmp::IsEmpty()
{
return _Bitmap.IsEmpty();
}
Buffer Bmp::Interpret(PixelType pixelType)
{
return _Bitmap.Interpret(pixelType);
}
}
_L_END
|
apache-2.0
|
tonywu522/biu_server
|
doc/api/classes/ActionDispatch/Cookies/VerifyAndUpgradeLegacySignedMessage.html
|
7516
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ActionDispatch::Cookies::VerifyAndUpgradeLegacySignedMessage</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />
<script src="../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.2.1</span><br />
<h1>
<span class="type">Module</span>
ActionDispatch::Cookies::VerifyAndUpgradeLegacySignedMessage
</h1>
<ul class="files">
<li><a href="../../../files/__/__/__/_rbenv/versions/2_2_1/lib/ruby/gems/2_2_0/gems/actionpack-4_2_1/lib/action_dispatch/middleware/cookies_rb.html">/Users/tony/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/cookies.rb</a></li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<div class="description">
<p>Passing the ActiveSupport::MessageEncryptor::NullSerializer downstream to
the Message{Encryptor,Verifier} allows us to handle the (de)serialization
step within the cookie jar, which gives us the opportunity to detect and
migrate legacy cookies.</p>
</div>
<!-- Method ref -->
<div class="sectiontitle">Methods</div>
<dl class="methods">
<dt>N</dt>
<dd>
<ul>
<li>
<a href="#method-c-new">new</a>
</li>
</ul>
</dd>
<dt>V</dt>
<dd>
<ul>
<li>
<a href="#method-i-verify_and_upgrade_legacy_signed_message">verify_and_upgrade_legacy_signed_message</a>
</li>
</ul>
</dd>
</dl>
<!-- Methods -->
<div class="sectiontitle">Class Public methods</div>
<div class="method">
<div class="title method-title" id="method-c-new">
<b>new</b>(*args)
<a href="../../../classes/ActionDispatch/Cookies/VerifyAndUpgradeLegacySignedMessage.html#method-c-new" name="method-c-new" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-c-new_source')" id="l_method-c-new_source">show</a>
</p>
<div id="method-c-new_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/cookies.rb, line 185</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">initialize</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">args</span>)
<span class="ruby-keyword">super</span>
<span class="ruby-ivar">@legacy_verifier</span> = <span class="ruby-constant">ActiveSupport</span><span class="ruby-operator">::</span><span class="ruby-constant">MessageVerifier</span>.<span class="ruby-identifier">new</span>(<span class="ruby-ivar">@options</span>[<span class="ruby-value">:secret_token</span>], <span class="ruby-identifier">serializer</span><span class="ruby-operator">:</span> <span class="ruby-constant">ActiveSupport</span><span class="ruby-operator">::</span><span class="ruby-constant">MessageEncryptor</span><span class="ruby-operator">::</span><span class="ruby-constant">NullSerializer</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="sectiontitle">Instance Public methods</div>
<div class="method">
<div class="title method-title" id="method-i-verify_and_upgrade_legacy_signed_message">
<b>verify_and_upgrade_legacy_signed_message</b>(name, signed_message)
<a href="../../../classes/ActionDispatch/Cookies/VerifyAndUpgradeLegacySignedMessage.html#method-i-verify_and_upgrade_legacy_signed_message" name="method-i-verify_and_upgrade_legacy_signed_message" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-verify_and_upgrade_legacy_signed_message_source')" id="l_method-i-verify_and_upgrade_legacy_signed_message_source">show</a>
</p>
<div id="method-i-verify_and_upgrade_legacy_signed_message_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/cookies.rb, line 190</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">verify_and_upgrade_legacy_signed_message</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">signed_message</span>)
<span class="ruby-identifier">deserialize</span>(<span class="ruby-identifier">name</span>, <span class="ruby-ivar">@legacy_verifier</span>.<span class="ruby-identifier">verify</span>(<span class="ruby-identifier">signed_message</span>)).<span class="ruby-identifier">tap</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">value</span><span class="ruby-operator">|</span>
<span class="ruby-keyword">self</span>[<span class="ruby-identifier">name</span>] = { <span class="ruby-identifier">value</span><span class="ruby-operator">:</span> <span class="ruby-identifier">value</span> }
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">rescue</span> <span class="ruby-constant">ActiveSupport</span><span class="ruby-operator">::</span><span class="ruby-constant">MessageVerifier</span><span class="ruby-operator">::</span><span class="ruby-constant">InvalidSignature</span>
<span class="ruby-keyword">nil</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Onagraceae/Oenothera/Oenothera auricula/Oenothera auricula williamsoni/README.md
|
197
|
# Oenothera auricula subvar. williamsoni Levl. SUBVARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
elisska/cloudera-cassandra
|
DATASTAX_CASSANDRA-2.2.6/javadoc/org/apache/cassandra/utils/memory/MemtableAllocator.html
|
23224
|
<!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 (version 1.7.0_51) on Thu Apr 28 18:37:25 UTC 2016 -->
<title>MemtableAllocator (apache-cassandra API)</title>
<meta name="date" content="2016-04-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="MemtableAllocator (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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/MemtableAllocator.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>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/utils/memory/MemoryUtil.html" title="class in org.apache.cassandra.utils.memory"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.DataReclaimer.html" title="interface in org.apache.cassandra.utils.memory"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/utils/memory/MemtableAllocator.html" target="_top">Frames</a></li>
<li><a href="MemtableAllocator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All 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: </li>
<li><a href="#nested_class_summary">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li>Constr | </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.apache.cassandra.utils.memory</div>
<h2 title="Class MemtableAllocator" class="title">Class MemtableAllocator</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.utils.memory.MemtableAllocator</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../../../../org/apache/cassandra/utils/memory/MemtableBufferAllocator.html" title="class in org.apache.cassandra.utils.memory">MemtableBufferAllocator</a>, <a href="../../../../../org/apache/cassandra/utils/memory/NativeAllocator.html" title="class in org.apache.cassandra.utils.memory">NativeAllocator</a></dd>
</dl>
<hr>
<br>
<pre>public abstract class <span class="strong">MemtableAllocator</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static interface </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.DataReclaimer.html" title="interface in org.apache.cassandra.utils.memory">MemtableAllocator.DataReclaimer</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.SubAllocator.html" title="class in org.apache.cassandra.utils.memory">MemtableAllocator.SubAllocator</a></strong></code>
<div class="block">Mark the BB as unused, permitting it to be reclaimed</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.DataReclaimer.html" title="interface in org.apache.cassandra.utils.memory">MemtableAllocator.DataReclaimer</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#NO_OP">NO_OP</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../../org/apache/cassandra/db/Cell.html" title="interface in org.apache.cassandra.db">Cell</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#clone(org.apache.cassandra.db.Cell, org.apache.cassandra.config.CFMetaData, org.apache.cassandra.utils.concurrent.OpOrder.Group)">clone</a></strong>(<a href="../../../../../org/apache/cassandra/db/Cell.html" title="interface in org.apache.cassandra.db">Cell</a> cell,
<a href="../../../../../org/apache/cassandra/config/CFMetaData.html" title="class in org.apache.cassandra.config">CFMetaData</a> cfm,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> writeOp)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract <a href="../../../../../org/apache/cassandra/db/CounterCell.html" title="interface in org.apache.cassandra.db">CounterCell</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#clone(org.apache.cassandra.db.CounterCell, org.apache.cassandra.config.CFMetaData, org.apache.cassandra.utils.concurrent.OpOrder.Group)">clone</a></strong>(<a href="../../../../../org/apache/cassandra/db/CounterCell.html" title="interface in org.apache.cassandra.db">CounterCell</a> cell,
<a href="../../../../../org/apache/cassandra/config/CFMetaData.html" title="class in org.apache.cassandra.config">CFMetaData</a> cfm,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> writeOp)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../../org/apache/cassandra/db/DecoratedKey.html" title="class in org.apache.cassandra.db">DecoratedKey</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#clone(org.apache.cassandra.db.DecoratedKey, org.apache.cassandra.utils.concurrent.OpOrder.Group)">clone</a></strong>(<a href="../../../../../org/apache/cassandra/db/DecoratedKey.html" title="class in org.apache.cassandra.db">DecoratedKey</a> key,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> opGroup)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract <a href="../../../../../org/apache/cassandra/db/DeletedCell.html" title="interface in org.apache.cassandra.db">DeletedCell</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#clone(org.apache.cassandra.db.DeletedCell, org.apache.cassandra.config.CFMetaData, org.apache.cassandra.utils.concurrent.OpOrder.Group)">clone</a></strong>(<a href="../../../../../org/apache/cassandra/db/DeletedCell.html" title="interface in org.apache.cassandra.db">DeletedCell</a> cell,
<a href="../../../../../org/apache/cassandra/config/CFMetaData.html" title="class in org.apache.cassandra.config">CFMetaData</a> cfm,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> writeOp)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../../org/apache/cassandra/db/ExpiringCell.html" title="interface in org.apache.cassandra.db">ExpiringCell</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#clone(org.apache.cassandra.db.ExpiringCell, org.apache.cassandra.config.CFMetaData, org.apache.cassandra.utils.concurrent.OpOrder.Group)">clone</a></strong>(<a href="../../../../../org/apache/cassandra/db/ExpiringCell.html" title="interface in org.apache.cassandra.db">ExpiringCell</a> cell,
<a href="../../../../../org/apache/cassandra/config/CFMetaData.html" title="class in org.apache.cassandra.config">CFMetaData</a> cfm,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> writeOp)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#isLive()">isLive</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.SubAllocator.html" title="class in org.apache.cassandra.utils.memory">MemtableAllocator.SubAllocator</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#offHeap()">offHeap</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.SubAllocator.html" title="class in org.apache.cassandra.utils.memory">MemtableAllocator.SubAllocator</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#onHeap()">onHeap</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.DataReclaimer.html" title="interface in org.apache.cassandra.utils.memory">MemtableAllocator.DataReclaimer</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#reclaimer()">reclaimer</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#setDiscarded()">setDiscarded</a></strong>()</code>
<div class="block">Indicate the memory and resources owned by this allocator are no longer referenced,
and can be reclaimed/reused.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.html#setDiscarding()">setDiscarding</a></strong>()</code>
<div class="block">Mark this allocator reclaiming; this will permit any outstanding allocations to temporarily
overshoot the maximum memory limit so that flushing can begin immediately</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="NO_OP">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>NO_OP</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.DataReclaimer.html" title="interface in org.apache.cassandra.utils.memory">MemtableAllocator.DataReclaimer</a> NO_OP</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="clone(org.apache.cassandra.db.Cell, org.apache.cassandra.config.CFMetaData, org.apache.cassandra.utils.concurrent.OpOrder.Group)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clone</h4>
<pre>public abstract <a href="../../../../../org/apache/cassandra/db/Cell.html" title="interface in org.apache.cassandra.db">Cell</a> clone(<a href="../../../../../org/apache/cassandra/db/Cell.html" title="interface in org.apache.cassandra.db">Cell</a> cell,
<a href="../../../../../org/apache/cassandra/config/CFMetaData.html" title="class in org.apache.cassandra.config">CFMetaData</a> cfm,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> writeOp)</pre>
</li>
</ul>
<a name="clone(org.apache.cassandra.db.CounterCell, org.apache.cassandra.config.CFMetaData, org.apache.cassandra.utils.concurrent.OpOrder.Group)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clone</h4>
<pre>public abstract <a href="../../../../../org/apache/cassandra/db/CounterCell.html" title="interface in org.apache.cassandra.db">CounterCell</a> clone(<a href="../../../../../org/apache/cassandra/db/CounterCell.html" title="interface in org.apache.cassandra.db">CounterCell</a> cell,
<a href="../../../../../org/apache/cassandra/config/CFMetaData.html" title="class in org.apache.cassandra.config">CFMetaData</a> cfm,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> writeOp)</pre>
</li>
</ul>
<a name="clone(org.apache.cassandra.db.DeletedCell, org.apache.cassandra.config.CFMetaData, org.apache.cassandra.utils.concurrent.OpOrder.Group)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clone</h4>
<pre>public abstract <a href="../../../../../org/apache/cassandra/db/DeletedCell.html" title="interface in org.apache.cassandra.db">DeletedCell</a> clone(<a href="../../../../../org/apache/cassandra/db/DeletedCell.html" title="interface in org.apache.cassandra.db">DeletedCell</a> cell,
<a href="../../../../../org/apache/cassandra/config/CFMetaData.html" title="class in org.apache.cassandra.config">CFMetaData</a> cfm,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> writeOp)</pre>
</li>
</ul>
<a name="clone(org.apache.cassandra.db.ExpiringCell, org.apache.cassandra.config.CFMetaData, org.apache.cassandra.utils.concurrent.OpOrder.Group)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clone</h4>
<pre>public abstract <a href="../../../../../org/apache/cassandra/db/ExpiringCell.html" title="interface in org.apache.cassandra.db">ExpiringCell</a> clone(<a href="../../../../../org/apache/cassandra/db/ExpiringCell.html" title="interface in org.apache.cassandra.db">ExpiringCell</a> cell,
<a href="../../../../../org/apache/cassandra/config/CFMetaData.html" title="class in org.apache.cassandra.config">CFMetaData</a> cfm,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> writeOp)</pre>
</li>
</ul>
<a name="clone(org.apache.cassandra.db.DecoratedKey, org.apache.cassandra.utils.concurrent.OpOrder.Group)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clone</h4>
<pre>public abstract <a href="../../../../../org/apache/cassandra/db/DecoratedKey.html" title="class in org.apache.cassandra.db">DecoratedKey</a> clone(<a href="../../../../../org/apache/cassandra/db/DecoratedKey.html" title="class in org.apache.cassandra.db">DecoratedKey</a> key,
<a href="../../../../../org/apache/cassandra/utils/concurrent/OpOrder.Group.html" title="class in org.apache.cassandra.utils.concurrent">OpOrder.Group</a> opGroup)</pre>
</li>
</ul>
<a name="reclaimer()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>reclaimer</h4>
<pre>public abstract <a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.DataReclaimer.html" title="interface in org.apache.cassandra.utils.memory">MemtableAllocator.DataReclaimer</a> reclaimer()</pre>
</li>
</ul>
<a name="onHeap()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>onHeap</h4>
<pre>public <a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.SubAllocator.html" title="class in org.apache.cassandra.utils.memory">MemtableAllocator.SubAllocator</a> onHeap()</pre>
</li>
</ul>
<a name="offHeap()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>offHeap</h4>
<pre>public <a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.SubAllocator.html" title="class in org.apache.cassandra.utils.memory">MemtableAllocator.SubAllocator</a> offHeap()</pre>
</li>
</ul>
<a name="setDiscarding()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDiscarding</h4>
<pre>public void setDiscarding()</pre>
<div class="block">Mark this allocator reclaiming; this will permit any outstanding allocations to temporarily
overshoot the maximum memory limit so that flushing can begin immediately</div>
</li>
</ul>
<a name="setDiscarded()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDiscarded</h4>
<pre>public void setDiscarded()</pre>
<div class="block">Indicate the memory and resources owned by this allocator are no longer referenced,
and can be reclaimed/reused.</div>
</li>
</ul>
<a name="isLive()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isLive</h4>
<pre>public boolean isLive()</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><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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/MemtableAllocator.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>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/utils/memory/MemoryUtil.html" title="class in org.apache.cassandra.utils.memory"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/cassandra/utils/memory/MemtableAllocator.DataReclaimer.html" title="interface in org.apache.cassandra.utils.memory"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/utils/memory/MemtableAllocator.html" target="_top">Frames</a></li>
<li><a href="MemtableAllocator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All 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: </li>
<li><a href="#nested_class_summary">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li>Constr | </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 © 2016 The Apache Software Foundation</small></p>
</body>
</html>
|
apache-2.0
|
AKSahu/WebAutomationFrameworks
|
SeleniumUIAutoTest/src/coreaf/ui/pages/HomePage.java
|
53
|
package coreaf.ui.pages;
public class HomePage {
}
|
apache-2.0
|
root0301/MyMap
|
app/src/main/java/com/wjc/slience/mymap/activity/MsgActivity.java
|
1450
|
package com.wjc.slience.mymap.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import com.wjc.slience.mymap.R;
import com.wjc.slience.mymap.common.ActivityCollector;
import com.wjc.slience.mymap.common.LogUtil;
import com.wjc.slience.mymap.db.MyMapDB;
import com.wjc.slience.mymap.model.Way;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
/**
* 日志信息页面显示
*/
public class MsgActivity extends Activity {
TextView msg;
String msgTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg);
//ActivityCollector.getInstance().addActivity(this);
msg = (TextView) findViewById(R.id.msg);
msgTxt = LogUtil.getInstance().readTheTrip();
msg.setText(msgTxt);
}
@Override
protected void onResume() {
super.onResume();
msgTxt = LogUtil.getInstance().readTheTrip();
msg.setText(msgTxt);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(MsgActivity.this,ChooseActivity.class);
startActivity(intent);
finish();
}
return super.onKeyDown(keyCode, event);
}
}
|
apache-2.0
|
sivaprasadreddy/springboot-learn-by-example
|
chapter-13/springboot-thymeleaf-security-demo/src/main/java/com/sivalabs/demo/security/AuthenticatedUser.java
|
1192
|
/**
*
*/
package com.sivalabs.demo.security;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import com.sivalabs.demo.entities.Role;
import com.sivalabs.demo.entities.User;
/**
* @author Siva
*
*/
public class AuthenticatedUser extends org.springframework.security.core.userdetails.User
{
private static final long serialVersionUID = 1L;
private User user;
public AuthenticatedUser(User user)
{
super(user.getEmail(), user.getPassword(), getAuthorities(user));
this.user = user;
}
public User getUser()
{
return user;
}
private static Collection<? extends GrantedAuthority> getAuthorities(User user)
{
Set<String> roleAndPermissions = new HashSet<>();
List<Role> roles = user.getRoles();
for (Role role : roles)
{
roleAndPermissions.add(role.getName());
}
String[] roleNames = new String[roleAndPermissions.size()];
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roleAndPermissions.toArray(roleNames));
return authorities;
}
}
|
apache-2.0
|
utsaslab/crashmonkey
|
code/tests/seq1/j-lang138.cpp
|
3828
|
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <dirent.h>
#include <cstring>
#include <errno.h>
#include <attr/xattr.h>
#include "../BaseTestCase.h"
#include "../../user_tools/api/workload.h"
#include "../../user_tools/api/actions.h"
using fs_testing::tests::DataTestResult;
using fs_testing::user_tools::api::WriteData;
using fs_testing::user_tools::api::WriteDataMmap;
using fs_testing::user_tools::api::Checkpoint;
using std::string;
#define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO))
namespace fs_testing {
namespace tests {
class testName: public BaseTestCase {
public:
virtual int setup() override {
test_path = mnt_dir_ ;
A_path = mnt_dir_ + "/A";
AC_path = mnt_dir_ + "/A/C";
B_path = mnt_dir_ + "/B";
foo_path = mnt_dir_ + "/foo";
bar_path = mnt_dir_ + "/bar";
Afoo_path = mnt_dir_ + "/A/foo";
Abar_path = mnt_dir_ + "/A/bar";
Bfoo_path = mnt_dir_ + "/B/foo";
Bbar_path = mnt_dir_ + "/B/bar";
ACfoo_path = mnt_dir_ + "/A/C/foo";
ACbar_path = mnt_dir_ + "/A/C/bar";
return 0;
}
virtual int run( int checkpoint ) override {
test_path = mnt_dir_ ;
A_path = mnt_dir_ + "/A";
AC_path = mnt_dir_ + "/A/C";
B_path = mnt_dir_ + "/B";
foo_path = mnt_dir_ + "/foo";
bar_path = mnt_dir_ + "/bar";
Afoo_path = mnt_dir_ + "/A/foo";
Abar_path = mnt_dir_ + "/A/bar";
Bfoo_path = mnt_dir_ + "/B/foo";
Bbar_path = mnt_dir_ + "/B/bar";
ACfoo_path = mnt_dir_ + "/A/C/foo";
ACbar_path = mnt_dir_ + "/A/C/bar";
int local_checkpoint = 0 ;
int fd_foo = cm_->CmOpen(foo_path.c_str() , O_RDWR|O_CREAT , 0777);
if ( fd_foo < 0 ) {
cm_->CmClose( fd_foo);
return errno;
}
if ( WriteData ( fd_foo, 0, 32768) < 0){
cm_->CmClose( fd_foo);
return errno;
}
if ( WriteData ( fd_foo, 0, 5000) < 0){
cm_->CmClose( fd_foo);
return errno;
}
if ( cm_->CmFsync( fd_foo) < 0){
return errno;
}
if ( cm_->CmCheckpoint() < 0){
return -1;
}
local_checkpoint += 1;
if (local_checkpoint == checkpoint) {
return 1;
}
if ( cm_->CmClose ( fd_foo) < 0){
return errno;
}
return 0;
}
virtual int check_test( unsigned int last_checkpoint, DataTestResult *test_result) override {
test_path = mnt_dir_ ;
A_path = mnt_dir_ + "/A";
AC_path = mnt_dir_ + "/A/C";
B_path = mnt_dir_ + "/B";
foo_path = mnt_dir_ + "/foo";
bar_path = mnt_dir_ + "/bar";
Afoo_path = mnt_dir_ + "/A/foo";
Abar_path = mnt_dir_ + "/A/bar";
Bfoo_path = mnt_dir_ + "/B/foo";
Bbar_path = mnt_dir_ + "/B/bar";
ACfoo_path = mnt_dir_ + "/A/C/foo";
ACbar_path = mnt_dir_ + "/A/C/bar";
return 0;
}
private:
string test_path;
string A_path;
string AC_path;
string B_path;
string foo_path;
string bar_path;
string Afoo_path;
string Abar_path;
string Bfoo_path;
string Bbar_path;
string ACfoo_path;
string ACbar_path;
};
} // namespace tests
} // namespace fs_testing
extern "C" fs_testing::tests::BaseTestCase *test_case_get_instance() {
return new fs_testing::tests::testName;
}
extern "C" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) {
delete tc;
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Bryophyta/Bryopsida/Funariales/Funariaceae/Entosthodon/Entosthodon usambaricus/README.md
|
193
|
# Entosthodon usambaricus Paris, 1896 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
ijuma/kafka
|
clients/src/main/java/org/apache/kafka/common/utils/ByteUtils.java
|
11546
|
/*
* 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.kafka.common.utils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
/**
* This classes exposes low-level methods for reading/writing from byte streams or buffers.
*/
public final class ByteUtils {
private ByteUtils() {}
/**
* Read an unsigned integer from the given position without modifying the buffers position
*
* @param buffer the buffer to read from
* @param index the index from which to read the integer
* @return The integer read, as a long to avoid signedness
*/
public static long readUnsignedInt(ByteBuffer buffer, int index) {
return buffer.getInt(index) & 0xffffffffL;
}
/**
* Read an unsigned integer stored in little-endian format from the {@link InputStream}.
*
* @param in The stream to read from
* @return The integer read (MUST BE TREATED WITH SPECIAL CARE TO AVOID SIGNEDNESS)
*/
public static int readUnsignedIntLE(InputStream in) throws IOException {
return in.read()
| (in.read() << 8)
| (in.read() << 16)
| (in.read() << 24);
}
/**
* Read an unsigned integer stored in little-endian format from a byte array
* at a given offset.
*
* @param buffer The byte array to read from
* @param offset The position in buffer to read from
* @return The integer read (MUST BE TREATED WITH SPECIAL CARE TO AVOID SIGNEDNESS)
*/
public static int readUnsignedIntLE(byte[] buffer, int offset) {
return (buffer[offset] << 0 & 0xff)
| ((buffer[offset + 1] & 0xff) << 8)
| ((buffer[offset + 2] & 0xff) << 16)
| ((buffer[offset + 3] & 0xff) << 24);
}
/**
* Write the given long value as a 4 byte unsigned integer. Overflow is ignored.
*
* @param buffer The buffer to write to
* @param index The position in the buffer at which to begin writing
* @param value The value to write
*/
public static void writeUnsignedInt(ByteBuffer buffer, int index, long value) {
buffer.putInt(index, (int) (value & 0xffffffffL));
}
/**
* Write the given long value as a 4 byte unsigned integer. Overflow is ignored.
*
* @param buffer The buffer to write to
* @param value The value to write
*/
public static void writeUnsignedInt(ByteBuffer buffer, long value) {
buffer.putInt((int) (value & 0xffffffffL));
}
/**
* Write an unsigned integer in little-endian format to the {@link OutputStream}.
*
* @param out The stream to write to
* @param value The value to write
*/
public static void writeUnsignedIntLE(OutputStream out, int value) throws IOException {
out.write(value);
out.write(value >>> 8);
out.write(value >>> 16);
out.write(value >>> 24);
}
/**
* Write an unsigned integer in little-endian format to a byte array
* at a given offset.
*
* @param buffer The byte array to write to
* @param offset The position in buffer to write to
* @param value The value to write
*/
public static void writeUnsignedIntLE(byte[] buffer, int offset, int value) {
buffer[offset] = (byte) value;
buffer[offset + 1] = (byte) (value >>> 8);
buffer[offset + 2] = (byte) (value >>> 16);
buffer[offset + 3] = (byte) (value >>> 24);
}
/**
* Read an integer stored in variable-length format using zig-zag decoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>.
*
* @param buffer The buffer to read from
* @return The integer read
*
* @throws IllegalArgumentException if variable-length value does not terminate after 5 bytes have been read
*/
public static int readVarint(ByteBuffer buffer) {
int value = 0;
int i = 0;
int b;
while (((b = buffer.get()) & 0x80) != 0) {
value |= (b & 0x7f) << i;
i += 7;
if (i > 28)
throw illegalVarintException(value);
}
value |= b << i;
return (value >>> 1) ^ -(value & 1);
}
/**
* Read an integer stored in variable-length format using zig-zag decoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>.
*
* @param in The input to read from
* @return The integer read
*
* @throws IllegalArgumentException if variable-length value does not terminate after 5 bytes have been read
* @throws IOException if {@link DataInput} throws {@link IOException}
*/
public static int readVarint(DataInput in) throws IOException {
int value = 0;
int i = 0;
int b;
while (((b = in.readByte()) & 0x80) != 0) {
value |= (b & 0x7f) << i;
i += 7;
if (i > 28)
throw illegalVarintException(value);
}
value |= b << i;
return (value >>> 1) ^ -(value & 1);
}
/**
* Read a long stored in variable-length format using zig-zag decoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>.
*
* @param in The input to read from
* @return The long value read
*
* @throws IllegalArgumentException if variable-length value does not terminate after 10 bytes have been read
* @throws IOException if {@link DataInput} throws {@link IOException}
*/
public static long readVarlong(DataInput in) throws IOException {
long value = 0L;
int i = 0;
long b;
while (((b = in.readByte()) & 0x80) != 0) {
value |= (b & 0x7f) << i;
i += 7;
if (i > 63)
throw illegalVarlongException(value);
}
value |= b << i;
return (value >>> 1) ^ -(value & 1);
}
/**
* Read a long stored in variable-length format using zig-zag decoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>.
*
* @param buffer The buffer to read from
* @return The long value read
*
* @throws IllegalArgumentException if variable-length value does not terminate after 10 bytes have been read
*/
public static long readVarlong(ByteBuffer buffer) {
long value = 0L;
int i = 0;
long b;
while (((b = buffer.get()) & 0x80) != 0) {
value |= (b & 0x7f) << i;
i += 7;
if (i > 63)
throw illegalVarlongException(value);
}
value |= b << i;
return (value >>> 1) ^ -(value & 1);
}
/**
* Write the given integer following the variable-length zig-zag encoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>
* into the output.
*
* @param value The value to write
* @param out The output to write to
*/
public static void writeVarint(int value, DataOutput out) throws IOException {
int v = (value << 1) ^ (value >> 31);
while ((v & 0xffffff80) != 0L) {
out.writeByte((v & 0x7f) | 0x80);
v >>>= 7;
}
out.writeByte((byte) v);
}
/**
* Write the given integer following the variable-length zig-zag encoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>
* into the buffer.
*
* @param value The value to write
* @param buffer The output to write to
*/
public static void writeVarint(int value, ByteBuffer buffer) {
int v = (value << 1) ^ (value >> 31);
while ((v & 0xffffff80) != 0L) {
byte b = (byte) ((v & 0x7f) | 0x80);
buffer.put(b);
v >>>= 7;
}
buffer.put((byte) v);
}
/**
* Write the given integer following the variable-length zig-zag encoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>
* into the output.
*
* @param value The value to write
* @param out The output to write to
*/
public static void writeVarlong(long value, DataOutput out) throws IOException {
long v = (value << 1) ^ (value >> 63);
while ((v & 0xffffffffffffff80L) != 0L) {
out.writeByte(((int) v & 0x7f) | 0x80);
v >>>= 7;
}
out.writeByte((byte) v);
}
/**
* Write the given integer following the variable-length zig-zag encoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>
* into the buffer.
*
* @param value The value to write
* @param buffer The buffer to write to
*/
public static void writeVarlong(long value, ByteBuffer buffer) {
long v = (value << 1) ^ (value >> 63);
while ((v & 0xffffffffffffff80L) != 0L) {
byte b = (byte) ((v & 0x7f) | 0x80);
buffer.put(b);
v >>>= 7;
}
buffer.put((byte) v);
}
/**
* Number of bytes needed to encode an integer in variable-length format.
*
* @param value The signed value
*/
public static int sizeOfVarint(int value) {
int v = (value << 1) ^ (value >> 31);
int bytes = 1;
while ((v & 0xffffff80) != 0L) {
bytes += 1;
v >>>= 7;
}
return bytes;
}
/**
* Number of bytes needed to encode a long in variable-length format.
*
* @param value The signed value
*/
public static int sizeOfVarlong(long value) {
long v = (value << 1) ^ (value >> 63);
int bytes = 1;
while ((v & 0xffffffffffffff80L) != 0L) {
bytes += 1;
v >>>= 7;
}
return bytes;
}
private static IllegalArgumentException illegalVarintException(int value) {
throw new IllegalArgumentException("Varint is too long, the most significant bit in the 5th byte is set, " +
"converted value: " + Integer.toHexString(value));
}
private static IllegalArgumentException illegalVarlongException(long value) {
throw new IllegalArgumentException("Varlong is too long, most significant bit in the 10th byte is set, " +
"converted value: " + Long.toHexString(value));
}
}
|
apache-2.0
|
training4developers/angular_11162015
|
app/www/index_filters.html
|
1265
|
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Angular.js</title>
<script src="/libs/jquery/dist/jquery.js"></script>
<script src="/libs/angular/angular.js"></script>
</head>
<body>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
{{message | higUpperCase | higAppend:'!!!!!!!'}}
<ul>
<li ng-repeat="color in colors | strlen:5">{{color}}</li>
</ul>
</div>
</div>
<script>
angular.module("MyApp", [])
.filter("strlen", function() {
return function(list, minLength,scope) {
console.dir(scope);
return list.filter(function(item) {
return String(item).length >= minLength;
});
}
})
.filter("higUpperCase", function() {
return function(value) {
return String(value).toUpperCase();
};
})
.filter("higAppend", function() {
return function(value, strToAppend) {
return String(value) + String(strToAppend)
};
})
.controller("MyCtrl", function($scope, $filter) {
$scope.message = "Hi Everyone";
$scope.colors = ["red","brown","black","blue","green","orange"];
var higUpperCaseFilter = $filter("higUpperCase");
console.log(higUpperCaseFilter("Hi Everyone!"));
});
</script>
</body>
</html>
|
apache-2.0
|
alexhersh/calico-docker
|
docs/calicoctl.md
|
2702
|
<!--- master only -->
>  This document applies to the HEAD of the calico-docker source tree.
>
> View the calico-docker documentation for the latest release [here](https://github.com/projectcalico/calico-docker/blob/v0.12.0/README.md).
<!--- else
> You are viewing the calico-docker documentation for release **release**.
<!--- end of master only -->
# calicoctl command line interface user reference
The command line tool, `calicoctl`, makes it easy to configure and start Calico
services and to manage Calico network and security policy.
The tool provides a simple interface for using Calico networking with Docker
containers. In addition, many of the calicoctl commands are useful for general
management of Calico configuration regardless of whether you are running Calico
on VMs, containers or bare metal.
This user reference is organized in sections based on the top level command options
of calicoctl.
## Top level help
Run `calicoctl --help` to display the following help menu for the top level
calicoctl commands.
```
calicoctl
Override the host:port of the ETCD server by setting the environment variable
ETCD_AUTHORITY [default: 127.0.0.1:2379]
Usage: calicoctl <command> [<args>...]
status Print current status information
node Configure the main calico/node container and establish Calico networking
container Configure containers and their addresses
profile Configure endpoint profiles
endpoint Configure the endpoints assigned to existing containers
pool Configure ip-pools
bgp Configure global bgp
ipam Configure IP address management
checksystem Check for incompatibilities on the host system
diags Save diagnostic information
version Display the version of calicoctl
config Configure low-level component configuration
See 'calicoctl <command> --help' to read about a specific subcommand.
```
## Top level command line options
Details on the `calicoctl` commands are described in the documents linked below
organized by top level command.
- [calicoctl status](calicoctl/status.md)
- [calicoctl node](calicoctl/node.md)
- [calicoctl container](calicoctl/container.md)
- [calicoctl profile](calicoctl/profile.md)
- [calicoctl endpoint](calicoctl/endpoint.md)
- [calicoctl pool](calicoctl/pool.md)
- [calicoctl bgp](calicoctl/bgp.md)
- [calicoctl ipam](calicoctl/ipam.md)
- [calicoctl checksystem](calicoctl/checksystem.md)
- [calicoctl diags](calicoctl/diags.md)
- [calicoctl version](calicoctl/version.md)
- [calicoctl config](calicoctl/config.md)
|
apache-2.0
|
google/grr
|
grr/server/grr_response_server/gui/ui/components/flow_args_form/collect_files_by_known_path_form.ng.html
|
1392
|
<div>
<mat-form-field appearance="outline" class="w100">
<mat-label>Absolute paths</mat-label>
<textarea matInput
placeholder="/some/path /another/path"
[formControl]="controls.paths"
class="monospace tall"
name="paths"
autocomplete="off"></textarea>
<mat-hint>
<app-literal-path-glob-expression-warning [path]="form.value['paths']"></app-literal-path-glob-expression-warning>
</mat-hint>
</mat-form-field>
<div class="validation" [hidden]="!form.controls['paths'].hasError('atLeastOnePathExpected')">
<mat-error *ngIf="form.controls['paths'].hasError('atLeastOnePathExpected')">At least one non-empty path expected.</mat-error>
</div>
<mat-radio-group aria-label="Collection level" [formControl]="controls.collectionLevel" [hidden]="hideAdvancedParams">
<mat-radio-button *ngFor="let cl of collectionLevels" [value]="cl.value" class="radio-option w100">
{{cl.label}}
</mat-radio-button>
</mat-radio-group>
<button mat-flat-button
type="button"
class="advanced-params-button"
(click)="toggleAdvancedParams()"
aria-label="View/hide advanced params">
<mat-icon>{{hideAdvancedParams ? 'expand_more' : 'expand_less'}}</mat-icon>
{{hideAdvancedParams ? 'View settings' : 'Hide settings'}}
</button>
</div>
|
apache-2.0
|
Xyrotechnology/Project-Anthrax
|
SD/libraries/Scripts/Pixhawk/Firmware-master/src/modules/px4iofirmware/px4io.h
|
8251
|
/****************************************************************************
*
* Copyright (c) 2012-2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file px4io.h
*
* General defines and structures for the PX4IO module firmware.
*/
#include <px4_config.h>
#include <stdbool.h>
#include <stdint.h>
#include <board_config.h>
#include "protocol.h"
#include <systemlib/pwm_limit/pwm_limit.h>
/*
* Constants and limits.
*/
#define PX4IO_SERVO_COUNT 8
#define PX4IO_CONTROL_CHANNELS 8
#define PX4IO_CONTROL_GROUPS 4
#define PX4IO_RC_INPUT_CHANNELS 18
#define PX4IO_RC_MAPPED_CONTROL_CHANNELS 8 /**< This is the maximum number of channels mapped/used */
/*
* Debug logging
*/
#ifdef DEBUG
# include <debug.h>
# define debug(fmt, args...) lowsyslog(fmt "\n", ##args)
#else
# define debug(fmt, args...) do {} while(0)
#endif
/*
* Registers.
*/
extern uint16_t r_page_status[]; /* PX4IO_PAGE_STATUS */
extern uint16_t r_page_actuators[]; /* PX4IO_PAGE_ACTUATORS */
extern uint16_t r_page_servos[]; /* PX4IO_PAGE_SERVOS */
extern uint16_t r_page_raw_rc_input[]; /* PX4IO_PAGE_RAW_RC_INPUT */
extern uint16_t r_page_rc_input[]; /* PX4IO_PAGE_RC_INPUT */
extern uint16_t r_page_adc[]; /* PX4IO_PAGE_RAW_ADC_INPUT */
extern volatile uint16_t r_page_setup[]; /* PX4IO_PAGE_SETUP */
extern volatile uint16_t r_page_controls[]; /* PX4IO_PAGE_CONTROLS */
extern uint16_t r_page_rc_input_config[]; /* PX4IO_PAGE_RC_INPUT_CONFIG */
extern uint16_t r_page_servo_failsafe[]; /* PX4IO_PAGE_FAILSAFE_PWM */
extern uint16_t r_page_servo_control_min[]; /* PX4IO_PAGE_CONTROL_MIN_PWM */
extern uint16_t r_page_servo_control_max[]; /* PX4IO_PAGE_CONTROL_MAX_PWM */
extern uint16_t r_page_servo_disarmed[]; /* PX4IO_PAGE_DISARMED_PWM */
/*
* Register aliases.
*
* Handy aliases for registers that are widely used.
*/
#define r_status_flags r_page_status[PX4IO_P_STATUS_FLAGS]
#define r_status_alarms r_page_status[PX4IO_P_STATUS_ALARMS]
#define r_raw_rc_count r_page_raw_rc_input[PX4IO_P_RAW_RC_COUNT]
#define r_raw_rc_values (&r_page_raw_rc_input[PX4IO_P_RAW_RC_BASE])
#define r_raw_rc_flags r_page_raw_rc_input[PX4IO_P_RAW_RC_FLAGS]
#define r_rc_valid r_page_rc_input[PX4IO_P_RC_VALID]
#define r_rc_values (&r_page_rc_input[PX4IO_P_RC_BASE])
#define r_mixer_limits r_page_status[PX4IO_P_STATUS_MIXER]
#define r_setup_features r_page_setup[PX4IO_P_SETUP_FEATURES]
#define r_setup_arming r_page_setup[PX4IO_P_SETUP_ARMING]
#define r_setup_pwm_rates r_page_setup[PX4IO_P_SETUP_PWM_RATES]
#define r_setup_pwm_defaultrate r_page_setup[PX4IO_P_SETUP_PWM_DEFAULTRATE]
#define r_setup_pwm_altrate r_page_setup[PX4IO_P_SETUP_PWM_ALTRATE]
#ifdef CONFIG_ARCH_BOARD_PX4IO_V1
#define r_setup_relays r_page_setup[PX4IO_P_SETUP_RELAYS]
#endif
#define r_setup_rc_thr_failsafe r_page_setup[PX4IO_P_SETUP_RC_THR_FAILSAFE_US]
#define r_setup_pwm_reverse r_page_setup[PX4IO_P_SETUP_PWM_REVERSE]
#define r_setup_trim_roll r_page_setup[PX4IO_P_SETUP_TRIM_ROLL]
#define r_setup_trim_pitch r_page_setup[PX4IO_P_SETUP_TRIM_PITCH]
#define r_setup_trim_yaw r_page_setup[PX4IO_P_SETUP_TRIM_YAW]
#define r_control_values (&r_page_controls[0])
/*
* System state structure.
*/
struct sys_state_s {
volatile uint64_t rc_channels_timestamp_received;
volatile uint64_t rc_channels_timestamp_valid;
/**
* Last FMU receive time, in microseconds since system boot
*/
volatile uint64_t fmu_data_received_time;
};
extern struct sys_state_s system_state;
/*
* PWM limit structure
*/
extern pwm_limit_t pwm_limit;
/*
* GPIO handling.
*/
#define LED_BLUE(_s) stm32_gpiowrite(GPIO_LED1, !(_s))
#define LED_AMBER(_s) stm32_gpiowrite(GPIO_LED2, !(_s))
#define LED_SAFETY(_s) stm32_gpiowrite(GPIO_LED3, !(_s))
#define LED_RING(_s) stm32_gpiowrite(GPIO_LED4, (_s))
#ifdef CONFIG_ARCH_BOARD_PX4IO_V1
# define PX4IO_RELAY_CHANNELS 4
# define POWER_SERVO(_s) stm32_gpiowrite(GPIO_SERVO_PWR_EN, (_s))
# define POWER_ACC1(_s) stm32_gpiowrite(GPIO_ACC1_PWR_EN, (_s))
# define POWER_ACC2(_s) stm32_gpiowrite(GPIO_ACC2_PWR_EN, (_s))
# define POWER_RELAY1(_s) stm32_gpiowrite(GPIO_RELAY1_EN, (_s))
# define POWER_RELAY2(_s) stm32_gpiowrite(GPIO_RELAY2_EN, (_s))
# define OVERCURRENT_ACC (!stm32_gpioread(GPIO_ACC_OC_DETECT))
# define OVERCURRENT_SERVO (!stm32_gpioread(GPIO_SERVO_OC_DETECT))
# define PX4IO_ADC_CHANNEL_COUNT 2
# define ADC_VBATT 4
# define ADC_IN5 5
#endif
#ifdef CONFIG_ARCH_BOARD_PX4IO_V2
# define PX4IO_RELAY_CHANNELS 0
# define POWER_SPEKTRUM(_s) stm32_gpiowrite(GPIO_SPEKTRUM_PWR_EN, (_s))
# define ENABLE_SBUS_OUT(_s) stm32_gpiowrite(GPIO_SBUS_OENABLE, !(_s))
# define VDD_SERVO_FAULT (!stm32_gpioread(GPIO_SERVO_FAULT_DETECT))
# define PX4IO_ADC_CHANNEL_COUNT 2
# define ADC_VSERVO 4
# define ADC_RSSI 5
#endif
#define BUTTON_SAFETY stm32_gpioread(GPIO_BTN_SAFETY)
#define CONTROL_PAGE_INDEX(_group, _channel) (_group * PX4IO_CONTROL_CHANNELS + _channel)
/*
* Mixer
*/
extern void mixer_tick(void);
extern int mixer_handle_text(const void *buffer, size_t length);
/* Set the failsafe values of all mixed channels (based on zero throttle, controls centered) */
extern void mixer_set_failsafe(void);
/**
* Safety switch/LED.
*/
extern void safety_init(void);
extern void failsafe_led_init(void);
/**
* FMU communications
*/
extern void interface_init(void);
extern void interface_tick(void);
/**
* Register space
*/
extern int registers_set(uint8_t page, uint8_t offset, const uint16_t *values, unsigned num_values);
extern int registers_get(uint8_t page, uint8_t offset, uint16_t **values, unsigned *num_values);
/**
* Sensors/misc inputs
*/
extern int adc_init(void);
extern uint16_t adc_measure(unsigned channel);
/**
* R/C receiver handling.
*
* Input functions return true when they receive an update from the RC controller.
*/
extern void controls_init(void);
extern void controls_tick(void);
extern int dsm_init(const char *device);
extern bool dsm_input(uint16_t *values, uint16_t *num_values, uint8_t *n_bytes, uint8_t **bytes);
extern void dsm_bind(uint16_t cmd, int pulses);
extern int sbus_init(const char *device);
extern bool sbus_input(uint16_t *values, uint16_t *num_values, bool *sbus_failsafe, bool *sbus_frame_drop,
uint16_t max_channels);
extern void sbus1_output(uint16_t *values, uint16_t num_values);
extern void sbus2_output(uint16_t *values, uint16_t num_values);
/** global debug level for isr_debug() */
extern volatile uint8_t debug_level;
/** send a debug message to the console */
extern void isr_debug(uint8_t level, const char *fmt, ...);
/** schedule a reboot */
extern void schedule_reboot(uint32_t time_delta_usec);
|
apache-2.0
|
Hexworks/zircon
|
docs/2020.2.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.internal.resource/-color-theme-resource/-s-o-l-a-r-i-z-e-d_-d-a-r-k_-v-i-o-l-e-t/color-theme.html
|
3673
|
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>colorTheme</title>
<link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../../";</script>
<script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../../styles/style.css" rel="Stylesheet">
<link href="../../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.internal.resource/ColorThemeResource.SOLARIZED_DARK_VIOLET/colorTheme/#/PointingToDeclaration//-828656838">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../../index.html">zircon.core</a>/<a href="../../index.html">org.hexworks.zircon.internal.resource</a>/<a href="../index.html">ColorThemeResource</a>/<a href="index.html">SOLARIZED_DARK_VIOLET</a>/<a href="color-theme.html">colorTheme</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>color</span><wbr></wbr><span>Theme</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">private val <a href="color-theme.html">colorTheme</a>: <a href="../../../org.hexworks.zircon.api.component/-color-theme/index.html">ColorTheme</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
</div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
|
apache-2.0
|
lgobinath/siddhi
|
modules/siddhi-core/src/main/java/org/wso2/siddhi/core/query/output/ratelimit/snapshot/PerSnapshotOutputRateLimiter.java
|
5177
|
/*
* Copyright (c) 2016, 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.siddhi.core.query.output.ratelimit.snapshot;
import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.event.ComplexEvent;
import org.wso2.siddhi.core.event.ComplexEventChunk;
import org.wso2.siddhi.core.event.stream.StreamEventPool;
import org.wso2.siddhi.core.util.Scheduler;
import org.wso2.siddhi.core.util.parser.SchedulerParser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
/**
* Parent implementation for per event periodic snapshot rate limiting. Multiple implementations of this will be
* there to represent different queries. Snapshot rate limiting will only emit current events representing the
* snapshot period.
*/
public class PerSnapshotOutputRateLimiter extends SnapshotOutputRateLimiter {
private final Long value;
private String id;
private ScheduledExecutorService scheduledExecutorService;
private ComplexEventChunk<ComplexEvent> eventChunk = new ComplexEventChunk<ComplexEvent>(false);
private ComplexEvent lastEvent;
private Scheduler scheduler;
private long scheduledTime;
private String queryName;
public PerSnapshotOutputRateLimiter(String id, Long value, ScheduledExecutorService scheduledExecutorService,
WrappedSnapshotOutputRateLimiter wrappedSnapshotOutputRateLimiter,
ExecutionPlanContext executionPlanContext, String queryName) {
super(wrappedSnapshotOutputRateLimiter, executionPlanContext);
this.queryName = queryName;
this.id = id;
this.value = value;
this.scheduledExecutorService = scheduledExecutorService;
}
@Override
public void process(ComplexEventChunk complexEventChunk) {
List<ComplexEventChunk<ComplexEvent>> outputEventChunks = new ArrayList<ComplexEventChunk<ComplexEvent>>();
complexEventChunk.reset();
synchronized (this) {
while (complexEventChunk.hasNext()) {
ComplexEvent event = complexEventChunk.next();
if (event.getType() == ComplexEvent.Type.TIMER) {
tryFlushEvents(outputEventChunks, event);
} else if (event.getType() == ComplexEvent.Type.CURRENT) {
complexEventChunk.remove();
tryFlushEvents(outputEventChunks, event);
lastEvent = event;
} else {
tryFlushEvents(outputEventChunks, event);
}
}
}
for (ComplexEventChunk eventChunk : outputEventChunks) {
sendToCallBacks(eventChunk);
}
}
private void tryFlushEvents(List<ComplexEventChunk<ComplexEvent>> outputEventChunks, ComplexEvent event) {
if (event.getTimestamp() >= scheduledTime) {
ComplexEventChunk<ComplexEvent> outputEventChunk = new ComplexEventChunk<ComplexEvent>(false);
if (lastEvent != null) {
outputEventChunk.add(cloneComplexEvent(lastEvent));
}
outputEventChunks.add(outputEventChunk);
scheduledTime += value;
scheduler.notifyAt(scheduledTime);
}
}
@Override
public SnapshotOutputRateLimiter clone(String key, WrappedSnapshotOutputRateLimiter
wrappedSnapshotOutputRateLimiter) {
return new PerSnapshotOutputRateLimiter(id + key, value, scheduledExecutorService,
wrappedSnapshotOutputRateLimiter, executionPlanContext, queryName);
}
@Override
public void start() {
scheduler = SchedulerParser.parse(scheduledExecutorService, this, executionPlanContext);
scheduler.setStreamEventPool(new StreamEventPool(0, 0, 0, 5));
scheduler.init(lockWrapper, queryName);
long currentTime = System.currentTimeMillis();
scheduledTime = currentTime + value;
scheduler.notifyAt(scheduledTime);
}
@Override
public void stop() {
//Nothing to stop
}
@Override
public Map<String, Object> currentState() {
Map<String, Object> state = new HashMap<>();
state.put("EventChunk", eventChunk.getFirst());
return state;
}
@Override
public void restoreState(Map<String, Object> state) {
eventChunk.clear();
eventChunk.add((ComplexEvent) state.get("EventList"));
}
}
|
apache-2.0
|
vigov5/planes
|
README.md
|
8
|
# planes
|
apache-2.0
|
idaholab/raven
|
framework/contrib/PythonFMU/pythonfmu/pythonfmu-export/cpp/cppfmu_cs.cpp
|
2874
|
/* Copyright 2016-2019, SINTEF Ocean.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "cppfmu/cppfmu_cs.hpp"
#include <stdexcept>
namespace cppfmu
{
// =============================================================================
// SlaveInstance
// =============================================================================
void SlaveInstance::SetupExperiment(
FMIBoolean /*toleranceDefined*/,
FMIReal /*tolerance*/,
FMIReal /*tStart*/,
FMIBoolean /*stopTimeDefined*/,
FMIReal /*tStop*/)
{
// Do nothing
}
void SlaveInstance::EnterInitializationMode()
{
// Do nothing
}
void SlaveInstance::ExitInitializationMode()
{
// Do nothing
}
void SlaveInstance::Terminate()
{
// Do nothing
}
void SlaveInstance::Reset()
{
// Do nothing
}
void SlaveInstance::SetReal(
const FMIValueReference /*vr*/[],
std::size_t nvr,
const FMIReal /*value*/[])
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::SetInteger(
const FMIValueReference /*vr*/[],
std::size_t nvr,
const FMIInteger /*value*/[])
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::SetBoolean(
const FMIValueReference /*vr*/[],
std::size_t nvr,
const FMIBoolean /*value*/[])
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::SetString(
const FMIValueReference /*vr*/[],
std::size_t nvr,
const FMIString /*value*/[])
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::GetReal(
const FMIValueReference /*vr*/[],
std::size_t nvr,
FMIReal /*value*/[]) const
{
if (nvr != 0) {
throw std::logic_error("Attempted to get nonexistent variable");
}
}
void SlaveInstance::GetInteger(
const FMIValueReference /*vr*/[],
std::size_t nvr,
FMIInteger /*value*/[]) const
{
if (nvr != 0) {
throw std::logic_error("Attempted to get nonexistent variable");
}
}
void SlaveInstance::GetBoolean(
const FMIValueReference /*vr*/[],
std::size_t nvr,
FMIBoolean /*value*/[]) const
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::GetString(
const FMIValueReference /*vr*/[],
std::size_t nvr,
FMIString /*value*/[]) const
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
SlaveInstance::~SlaveInstance() CPPFMU_NOEXCEPT
{
// Do nothing
}
} // namespace cppfmu
|
apache-2.0
|
baade-org/eel
|
eel-core/src/main/java/org/baade/eel/core/player/IPlayer.java
|
290
|
package org.baade.eel.core.player;
import org.baade.eel.core.ILifecycle;
import org.baade.eel.core.message.IMessage;
import org.baade.eel.core.processor.IProcessor;
public interface IPlayer extends ILifecycle {
public void send(IMessage message);
public IProcessor getProcessor();
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Acaena/Acaena eupatoria/ Syn. Acaena montevidensis/README.md
|
185
|
# Acaena montevidensis Hook.f. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
allure-framework/allure-java
|
allure-java-commons/src/test/java/io/qameta/allure/testdata/DummyCard.java
|
1043
|
/*
* Copyright 2019 Qameta Software OÜ
*
* 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 io.qameta.allure.testdata;
/**
* @author sskorol (Sergey Korol)
*/
public class DummyCard {
private final String number;
public DummyCard(final String number) {
this.number = number;
}
public String getNumber() {
return number;
}
@Override
public String toString() {
return "DummyCard{" +
"number='" + number + '\'' +
'}';
}
}
|
apache-2.0
|
aspnet/AspNetCore
|
src/Mvc/Mvc.RazorPages/src/IPageActivatorProvider.cs
|
1873
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Microsoft.AspNetCore.Mvc.RazorPages
{
/// <summary>
/// Provides methods to create a Razor page.
/// </summary>
public interface IPageActivatorProvider
{
/// <summary>
/// Creates a Razor page activator.
/// </summary>
/// <param name="descriptor">The <see cref="CompiledPageActionDescriptor"/>.</param>
/// <returns>The delegate used to activate the page.</returns>
Func<PageContext, ViewContext, object> CreateActivator(CompiledPageActionDescriptor descriptor);
/// <summary>
/// Releases a Razor page.
/// </summary>
/// <param name="descriptor">The <see cref="CompiledPageActionDescriptor"/>.</param>
/// <returns>The delegate used to dispose the activated page.</returns>
Action<PageContext, ViewContext, object>? CreateReleaser(CompiledPageActionDescriptor descriptor);
/// <summary>
/// Releases a Razor page asynchronously.
/// </summary>
/// <param name="descriptor">The <see cref="CompiledPageActionDescriptor"/>.</param>
/// <returns>The delegate used to dispose the activated page asynchronously.</returns>
Func<PageContext, ViewContext, object, ValueTask>? CreateAsyncReleaser(CompiledPageActionDescriptor descriptor)
{
var releaser = CreateReleaser(descriptor);
if (releaser is null)
{
return null;
}
return (context, viewContext, page) =>
{
releaser(context, viewContext, page);
return default;
};
}
}
}
|
apache-2.0
|
nivanov/ignite
|
modules/platforms/cpp/odbc-test/src/sql_test_suite_fixture.cpp
|
10627
|
/*
* 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.
*/
#include "sql_test_suite_fixture.h"
#include "test_utils.h"
using namespace ignite_test;
namespace ignite
{
SqlTestSuiteFixture::SqlTestSuiteFixture():
testCache(0),
env(NULL),
dbc(NULL),
stmt(NULL)
{
grid = StartNode("queries-test.xml");
testCache = grid.GetCache<int64_t, TestType>("cache");
// Allocate an environment handle
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
BOOST_REQUIRE(env != NULL);
// We want ODBC 3 support
SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, reinterpret_cast<void*>(SQL_OV_ODBC3), 0);
// Allocate a connection handle
SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
BOOST_REQUIRE(dbc != NULL);
// Connect string
SQLCHAR connectStr[] = "DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache";
SQLCHAR outstr[ODBC_BUFFER_SIZE];
SQLSMALLINT outstrlen;
// Connecting to ODBC server.
SQLRETURN ret = SQLDriverConnect(dbc, NULL, connectStr, static_cast<SQLSMALLINT>(sizeof(connectStr)),
outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_COMPLETE);
if (!SQL_SUCCEEDED(ret))
{
Ignition::StopAll(true);
BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_DBC, dbc));
}
// Allocate a statement handle
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
BOOST_REQUIRE(stmt != NULL);
}
SqlTestSuiteFixture::~SqlTestSuiteFixture()
{
// Releasing statement handle.
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
// Disconneting from the server.
SQLDisconnect(dbc);
// Releasing allocated handles.
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
SQLFreeHandle(SQL_HANDLE_ENV, env);
ignite::Ignition::StopAll(true);
}
void SqlTestSuiteFixture::CheckSingleResult0(const char* request,
SQLSMALLINT type, void* column, SQLLEN bufSize, SQLLEN* resSize) const
{
SQLRETURN ret;
ret = SQLBindCol(stmt, 1, type, column, bufSize, resSize);
if (!SQL_SUCCEEDED(ret))
BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
ret = SQLExecDirect(stmt, reinterpret_cast<SQLCHAR*>(const_cast<char*>(request)), SQL_NTS);
if (!SQL_SUCCEEDED(ret))
BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
ret = SQLFetch(stmt);
if (!SQL_SUCCEEDED(ret))
BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
ret = SQLFetch(stmt);
BOOST_CHECK(ret == SQL_NO_DATA);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<std::string>(const char* request, const std::string& expected)
{
SQLCHAR res[ODBC_BUFFER_SIZE] = { 0 };
SQLLEN resLen = 0;
CheckSingleResult0(request, SQL_C_CHAR, res, ODBC_BUFFER_SIZE, &resLen);
std::string actual;
if (resLen > 0)
actual.assign(reinterpret_cast<char*>(res), static_cast<size_t>(resLen));
BOOST_CHECK_EQUAL(actual, expected);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int64_t>(const char* request, const int64_t& expected)
{
CheckSingleResultNum0<int64_t>(request, expected, SQL_C_SBIGINT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int32_t>(const char* request, const int32_t& expected)
{
CheckSingleResultNum0<int32_t>(request, expected, SQL_C_SLONG);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int16_t>(const char* request, const int16_t& expected)
{
CheckSingleResultNum0<int16_t>(request, expected, SQL_C_SSHORT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int8_t>(const char* request, const int8_t& expected)
{
CheckSingleResultNum0<int8_t>(request, expected, SQL_C_STINYINT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<float>(const char* request, const float& expected)
{
SQLREAL res = 0;
CheckSingleResult0(request, SQL_C_FLOAT, &res, 0, 0);
BOOST_CHECK_CLOSE(static_cast<float>(res), expected, 1E-6f);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<double>(const char* request, const double& expected)
{
SQLDOUBLE res = 0;
CheckSingleResult0(request, SQL_C_DOUBLE, &res, 0, 0);
BOOST_CHECK_CLOSE(static_cast<double>(res), expected, 1E-6);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<bool>(const char* request, const bool& expected)
{
SQLCHAR res = 0;
CheckSingleResult0(request, SQL_C_BIT, &res, 0, 0);
BOOST_CHECK_EQUAL((res != 0), expected);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<ignite::Guid>(const char* request, const ignite::Guid& expected)
{
SQLGUID res;
memset(&res, 0, sizeof(res));
CheckSingleResult0(request, SQL_C_GUID, &res, 0, 0);
BOOST_CHECK_EQUAL(res.Data1, expected.GetMostSignificantBits() & 0xFFFFFFFF00000000ULL >> 32);
BOOST_CHECK_EQUAL(res.Data2, expected.GetMostSignificantBits() & 0x00000000FFFF0000ULL >> 16);
BOOST_CHECK_EQUAL(res.Data3, expected.GetMostSignificantBits() & 0x000000000000FFFFULL);
for (int i = 0; i < sizeof(res.Data4); ++i)
BOOST_CHECK_EQUAL(res.Data4[i], (expected.GetLeastSignificantBits() & (0xFFULL << (8 * i))) >> (8 * i));
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<std::string>(const char* request)
{
SQLCHAR res[ODBC_BUFFER_SIZE] = { 0 };
SQLLEN resLen = 0;
CheckSingleResult0(request, SQL_C_CHAR, res, ODBC_BUFFER_SIZE, &resLen);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int64_t>(const char* request)
{
CheckSingleResultNum0<int64_t>(request, SQL_C_SBIGINT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int32_t>(const char* request)
{
CheckSingleResultNum0<int32_t>(request, SQL_C_SLONG);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int16_t>(const char* request)
{
CheckSingleResultNum0<int16_t>(request, SQL_C_SSHORT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int8_t>(const char* request)
{
CheckSingleResultNum0<int8_t>(request, SQL_C_STINYINT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<float>(const char* request)
{
SQLREAL res = 0;
CheckSingleResult0(request, SQL_C_FLOAT, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<double>(const char* request)
{
SQLDOUBLE res = 0;
CheckSingleResult0(request, SQL_C_DOUBLE, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Date>(const char* request)
{
SQL_DATE_STRUCT res;
CheckSingleResult0(request, SQL_C_DATE, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Timestamp>(const char* request)
{
SQL_TIMESTAMP_STRUCT res;
CheckSingleResult0(request, SQL_C_TIMESTAMP, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Time>(const char* request)
{
SQL_TIME_STRUCT res;
CheckSingleResult0(request, SQL_C_TIME, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<std::vector<int8_t> >(const char* request, const std::vector<int8_t>& expected)
{
SQLCHAR res[ODBC_BUFFER_SIZE] = { 0 };
SQLLEN resLen = 0;
CheckSingleResult0(request, SQL_C_BINARY, res, ODBC_BUFFER_SIZE, &resLen);
BOOST_REQUIRE_EQUAL(resLen, expected.size());
if (resLen > 0)
{
std::vector<int8_t> actual(res, res + resLen);
BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());
}
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<ignite::common::Decimal>(const char* request, const ignite::common::Decimal& expected)
{
SQLCHAR res[ODBC_BUFFER_SIZE] = { 0 };
SQLLEN resLen = 0;
CheckSingleResult0(request, SQL_C_CHAR, res, ODBC_BUFFER_SIZE, &resLen);
ignite::common::Decimal actual(std::string(res, res + resLen));
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Date>(const char* request, const Date& expected)
{
SQL_DATE_STRUCT res;
CheckSingleResult0(request, SQL_C_DATE, &res, 0, 0);
using ignite::impl::binary::BinaryUtils;
Date actual = common::MakeDateGmt(res.year, res.month, res.day);
BOOST_REQUIRE_EQUAL(actual.GetSeconds(), expected.GetSeconds());
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Timestamp>(const char* request, const Timestamp& expected)
{
SQL_TIMESTAMP_STRUCT res;
CheckSingleResult0(request, SQL_C_TIMESTAMP, &res, 0, 0);
using ignite::impl::binary::BinaryUtils;
Timestamp actual = common::MakeTimestampGmt(res.year, res.month, res.day, res.hour, res.minute, res.second, res.fraction);
BOOST_REQUIRE_EQUAL(actual.GetSeconds(), expected.GetSeconds());
BOOST_REQUIRE_EQUAL(actual.GetSecondFraction(), expected.GetSecondFraction());
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Time>(const char* request, const Time& expected)
{
SQL_TIME_STRUCT res;
CheckSingleResult0(request, SQL_C_TIME, &res, 0, 0);
using ignite::impl::binary::BinaryUtils;
Time actual = common::MakeTimeGmt(res.hour, res.minute, res.second);
BOOST_REQUIRE_EQUAL(actual.GetSeconds(), expected.GetSeconds());
}
}
|
apache-2.0
|
hazendaz/assertj-core
|
src/test/java/org/assertj/core/api/date/DateAssert_isBetween_Test.java
|
1673
|
/*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.api.date;
import static org.mockito.Mockito.verify;
import java.time.Instant;
import java.util.Date;
import org.assertj.core.api.DateAssert;
/**
* Tests for {@link DateAssert#isBetween(Date, Date)}, {@link DateAssert#isBetween(String, String)} and
* {@link DateAssert#isBetween(Instant, Instant)}.
*
* @author Joel Costigliola
*/
class DateAssert_isBetween_Test extends AbstractDateAssertWithDateArg_Test {
@Override
protected DateAssert assertionInvocationWithDateArg() {
return assertions.isBetween(otherDate, otherDate);
}
@Override
protected DateAssert assertionInvocationWithStringArg(String dateAsString) {
return assertions.isBetween(dateAsString, dateAsString);
}
@Override
protected DateAssert assertionInvocationWithInstantArg() {
return assertions.isBetween(otherDate.toInstant(), otherDate.toInstant());
}
@Override
protected void verifyAssertionInvocation(Date date) {
verify(dates).assertIsBetween(getInfo(assertions), getActual(assertions), date, date, true, false);
}
}
|
apache-2.0
|
Ztiany/AndroidBase
|
lib_base/src/main/java/com/android/base/app/dagger/ContextType.java
|
438
|
package com.android.base.app.dagger;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import javax.inject.Qualifier;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Qualifier
@Documented
@Retention(RUNTIME)
public @interface ContextType {
String ACTIVITY = "Activity";
String CONTEXT = "Context";
String APPLICATION = "Application";
String value() default APPLICATION;
}
|
apache-2.0
|
tensorflow/tensorboard
|
tensorboard/plugins/histogram/vz_histogram_timeseries/vz-histogram-timeseries.ts
|
22012
|
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import {customElement, observe, property} from '@polymer/decorators';
import {html, PolymerElement} from '@polymer/polymer';
import * as d3Typed from 'd3';
import {DarkModeMixin} from '../../../components/polymer/dark_mode_mixin';
import {LegacyElementMixin} from '../../../components/polymer/legacy_element_mixin';
// Copied from `tf-histogram-dashboard/histogramCore`; TODO(wchargin):
// resolve dependency structure.
export type VzHistogram = {
wall_time: number; // in seconds
step: number;
bins: D3HistogramBin[];
};
export type D3HistogramBin = {
x: number;
dx: number;
y: number;
};
// TypeScript can't deal with d3's style of overloading and
// polymorphism, and constantly fails to select the correct overload.
// This module was converted from working non-TypeScript code, so we
// grandfather it in untyped.
const d3: any = d3Typed;
export interface VzHistogramTimeseries extends HTMLElement {
setSeriesData(series: string, data: VzHistogram[]): void;
redraw(): void;
}
@customElement('vz-histogram-timeseries')
class _VzHistogramTimeseries
extends LegacyElementMixin(DarkModeMixin(PolymerElement))
implements VzHistogramTimeseries
{
static readonly template = html`
<div id="tooltip"><span></span></div>
<svg id="svg">
<g>
<g class="axis x"></g>
<g class="axis y"></g>
<g class="axis y slice"></g>
<g class="stage">
<rect class="background"></rect>
</g>
<g class="x-axis-hover"></g>
<g class="y-axis-hover"></g>
<g class="y-slice-axis-hover"></g>
</g>
</svg>
<style>
:host {
color: #aaa;
display: flex;
flex-direction: column;
flex-grow: 1;
flex-shrink: 1;
position: relative;
--vz-histogram-timeseries-hover-bg-color: #fff;
--vz-histogram-timeseries-outline-color: #fff;
--vz-histogram-timeseries-hover-outline-color: #000;
}
:host(.dark-mode) {
--vz-histogram-timeseries-hover-bg-color: var(
--primary-background-color
);
--vz-histogram-timeseries-outline-color: var(--paper-grey-600);
--vz-histogram-timeseries-hover-outline-color: #fff;
}
svg {
font-family: roboto, sans-serif;
overflow: visible;
display: block;
width: 100%;
flex-grow: 1;
flex-shrink: 1;
}
text {
fill: currentColor;
}
#tooltip {
position: absolute;
display: block;
opacity: 0;
font-weight: bold;
font-size: 11px;
}
.background {
fill-opacity: 0;
fill: red;
}
.histogram {
pointer-events: none;
}
.hover {
font-size: 9px;
dominant-baseline: middle;
opacity: 0;
}
.hover circle {
stroke: white;
stroke-opacity: 0.5;
stroke-width: 1px;
}
.hover text {
fill: black;
opacity: 0;
}
.hover.hover-closest circle {
fill: var(--vz-histogram-timeseries-hover-outline-color) !important;
}
.hover.hover-closest text {
opacity: 1;
}
.baseline {
stroke: black;
stroke-opacity: 0.1;
}
.outline {
fill: none;
stroke: var(--vz-histogram-timeseries-outline-color);
stroke-opacity: 0.5;
}
.outline.outline-hover {
stroke: var(--vz-histogram-timeseries-hover-outline-color) !important;
stroke-opacity: 1;
}
.x-axis-hover,
.y-axis-hover,
.y-slice-axis-hover {
pointer-events: none;
}
.x-axis-hover .label,
.y-axis-hover .label,
.y-slice-axis-hover .label {
opacity: 0;
font-weight: bold;
font-size: 11px;
text-anchor: end;
}
.x-axis-hover text {
text-anchor: middle;
}
.y-axis-hover text,
.y-slice-axis-hover text {
text-anchor: start;
}
.x-axis-hover line,
.y-axis-hover line,
.y-slice-axis-hover line {
stroke: currentColor;
}
.x-axis-hover rect,
.y-axis-hover rect,
.y-slice-axis-hover rect {
fill: var(--vz-histogram-timeseries-hover-bg-color);
}
#tooltip,
.x-axis-hover text,
.y-axis-hover text,
.y-slice-axis-hover text {
color: var(--vz-histogram-timeseries-hover-outline-color);
}
.axis {
font-size: 11px;
}
.axis path.domain {
fill: none;
}
.axis .tick line {
stroke: #ddd;
}
.axis.slice {
opacity: 0;
}
.axis.slice .tick line {
stroke-dasharray: 2;
}
.small .axis text {
display: none;
}
.small .axis .tick:first-of-type text {
display: block;
}
.small .axis .tick:last-of-type text {
display: block;
}
.medium .axis text {
display: none;
}
.medium .axis .tick:nth-child(2n + 1) text {
display: block;
}
.large .axis text {
display: none;
}
.large .axis .tick:nth-child(2n + 1) text {
display: block;
}
</style>
`;
@property({type: String})
mode: string = 'offset';
@property({type: String})
timeProperty: string = 'step';
@property({type: String})
bins: string = 'bins';
@property({type: String})
x: string = 'x';
@property({type: String})
dx: string = 'dx';
@property({type: String})
y: string = 'y';
@property({type: Object})
colorScale = d3.scaleOrdinal(d3.schemeCategory10);
@property({type: Number})
modeTransitionDuration: number = 500;
@property({type: Boolean})
_attached: boolean;
@property({type: String})
_name: string = null;
@property({type: Array})
_data: VzHistogram[] = null;
ready() {
super.ready();
// Polymer's way of scoping styles on nodes that d3 created
this.scopeSubtree(this.$.svg, true);
}
override attached() {
this._attached = true;
}
override detached() {
this._attached = false;
}
setSeriesData(name, data) {
this._name = name;
this._data = data;
this.redraw();
}
@observe('timeProperty', 'colorScale', '_attached')
_redrawOnChange() {
this.redraw();
}
/**
* Redraws the chart. This is only called if the chart is attached to the
* screen and if the chart has data.
*/
redraw() {
this._draw(0);
}
@observe('mode')
_modeRedraw() {
this._draw(this.modeTransitionDuration);
}
_draw(duration) {
if (!this._attached || !this._data) {
return;
}
//
// Data verification
//
if (duration === undefined)
throw new Error('vz-histogram-timeseries _draw needs duration');
if (this._data.length <= 0) throw new Error('Not enough steps in the data');
if (!this._data[0].hasOwnProperty(this.bins))
throw new Error("No bins property of '" + this.bins + "' in data");
if (this._data[0][this.bins].length <= 0)
throw new Error('Must have at least one bin in bins in data');
if (!this._data[0][this.bins][0].hasOwnProperty(this.x))
throw new Error("No x property '" + this.x + "' on bins data");
if (!this._data[0][this.bins][0].hasOwnProperty(this.dx))
throw new Error("No dx property '" + this.dx + "' on bins data");
if (!this._data[0][this.bins][0].hasOwnProperty(this.y))
throw new Error("No y property '" + this.y + "' on bins data");
//
// Initialization
//
var timeProp = this.timeProperty;
var xProp = this.x;
var binsProp = this.bins;
var dxProp = this.dx;
var yProp = this.y;
var data = this._data;
var name = this._name;
var mode = this.mode;
var color = d3.hcl(this.colorScale(name));
var tooltip = d3.select(this.$.tooltip);
var xAccessor = function (d) {
return d[xProp];
};
var yAccessor = function (d) {
return d[yProp];
};
var dxAccessor = function (d) {
return d[dxProp];
};
var xRightAccessor = function (d) {
return d[xProp] + d[dxProp];
};
var timeAccessor = function (d) {
return d[timeProp];
};
if (timeProp === 'relative') {
timeAccessor = function (d) {
return d.wall_time - data[0].wall_time;
};
}
var brect = this.$.svg.getBoundingClientRect();
var outerWidth = brect.width,
outerHeight = brect.height;
var sliceHeight,
margin = {top: 5, right: 60, bottom: 20, left: 24};
if (mode === 'offset') {
sliceHeight = outerHeight / 2.5;
margin.top = sliceHeight + 5;
} else {
sliceHeight = outerHeight - margin.top - margin.bottom;
}
var width = outerWidth - margin.left - margin.right,
height = outerHeight - margin.top - margin.bottom;
var leftMin = d3.min(data, xAccessor),
rightMax = d3.max(data, xRightAccessor);
//
// Text formatters
//
var format = d3.format('.3n');
var yAxisFormat = d3.format('.0f');
if (timeProp === 'wall_time') {
yAxisFormat = d3.timeFormat('%m/%d %X');
} else if (timeProp === 'relative') {
yAxisFormat = function (d: number) {
return d3.format('.1r')(d / 3.6e6) + 'h'; // Convert to hours.
};
}
//
// Calculate the extents
//
var xExtents = data.map(function (d, i) {
return [
d3.min(d[binsProp], xAccessor),
d3.max(d[binsProp], xRightAccessor),
];
});
var yExtents = data.map(function (d) {
return d3.extent(d[binsProp], yAccessor);
});
//
// Scales and axis
//
var outlineCanvasSize = 500;
var extent = d3.extent(data, timeAccessor);
var yScale = (timeProp === 'wall_time' ? d3.scaleTime() : d3.scaleLinear())
.domain(extent)
.range([0, mode === 'offset' ? height : 0]);
var ySliceScale = d3
.scaleLinear()
.domain([
0,
d3.max(data, function (d, i) {
return yExtents[i][1];
}),
])
.range([sliceHeight, 0]);
var yLineScale = d3
.scaleLinear()
.domain(ySliceScale.domain())
.range([outlineCanvasSize, 0]);
var xScale = d3
.scaleLinear()
.domain([
d3.min(data, function (d, i) {
return xExtents[i][0];
}),
d3.max(data, function (d, i) {
return xExtents[i][1];
}),
])
.nice()
.range([0, width]);
var xLineScale = d3
.scaleLinear()
.domain(xScale.domain())
.range([0, outlineCanvasSize]);
const fillColor = d3
.scaleLinear()
.domain(d3.extent(data, timeAccessor))
.range([color.brighter(), color.darker()])
.interpolate(d3.interpolateHcl);
var xAxis = d3.axisBottom(xScale).ticks(Math.max(2, width / 20));
var yAxis = d3
.axisRight(yScale)
.ticks(Math.max(2, height / 15))
.tickFormat(yAxisFormat);
var ySliceAxis = d3
.axisRight(ySliceScale)
.ticks(Math.max(2, height / 15))
.tickSize(width + 5)
.tickFormat(format);
var xBinCentroid = function (d) {
return d[xProp] + d[dxProp] / 2;
};
var linePath = d3
.line()
.x(function (d) {
return xLineScale(xBinCentroid(d));
})
.y(function (d) {
return yLineScale(d[yProp]);
});
var path = function (d) {
// Draw a line from 0 to the first point and from the last point to 0.
return (
'M' +
xLineScale(xBinCentroid(d[0])) +
',' +
yLineScale(0) +
'L' +
linePath(d).slice(1) +
'L' +
xLineScale(xBinCentroid(d[d.length - 1])) +
',' +
yLineScale(0)
);
};
//
// Render
//
var svgNode = this.$.svg;
var svg = d3.select(svgNode);
var svgTransition = svg.transition().duration(duration);
var g = svg
.select('g')
.classed('small', function () {
return width > 0 && width <= 150;
})
.classed('medium', function () {
return width > 150 && width <= 300;
})
.classed('large', function () {
return width > 300;
});
var gTransition = svgTransition
.select('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var bisect = d3.bisector(xRightAccessor).left;
var stage = g
.select('.stage')
.on('mouseover', function () {
hoverUpdate.style('opacity', 1);
xAxisHoverUpdate.style('opacity', 1);
yAxisHoverUpdate.style('opacity', 1);
ySliceAxisHoverUpdate.style('opacity', 1);
tooltip.style('opacity', 1);
})
.on('mouseout', function () {
hoverUpdate.style('opacity', 0);
xAxisHoverUpdate.style('opacity', 0);
yAxisHoverUpdate.style('opacity', 0);
ySliceAxisHoverUpdate.style('opacity', 0);
hoverUpdate.classed('hover-closest', false);
outlineUpdate.classed('outline-hover', false);
tooltip.style('opacity', 0);
})
.on('mousemove', onMouseMove);
var background = stage
.select('.background')
.attr('transform', 'translate(' + -margin.left + ',' + -margin.top + ')')
.attr('width', outerWidth)
.attr('height', outerHeight);
var histogram = stage.selectAll('.histogram').data(data),
histogramExit = histogram.exit().remove(),
histogramEnter = histogram.enter().append('g').attr('class', 'histogram'),
histogramUpdate = histogramEnter.merge(histogram).sort(function (a, b) {
return timeAccessor(a) - timeAccessor(b);
}),
histogramTransition = gTransition
.selectAll('.histogram')
.attr('transform', function (d) {
return (
'translate(0, ' +
(mode === 'offset' ? yScale(timeAccessor(d)) - sliceHeight : 0) +
')'
);
});
var baselineEnter = histogramEnter.append('line').attr('class', 'baseline'),
baselineUpdate = histogramTransition
.select('.baseline')
.style('stroke-opacity', function (d) {
return mode === 'offset' ? 0.1 : 0;
})
.attr('y1', sliceHeight)
.attr('y2', sliceHeight)
.attr('x2', width);
var outlineEnter = histogramEnter.append('path').attr('class', 'outline'),
outlineUpdate = histogramUpdate
.select('.outline')
.attr('vector-effect', 'non-scaling-stroke')
.attr('d', function (d) {
return path(d[binsProp]);
})
.style('stroke-width', 1),
outlineTransition = histogramTransition
.select('.outline')
.attr(
'transform',
'scale(' +
width / outlineCanvasSize +
', ' +
sliceHeight / outlineCanvasSize +
')'
)
.style('stroke', function (d) {
return mode === 'offset' ? '' : fillColor(timeAccessor(d));
})
.style('fill-opacity', function (d) {
return mode === 'offset' ? 1 : 0;
})
.style('fill', function (d) {
return fillColor(timeAccessor(d));
});
var hoverEnter = histogramEnter.append('g').attr('class', 'hover');
var hoverUpdate = histogramUpdate
.select('.hover')
.style('fill', function (d) {
return fillColor(timeAccessor(d));
});
hoverEnter.append('circle').attr('r', 2);
hoverEnter.append('text').style('display', 'none').attr('dx', 4);
var xAxisHover = g.select('.x-axis-hover').selectAll('.label').data(['x']),
xAxisHoverEnter = xAxisHover.enter().append('g').attr('class', 'label'),
xAxisHoverUpdate = xAxisHover.merge(xAxisHoverEnter);
xAxisHoverEnter
.append('rect')
.attr('x', -20)
.attr('y', 6)
.attr('width', 40)
.attr('height', 14);
xAxisHoverEnter
.append('line')
.attr('x1', 0)
.attr('x2', 0)
.attr('y1', 0)
.attr('y2', 6);
xAxisHoverEnter.append('text').attr('dy', 18);
var yAxisHover = g.select('.y-axis-hover').selectAll('.label').data(['y']),
yAxisHoverEnter = yAxisHover.enter().append('g').attr('class', 'label'),
yAxisHoverUpdate = yAxisHover.merge(yAxisHoverEnter);
yAxisHoverEnter
.append('rect')
.attr('x', 8)
.attr('y', -6)
.attr('width', 40)
.attr('height', 14);
yAxisHoverEnter
.append('line')
.attr('x1', 0)
.attr('x2', 6)
.attr('y1', 0)
.attr('y2', 0);
yAxisHoverEnter.append('text').attr('dx', 8).attr('dy', 4);
var ySliceAxisHover = g
.select('.y-slice-axis-hover')
.selectAll('.label')
.data(['y']),
ySliceAxisHoverEnter = ySliceAxisHover
.enter()
.append('g')
.attr('class', 'label'),
ySliceAxisHoverUpdate = ySliceAxisHover.merge(ySliceAxisHoverEnter);
ySliceAxisHoverEnter
.append('rect')
.attr('x', 8)
.attr('y', -6)
.attr('width', 40)
.attr('height', 14);
ySliceAxisHoverEnter
.append('line')
.attr('x1', 0)
.attr('x2', 6)
.attr('y1', 0)
.attr('y2', 0);
ySliceAxisHoverEnter.append('text').attr('dx', 8).attr('dy', 4);
gTransition
.select('.y.axis.slice')
.style('opacity', mode === 'offset' ? 0 : 1)
.attr(
'transform',
'translate(0, ' + (mode === 'offset' ? -sliceHeight : 0) + ')'
)
.call(ySliceAxis);
gTransition
.select('.x.axis')
.attr('transform', 'translate(0, ' + height + ')')
.call(xAxis);
gTransition
.select('.y.axis')
.style('opacity', mode === 'offset' ? 1 : 0)
.attr(
'transform',
'translate(' + width + ', ' + (mode === 'offset' ? 0 : height) + ')'
)
.call(yAxis);
gTransition.selectAll('.tick text').attr('fill', '#aaa');
gTransition.selectAll('.axis path.domain').attr('stroke', 'none');
function onMouseMove() {
var m = d3.mouse(this),
v = xScale.invert(m[0]),
t = yScale.invert(m[1]);
function hoverXIndex(d) {
return Math.min(d[binsProp].length - 1, bisect(d[binsProp], v));
}
var closestSliceData;
var closestSliceDistance = Infinity;
var lastSliceData;
hoverUpdate.attr('transform', function (d, i) {
var index = hoverXIndex(d);
lastSliceData = d;
var x = xScale(
d[binsProp][index][xProp] + d[binsProp][index][dxProp] / 2
);
var y = ySliceScale(d[binsProp][index][yProp]);
var globalY =
mode === 'offset' ? yScale(timeAccessor(d)) - (sliceHeight - y) : y;
var dist = Math.abs(m[1] - globalY);
if (dist < closestSliceDistance) {
closestSliceDistance = dist;
closestSliceData = d;
}
return 'translate(' + x + ',' + y + ')';
});
hoverUpdate.select('text').text(function (d) {
var index = hoverXIndex(d);
return d[binsProp][index][yProp];
});
hoverUpdate.classed('hover-closest', function (d) {
return d === closestSliceData;
});
outlineUpdate.classed('outline-hover', function (d) {
return d === closestSliceData;
});
var index = hoverXIndex(lastSliceData);
xAxisHoverUpdate
.attr('transform', function (d) {
return (
'translate(' +
xScale(
lastSliceData[binsProp][index][xProp] +
lastSliceData[binsProp][index][dxProp] / 2
) +
', ' +
height +
')'
);
})
.select('text')
.text(function (d) {
return format(
lastSliceData[binsProp][index][xProp] +
lastSliceData[binsProp][index][dxProp] / 2
);
});
var fy = yAxis.tickFormat();
yAxisHoverUpdate
.attr('transform', function (d) {
return (
'translate(' +
width +
', ' +
(mode === 'offset' ? yScale(timeAccessor(closestSliceData)) : 0) +
')'
);
})
.style('display', mode === 'offset' ? '' : 'none')
.select('text')
.text(function (d) {
return fy(timeAccessor(closestSliceData));
});
var fsy = ySliceAxis.tickFormat();
ySliceAxisHoverUpdate
.attr('transform', function (d) {
return (
'translate(' +
width +
', ' +
(mode === 'offset'
? 0
: ySliceScale(closestSliceData[binsProp][index][yProp])) +
')'
);
})
.style('display', mode === 'offset' ? 'none' : '')
.select('text')
.text(function (d) {
return fsy(closestSliceData[binsProp][index][yProp]);
});
var svgMouse = d3.mouse(svgNode);
tooltip
.style(
'transform',
'translate(' + (svgMouse[0] + 15) + 'px,' + (svgMouse[1] - 15) + 'px)'
)
.select('span')
.text(
mode === 'offset'
? fsy(closestSliceData[binsProp][index][yProp])
: (timeProp === 'step' ? 'step ' : '') +
fy(timeAccessor(closestSliceData))
);
}
}
}
|
apache-2.0
|
bojanvu23/android_packages_apps_Trebuchet_Gradle
|
Trebuchet/src/main/java/com/lite/android/launcher3/Insettable.java
|
906
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.lite.android.launcher3;
import android.graphics.Rect;
/**
* Allows the implementing {@link View} to not draw underneath system bars.
* e.g., notification bar on top and home key area on the bottom.
*/
public interface Insettable {
void setInsets(Rect insets);
}
|
apache-2.0
|
velmuruganvelayutham/jpa
|
examples/Chapter4/11-tableIdGeneration/src/model/examples/model/Address.java
|
1622
|
package examples.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
@Entity
public class Address {
@TableGenerator(name="Address_Gen",
table="ID_GEN",
pkColumnName="GEN_NAME",
valueColumnName="GEN_VAL",
pkColumnValue="Addr_Gen",
initialValue=10000,
allocationSize=100)
@Id @GeneratedValue(strategy=GenerationType.TABLE,
generator="Address_Gen")
private int id;
private String street;
private String city;
private String state;
private String zip;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String address) {
this.street = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String toString() {
return "Address id: " + getId() +
", street: " + getStreet() +
", city: " + getCity() +
", state: " + getState() +
", zip: " + getZip();
}
}
|
apache-2.0
|
zjshen/presto
|
presto-main/src/main/java/com/facebook/presto/operator/aggregation/AbstractMinMaxByNAggregation.java
|
8905
|
/*
* 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.facebook.presto.operator.aggregation;
import com.facebook.presto.byteCode.DynamicClassLoader;
import com.facebook.presto.metadata.FunctionInfo;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.ParametricAggregation;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.aggregation.state.MinMaxByNState;
import com.facebook.presto.operator.aggregation.state.MinMaxByNStateFactory;
import com.facebook.presto.operator.aggregation.state.MinMaxByNStateSerializer;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.type.ArrayType;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import java.lang.invoke.MethodHandle;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static com.facebook.presto.metadata.Signature.orderableTypeParameter;
import static com.facebook.presto.metadata.Signature.typeParameter;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INDEX;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.NULLABLE_BLOCK_INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.STATE;
import static com.facebook.presto.operator.aggregation.AggregationUtils.generateAggregationName;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.util.Reflection.methodHandle;
import static java.util.Objects.requireNonNull;
public abstract class AbstractMinMaxByNAggregation
extends ParametricAggregation
{
private static final MethodHandle INPUT_FUNCTION = methodHandle(AbstractMinMaxByNAggregation.class, "input", BlockComparator.class, Type.class, Type.class, MinMaxByNState.class, Block.class, Block.class, int.class, long.class);
private static final MethodHandle COMBINE_FUNCTION = methodHandle(AbstractMinMaxByNAggregation.class, "combine", MinMaxByNState.class, MinMaxByNState.class);
private static final MethodHandle OUTPUT_FUNCTION = methodHandle(AbstractMinMaxByNAggregation.class, "output", ArrayType.class, MinMaxByNState.class, BlockBuilder.class);
private final String name;
private final Function<Type, BlockComparator> typeToComparator;
private final Signature signature;
protected AbstractMinMaxByNAggregation(String name, Function<Type, BlockComparator> typeToComparator)
{
this.name = requireNonNull(name, "name is null");
this.typeToComparator = requireNonNull(typeToComparator, "typeToComparator is null");
this.signature = new Signature(name, ImmutableList.of(typeParameter("V"), orderableTypeParameter("K")), "array<V>", ImmutableList.of("V", "K", StandardTypes.BIGINT), false, false);
}
@Override
public Signature getSignature()
{
return signature;
}
@Override
public FunctionInfo specialize(Map<String, Type> types, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
{
Type keyType = types.get("K");
Type valueType = types.get("V");
Signature signature = new Signature(name, new ArrayType(valueType).getTypeSignature(), valueType.getTypeSignature(), keyType.getTypeSignature(), BIGINT.getTypeSignature());
InternalAggregationFunction aggregation = generateAggregation(valueType, keyType);
return new FunctionInfo(signature, getDescription(), aggregation);
}
public static void input(BlockComparator comparator, Type valueType, Type keyType, MinMaxByNState state, Block value, Block key, int blockIndex, long n)
{
TypedKeyValueHeap heap = state.getTypedKeyValueHeap();
if (heap == null) {
if (n <= 0) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "third argument of max_by/min_by must be a positive integer");
}
heap = new TypedKeyValueHeap(comparator, keyType, valueType, Ints.checkedCast(n));
state.setTypedKeyValueHeap(heap);
}
long startSize = heap.getEstimatedSize();
if (!key.isNull(blockIndex)) {
heap.add(key, value, blockIndex);
}
state.addMemoryUsage(heap.getEstimatedSize() - startSize);
}
public static void combine(MinMaxByNState state, MinMaxByNState otherState)
{
TypedKeyValueHeap otherHeap = otherState.getTypedKeyValueHeap();
if (otherHeap == null) {
return;
}
TypedKeyValueHeap heap = state.getTypedKeyValueHeap();
if (heap == null) {
state.setTypedKeyValueHeap(otherHeap);
return;
}
long startSize = heap.getEstimatedSize();
heap.addAll(otherHeap);
state.addMemoryUsage(heap.getEstimatedSize() - startSize);
}
public static void output(ArrayType outputType, MinMaxByNState state, BlockBuilder out)
{
TypedKeyValueHeap heap = state.getTypedKeyValueHeap();
if (heap == null || heap.isEmpty()) {
out.appendNull();
return;
}
Type elementType = outputType.getElementType();
BlockBuilder arrayBlockBuilder = out.beginBlockEntry();
BlockBuilder reversedBlockBuilder = elementType.createBlockBuilder(new BlockBuilderStatus(), heap.getCapacity());
long startSize = heap.getEstimatedSize();
heap.popAll(reversedBlockBuilder);
state.addMemoryUsage(heap.getEstimatedSize() - startSize);
for (int i = reversedBlockBuilder.getPositionCount() - 1; i >= 0; i--) {
elementType.appendTo(reversedBlockBuilder, i, arrayBlockBuilder);
}
out.closeEntry();
}
protected InternalAggregationFunction generateAggregation(Type valueType, Type keyType)
{
DynamicClassLoader classLoader = new DynamicClassLoader(AbstractMinMaxNAggregation.class.getClassLoader());
BlockComparator comparator = typeToComparator.apply(keyType);
List<Type> inputTypes = ImmutableList.of(valueType, keyType, BIGINT);
MinMaxByNStateSerializer stateSerializer = new MinMaxByNStateSerializer(comparator, keyType, valueType);
Type intermediateType = stateSerializer.getSerializedType();
ArrayType outputType = new ArrayType(valueType);
List<AggregationMetadata.ParameterMetadata> inputParameterMetadata = ImmutableList.of(
new AggregationMetadata.ParameterMetadata(STATE),
new AggregationMetadata.ParameterMetadata(NULLABLE_BLOCK_INPUT_CHANNEL, valueType),
new AggregationMetadata.ParameterMetadata(BLOCK_INPUT_CHANNEL, keyType),
new AggregationMetadata.ParameterMetadata(BLOCK_INDEX),
new AggregationMetadata.ParameterMetadata(INPUT_CHANNEL, BIGINT));
AggregationMetadata metadata = new AggregationMetadata(
generateAggregationName(name, valueType, inputTypes),
inputParameterMetadata,
INPUT_FUNCTION.bindTo(comparator).bindTo(valueType).bindTo(keyType),
null,
null,
COMBINE_FUNCTION,
OUTPUT_FUNCTION.bindTo(outputType),
MinMaxByNState.class,
stateSerializer,
new MinMaxByNStateFactory(),
outputType,
false);
GenericAccumulatorFactoryBinder factory = new AccumulatorCompiler().generateAccumulatorFactoryBinder(metadata, classLoader);
return new InternalAggregationFunction(name, inputTypes, intermediateType, outputType, true, false, factory);
}
}
|
apache-2.0
|
donnadionne/grpc
|
src/python/grpcio_health_checking/grpc_version.py
|
710
|
# Copyright 2016 gRPC 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.
# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_health_checking/grpc_version.py.template`!!!
VERSION = '1.33.0.dev0'
|
apache-2.0
|
muuki88/docmatcher
|
src/main/java/de/mukis/docmatcher/csv/Columns.java
|
1454
|
package de.mukis.docmatcher.csv;
import java.util.Arrays;
import java.util.Objects;
import de.mukis.docmatcher.csv.matcher.CsvMatcher;
public class Columns {
private final int[] columns;
private Columns(int[] columns) {
this.columns = columns;
}
public static Columns columns(int first, int second, int... columns) {
int[] cols = new int[2 + columns.length];
cols[0] = first;
cols[1] = second;
System.arraycopy(columns, 0, cols, 2, columns.length);
return new Columns(cols);
}
public static Columns column(int col) {
return new Columns(new int[] { col });
}
public CsvMatcher are(CsvMatcher matcher) {
matcher.setColumns(this);
return matcher;
}
public CsvMatcher is(CsvMatcher matcher) {
return are(matcher);
}
public int[] get() {
return columns;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(columns);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Columns other = (Columns) obj;
return Objects.deepEquals(columns, other.columns);
}
}
|
apache-2.0
|
kunickiaj/datacollector
|
sdc-kafka_0_9/src/main/java/com/streamsets/pipeline/kafka/impl/KafkaProducer09.java
|
4703
|
/*
* Copyright 2017 StreamSets 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.streamsets.pipeline.kafka.impl;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.kafka.api.PartitionStrategy;
import com.streamsets.pipeline.lib.kafka.KafkaConstants;
import com.streamsets.pipeline.lib.kafka.KafkaErrors;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Properties;
public class KafkaProducer09 extends BaseKafkaProducer09 {
private static final Logger LOG = LoggerFactory.getLogger(KafkaProducer09.class);
public static final String ACKS_DEFAULT = "1";
public static final String RANDOM_PARTITIONER_CLASS = "com.streamsets.pipeline.kafka.impl.RandomPartitioner";
public static final String ROUND_ROBIN_PARTITIONER_CLASS = "com.streamsets.pipeline.kafka.impl.RoundRobinPartitioner";
public static final String EXPRESSION_PARTITIONER_CLASS = "com.streamsets.pipeline.kafka.impl.ExpressionPartitioner";
private final String metadataBrokerList;
private final Map<String, Object> kafkaProducerConfigs;
private final PartitionStrategy partitionStrategy;
public KafkaProducer09(
String metadataBrokerList,
Map<String, Object> kafkaProducerConfigs,
PartitionStrategy partitionStrategy,
boolean sendWriteResponse
) {
super(sendWriteResponse);
this.metadataBrokerList = metadataBrokerList;
this.kafkaProducerConfigs = kafkaProducerConfigs;
this.partitionStrategy = partitionStrategy;
}
@Override
protected Producer<Object, byte[]> createKafkaProducer() {
Properties props = new Properties();
// bootstrap servers
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, metadataBrokerList);
// request.required.acks
props.put(ProducerConfig.ACKS_CONFIG, ACKS_DEFAULT);
// partitioner.class
props.put(
KafkaConstants.KEY_SERIALIZER_CLASS_CONFIG,
kafkaProducerConfigs.get(KafkaConstants.KEY_SERIALIZER_CLASS_CONFIG));
props.put(KafkaConstants.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
configurePartitionStrategy(props, partitionStrategy);
addUserConfiguredProperties(kafkaProducerConfigs, props);
return new KafkaProducer<>(props);
}
@Override
protected StageException createWriteException(Exception e) {
// error writing this record to kafka broker.
LOG.error(KafkaErrors.KAFKA_50.getMessage(), e.toString(), e);
// throwing of this exception results in stopped pipeline as it is not handled by KafkaTarget
// Retry feature at the pipeline level will re attempt
return new StageException(KafkaErrors.KAFKA_50, e.toString(), e);
}
private void configurePartitionStrategy(Properties props, PartitionStrategy partitionStrategy) {
if (partitionStrategy == PartitionStrategy.RANDOM) {
props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, RANDOM_PARTITIONER_CLASS);
} else if (partitionStrategy == PartitionStrategy.ROUND_ROBIN) {
props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, ROUND_ROBIN_PARTITIONER_CLASS);
} else if (partitionStrategy == PartitionStrategy.EXPRESSION) {
props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, EXPRESSION_PARTITIONER_CLASS);
} else if (partitionStrategy == PartitionStrategy.DEFAULT) {
// org.apache.kafka.clients.producer.internals.DefaultPartitioner
}
}
private void addUserConfiguredProperties(Map<String, Object> kafkaClientConfigs, Properties props) {
//The following options, if specified, are ignored : "bootstrap.servers"
if (kafkaClientConfigs != null && !kafkaClientConfigs.isEmpty()) {
kafkaClientConfigs.remove(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG);
for (Map.Entry<String, Object> producerConfig : kafkaClientConfigs.entrySet()) {
props.put(producerConfig.getKey(), producerConfig.getValue());
}
}
}
}
|
apache-2.0
|
pechemann/jec-glasscat-core
|
src/com/onsoft/glasscat/security/session/managers/EjpSessionManager.ts
|
4312
|
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
//
// Copyright 2016-2018 Pascal ECHEMANN.
//
// 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.
import {SessionManager} from "./SessionManager";
import {GlobalGuidGenerator} from "jec-commons";
import * as crypto from "crypto";
import {SecurityManager} from "../../../core/SecurityManager";
import {Session, SessionError, SessionId} from "jec-exchange";
import {SessionStorage} from "../connectors/SessionStorage";
import {SessionIdUtil} from "../utils/SessionIdUtil";
import {SessionIdBuilder} from "../utils/SessionIdBuilder";
/**
* The default <code>SessionManager</code> implementation to be used by GlassCat
* servers.
*/
export class EjpSessionManager implements SessionManager {
//////////////////////////////////////////////////////////////////////////////
// Constructor function
//////////////////////////////////////////////////////////////////////////////
/**
* Creates a new <code>EjpSessionManager</code> instance.
*/
constructor() {
this.init();
}
//////////////////////////////////////////////////////////////////////////////
// Private properties
//////////////////////////////////////////////////////////////////////////////
/**
* The reference to the GUID for this manager.
*/
private _guid:string = null;
/**
* The type of algorithm used by the associated<code>UserHashModule</code>
* instance for cookies encryption.
*/
private readonly HASH_ALGORITHM:string = "sha256";
/**
* The type of output encoding used by the associated
* <code>UserHashModule</code> instance for cookies encryption.
*/
private readonly OUTPUT_ENCODING:any = "hex";
/**
* The reference to the <code>SessionStorage</code> instance for this manager.
*/
private _connector:SessionStorage = null;
/**
* The reference to the <code>SessionIdBuilder</code> instance for this
* manager.
*/
private _sessionIdBuilder:SessionIdBuilder = null;
//////////////////////////////////////////////////////////////////////////////
// Private methods
//////////////////////////////////////////////////////////////////////////////
/**
* Initializes this session manager.
*/
private init():void {
this._guid = GlobalGuidGenerator.getInstance().generate();
this._sessionIdBuilder = new SessionIdBuilder();
}
//////////////////////////////////////////////////////////////////////////////
// Public methods
//////////////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
public getSessionStorage():SessionStorage {
return this._connector;
}
/**
* @inheritDoc
*/
public setSessionStorage(sessionStorage:SessionStorage):void {
//TODO : log this action
this._connector = sessionStorage;
}
/**
* @inheritDoc
*/
public initSessionId():SessionId {
const sha:crypto.Hash = crypto.createHash(this.HASH_ALGORITHM)
.update(Date.now() + this._guid);
const sessionId:SessionId = this._sessionIdBuilder.buildSessionId(
sha.digest(this.OUTPUT_ENCODING)
);
return sessionId;
}
/**
* @inheritDoc
*/
public addSession(session:Session, result:(error?:SessionError)=>any):void {
this._connector.add(session, result);
}
/**
* @inheritDoc
*/
public getSession(sessionId:SessionId, success:(session:Session)=>any,
error:(error:SessionError)=>any):void {
this._connector.get(
sessionId,
success,
error
);
}
/**
* @inheritDoc
*/
public removeSession(sessionId:SessionId,
result:(error?:SessionError)=>any):void {
this._connector.remove(sessionId, result);
}
}
|
apache-2.0
|
ambasta/aws-sdk-cpp
|
aws-cpp-sdk-autoscaling/source/model/DeleteAutoScalingGroupRequest.cpp
|
1408
|
/*
* Copyright 2010-2016 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.
*/
#include <aws/autoscaling/model/DeleteAutoScalingGroupRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::AutoScaling::Model;
using namespace Aws::Utils;
DeleteAutoScalingGroupRequest::DeleteAutoScalingGroupRequest() :
m_autoScalingGroupNameHasBeenSet(false),
m_forceDelete(false),
m_forceDeleteHasBeenSet(false)
{
}
Aws::String DeleteAutoScalingGroupRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=DeleteAutoScalingGroup&";
if(m_autoScalingGroupNameHasBeenSet)
{
ss << "AutoScalingGroupName=" << StringUtils::URLEncode(m_autoScalingGroupName.c_str()) << "&";
}
if(m_forceDeleteHasBeenSet)
{
ss << "ForceDelete=" << m_forceDelete << "&";
}
ss << "Version=2011-01-01";
return ss.str();
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Cylindrosporium/Cylindrosporium paludosum/README.md
|
203
|
# Cylindrosporium paludosum J. Schröt. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Cylindrosporium paludosum J. Schröt.
### Remarks
null
|
apache-2.0
|
baowp/platform
|
biz/src/main/java/com/abbcc/service/CellbindService.java
|
1720
|
/**
* Copyright (c) 2010 Abbcc Corp.
* No 225,Wen Yi RD, Hang Zhou, Zhe Jiang, China.
* All rights reserved.
*
* "AdminService.java is the copyrighted,
* proprietary property of Abbcc Company and its
* subsidiaries and affiliates which retain all right, title and interest
* therein."
*
* Revision History
*
* Date Programmer Notes
* --------- --------------------- --------------------------------------------
* 2009-12-9 wangjin initial
**/
package com.abbcc.service;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import com.abbcc.common.PaginationSupport;
import com.abbcc.models.AbcCellbind;
/**
* *AdminService.java
*/
public interface CellbindService extends BaseService{
public void save(AbcCellbind transientInstance);
public void delete(AbcCellbind persistentInstance);
public AbcCellbind findById(String id);
public List<AbcCellbind> findByExample(AbcCellbind instance);
public List<AbcCellbind> findAll();
public void saveOrUpdate(AbcCellbind instance);
public PaginationSupport findPageByCriteria(
DetachedCriteria detachedCriteria);
public PaginationSupport findPageByCriteria(
DetachedCriteria detachedCriteria, int startIndex);
public PaginationSupport findPageByCriteria(
DetachedCriteria detachedCriteria, int pageSize, int startIndex);
public List findAllByCriteria(DetachedCriteria detachedCriteria);
public int getCountByCriteria(DetachedCriteria detachedCriteria);
public void callProcedure(String procString, List<Object> params)
throws Exception;
public List getCallProcedureResult(String procString, List<Object> params)
throws Exception;
}
|
apache-2.0
|
vincent99/cattle
|
code/iaas/model/src/main/java/io/cattle/platform/core/model/tables/ConfigItemStatusTable.java
|
7442
|
/*
* This file is generated by jOOQ.
*/
package io.cattle.platform.core.model.tables;
import io.cattle.platform.core.model.CattleTable;
import io.cattle.platform.core.model.Keys;
import io.cattle.platform.core.model.tables.records.ConfigItemStatusRecord;
import io.cattle.platform.db.jooq.converter.DateConverter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.9.3"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ConfigItemStatusTable extends TableImpl<ConfigItemStatusRecord> {
private static final long serialVersionUID = -1272483914;
/**
* The reference instance of <code>cattle.config_item_status</code>
*/
public static final ConfigItemStatusTable CONFIG_ITEM_STATUS = new ConfigItemStatusTable();
/**
* The class holding records for this type
*/
@Override
public Class<ConfigItemStatusRecord> getRecordType() {
return ConfigItemStatusRecord.class;
}
/**
* The column <code>cattle.config_item_status.id</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> ID = createField("id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, "");
/**
* The column <code>cattle.config_item_status.name</code>.
*/
public final TableField<ConfigItemStatusRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>cattle.config_item_status.requested_version</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> REQUESTED_VERSION = createField("requested_version", org.jooq.impl.SQLDataType.BIGINT.nullable(false).defaultValue(org.jooq.impl.DSL.inline("0", org.jooq.impl.SQLDataType.BIGINT)), this, "");
/**
* The column <code>cattle.config_item_status.applied_version</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> APPLIED_VERSION = createField("applied_version", org.jooq.impl.SQLDataType.BIGINT.nullable(false).defaultValue(org.jooq.impl.DSL.inline("-1", org.jooq.impl.SQLDataType.BIGINT)), this, "");
/**
* The column <code>cattle.config_item_status.source_version</code>.
*/
public final TableField<ConfigItemStatusRecord, String> SOURCE_VERSION = createField("source_version", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "");
/**
* The column <code>cattle.config_item_status.requested_updated</code>.
*/
public final TableField<ConfigItemStatusRecord, Date> REQUESTED_UPDATED = createField("requested_updated", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "", new DateConverter());
/**
* The column <code>cattle.config_item_status.applied_updated</code>.
*/
public final TableField<ConfigItemStatusRecord, Date> APPLIED_UPDATED = createField("applied_updated", org.jooq.impl.SQLDataType.TIMESTAMP, this, "", new DateConverter());
/**
* The column <code>cattle.config_item_status.agent_id</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> AGENT_ID = createField("agent_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.config_item_status.account_id</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> ACCOUNT_ID = createField("account_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.config_item_status.service_id</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> SERVICE_ID = createField("service_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.config_item_status.resource_id</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> RESOURCE_ID = createField("resource_id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, "");
/**
* The column <code>cattle.config_item_status.resource_type</code>.
*/
public final TableField<ConfigItemStatusRecord, String> RESOURCE_TYPE = createField("resource_type", org.jooq.impl.SQLDataType.VARCHAR.length(128).nullable(false), this, "");
/**
* The column <code>cattle.config_item_status.environment_id</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> STACK_ID = createField("environment_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.config_item_status.host_id</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> HOST_ID = createField("host_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>cattle.config_item_status.deployment_unit_id</code>.
*/
public final TableField<ConfigItemStatusRecord, Long> DEPLOYMENT_UNIT_ID = createField("deployment_unit_id", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* Create a <code>cattle.config_item_status</code> table reference
*/
public ConfigItemStatusTable() {
this("config_item_status", null);
}
/**
* Create an aliased <code>cattle.config_item_status</code> table reference
*/
public ConfigItemStatusTable(String alias) {
this(alias, CONFIG_ITEM_STATUS);
}
private ConfigItemStatusTable(String alias, Table<ConfigItemStatusRecord> aliased) {
this(alias, aliased, null);
}
private ConfigItemStatusTable(String alias, Table<ConfigItemStatusRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return CattleTable.CATTLE;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<ConfigItemStatusRecord, Long> getIdentity() {
return Keys.IDENTITY_CONFIG_ITEM_STATUS;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<ConfigItemStatusRecord> getPrimaryKey() {
return Keys.KEY_CONFIG_ITEM_STATUS_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<ConfigItemStatusRecord>> getKeys() {
return Arrays.<UniqueKey<ConfigItemStatusRecord>>asList(Keys.KEY_CONFIG_ITEM_STATUS_PRIMARY, Keys.KEY_CONFIG_ITEM_STATUS_IDX_CONFIG_ITEM_STATUS_RESOURCE);
}
/**
* {@inheritDoc}
*/
@Override
public List<ForeignKey<ConfigItemStatusRecord, ?>> getReferences() {
return Arrays.<ForeignKey<ConfigItemStatusRecord, ?>>asList(Keys.FK_CONFIG_ITEM__NAME, Keys.FK_CONFIG_ITEM__AGENT_ID, Keys.FK_CONFIG_ITEM__ACCOUNT_ID, Keys.FK_CONFIG_ITEM__SERVICE_ID, Keys.FK_CONFIG_ITEM__ENVIRONMENT_ID, Keys.FK_CONFIG_ITEM__HOST_ID, Keys.FK_CONFIG_ITEM__DEPLOYMENT_UNIT_ID);
}
/**
* {@inheritDoc}
*/
@Override
public ConfigItemStatusTable as(String alias) {
return new ConfigItemStatusTable(alias, this);
}
/**
* Rename this table
*/
@Override
public ConfigItemStatusTable rename(String name) {
return new ConfigItemStatusTable(name, null);
}
}
|
apache-2.0
|
alibehzadian/Smartlab
|
Custom Views/PersianDatePicker-Example/src/com/example/persiandatepicker/PersianDatePicker.java
|
2282
|
package com.example.persiandatepicker;
import java.util.Date;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.Toast;
public class PersianDatePicker extends LinearLayout {
private NumberPicker yearNumberPicker, monthNumberPicker, dayNumberPicker;
public PersianDatePicker(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public PersianDatePicker(Context context) {
this(context, null, -1);
}
public PersianDatePicker(final Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View root = inflater.inflate(R.layout.pdp, this);
yearNumberPicker = (NumberPicker) root
.findViewById(R.id.yearNumberPicker);
monthNumberPicker = (NumberPicker) root
.findViewById(R.id.monthNumberPicker);
dayNumberPicker = (NumberPicker) root
.findViewById(R.id.dayNumberPicker);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PersianDatePicker, 0, 0);
int year = 1393,month=6,day=19;
year = a.getInteger(R.styleable.PersianDatePicker_year, 1393);
month = a.getInteger(R.styleable.PersianDatePicker_month, 6);
day = a.getInteger(R.styleable.PersianDatePicker_day, 19);
a.recycle();
yearNumberPicker.setMinValue(1380);
yearNumberPicker.setMaxValue(1400);
yearNumberPicker.setValue(year);
monthNumberPicker.setMinValue(1);
monthNumberPicker.setMaxValue(12);
monthNumberPicker.setValue(month);
dayNumberPicker.setMaxValue(31);
dayNumberPicker.setMinValue(1);
dayNumberPicker.setValue(day);
yearNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker np, int oldValue, int newValue) {
Toast.makeText(context, "Year changed:" + oldValue + " -> " + newValue, Toast.LENGTH_LONG).show();
}
});
}
public Date getSelectedDate() {
return null;
}
public void setSelectedDate(Date date) {
}
}
|
apache-2.0
|
UniversalDependencies/docs
|
treebanks/no_bokmaal/no_bokmaal-pos-PART.md
|
7980
|
---
layout: base
title: 'Statistics of PART in UD_Norwegian-Bokmaal'
udver: '2'
---
## Treebank Statistics: UD_Norwegian-Bokmaal: POS Tags: `PART`
There are 4 `PART` lemmas (0%), 4 `PART` types (0%) and 6998 `PART` tokens (2%).
Out of 17 observed tags, the rank of `PART` is: 17 in number of lemmas, 17 in number of types and 13 in number of tokens.
The 10 most frequent `PART` lemmas: <em>å, ikke, ei, og</em>
The 10 most frequent `PART` types: <em>å, ikke, og, ei</em>
The 10 most frequent ambiguous lemmas: <em>å</em> (<tt><a href="no_bokmaal-pos-PART.html">PART</a></tt> 4309, <tt><a href="no_bokmaal-pos-INTJ.html">INTJ</a></tt> 6, <tt><a href="no_bokmaal-pos-X.html">X</a></tt> 4), <em>og</em> (<tt><a href="no_bokmaal-pos-CCONJ.html">CCONJ</a></tt> 7977, <tt><a href="no_bokmaal-pos-X.html">X</a></tt> 3, <tt><a href="no_bokmaal-pos-ADV.html">ADV</a></tt> 1, <tt><a href="no_bokmaal-pos-PART.html">PART</a></tt> 1)
The 10 most frequent ambiguous types: <em>å</em> (<tt><a href="no_bokmaal-pos-PART.html">PART</a></tt> 4246, <tt><a href="no_bokmaal-pos-CCONJ.html">CCONJ</a></tt> 4, <tt><a href="no_bokmaal-pos-X.html">X</a></tt> 4, <tt><a href="no_bokmaal-pos-ADP.html">ADP</a></tt> 1, <tt><a href="no_bokmaal-pos-AUX.html">AUX</a></tt> 1, <tt><a href="no_bokmaal-pos-INTJ.html">INTJ</a></tt> 1), <em>og</em> (<tt><a href="no_bokmaal-pos-CCONJ.html">CCONJ</a></tt> 7570, <tt><a href="no_bokmaal-pos-PART.html">PART</a></tt> 5, <tt><a href="no_bokmaal-pos-X.html">X</a></tt> 3, <tt><a href="no_bokmaal-pos-ADV.html">ADV</a></tt> 1, <tt><a href="no_bokmaal-pos-SCONJ.html">SCONJ</a></tt> 1), <em>ei</em> (<tt><a href="no_bokmaal-pos-DET.html">DET</a></tt> 38, <tt><a href="no_bokmaal-pos-PART.html">PART</a></tt> 1)
* <em>å</em>
* <tt><a href="no_bokmaal-pos-PART.html">PART</a></tt> 4246: <em>Det var grusomt <b>å</b> høre på . »</em>
* <tt><a href="no_bokmaal-pos-CCONJ.html">CCONJ</a></tt> 4: <em>De fleste av småpartiene vil samarbeide med Ap , men er ikke enige om hvem andre det er som bør få være med <b>å</b> styre .</em>
* <tt><a href="no_bokmaal-pos-X.html">X</a></tt> 4: <em>Itj bruk tid på <b>å</b> ha på dåkk klea , ell bærg brølløpsbildan .</em>
* <tt><a href="no_bokmaal-pos-ADP.html">ADP</a></tt> 1: <em>Derfor spør jeg meg selv ; hvis det er lov å betale Ruter penger for å oppfordre offentligheten til å dø av hjerteinfarkt - er det da også OK og dra hjem til de ansatte i Ruter og skyte amfetamin inn <b>å</b> øya på familiene deres ?</em>
* <tt><a href="no_bokmaal-pos-AUX.html">AUX</a></tt> 1: <em>Og for at også jeg <b>å</b> komme med en bekjennelse :</em>
* <tt><a href="no_bokmaal-pos-INTJ.html">INTJ</a></tt> 1: <em>" <b>å</b> ja , det har vært et døende språk i over hundre år .</em>
* <em>og</em>
* <tt><a href="no_bokmaal-pos-CCONJ.html">CCONJ</a></tt> 7570: <em>Det blir et spark som straff , i moralens navn <b>og</b> på vegne av oss alle .</em>
* <tt><a href="no_bokmaal-pos-PART.html">PART</a></tt> 5: <em>Og han synes det er helt greit å slippe <b>og</b> skifte dekk selv .</em>
* <tt><a href="no_bokmaal-pos-X.html">X</a></tt> 3: <em>Kåm dåkk ut , <b>og</b> det litt breinnkvikt " , kanskje ?</em>
* <tt><a href="no_bokmaal-pos-ADV.html">ADV</a></tt> 1: <em>Jeg tror det er fullt mulig å finne en driftsmodell som muliggjør et fortsatt liv side om side med nettet <b>og</b> langt utover 20 år .</em>
* <tt><a href="no_bokmaal-pos-SCONJ.html">SCONJ</a></tt> 1: <em>Den endelige beslutningen , eller overveiingen <b>og</b> å begå drap , ble tatt av domfelte om ettermiddagen og kvelden på drapsdagen 31. oktober 1996 da domfelte ladet våpenet , satte det i et skulderhylster og dro til Skaregata 2 .</em>
* <em>ei</em>
* <tt><a href="no_bokmaal-pos-DET.html">DET</a></tt> 38: <em>Hva i all verden skal jeg skrive om i <b>ei</b> slik bok ? » .</em>
* <tt><a href="no_bokmaal-pos-PART.html">PART</a></tt> 1: <em>Forlovede par skilles ikke i en kongelig prosesjon , <b>ei</b> heller ved det kongelige taffel .</em>
## Morphology
The form / lemma ratio of `PART` is 1.000000 (the average of all parts of speech is 1.381903).
The 1st highest number of forms (2) was observed with the lemma “å”: <em>og, å</em>.
The 2nd highest number of forms (1) was observed with the lemma “ei”: <em>ei</em>.
The 3rd highest number of forms (1) was observed with the lemma “ikke”: <em>ikke</em>.
`PART` occurs with 1 features: <tt><a href="no_bokmaal-feat-Polarity.html">Polarity</a></tt> (2687; 38% instances)
`PART` occurs with 1 feature-value pairs: `Polarity=Neg`
`PART` occurs with 2 feature combinations.
The most frequent feature combination is `_` (4311 tokens).
Examples: <em>å, og, ei</em>
## Relations
`PART` nodes are attached to their parents using 8 different relations: <tt><a href="no_bokmaal-dep-mark.html">mark</a></tt> (4305; 62% instances), <tt><a href="no_bokmaal-dep-advmod.html">advmod</a></tt> (2634; 38% instances), <tt><a href="no_bokmaal-dep-nmod.html">nmod</a></tt> (34; 0% instances), <tt><a href="no_bokmaal-dep-conj.html">conj</a></tt> (13; 0% instances), <tt><a href="no_bokmaal-dep-root.html">root</a></tt> (5; 0% instances), <tt><a href="no_bokmaal-dep-flat-name.html">flat:name</a></tt> (3; 0% instances), <tt><a href="no_bokmaal-dep-orphan.html">orphan</a></tt> (2; 0% instances), <tt><a href="no_bokmaal-dep-reparandum.html">reparandum</a></tt> (2; 0% instances)
Parents of `PART` nodes belong to 13 different parts of speech: <tt><a href="no_bokmaal-pos-VERB.html">VERB</a></tt> (5954; 85% instances), <tt><a href="no_bokmaal-pos-ADJ.html">ADJ</a></tt> (495; 7% instances), <tt><a href="no_bokmaal-pos-NOUN.html">NOUN</a></tt> (323; 5% instances), <tt><a href="no_bokmaal-pos-ADV.html">ADV</a></tt> (99; 1% instances), <tt><a href="no_bokmaal-pos-PRON.html">PRON</a></tt> (56; 1% instances), <tt><a href="no_bokmaal-pos-ADP.html">ADP</a></tt> (21; 0% instances), <tt><a href="no_bokmaal-pos-PROPN.html">PROPN</a></tt> (20; 0% instances), <tt><a href="no_bokmaal-pos-DET.html">DET</a></tt> (11; 0% instances), <tt><a href="no_bokmaal-pos-SCONJ.html">SCONJ</a></tt> (9; 0% instances), (5; 0% instances), <tt><a href="no_bokmaal-pos-INTJ.html">INTJ</a></tt> (2; 0% instances), <tt><a href="no_bokmaal-pos-NUM.html">NUM</a></tt> (2; 0% instances), <tt><a href="no_bokmaal-pos-AUX.html">AUX</a></tt> (1; 0% instances)
6890 (98%) `PART` nodes are leaves.
96 (1%) `PART` nodes have one child.
7 (0%) `PART` nodes have two children.
5 (0%) `PART` nodes have three or more children.
The highest child degree of a `PART` node is 4.
Children of `PART` nodes are attached using 9 different relations: <tt><a href="no_bokmaal-dep-advmod.html">advmod</a></tt> (86; 67% instances), <tt><a href="no_bokmaal-dep-punct.html">punct</a></tt> (18; 14% instances), <tt><a href="no_bokmaal-dep-cc.html">cc</a></tt> (11; 9% instances), <tt><a href="no_bokmaal-dep-obl.html">obl</a></tt> (5; 4% instances), <tt><a href="no_bokmaal-dep-conj.html">conj</a></tt> (2; 2% instances), <tt><a href="no_bokmaal-dep-discourse.html">discourse</a></tt> (2; 2% instances), <tt><a href="no_bokmaal-dep-orphan.html">orphan</a></tt> (2; 2% instances), <tt><a href="no_bokmaal-dep-ccomp.html">ccomp</a></tt> (1; 1% instances), <tt><a href="no_bokmaal-dep-xcomp.html">xcomp</a></tt> (1; 1% instances)
Children of `PART` nodes belong to 8 different parts of speech: <tt><a href="no_bokmaal-pos-ADV.html">ADV</a></tt> (57; 45% instances), <tt><a href="no_bokmaal-pos-ADJ.html">ADJ</a></tt> (31; 24% instances), <tt><a href="no_bokmaal-pos-PUNCT.html">PUNCT</a></tt> (18; 14% instances), <tt><a href="no_bokmaal-pos-CCONJ.html">CCONJ</a></tt> (12; 9% instances), <tt><a href="no_bokmaal-pos-NOUN.html">NOUN</a></tt> (6; 5% instances), <tt><a href="no_bokmaal-pos-INTJ.html">INTJ</a></tt> (2; 2% instances), <tt><a href="no_bokmaal-pos-ADP.html">ADP</a></tt> (1; 1% instances), <tt><a href="no_bokmaal-pos-VERB.html">VERB</a></tt> (1; 1% instances)
|
apache-2.0
|
rock3r/detekt
|
docs/pages/kdoc/detekt-api/io.gitlab.arturbosch.detekt.api/-context/report.md
|
2442
|
---
title: Context.report - detekt-api
---
[detekt-api](../../index.html) / [io.gitlab.arturbosch.detekt.api](../index.html) / [Context](index.html) / [report](./report.html)
# report
`abstract fun ~~report~~(finding: `[`Finding`](../-finding/index.html)`, aliases: `[`Set`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html)`<`[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`> = emptySet()): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)
**Deprecated:** Overloaded version with extra ruleSetId parameter should be used.
Reports a single new violation.
`open fun report(finding: `[`Finding`](../-finding/index.html)`, aliases: `[`Set`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html)`<`[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`> = emptySet(), ruleSetId: `[`RuleSetId`](../-rule-set-id.html)`? = null): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)
Reports a single new violation.
By contract the implementation can check if
this finding is already suppressed and should not get reported.
An alias set can be given to additionally check if an alias was used when suppressing.
Additionally suppression by rule set id is supported.
`abstract fun ~~report~~(findings: `[`List`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)`<`[`Finding`](../-finding/index.html)`>, aliases: `[`Set`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html)`<`[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`> = emptySet()): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)
**Deprecated:** Overloaded version with extra ruleSetId parameter should be used.
`open fun report(findings: `[`List`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)`<`[`Finding`](../-finding/index.html)`>, aliases: `[`Set`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html)`<`[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`> = emptySet(), ruleSetId: `[`RuleSetId`](../-rule-set-id.html)`? = null): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)
Same as [report](./report.html) but reports a list of findings.
|
apache-2.0
|
phoxy/phoxy
|
subsystem/internal.js
|
2785
|
phoxy.internal =
{
ChangeURL : function (url)
{
url = phoxy.ConstructURL(url);
phoxy.Log(4, "History push", url);
if (url[0] !== '/')
url = '/' + url;
history.pushState({}, document.title, url);
return false;
}
,
Reset : function (url)
{
if ((url || true) === true)
return location.reload();
location = url;
}
,
Config : function()
{
return phoxy._.config;
}
,
Log : function(level)
{
if (phoxy.state.verbose < level)
return;
var error_names = phoxy._.internal.error_names;
var errorname = error_names[level < error_names.length ? level : error_names.length - 1];
var args = [];
for (var v in arguments)
args.push(arguments[v]);
args[0] = errorname;
var error_methods = phoxy._.internal.error_methods;
var method = error_methods[level < error_methods.length ? level : error_methods.length - 1];
console[method].apply(console, args);
if (level === 0)
throw "Break execution on fatal log";
}
,
Override: function(method_name, new_method)
{
return phoxy._.internal.Override(phoxy, method_name, new_method);
}
};
phoxy._.internal =
{
Load : function( )
{
phoxy.state.loaded = true;
phoxy._.click.InitClickHook();
}
,
GenerateUniqueID : function()
{
var ret = "";
var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 10; i++)
ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));
return "phoxy_" + ret;
}
,
DispatchEvent : function(dom_element_id, event_name)
{
var that = phoxy._.render.Div(dom_element_id);
if (document.createEvent)
{
var event = document.createEvent("HTMLEvents");
event.initEvent(event_name, true, true);
event.eventName = event_name;
that.dispatchEvent(event);
}
else
{
var event = document.createEventObject();
event.eventType = event_name;
event.eventName = event_name;
that.fireEvent("on" + event.eventType, event);
}
}
,
HookEvent : function(dom_element_id, event_name, callback)
{
var that = phoxy._.render.Div(dom_element_id);
that.addEventListener(event_name, callback);
}
,
Override : function(object, method_name, new_method)
{
var origin = object[method_name];
object[method_name] = new_method;
object[method_name].origin = origin;
}
,
error_names :
[
"FATAL",
"ERROR",
"WARNING",
"INFO",
"DEBUG"
],
error_methods :
[
"error",
"error",
"warn",
"info",
"log",
"debug"
]
};
|
apache-2.0
|
lucky-code/Practice
|
kuaichuan2.0/app/src/main/java/com/ckt/io/wifidirect/fragment/DeviceListFragment.java
|
6668
|
package com.ckt.io.wifidirect.fragment;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.ckt.io.wifidirect.activity.WiFiDirectActivity;
import com.ckt.io.wifidirect.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lu on 2016/5/22.
*/
public class DeviceListFragment extends ListFragment implements WifiP2pManager.PeerListListener,SwipeRefreshLayout.OnRefreshListener {
private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
ProgressDialog progressDialog = null;
View mContentView = null;
private WifiP2pDevice device;
private SwipeRefreshLayout swipeRefreshLayout;
private WifiManager wifiManager = null;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.setListAdapter(new WiFiPeerListAdapter(getActivity(), R.layout.row_devices, peers));
wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
swipeRefreshLayout = (SwipeRefreshLayout)getActivity().findViewById(R.id.id_swip_ly);
swipeRefreshLayout.setOnRefreshListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.device_list, null);
return mContentView;
}
public void onRefresh(){
if (!wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
}
Intent intent = new Intent("UPDATE_PEERS");
getActivity().sendBroadcast(intent);
swipeRefreshLayout.setRefreshing(false);
}
/**
* @return this device
*/
public WifiP2pDevice getDevice() {
return device;
}
private static String getDeviceStatus(int deviceStatus) {
Log.d(WiFiDirectActivity.TAG, "Peer status :" + deviceStatus);
switch (deviceStatus) {
case WifiP2pDevice.AVAILABLE:
return "Available";
case WifiP2pDevice.INVITED:
return "Invited";
case WifiP2pDevice.CONNECTED:
return "Connected";
case WifiP2pDevice.FAILED:
return "Failed";
case WifiP2pDevice.UNAVAILABLE:
return "Unavailable";
default:
return "Unknown";
}
}
/**
* Initiate a connection with the peer.
*/
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
WifiP2pDevice device = (WifiP2pDevice) getListAdapter().getItem(position);
((DeviceActionListener) getActivity()).showDetails(device);
}
/**
* Array adapter for ListFragment that maintains WifiP2pDevice list.
*/
private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> {
private List<WifiP2pDevice> items;
/**
* @param context
* @param textViewResourceId
* @param objects
*/
public WiFiPeerListAdapter(Context context, int textViewResourceId,
List<WifiP2pDevice> objects) {
super(context, textViewResourceId, objects);
items = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row_devices, null);
}
WifiP2pDevice device = items.get(position);
if (device != null) {
TextView top = (TextView) v.findViewById(R.id.device_name);
TextView bottom = (TextView) v.findViewById(R.id.device_details);
if (top != null) {
top.setText(device.deviceName);
}
if (bottom != null) {
bottom.setText(getDeviceStatus(device.status));
}
}
return v;
}
}
/**
* Update UI for this device.
*
* @param device WifiP2pDevice object
*/
public void updateThisDevice(WifiP2pDevice device) {
this.device = device;
TextView view = (TextView) mContentView.findViewById(R.id.my_name);
view.setText(device.deviceName);
view = (TextView) mContentView.findViewById(R.id.my_status);
view.setText(getDeviceStatus(device.status));
}
@Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
peers.clear();
peers.addAll(peerList.getDeviceList());
((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
if (peers.size() == 0) {
Log.d(WiFiDirectActivity.TAG, "No devices found");
return;
}
}
public void clearPeers() {
peers.clear();
((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
}
/**
*
*/
public void onInitiateDiscovery() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel", "finding peers", true,
true, new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
});
}
/**
* An interface-callback for the activity to listen to fragment interaction
* events.
*/
public interface DeviceActionListener {
void showDetails(WifiP2pDevice device);
void cancelDisconnect();
void connect(WifiP2pConfig config);
void disconnect();
}
}
|
apache-2.0
|
ascrutae/sky-walking
|
oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/meter/function/avg/AvgFunction.java
|
7837
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.oap.server.core.analysis.meter.function.avg;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.skywalking.oap.server.core.Const;
import org.apache.skywalking.oap.server.core.UnexpectedException;
import org.apache.skywalking.oap.server.core.analysis.manual.instance.InstanceTraffic;
import org.apache.skywalking.oap.server.core.analysis.meter.MeterEntity;
import org.apache.skywalking.oap.server.core.analysis.meter.function.AcceptableValue;
import org.apache.skywalking.oap.server.core.analysis.meter.function.MeterFunction;
import org.apache.skywalking.oap.server.core.analysis.metrics.LongValueHolder;
import org.apache.skywalking.oap.server.core.analysis.metrics.Metrics;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.ConstOne;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.Entrance;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.SourceFrom;
import org.apache.skywalking.oap.server.core.query.sql.Function;
import org.apache.skywalking.oap.server.core.remote.grpc.proto.RemoteData;
import org.apache.skywalking.oap.server.core.storage.StorageHashMapBuilder;
import org.apache.skywalking.oap.server.core.storage.annotation.Column;
@MeterFunction(functionName = "avg")
@ToString
public abstract class AvgFunction extends Metrics implements AcceptableValue<Long>, LongValueHolder {
protected static final String SUMMATION = "summation";
protected static final String COUNT = "count";
protected static final String VALUE = "value";
@Setter
@Getter
@Column(columnName = ENTITY_ID, length = 512)
private String entityId;
/**
* Service ID is required for sort query.
*/
@Setter
@Getter
@Column(columnName = InstanceTraffic.SERVICE_ID)
private String serviceId;
@Getter
@Setter
@Column(columnName = SUMMATION, storageOnly = true)
protected long summation;
@Getter
@Setter
@Column(columnName = COUNT, storageOnly = true)
protected long count;
@Getter
@Setter
@Column(columnName = VALUE, dataType = Column.ValueDataType.COMMON_VALUE, function = Function.Avg)
private long value;
@Entrance
public final void combine(@SourceFrom long summation, @ConstOne long count) {
this.summation += summation;
this.count += count;
}
@Override
public final boolean combine(Metrics metrics) {
AvgFunction longAvgMetrics = (AvgFunction) metrics;
combine(longAvgMetrics.summation, longAvgMetrics.count);
return true;
}
@Override
public final void calculate() {
long result = this.summation / this.count;
// The minimum of avg result is 1, that means once there's some data in a duration user can get "1" instead of
// "0".
if (result == 0 && this.summation > 0) {
result = 1;
}
this.value = result;
}
@Override
public Metrics toHour() {
AvgFunction metrics = (AvgFunction) createNew();
metrics.setEntityId(getEntityId());
metrics.setTimeBucket(toTimeBucketInHour());
metrics.setServiceId(getServiceId());
metrics.setSummation(getSummation());
metrics.setCount(getCount());
return metrics;
}
@Override
public Metrics toDay() {
AvgFunction metrics = (AvgFunction) createNew();
metrics.setEntityId(getEntityId());
metrics.setTimeBucket(toTimeBucketInDay());
metrics.setServiceId(getServiceId());
metrics.setSummation(getSummation());
metrics.setCount(getCount());
return metrics;
}
@Override
public int remoteHashCode() {
return entityId.hashCode();
}
@Override
public void deserialize(final RemoteData remoteData) {
this.count = remoteData.getDataLongs(0);
this.summation = remoteData.getDataLongs(1);
setTimeBucket(remoteData.getDataLongs(2));
this.entityId = remoteData.getDataStrings(0);
this.serviceId = remoteData.getDataStrings(1);
}
@Override
public RemoteData.Builder serialize() {
RemoteData.Builder remoteBuilder = RemoteData.newBuilder();
remoteBuilder.addDataLongs(count);
remoteBuilder.addDataLongs(summation);
remoteBuilder.addDataLongs(getTimeBucket());
remoteBuilder.addDataStrings(entityId);
remoteBuilder.addDataStrings(serviceId);
return remoteBuilder;
}
@Override
protected String id0() {
return getTimeBucket() + Const.ID_CONNECTOR + entityId;
}
@Override
public void accept(final MeterEntity entity, final Long value) {
this.entityId = entity.id();
this.serviceId = entity.serviceId();
this.summation += value;
this.count += 1;
}
@Override
public Class<? extends StorageHashMapBuilder> builder() {
return AvgStorageBuilder.class;
}
public static class AvgStorageBuilder implements StorageHashMapBuilder<AvgFunction> {
@Override
public AvgFunction storage2Entity(final Map<String, Object> dbMap) {
AvgFunction metrics = new AvgFunction() {
@Override
public AcceptableValue<Long> createNew() {
throw new UnexpectedException("createNew should not be called");
}
};
metrics.setSummation(((Number) dbMap.get(SUMMATION)).longValue());
metrics.setValue(((Number) dbMap.get(VALUE)).longValue());
metrics.setCount(((Number) dbMap.get(COUNT)).longValue());
metrics.setTimeBucket(((Number) dbMap.get(TIME_BUCKET)).longValue());
metrics.setServiceId((String) dbMap.get(InstanceTraffic.SERVICE_ID));
metrics.setEntityId((String) dbMap.get(ENTITY_ID));
return metrics;
}
@Override
public Map<String, Object> entity2Storage(final AvgFunction storageData) {
Map<String, Object> map = new HashMap<>();
map.put(SUMMATION, storageData.getSummation());
map.put(VALUE, storageData.getValue());
map.put(COUNT, storageData.getCount());
map.put(TIME_BUCKET, storageData.getTimeBucket());
map.put(InstanceTraffic.SERVICE_ID, storageData.getServiceId());
map.put(ENTITY_ID, storageData.getEntityId());
return map;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AvgFunction)) {
return false;
}
AvgFunction function = (AvgFunction) o;
return Objects.equals(entityId, function.entityId) &&
getTimeBucket() == function.getTimeBucket();
}
@Override
public int hashCode() {
return Objects.hash(entityId, getTimeBucket());
}
}
|
apache-2.0
|
sheshkovsky/jaryan
|
comments/forms.py
|
9802
|
import time
import django
from django import forms
try:
from django.forms.utils import ErrorDict
except ImportError:
from django.forms.util import ErrorDict
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.crypto import salted_hmac, constant_time_compare
from django.utils.encoding import force_text
from django.utils.text import get_text_list
from django.utils import timezone
from django.utils.translation import ungettext, ugettext, ugettext_lazy as _
from comments.models import Comment, ThreadedComment
COMMENT_MAX_LENGTH = getattr(settings, 'COMMENT_MAX_LENGTH', 3000)
DEFAULT_COMMENTS_TIMEOUT = getattr(settings, 'COMMENTS_TIMEOUT', (2 * 60 * 60)) # 2h
class CommentSecurityForm(forms.Form):
"""
Handles the security aspects (anti-spoofing) for comment forms.
"""
content_type = forms.CharField(widget=forms.HiddenInput)
object_pk = forms.CharField(widget=forms.HiddenInput)
timestamp = forms.IntegerField(widget=forms.HiddenInput)
security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)
def __init__(self, target_object, data=None, initial=None, **kwargs):
self.target_object = target_object
if initial is None:
initial = {}
initial.update(self.generate_security_data())
super(CommentSecurityForm, self).__init__(data=data, initial=initial, **kwargs)
def security_errors(self):
"""Return just those errors associated with security"""
errors = ErrorDict()
for f in ["honeypot", "timestamp", "security_hash"]:
if f in self.errors:
errors[f] = self.errors[f]
return errors
def clean_security_hash(self):
"""Check the security hash."""
security_hash_dict = {
'content_type': self.data.get("content_type", ""),
'object_pk': self.data.get("object_pk", ""),
'timestamp': self.data.get("timestamp", ""),
}
expected_hash = self.generate_security_hash(**security_hash_dict)
actual_hash = self.cleaned_data["security_hash"]
if not constant_time_compare(expected_hash, actual_hash):
raise forms.ValidationError("Security hash check failed.")
return actual_hash
def clean_timestamp(self):
"""Make sure the timestamp isn't too far (default is > 2 hours) in the past."""
ts = self.cleaned_data["timestamp"]
if time.time() - ts > DEFAULT_COMMENTS_TIMEOUT:
raise forms.ValidationError("Timestamp check failed")
return ts
def generate_security_data(self):
"""Generate a dict of security data for "initial" data."""
timestamp = int(time.time())
security_dict = {
'content_type': str(self.target_object._meta),
'object_pk': str(self.target_object._get_pk_val()),
'timestamp': str(timestamp),
'security_hash': self.initial_security_hash(timestamp),
}
return security_dict
def initial_security_hash(self, timestamp):
"""
Generate the initial security hash from self.content_object
and a (unix) timestamp.
"""
initial_security_dict = {
'content_type': str(self.target_object._meta),
'object_pk': str(self.target_object._get_pk_val()),
'timestamp': str(timestamp),
}
return self.generate_security_hash(**initial_security_dict)
def generate_security_hash(self, content_type, object_pk, timestamp):
"""
Generate a HMAC security hash from the provided info.
"""
info = (content_type, object_pk, timestamp)
key_salt = "django.contrib.forms.CommentSecurityForm"
value = "-".join(info)
return salted_hmac(key_salt, value).hexdigest()
class CommentDetailsForm(CommentSecurityForm):
"""
Handles the specific details of the comment (name, comment, etc.).
"""
name = forms.CharField(label=_("Name"), max_length=50, widget=forms.HiddenInput)
email = forms.EmailField(label=_("Email address"), widget=forms.HiddenInput)
url = forms.URLField(label=_("URL"), required=False, widget=forms.HiddenInput)
comment = forms.CharField(label=_('Comment'), widget=forms.Textarea,
max_length=COMMENT_MAX_LENGTH)
def get_comment_object(self):
"""
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``).
"""
if not self.is_valid():
raise ValueError("get_comment_object may only be called on valid forms")
CommentModel = self.get_comment_model()
new = CommentModel(**self.get_comment_create_data())
new = self.check_for_duplicate_comment(new)
return new
def get_comment_model(self):
"""
Get the comment model to create with this form. Subclasses in custom
comment apps should override this, get_comment_create_data, and perhaps
check_for_duplicate_comment to provide custom comment models.
"""
return Comment
def get_comment_create_data(self):
"""
Returns the dict of data to be used to create a comment. Subclasses in
custom comment apps that override get_comment_model can override this
method to add extra fields onto a custom comment model.
"""
return dict(
content_type=ContentType.objects.get_for_model(self.target_object),
object_pk=force_text(self.target_object._get_pk_val()),
user_name=self.cleaned_data["name"],
user_email=self.cleaned_data["email"],
user_url=self.cleaned_data["url"],
comment=self.cleaned_data["comment"],
submit_date=timezone.now(),
site_id=settings.SITE_ID,
is_public=True,
is_removed=False,
)
def check_for_duplicate_comment(self, new):
"""
Check that a submitted comment isn't a duplicate. This might be caused
by someone posting a comment twice. If it is a dup, silently return the *previous* comment.
"""
possible_duplicates = self.get_comment_model()._default_manager.using(
self.target_object._state.db
).filter(
content_type=new.content_type,
object_pk=new.object_pk,
user_name=new.user_name,
user_email=new.user_email,
user_url=new.user_url,
)
for old in possible_duplicates:
if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment:
return old
return new
def clean_comment(self):
"""
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
contain anything in PROFANITIES_LIST.
"""
comment = self.cleaned_data["comment"]
if (not getattr(settings, 'COMMENTS_ALLOW_PROFANITIES', False) and
getattr(settings, 'PROFANITIES_LIST', False)):
bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
if bad_words:
raise forms.ValidationError(ungettext(
"Watch your mouth! The word %s is not allowed here.",
"Watch your mouth! The words %s are not allowed here.",
len(bad_words)) % get_text_list(
['"%s%s%s"' % (i[0], '-' * (len(i) - 2), i[-1])
for i in bad_words], ugettext('and')))
return comment
class CommentForm(CommentDetailsForm):
honeypot = forms.CharField(required=False,
label=_('If you enter anything in this field '
'your comment will be treated as spam'))
def clean_honeypot(self):
"""Check that nothing's been entered into the honeypot."""
value = self.cleaned_data["honeypot"]
if value:
raise forms.ValidationError(self.fields["honeypot"].label)
return value
class ThreadedCommentForm(CommentForm):
title = forms.CharField(label=_('Title'), required=False, max_length=getattr(settings, 'COMMENTS_TITLE_MAX_LENGTH', 255), widget=forms.HiddenInput)
parent = forms.IntegerField(required=False, widget=forms.HiddenInput)
def __init__(self, target_object, parent=None, data=None, initial=None):
if django.VERSION >= (1,7):
# Using collections.OrderedDict from Python 2.7+
# This class does not have an insert method, have to replace it.
from collections import OrderedDict
keys = list(self.base_fields.keys())
keys.remove('title')
keys.insert(keys.index('comment'), 'title')
self.base_fields = OrderedDict((k, self.base_fields[k]) for k in keys)
else:
self.base_fields.insert(
self.base_fields.keyOrder.index('comment'), 'title',
self.base_fields.pop('title')
)
self.parent = parent
if initial is None:
initial = {}
initial.update({'parent': self.parent})
super(ThreadedCommentForm, self).__init__(target_object, data=data, initial=initial)
def get_comment_model(self):
return ThreadedComment
def get_comment_create_data(self):
d = super(ThreadedCommentForm, self).get_comment_create_data()
d['parent_id'] = self.cleaned_data['parent']
d['title'] = self.cleaned_data['title']
return d
|
apache-2.0
|
google-code/android-scripting
|
jruby/src/test/externals/ruby_test/test/core/Process/class/tc_gid.rb
|
1434
|
######################################################################
# tc_gid.rb
#
# Test case for the Process.gid and Process.gid= module methods.
#
# NOTE: The Process.gid= tests are only run if the test is run as the
# root user.
######################################################################
require 'test/unit'
require 'test/helper'
class TC_Process_Gid_ModuleMethod < Test::Unit::TestCase
include Test::Helper
unless JRUBY || WINDOWS
def setup
@nobody_gid = Etc.getgrnam('nobody').gid
@login_gid = Etc.getpwnam(Etc.getlogin).gid
end
end
def test_gid_basic
assert_respond_to(Process, :gid)
assert_respond_to(Process, :gid=)
end
unless WINDOWS
def test_gid
if ROOT
assert_equal(0, Process.gid)
else
# assert_equal(@login_gid, Process.gid)
end
end
if ROOT
def test_gid=
assert_nothing_raised{ Process.gid = @nobody_gid }
assert_equal(@nobody_gid, Process.gid)
assert_nothing_raised{ Process.gid = @login_gid }
assert_equal(@login_gid, Process.gid)
end
end
def test_gid_expected_errors
assert_raises(ArgumentError){ Process.gid(0) }
assert_raises(TypeError){ Process.gid = "bogus" }
end
def teardown
@nobody_gid = nil
@login_gid = nil
end
end
end
|
apache-2.0
|
wapalxj/Java
|
javaworkplace/SXT/src/C00_data/Test_code.java
|
1493
|
package C00_data;
/**
* Created by Administrator on 2016/8/30.
* 进制问题
*
* 二进制显示的是补码,计算机接收的直接量也是补码
*/
public class Test_code {
public static void main(String[] args) {
/*
二进制显示的是补码,计算机接收的直接量也是补码
*/
byte a=-5;
System.out.println("a:"+a);
System.out.println("a的二进制:"+Integer.toBinaryString(a));
byte b=(byte)0xff;
System.out.println("b:"+b);
System.out.println("b的二进制:"+Integer.toBinaryString(b));
byte c=-1;
System.out.println("c:"+c);
System.out.println("c的二进制:"+Integer.toBinaryString(c));
//二进制转换为10进制,字符串第一位可以为-号
//这种方式字符串中为原码
String cc="-111";
int d = Integer.parseInt(cc, 2); // 2进制
System.out.println("d:"+d);
/**
byte short通过算数运算和逻辑运算结果都会是int
*/
byte b1=1;
short s1=2;
// short ss=b1+1;//编译出错
// short ss=s1+1;//编译出错
// short ss=b1+s1;//编译出错
int i=b1+s1;
/**
* 移位运算
*/
byte b2=3;
b2<<=1;
System.out.println("b2<<=1-->"+b2);
/**
*127+1=-128
*/
byte b3=127;
b3++;
System.out.println("127+1="+b3);
}
}
|
apache-2.0
|
aspoman/flink-china-doc
|
libs/gelly_guide.md
|
1059
|
---
title: "Gelly: Flink Graph API"
---
<!--
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.
-->
<meta http-equiv="refresh" content="1; url={{ site.baseurl }}/apis/batch/libs/gelly.html" />
The *Gelly API guide* has been moved. Redirecting to [{{ site.baseurl }}/apis/batch/libs/gelly.html]({{ site.baseurl }}/apis/batch/libs/gelly.html) in 1 second.
|
apache-2.0
|
theoddbeard/PanzerParty
|
core/app.js
|
1246
|
/**
* Main framework
*/
var http = require('http');
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');
var mime = require('mime');
var engineMod = require('./engine.js')
var WebApp = function(path,config){
console.log('Starting PanzerParty at '+path);
var basepath = path;
function checkConfig(config){
if (typeof(config.port)==='undefined')
config.port = 8090;
if (typeof(config.path)==='undefined')
config.path = {};
if (typeof(config.path.statics==='undefined'))
config.path.statics = '/static';
if (typeof(config.path.modules==='undefined'))
config.path.modules = '/modules';
if (typeof(config.path.controllers)==='undefined')
config.path.controllers = '/controllers';
if (typeof(config.path.views)==='undefined')
config.path.views='/views';
if (typeof(config.path.layouts)==='undefined')
config.path.layuots='/layouts';
if (typeof(config.path.l10n)==='undefined')
config.path.l10n='/l10n';
if (typeof(config.controllers)==='undefined')
config.controllers = [];
}
config.root = basepath;
checkConfig(config);
var engine = new engineMod.Engine(config);
this.start = function(){
engine.start();
};
};
exports.WebApp = WebApp;
|
apache-2.0
|
UniversalDependencies/universaldependencies.github.io
|
treebanks/swl_sslc/swl_sslc-dep-advcl.html
|
8515
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of advcl in UD_Swedish_Sign_Language-SSLC</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/swl_sslc/swl_sslc-dep-advcl.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_swedish_sign_language-sslc-relations-advcl">Treebank Statistics: UD_Swedish_Sign_Language-SSLC: Relations: <code class="language-plaintext highlighter-rouge">advcl</code></h2>
<p>This relation is universal.</p>
<p>22 nodes (1%) are attached to their parents as <code class="language-plaintext highlighter-rouge">advcl</code>.</p>
<p>18 instances of <code class="language-plaintext highlighter-rouge">advcl</code> (82%) are left-to-right (parent precedes child).
Average distance between parent and child is 3.5.</p>
<p>The following 5 pairs of parts of speech are connected with <code class="language-plaintext highlighter-rouge">advcl</code>: <tt><a href="swl_sslc-pos-VERB.html">VERB</a></tt>-<tt><a href="swl_sslc-pos-VERB.html">VERB</a></tt> (15; 68% instances), <tt><a href="swl_sslc-pos-VERB.html">VERB</a></tt>-<tt><a href="swl_sslc-pos-ADJ.html">ADJ</a></tt> (2; 9% instances), <tt><a href="swl_sslc-pos-VERB.html">VERB</a></tt>-<tt><a href="swl_sslc-pos-ADV.html">ADV</a></tt> (2; 9% instances), <tt><a href="swl_sslc-pos-VERB.html">VERB</a></tt>-<tt><a href="swl_sslc-pos-NOUN.html">NOUN</a></tt> (2; 9% instances), <tt><a href="swl_sslc-pos-NOUN.html">NOUN</a></tt>-<tt><a href="swl_sslc-pos-NOUN.html">NOUN</a></tt> (1; 5% instances).</p>
<pre><code class="language-conllu"># visual-style 2 bgColor:blue
# visual-style 2 fgColor:white
# visual-style 1 bgColor:blue
# visual-style 1 fgColor:white
# visual-style 1 2 advcl color:blue
1 VAKNA _ VERB VB _ 0 root _ _
2 SOLSTRÅLA _ VERB VB _ 1 advcl _ _
3 SITTA@z _ VERB VB _ 1 conj _ _
4 NEKA _ VERB VB _ 1 conj _ _
</code></pre>
<pre><code class="language-conllu"># visual-style 2 bgColor:blue
# visual-style 2 fgColor:white
# visual-style 3 bgColor:blue
# visual-style 3 fgColor:white
# visual-style 3 2 advcl color:blue
1 PRO1 _ PRON PN _ 2 nsubj _ _
2 LITEN-PERSON _ ADJ JJ _ 3 advcl _ _
3 HA*INTE _ VERB VB _ 0 root _ _
4 PERSON^TECKEN _ NOUN NN _ 3 obj _ _
5 PRO1 _ PRON PN _ 1 nsubj _ _
6 PU@g _ INTJ G _ 4 discourse _ _
</code></pre>
<pre><code class="language-conllu"># visual-style 3 bgColor:blue
# visual-style 3 fgColor:white
# visual-style 1 bgColor:blue
# visual-style 1 fgColor:white
# visual-style 1 3 advcl color:blue
1 SCHASA@ca _ VERB VBCA _ 0 root _ _
2 BI _ NOUN NN _ 3 nsubj _ _
3 BORTA _ ADV AB _ 1 advcl _ _
4 FINEMANG _ ADJ JJ _ 1 discourse _ _
5 LÅTA-VARA _ X G _ 1 discourse _ _
</code></pre>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
|
apache-2.0
|
ZGRTech/Arinna
|
nortwind/Arinna.Northwind.ProductService.Business/CategoryManager.cs
|
529
|
using Arinna.Northwind.ProductService.Business.Contract;
using Arinna.Northwind.ProductService.Data.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Text;
namespace Arinna.Northwind.ProductService.Business
{
public class CategoryManager: ICategoryManager
{
private readonly ICategoryRepository categoryRepository;
public CategoryManager(ICategoryRepository categoryRepository)
{
this.categoryRepository = categoryRepository;
}
}
}
|
apache-2.0
|
lian-yue/lianyue-server
|
app/viewModels/token/routes.js
|
155
|
import Router from 'viewModels/router'
import read from './read'
const router = new Router;
router.get('token/read', '/', read);
export default router
|
apache-2.0
|
tcat-tamu/crypto
|
bundles/edu.tamu.tcat.crypto.bouncycastle/src/edu/tamu/tcat/crypto/bouncycastle/internal/Activator.java
|
2300
|
/*
* Copyright 2014 Texas A&M Engineering Experiment Station
*
* 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 edu.tamu.tcat.crypto.bouncycastle.internal;
import java.security.Provider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static Activator activator;
private static BundleContext bundleContext;
/**
* Instantiate and use this {@link Provider} instance instead of adding it to the
* JVM via {@link java.security.Security#addProvider(Provider)}.
* <br/>There are problems in "redeployable"
* environments (such as OSGI and Tomcat) with using JVM-global singletons. Namely,
* the provider could be added once if whatever added it was "undeployed", the provider
* becomes invalid and throws exceptions when trying to access it.
* <br/>
* To avoid these issues, the provider is constructed explicitly where needed and
* given as an argument to cypher API explicitly rather than having the security
* framework look up a provider by identifier or choose a default.
*/
private final Provider bouncyCastleProvider = new BouncyCastleProvider();
public static Activator getDefault() {
return activator;
}
public static BundleContext getContext() {
return bundleContext;
}
@Override
public void start(BundleContext bundleContext) throws Exception {
Activator.bundleContext = bundleContext;
activator = this;
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
Activator.bundleContext = null;
activator = null;
}
public Provider getBouncyCastleProvider()
{
return bouncyCastleProvider;
}
}
|
apache-2.0
|
boundary/boundary-event-sdk
|
src/test/java/com/boundary/sdk/event/esper/NewEmployeeEvent.java
|
1889
|
// Copyright 2014-2015 Boundary, 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.boundary.sdk.event.esper;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class NewEmployeeEvent implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8757562061344149582L;
Employee employee;
NewEmployeeEvent(Employee employee) {
this.employee = employee;
}
public NewEmployeeEvent(String firstName,
Map<String,Address> addresses) {
for (Entry<String, Address> entry : addresses.entrySet() ) {
addresses.put(entry.getKey(), entry.getValue());
}
}
public String getName() {
return this.employee.getName();
}
public Address getAddress(String type) {
return employee.getAddresses().get(type);
}
public Employee getSubordinate(int index) {
return employee.getSubordinate(index);
}
public Employee[] getAllSubordinates() {
Employee[] subordinates = new Employee[1];
return employee.getAllSubordinates();
}
public Iterable<EducationHistory> getEducation() {
return employee.getEducation();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("NewEmployeeEvent [employee=");
builder.append(employee);
builder.append("]");
return builder.toString();
}
}
|
apache-2.0
|
YaelMendes/jboss-eap-quickstarts
|
contacts-jquerymobile/src/main/webapp/index.html
|
20643
|
<!--
JBoss, Home of Professional Open Source
Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
contributors by the @authors tag. See the copyright.txt in the
distribution for a full listing of individual contributors.
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.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Contacts</title>
<!-- Disable phone number detection on iOS. -->
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Default theme with just 2 schemes, A (light) and B (dark) -->
<link rel="stylesheet" href="css/jquery.mobile-1.4.2.css" type="text/css" media="all" />
<!-- <link rel="stylesheet" href="css/jquery.mobile-1.4.2.min.css" type="text/css" media="all" /> -->
<!-- <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" /> -->
<!-- Import jQuery so that it can be used by the custom JavaScript -->
<script src="js/libs/jquery-2.0.3.js"></script>
<!-- <script src="js/libs/jquery-2.0.3.min.js"></script> -->
<!-- <script src="http://code.jquery.com/jquery-2.0.3.js"></script> -->
<!-- This is the CSS for the Validation plug-in. -->
<link rel="stylesheet" href="css/app-style.css" type="text/css" media="all" />
<link rel="stylesheet" href="css/validator.css" type="text/css" media="all" />
<!-- <link rel="stylesheet" href="css/app-style.min.css" type="text/css" media="all" /> -->
<!-- <link rel="stylesheet" href="css/validator.min.css" type="text/css" media="all" /> -->
<!-- This is the CSS for the International Telephone Input plug-in. -->
<link rel="stylesheet" href="css/intlTelInput-6.4.3.css">
<!-- Import the custom JavaScript -->
<script src="js/namespace.js"></script>
<script src="js/util.js"></script>
<script src="js/formSetup.js"></script>
<script src="js/app.js"></script>
<script src="js/validation.js"></script>
<script src="js/submissions.js"></script>
<script src="js/theming.js"></script>
<!-- <script src="js/namespace.min.js"></script> -->
<!-- <script src="js/util.min.js"></script> -->
<!-- <script src="js/formSetup.min.js"></script> -->
<!-- <script src="js/app.min.js"></script> -->
<!-- <script src="js/validation.min.js"></script> -->
<!-- <script src="js/submissions.min.js"></script> -->
<!-- <script src="js/theming.min.js"></script> -->
<!-- Mobile browsers do not support HTML5 form validation, this lib provides client side validation. -->
<script src="js/libs/jquery.validate-1.13.1.js"></script>
<!-- <script src="js/libs/jquery.validate-1.13.1.min.js"></script> -->
<!-- <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script> -->
<script src="js/libs/additional-methods-1.13.1.js"></script>
<!-- <script src="js/libs/additional-methods-1.13.1.min.js"></script> -->
<!-- <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/additional-methods.js"></script> -->
<!-- The jQuery Validator plug-in does not cover enough of the phone number use cases. The intlTelInput plug-in was used
instead as it covers all forms of phone numbers. -->
<script src="js/libs/intlTelInput-libPhoneNumber-7.2.1.js"></script>
<script src="js/libs/intlTelInput-6.4.3.js"></script>
<!-- <script src="js/libs/intlTelInput-6.4.3.min.js"></script> -->
<!-- Because the mobileinit event is triggered immediately, you'll need to bind your event handler
before jQuery Mobile is loaded.
Unlike other jQuery projects, such as jQuery and jQuery UI, jQuery Mobile automatically applies
many markup enhancements as soon as it loads (long before the document.ready event fires).
Therefore call the jQuery Mobile code last. -->
<script src="js/libs/jquery.mobile-1.4.2.js"></script>
<!-- <script src="js/libs/jquery.mobile-1.4.2.min.js"></script> -->
<!-- <script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.js"></script> -->
</head>
<body>
<!-- This is the main list. It is just names. -->
<!-- It is worth noting that in a jQuery Mobile app, only the first "page" is loaded & displayed.
The following/other pages will be partially loaded. Just their "divs." -->
<div data-role="page" id="contacts-list-page" class="ui-page-theme-a" data-url="/jboss-contacts-jquerymobile/">
<div data-role="panel" id="contacts-list-page-menu-panel">
<ul data-role="listview" id="contacts-list-page-menu-panel-listview">
<li><a href="#contacts-add-page">Add Contact</a></li>
<li><a href="#contacts-detail-list-page">Detailed List</a></li>
<li><a href="#about-page">About</a></li>
<li><a href="#contacts-theming-dialog" data-rel="popup" data-position-to="window">Themes</a></li>
</ul>
</div>
<div data-role="header" data-position="fixed" >
<a href="#contacts-list-page-menu-panel" id="contacts-list-page-menu-button" class="ui-btn ui-corner-all ui-shadow ui-icon-bars ui-btn-icon-notext ui-mini ui-btn-inline">Menu</a>
<h1>Contacts</h1>
<a href="#contacts-detail-list-page" id="contacts-detail-list-page-button" class="ui-btn ui-corner-all ui-shadow ui-icon-arrow-d ui-btn-icon-right ui-mini ui-btn-inline">Details</a>
</div>
<div role="main" class="ui-content">
<form id="filter-form-list-page" class="ui-filterable">
<input id="filter-input-list-page" data-type="search">
</form>
<ul data-role="listview" id="contacts-display-listview" class="sortedList" data-autodividers="true" data-filter="true" data-input="#filter-input-list-page">
<!-- The list of Contacts gets inserted here. -->
</ul>
</div>
<div data-role="footer" >
<h4>Red Hat JBoss Quickstarts</h4>
</div>
<!-- A Theme choosing dialog. -->
<div data-role="popup" id="contacts-theming-dialog">
<div data-role="header">
<h1>Theming</h1>
</div>
<div role="main" class="ui-content">
<h3>Try out these different Themes!</h3>
<button id="theme-button-a" class="ui-btn ui-corner-all ui-shadow">A - Light</button>
<button id="theme-button-b" class="ui-btn ui-corner-all ui-shadow">B - Dark</button>
</div>
</div>
</div>
<!-- This is the detail view of the main list. -->
<div data-role="page" id="contacts-detail-list-page" class="ui-page-theme-a" >
<div data-role="panel" id="contacts-detail-list-page-menu-panel">
<ul data-role="listview" id="contacts-detail-list-page-menu-panel-listview">
<li><a href="#contacts-add-page">Add Contact</a></li>
<li><a href="#contacts-list-page">List view</a></li>
<li><a href="#about-page">About</a></li>
<li><a href="#contacts-theming-dialog" data-rel="popup" data-position-to="window">Themes</a></li>
</ul>
</div>
<div data-role="header" data-position="fixed" >
<a href="#contacts-detail-list-page-menu-panel" id="contacts-detail-list-page-menu-button" class="ui-btn ui-corner-all ui-shadow ui-icon-bars ui-btn-icon-notext ui-mini ui-btn-inline">Menu</a>
<h1>Contacts
</h1>
<a href="#contacts-list-page" id="contacts-list-page-button" class="ui-btn ui-corner-all ui-shadow ui-icon-arrow-d ui-btn-icon-right ui-mini ui-btn-inline">List</a>
</div>
<div role="main" class="ui-content">
<form id="filter-form-detail-list-page" class="ui-filterable">
<input id="filter-input-detail-list-page" data-type="search">
</form>
<ul data-role="listview" id="contacts-display-detail-listview" class="sortedList" data-autodividers="true" data-filter="true" data-input="#filter-input-detail-list-page">
<!-- The list of Contacts gets inserted here. -->
</ul>
</div>
<div data-role="footer" >
<h4>Red Hat JBoss Quickstarts</h4>
</div>
</div>
<!-- This is for the Info/About page. -->
<div data-role="page" id="about-page" class="ui-page-theme-a" >
<div data-role="panel" id="contacts-about-page-menu-panel">
<ul data-role="listview" id="contacts-about-page-menu-panel-listview">
<li><a href="#contacts-add-page">Add Contact</a></li>
<li><a href="#contacts-list-page">List view</a></li>
<li><a href="#about-page">About</a></li>
<li><a href="#contacts-theming-dialog" data-rel="popup" data-position-to="window">Themes</a></li>
</ul>
</div>
<div data-role="header" data-position="fixed" >
<a href="#contacts-about-page-menu-panel" id="contacts-about-page-menu-button" class="ui-btn ui-corner-all ui-shadow ui-icon-bars ui-btn-icon-notext ui-mini ui-btn-inline">Menu</a>
<h1>About</h1>
</div>
<div role="main" class="ui-content" >
<p>Learn more about Red Hat JBoss Enterprise Application Platform.</p>
<ul>
<li><a href="https://access.redhat.com/site/documentation/JBoss_Enterprise_Application_Platform/">Documentation</a></li>
<li><a href="http://www.redhat.com/en/technologies/jboss-middleware/application-platform">Product Information</a></li>
</ul>
</div>
</div>
<!-- A blank form for adding a contact. -->
<div data-role="page" id="contacts-add-page" class="ui-page-theme-a" >
<div data-role="panel" id="contacts-add-page-menu-panel">
<ul data-role="listview" id="contacts-add-page-menu-panel-listview">
<li><a href="#contacts-list-page">List view</a></li>
<li><a href="#about-page">About</a></li>
<li><a href="#contacts-theming-dialog" data-rel="popup" data-position-to="window">Themes</a></li>
</ul>
</div>
<div data-role="header" data-position="fixed" >
<a href="#contacts-add-page-menu-panel" id="contacts-add-page-menu-button" class="ui-btn ui-corner-all ui-shadow ui-icon-bars ui-btn-icon-notext ui-mini ui-btn-inline">Menu</a>
<h1>Add Contact</h1>
</div>
<div role="main" class="ui-content">
<!--
In order to catch server side errors we need to disable the automatic page transition when the form is
submitted. This done is by adding data-ajax="false" to the form element. We then manually change the page
in the function that handles form submission. Thus allowing us to control when the form transitions to
another page.
-->
<form name="contacts-add-form" id="contacts-add-form" class="contact_info" method="post" data-ajax="false">
<div>
<label for="contacts-add-input-firstName">First Name:</label>
<input name="firstName" id="contacts-add-input-firstName" class="name" data-clear-btn="true" value="" placeholder="Enter a first name." type="text"/>
</div>
<div>
<label for="contacts-add-input-lastName">Last Name:</label>
<input name="lastName" id="contacts-add-input-lastName" class="name" data-clear-btn="true" value="" placeholder="Enter a last name." type="text"/>
</div>
<div>
<label for="contacts-add-input-tel">Phone:</label>
<input name="phoneNumber" id="contacts-add-input-tel" class="phoneNumber" data-clear-btn="true" value="" type="tel"/>
</div>
<div>
<label for="contacts-add-input-email">Email:</label>
<input name="email" id="contacts-add-input-email" class="email" data-clear-btn="true" value="" placeholder="[email protected]" type="email"/>
</div>
<div>
<label for="contacts-add-input-date">Birth Date:</label>
<input name="birthDate" id="contacts-add-input-date" class="birthDate" data-clear-btn="true" value="" placeholder="YYYY-MM-DD" type="date" min="1900-01-01"/>
</div>
<input id="submit-add-btn" data-inline="true" type="submit" value="Save" />
<input id="clear-add-btn" data-inline="true" type="reset" value="Clear" />
<input id="cancel-add-btn" data-inline="true" type="reset" value="Cancel" />
</form>
</div>
<div data-role="footer" data-position="fixed" >
<fieldset class="ui-grid-b">
<!-- There is currently a bug in jQM 1.4.2. The CSS forces all ui-btn in a toolbar(header or footer) to be
set to display:inline-block. This interferes with the Grid making the buttons appear normal sized.
To fix this we had to override the style with a 'block-button' class referenced in app.css, this
should be removed when the bug is fixed.-->
<div class="ui-block-a">
<a class="ui-btn ui-corner-all ui-shadow ui-btn-b block-button" onclick="$('#submit-add-btn').trigger('click');">Save</a>
</div>
<div class="ui-block-b">
<a class="ui-btn ui-corner-all ui-shadow block-button" onclick="$('#clear-add-btn').trigger('click');">Clear</a>
</div>
<div class="ui-block-c">
<a href="#contacts-list-page" class="ui-btn ui-corner-all ui-shadow block-button" onclick="$('#cancel-add-btn').trigger('click');">Cancel</a>
</div>
</fieldset>
</div>
</div>
<!-- A pre-populated form for editing a contact -->
<div data-role="page" id="contacts-edit-page" class="ui-page-theme-a" >
<div data-role="panel" id="contacts-edit-page-menu-panel">
<ul data-role="listview" id="contacts-edit-page-menu-panel-listview">
<li><a href="#contacts-add-page">Add Contact</a></li>
<li><a href="#contacts-list-page">List view</a></li>
<li><a href="#about-page">About</a></li>
<li><a href="#contacts-theming-dialog" data-rel="popup" data-position-to="window">Themes</a></li>
</ul>
</div>
<div data-role="header" data-position="fixed" >
<a href="#contacts-edit-page-menu-panel" id="contacts-edit-page-menu-button" class="ui-btn ui-corner-all ui-shadow ui-icon-bars ui-btn-icon-notext ui-mini ui-btn-inline">Menu</a>
<h1>Edit Contact</h1>
<a href="#contact-delete-dialog" id="contacts-delete-button" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-mini ui-btn-inline" data-rel="popup" data-position-to="window">Delete</a>
</div>
<div role="main" class="ui-content">
<!--
PUT and DELETE are not supported in an HTML form, you must use POST.
Please see http://www.w3.org/TR/2010/WD-html5-diff-20101019/#changes-2010-06-24
In order to catch server side errors we need to disable the automatic page transition when the form is
submitted. This done is by adding data-ajax="false" to the form element. We then manually change the page
in the function that handles form submission. Thus allowing us to control when the form transitions to
another page.
-->
<form name="contacts-edit-form" id="contacts-edit-form" class="contact_info" method="post" data-ajax="false">
<div>
<label for="contacts-edit-input-firstName">First Name:</label>
<input name="firstName" id="contacts-edit-input-firstName" class="name" data-clear-btn="true" value="" placeholder="Enter a first name." type="text"/>
</div>
<div>
<label for="contacts-edit-input-lastName">Last Name:</label>
<input name="lastName" id="contacts-edit-input-lastName" class="name" data-clear-btn="true" value="" placeholder="Enter a last name." type="text"/>
</div>
<div>
<label for="contacts-edit-input-tel">Phone:</label>
<input name="phoneNumber" id="contacts-edit-input-tel" class="phoneNumber" data-clear-btn="true" value="" type="tel"/>
</div>
<div>
<label for="contacts-edit-input-email">Email:</label>
<input name="email" id="contacts-edit-input-email" class="email" data-clear-btn="true" value="" placeholder="[email protected]" type="email"/>
</div>
<div>
<label for="contacts-edit-input-date">Birth Date:</label>
<input name="birthDate" id="contacts-edit-input-date" class="birthDate" data-clear-btn="true" value="" placeholder="YYYY-MM-DD" type="date" min="1900-01-01"/>
</div>
<div>
<input name="id" id="contacts-edit-input-id" value="" type="hidden"/>
</div>
<input id="submit-edit-btn" data-inline="true" type="submit" value="Save" />
<input id="reset-edit-btn" data-inline="true" type="reset" value="Reset" />
<input id="cancel-edit-btn" data-inline="true" type="reset" value="Cancel" />
</form>
</div>
<div data-role="footer" data-position="fixed" >
<fieldset class="ui-grid-b">
<!-- There is currently a bug in jQM 1.4.2. The CSS forces all ui-btn in a toolbar(header or footer) to be
set to display:inline-block. This interferes with the Grid making the buttons appear normal sized.
To fix this we had to override the style with a 'block-button' class referenced in app.css, this
should be removed when the bug is fixed.-->
<div class="ui-block-a">
<a class="ui-btn ui-corner-all ui-shadow ui-btn-b block-button" onclick="$('#submit-edit-btn').trigger('click');">Save</a>
</div>
<div class="ui-block-b">
<a class="ui-btn ui-corner-all ui-shadow block-button" onclick="$('#reset-edit-btn').trigger('click');">Reset</a>
</div>
<div class="ui-block-c">
<a href="#contacts-list-page" class="ui-btn ui-corner-all ui-shadow block-button" onclick="$('#cancel-edit-btn').trigger('click');">Cancel</a>
</div>
</fieldset>
</div>
<!-- A delete confirmation dialog. -->
<div data-role="popup" id="contact-delete-dialog" data-overlay-theme="b">
<div data-role="header">
<h1>Delete Contact</h1>
</div>
<div role="main" class="ui-content">
<!-- PUT and DELETE are not supported in an HTML form. Please see http://www.w3.org/TR/2010/WD-html5-diff-20101019/#changes-2010-06-24
That is why we are using a dialog with simple Yes/No. The ID of the Contact to be deleted will programatically be
pulled in from the Update form.
-->
<h3>Are you sure you want to Delete?</h3>
<a href="#contacts-list-page" id="confirm-delete-button" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-b">Yes</a>
<a href="#contacts-list-page" id="cancel-delete-button" class="ui-btn ui-corner-all ui-shadow ui-btn-inline">No</a>
</div>
</div>
</div>
</body>
</html>
|
apache-2.0
|
etechi/ServiceFramework
|
Projects/Server/Common/SF.Common.Abstractions/Auth/Permissions/IRoleManager.cs
|
1380
|
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2017 Yang Chen ([email protected])
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.
Detail: https://github.com/etechi/ServiceFramework/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using System.Threading.Tasks;
using SF.Entities;
namespace SF.Auth.Permissions
{
public class RoleQueryArgument : ObjectQueryArgument<ObjectKey<string>>
{
}
public interface IRoleManager<TRoleInternal,TQueryArgument>
: IEntityManager<ObjectKey<string>, TRoleInternal>,
IEntitySource<ObjectKey<string>, TRoleInternal, TQueryArgument>
where TRoleInternal: Models.RoleInternal
where TQueryArgument: RoleQueryArgument
{
}
public interface IRoleManager : IRoleManager<Models.RoleInternal, RoleQueryArgument>
{ }
}
|
apache-2.0
|
ua-eas/ua-rice-2.1.9
|
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/web/form/MaintenanceForm.java
|
2006
|
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.web.form;
import org.kuali.rice.krad.maintenance.MaintenanceDocument;
import org.kuali.rice.krad.uif.UifConstants.ViewType;
/**
* Form class for <code>MaintenanceView</code> screens
*
* @author Kuali Rice Team ([email protected])
*/
public class MaintenanceForm extends DocumentFormBase {
private static final long serialVersionUID = -5805825500852498048L;
protected String dataObjectClassName;
protected String maintenanceAction;
public MaintenanceForm() {
super();
setViewTypeName(ViewType.MAINTENANCE);
}
@Override
public MaintenanceDocument getDocument() {
return (MaintenanceDocument) super.getDocument();
}
// This is to provide a setter with matching type to
// public MaintenanceDocument getDocument() so that no
// issues occur with spring 3.1-M2 bean wrappers
public void setDocument(MaintenanceDocument document) {
super.setDocument(document);
}
public String getDataObjectClassName() {
return this.dataObjectClassName;
}
public void setDataObjectClassName(String dataObjectClassName) {
this.dataObjectClassName = dataObjectClassName;
}
public String getMaintenanceAction() {
return this.maintenanceAction;
}
public void setMaintenanceAction(String maintenanceAction) {
this.maintenanceAction = maintenanceAction;
}
}
|
apache-2.0
|
hallielaine/DecaFS
|
test/persistent_stl_test/persistent_map_unittest.cc
|
2002
|
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <utility>
#include "gtest/gtest.h"
#include "persistent_map.h"
using ::std::make_pair;
const char *testfile = "test.map";
class MapTest : public ::testing::Test {
protected:
PersistentMap<int, int> pm;
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(MapTest, SimpleInsertFindErase) {
pm.open(testfile);
auto insert = pm.insert(make_pair(1, 2));
EXPECT_TRUE(insert.second);
EXPECT_EQ(1, insert.first->first);
EXPECT_EQ(2, insert.first->second);
EXPECT_EQ(1, pm.size());
auto find = pm.find(1);
EXPECT_EQ(1, find->first);
EXPECT_EQ(2, find->second);
auto erase = pm.erase(find);
EXPECT_EQ(pm.end(), erase);
EXPECT_EQ(0, pm.size());
pm.clear();
EXPECT_EQ(0, pm.size());
pm.close();
}
TEST_F(MapTest, ReopenInsertFindErase) {
pm.open(testfile);
auto insert = pm.insert(make_pair(1, 2));
EXPECT_TRUE(insert.second);
EXPECT_EQ(1, insert.first->first);
EXPECT_EQ(2, insert.first->second);
EXPECT_EQ(1, pm.size());
pm.close();
pm.open(testfile);
EXPECT_EQ(1, pm.size());
auto find = pm.find(1);
EXPECT_EQ(1, find->first);
EXPECT_EQ(2, find->second);
auto erase = pm.erase(find);
EXPECT_EQ(pm.end(), erase);
EXPECT_EQ(0, pm.size());
pm.clear();
EXPECT_EQ(0, pm.size());
pm.close();
}
TEST_F(MapTest, SimpleArrayAccess) {
pm.open(testfile);
pm[1] = 2;
EXPECT_EQ(2, pm[1]);
pm[1] = 3;
EXPECT_EQ(3, pm[1]);
pm[7] = 9;
EXPECT_EQ(9, pm[7]);
EXPECT_EQ(2, pm.size());
pm.clear();
EXPECT_EQ(0, pm.size());
pm.close();
}
TEST_F(MapTest, ReopenArrayAccess) {
pm.open(testfile);
pm[1] = 2;
EXPECT_EQ(2, pm[1]);
pm[1] = 3;
EXPECT_EQ(3, pm[1]);
pm[7] = 9;
EXPECT_EQ(9, pm[7]);
EXPECT_EQ(2, pm.size());
pm.close();
pm.open(testfile);
EXPECT_EQ(2, pm.size());
EXPECT_EQ(3, pm[1]);
EXPECT_EQ(9, pm[7]);
EXPECT_EQ(2, pm.size());
pm.clear();
EXPECT_EQ(0, pm.size());
pm.close();
}
|
apache-2.0
|
MorganR/wizards-chess
|
WizardsChess/WizardsChessUtils/Chess/Pieces/ChessPiece.cs
|
1218
|
using System;
using System.Collections;
using System.Collections.Generic;
using WizardsChess.Movement;
// Board arranged in A-H, 1-8. where A-H is replaced by 9-16
namespace WizardsChess.Chess.Pieces {
public abstract class ChessPiece{
public ChessPiece(ChessTeam team){
Team = team;
HasMoved = false;
CanJump = false;
}
/*
public ChessPiece(ChessPiece piece)
{
Type = piece.Type;
Team = piece.Team;
HasMoved = piece.HasMoved;
CanJump = piece.CanJump;
}
*/
public abstract ChessPiece DeepCopy();
public PieceType Type { get; protected set; }
public ChessTeam Team { get; }
public bool HasMoved { get; set; }
public bool CanJump { get; protected set; }
public virtual string ToShortString()
{
string piece = Type.ToString().Substring(0, 1);
if (Team == ChessTeam.White)
{
return piece + "w";
}
else if (Team == ChessTeam.Black)
{
return piece + "b";
}
else
{
return piece;
}
}
public override string ToString()
{
return Team.ToString() + "-" + Type.ToString();
}
public abstract IReadOnlyList<Vector2D> GetAllowedMotionVectors();
public abstract IReadOnlyList<Vector2D> GetAttackMotionVectors();
}
}
|
apache-2.0
|
nemtsov/lightbox
|
src/templates.js
|
1861
|
import 'style!../sass/spinner.scss';
const backdrop = `
<div class="js-blocking" id="lightbox-blocking">
<span class="lightbox-spinner"></span>
</div>
`;
const prevControl = `
<div class="lightbox-extra control prev js-control js-prev">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="60" height="60" viewBox="0 0 60 60" xml:space="preserve">
<circle class="lightbox-icon-bg" cx="30" cy="30" r="30"/>
<path class="lightbox-icon-arrow" d="M36.8,36.4L30.3,30l6.5-6.4l-3.5-3.4l-10,9.8l10,9.8L36.8,36.4z"/>
</svg>
</div>
`;
const nextControl = `
<div class="lightbox-extra control next js-control js-next">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="60" height="60" viewBox="0 0 60 60" xml:space="preserve">
<circle class="lightbox-icon-bg" cx="30" cy="30" r="30"/>
<path class="lightbox-icon-arrow" d="M24.2,23.5l6.6,6.5l-6.6,6.5l3.6,3.5L37.8,30l-10.1-9.9L24.2,23.5z"/>
</svg>
</div>
`;
const closeControl = `
<div class="lightbox-extra control close js-control js-close">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
<circle class="lightbox-icon-bg" cx="50" cy="50" r="47.5"/>
<polygon class="lightbox-icon-close" points="64.5,39.8 60.2,35.5 50,45.7 39.8,35.5 35.5,39.8 45.7,50 35.5,60.2 39.8,64.5 50,54.3 60.2,64.5 64.5,60.2 54.3,50"/>
</svg>
</div>
`;
export const lightbox = `
<div class="js-lightbox-wrap offscreen" id="lightbox-wrap">
${backdrop}
<div class="js-lightbox-inner-wrap" id="lightbox-inner-wrap">
<div class="js-img-wrap" id="lightbox-img-wrap">
${prevControl}
${nextControl}
${closeControl}
<div class="lightbox-contents js-contents"></div>
</div>
</div>
</div>
`;
|
apache-2.0
|
mdoering/backbone
|
life/Chromista/Oomycota/Oomycetes/Eurychasmataceae/Eurychasmidium/Eurychasmidium joyceae/ Syn. Eurychasmidium joycei/README.md
|
201
|
# Eurychasmidium joycei (Sparrow) M.W. Dick SPECIES
#### Status
SYNONYM
#### According to
Index Fungorum
#### Published in
null
#### Original name
Eurychasma joyceae Sparrow, 1969
### Remarks
null
|
apache-2.0
|
nghiant2710/base-images
|
balena-base-images/golang/odroid-c1/alpine/3.13/1.14.13/run/Dockerfile
|
2468
|
# AUTOGENERATED FILE
FROM balenalib/odroid-c1-alpine:3.13-run
ENV GO_VERSION 1.14.13
# set up nsswitch.conf for Go's "netgo" implementation
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
# gcc for cgo
RUN apk add --no-cache git gcc ca-certificates
RUN fetchDeps='curl' \
&& set -x \
&& apk add --no-cache $fetchDeps \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-armv7hf.tar.gz" \
&& echo "8ed9ed68ffcbf708850ea06bec03e601303067ee919467a1b5b096ca779188d7 go$GO_VERSION.linux-alpine-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-alpine-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-alpine-armv7hf.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
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/[email protected]" \
&& echo "Running test-stack@golang" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
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: \nGo v1.14.13 \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
|
apache-2.0
|
tensorflow/tfhub.dev
|
assets/docs/sayakpaul/deeplabv3-xception65-ade20k/1/default/lite/2.md
|
1900
|
# Lite sayakpaul/deeplabv3-xception65-ade20k/1/default/2
Lightweight deep learning model for semantic image segmentation.
<!-- parent-model: sayakpaul/deeplabv3-xception65-ade20k/1 -->
<!-- asset-path: legacy -->
<!-- interactive-visualizer: tflite_image_segmenter -->
<!-- colab: https://colab.research.google.com/github/sayakpaul/Adventures-in-TensorFlow-Lite/blob/master/DeepLabV3/DeepLab_TFLite_ADE20k.ipynb -->
### Overview
DeepLab is a state-of-art deep learning model for semantic image segmentation, where the goal is to assign semantic labels (e.g. person, dog, cat) to every pixel in the input image. It was published in [1].
### Note
- The TensorFlow Lite model was generated from [`xception65_ade20k_train`](http://download.tensorflow.org/models/deeplabv3_xception_ade20k_train_2018_05_29.tar.gz) checkpoint. More information about the different DeepLabV3 checkpoints is available [here](https://github.com/tensorflow/models/blob/master/research/deeplab/g3doc/model_zoo.md).
- The model is metadata populated which makes it extremely easier for mobile application developers to consume this model in their applications. Know more about TFLite metadata from [here](https://www.tensorflow.org/lite/convert/metadata).
- This model was quantized using _dynamic range quantization_ as described [here](https://www.tensorflow.org/lite/performance/post_training_quant).
- Example usage and TensorFlow Lite conversion process are demonstrated in the accompanying Colab Notebook.
### Example use
For a good understanding of the model usage check out this [sample application](https://github.com/tensorflow/examples/tree/master/lite/examples/image_segmentation/android).
### Acknowledgements
Thanks to Khanh LeViet for his constant guidance.
References
--------------
[1] [Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation](https://arxiv.org/abs/1802.02611).
|
apache-2.0
|
lesjaw/Olmatix
|
olmatix/src/main/java/com/olmatix/model/SpinnerObject.java
|
641
|
package com.olmatix.model;
/**
* Created by Rahman on 12/28/2016.
*/
public class SpinnerObject {
private String databaseId;
private String databaseValue;
public SpinnerObject() {
this.databaseId = databaseId;
this.databaseValue = databaseValue;
}
public String getDatabaseId() {
return databaseId;
}
public void setDatabaseId(String databaseId) {
this.databaseId = databaseId;
}
public String getDatabaseValue() {
return databaseValue;
}
public void setDatabaseValue(String databaseValue) {
this.databaseValue = databaseValue;
}
}
|
apache-2.0
|
trasa/aws-sdk-java
|
aws-java-sdk-elasticloadbalancing/src/main/java/com/amazonaws/services/elasticloadbalancing/model/LoadBalancerAttributeNotFoundException.java
|
1217
|
/*
* Copyright 2010-2016 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.elasticloadbalancing.model;
import com.amazonaws.AmazonServiceException;
/**
* <p>
* The specified load balancer attribute does not exist.
* </p>
*/
public class LoadBalancerAttributeNotFoundException extends AmazonServiceException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new LoadBalancerAttributeNotFoundException with the specified error
* message.
*
* @param message Describes the error encountered.
*/
public LoadBalancerAttributeNotFoundException(String message) {
super(message);
}
}
|
apache-2.0
|
citrix/terraform-provider-netscaler
|
citrixadc/resource_citrixadc_transformaction.go
|
8186
|
package citrixadc
import (
"github.com/citrix/adc-nitro-go/resource/config/transform"
"github.com/citrix/adc-nitro-go/service"
"github.com/hashicorp/terraform/helper/schema"
"fmt"
"log"
)
func resourceCitrixAdcTransformaction() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
Create: createTransformactionFunc,
Read: readTransformactionFunc,
Update: updateTransformactionFunc,
Delete: deleteTransformactionFunc,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"comment": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"cookiedomainfrom": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"cookiedomaininto": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"priority": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"profilename": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"requrlfrom": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"requrlinto": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"resurlfrom": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"resurlinto": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"state": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}
func createTransformactionFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In createTransformactionFunc")
client := meta.(*NetScalerNitroClient).client
transformactionName := d.Get("name").(string)
// Create does not support all attributes
transformactionNew := transform.Transformaction{
Name: d.Get("name").(string),
Priority: d.Get("priority").(int),
Profilename: d.Get("profilename").(string),
State: d.Get("state").(string),
}
_, err := client.AddResource(service.Transformaction.Type(), transformactionName, &transformactionNew)
if err != nil {
return err
}
// Need to update with full set of attributes
transformaction := transform.Transformaction{
Comment: d.Get("comment").(string),
Cookiedomainfrom: d.Get("cookiedomainfrom").(string),
Cookiedomaininto: d.Get("cookiedomaininto").(string),
Name: d.Get("name").(string),
Priority: d.Get("priority").(int),
Requrlfrom: d.Get("requrlfrom").(string),
Requrlinto: d.Get("requrlinto").(string),
Resurlfrom: d.Get("resurlfrom").(string),
Resurlinto: d.Get("resurlinto").(string),
State: d.Get("state").(string),
}
_, err = client.UpdateResource(service.Transformaction.Type(), transformactionName, &transformaction)
if err != nil {
return err
}
d.SetId(transformactionName)
err = readTransformactionFunc(d, meta)
if err != nil {
log.Printf("[ERROR] netscaler-provider: ?? we just created this transformaction but we can't read it ?? %s", transformactionName)
return nil
}
return nil
}
func readTransformactionFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In readTransformactionFunc")
client := meta.(*NetScalerNitroClient).client
transformactionName := d.Id()
log.Printf("[DEBUG] citrixadc-provider: Reading transformaction state %s", transformactionName)
data, err := client.FindResource(service.Transformaction.Type(), transformactionName)
if err != nil {
log.Printf("[WARN] citrixadc-provider: Clearing transformaction state %s", transformactionName)
d.SetId("")
return nil
}
d.Set("name", data["name"])
d.Set("comment", data["comment"])
d.Set("cookiedomainfrom", data["cookiedomainfrom"])
d.Set("cookiedomaininto", data["cookiedomaininto"])
d.Set("name", data["name"])
d.Set("priority", data["priority"])
d.Set("profilename", data["profilename"])
d.Set("requrlfrom", data["requrlfrom"])
d.Set("requrlinto", data["requrlinto"])
d.Set("resurlfrom", data["resurlfrom"])
d.Set("resurlinto", data["resurlinto"])
d.Set("state", data["state"])
return nil
}
func updateTransformactionFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In updateTransformactionFunc")
client := meta.(*NetScalerNitroClient).client
transformactionName := d.Get("name").(string)
transformaction := transform.Transformaction{
Name: d.Get("name").(string),
}
hasChange := false
if d.HasChange("comment") {
log.Printf("[DEBUG] citrixadc-provider: Comment has changed for transformaction %s, starting update", transformactionName)
transformaction.Comment = d.Get("comment").(string)
hasChange = true
}
if d.HasChange("cookiedomainfrom") {
log.Printf("[DEBUG] citrixadc-provider: Cookiedomainfrom has changed for transformaction %s, starting update", transformactionName)
transformaction.Cookiedomainfrom = d.Get("cookiedomainfrom").(string)
hasChange = true
}
if d.HasChange("cookiedomaininto") {
log.Printf("[DEBUG] citrixadc-provider: Cookiedomaininto has changed for transformaction %s, starting update", transformactionName)
transformaction.Cookiedomaininto = d.Get("cookiedomaininto").(string)
hasChange = true
}
if d.HasChange("name") {
log.Printf("[DEBUG] citrixadc-provider: Name has changed for transformaction %s, starting update", transformactionName)
transformaction.Name = d.Get("name").(string)
hasChange = true
}
if d.HasChange("priority") {
log.Printf("[DEBUG] citrixadc-provider: Priority has changed for transformaction %s, starting update", transformactionName)
transformaction.Priority = d.Get("priority").(int)
hasChange = true
}
if d.HasChange("profilename") {
log.Printf("[DEBUG] citrixadc-provider: Profilename has changed for transformaction %s, starting update", transformactionName)
transformaction.Profilename = d.Get("profilename").(string)
hasChange = true
}
if d.HasChange("requrlfrom") {
log.Printf("[DEBUG] citrixadc-provider: Requrlfrom has changed for transformaction %s, starting update", transformactionName)
transformaction.Requrlfrom = d.Get("requrlfrom").(string)
hasChange = true
}
if d.HasChange("requrlinto") {
log.Printf("[DEBUG] citrixadc-provider: Requrlinto has changed for transformaction %s, starting update", transformactionName)
transformaction.Requrlinto = d.Get("requrlinto").(string)
hasChange = true
}
if d.HasChange("resurlfrom") {
log.Printf("[DEBUG] citrixadc-provider: Resurlfrom has changed for transformaction %s, starting update", transformactionName)
transformaction.Resurlfrom = d.Get("resurlfrom").(string)
hasChange = true
}
if d.HasChange("resurlinto") {
log.Printf("[DEBUG] citrixadc-provider: Resurlinto has changed for transformaction %s, starting update", transformactionName)
transformaction.Resurlinto = d.Get("resurlinto").(string)
hasChange = true
}
if d.HasChange("state") {
log.Printf("[DEBUG] citrixadc-provider: State has changed for transformaction %s, starting update", transformactionName)
transformaction.State = d.Get("state").(string)
hasChange = true
}
if hasChange {
_, err := client.UpdateResource(service.Transformaction.Type(), transformactionName, &transformaction)
if err != nil {
return fmt.Errorf("Error updating transformaction %s", transformactionName)
}
}
return readTransformactionFunc(d, meta)
}
func deleteTransformactionFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In deleteTransformactionFunc")
client := meta.(*NetScalerNitroClient).client
transformactionName := d.Id()
err := client.DeleteResource(service.Transformaction.Type(), transformactionName)
if err != nil {
return err
}
d.SetId("")
return nil
}
|
apache-2.0
|
yeminhtut/yeminhtut.github.io
|
css/freelancer.css
|
7900
|
/*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
body {
overflow-x: hidden;
}
p {
font-size: 20px;
}
p.small {
font-size: 16px;
}
a,
a:hover,
a:focus,
a:active,
a.active {
outline: 0;
color: #18bc9c;
}
h1,
h2,
h3,
h4,
h5,
h6 {
text-transform: uppercase;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight: 700;
}
hr.star-light,
hr.star-primary {
margin: 25px auto 30px;
padding: 0;
max-width: 250px;
border: 0;
border-top: solid 5px;
text-align: center;
}
hr.star-light:after,
hr.star-primary:after {
content: "\f005";
display: inline-block;
position: relative;
top: -.8em;
padding: 0 .25em;
font-family: FontAwesome;
font-size: 2em;
}
hr.star-light {
border-color: #fff;
}
hr.star-light:after {
color: #fff;
background-color: #2fa9dd;
}
#about .star-light:after {
color: #fff;
background-color: #18bc9c;
}
hr.star-primary {
border-color: #2c3e50;
}
hr.star-primary:after {
color: #2c3e50;
background-color: #fff;
}
.img-centered {
margin: 0 auto;
}
header {
text-align: center;
color: #fff;
background: #2fa9dd;
}
header .container {
padding-top: 100px;
padding-bottom: 50px;
}
header img {
display: block;
margin: 0 auto 20px;
}
header .intro-text .name {
display: block;
text-transform: uppercase;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-size: 2em;
font-weight: 700;
}
header .intro-text .skills {
font-size: 1.25em;
font-weight: 300;
}
@media(min-width:768px) {
header .container {
padding-top: 200px;
padding-bottom: 100px;
}
header .intro-text .name {
font-size: 4.75em;
}
header .intro-text .skills {
font-size: 1.75em;
}
}
@media(min-width:768px) {
.navbar-fixed-top {
padding: 25px 0;
-webkit-transition: padding .3s;
-moz-transition: padding .3s;
transition: padding .3s;
}
.navbar-fixed-top .navbar-brand {
font-size: 2em;
-webkit-transition: all .3s;
-moz-transition: all .3s;
transition: all .3s;
}
.navbar-fixed-top.navbar-shrink {
padding: 10px 0;
}
.navbar-fixed-top.navbar-shrink .navbar-brand {
font-size: 1.5em;
}
}
.navbar {
text-transform: uppercase;
font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
font-weight: 700;
}
.navbar a:focus {
outline: 0;
}
.navbar .navbar-nav {
letter-spacing: 1px;
}
.navbar .navbar-nav li a:focus {
outline: 0;
}
.navbar-default,
.navbar-inverse {
border: 0;
}
section {
padding: 100px 0;
}
section h2 {
margin: 0;
font-size: 3em;
}
section.success {
color: #fff;
background: #18bc9c;
}
@media(max-width:767px) {
section {
padding: 75px 0;
}
section.first {
padding-top: 75px;
}
}
#portfolio .portfolio-item {
right: 0;
margin: 0 0 15px;
}
#portfolio .portfolio-item .portfolio-link {
display: block;
position: relative;
margin: 0 auto;
max-width: 400px;
}
#portfolio .portfolio-item .portfolio-link .caption {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
background: rgba(24,188,156,.9);
-webkit-transition: all ease .5s;
-moz-transition: all ease .5s;
transition: all ease .5s;
}
#portfolio .portfolio-item .portfolio-link .caption:hover {
opacity: 1;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content {
position: absolute;
top: 50%;
width: 100%;
height: 20px;
margin-top: -12px;
text-align: center;
font-size: 20px;
color: #fff;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content i {
margin-top: -12px;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content h3,
#portfolio .portfolio-item .portfolio-link .caption .caption-content h4 {
margin: 0;
}
#portfolio * {
z-index: 2;
}
@media(min-width:767px) {
#portfolio .portfolio-item {
margin: 0 0 30px;
}
}
.btn-outline {
margin-top: 15px;
border: solid 2px #fff;
font-size: 20px;
color: #fff;
background: 0 0;
transition: all .3s ease-in-out;
}
.btn-outline:hover,
.btn-outline:focus,
.btn-outline:active,
.btn-outline.active {
border: solid 2px #fff;
color: #18bc9c;
background: #fff;
}
.floating-label-form-group {
position: relative;
margin-bottom: 0;
padding-bottom: .5em;
border-bottom: 1px solid #eee;
}
.floating-label-form-group input,
.floating-label-form-group textarea {
z-index: 1;
position: relative;
padding-right: 0;
padding-left: 0;
border: 0;
border-radius: 0;
font-size: 1.5em;
background: 0 0;
box-shadow: none!important;
resize: none;
}
.floating-label-form-group label {
display: block;
z-index: 0;
position: relative;
top: 2em;
margin: 0;
font-size: .85em;
line-height: 1.764705882em;
vertical-align: middle;
vertical-align: baseline;
opacity: 0;
-webkit-transition: top .3s ease,opacity .3s ease;
-moz-transition: top .3s ease,opacity .3s ease;
-ms-transition: top .3s ease,opacity .3s ease;
transition: top .3s ease,opacity .3s ease;
}
.floating-label-form-group::not(:first-child) {
padding-left: 14px;
border-left: 1px solid #eee;
}
.floating-label-form-group-with-value label {
top: 0;
opacity: 1;
}
.floating-label-form-group-with-focus label {
color: #18bc9c;
}
form .row:first-child .floating-label-form-group {
border-top: 1px solid #eee;
}
footer {
color: #fff;
}
footer h3 {
margin-bottom: 30px;
}
footer .footer-above {
padding-top: 50px;
background-color: #2c3e50;
}
footer .footer-col {
margin-bottom: 50px;
}
footer .footer-below {
padding: 25px 0;
background-color: #233140;
}
.btn-social {
display: inline-block;
width: 50px;
height: 50px;
border: 2px solid #fff;
border-radius: 100%;
text-align: center;
font-size: 20px;
line-height: 45px;
}
.btn:focus,
.btn:active,
.btn.active {
outline: 0;
}
.scroll-top {
z-index: 1049;
position: fixed;
right: 2%;
bottom: 2%;
width: 50px;
height: 50px;
}
.scroll-top .btn {
width: 50px;
height: 50px;
border-radius: 100%;
font-size: 20px;
line-height: 28px;
}
.scroll-top .btn:focus {
outline: 0;
}
.portfolio-modal .modal-content {
padding: 100px 0;
min-height: 100%;
border: 0;
border-radius: 0;
text-align: center;
background-clip: border-box;
-webkit-box-shadow: none;
box-shadow: none;
}
.portfolio-modal .modal-content h2 {
margin: 0;
font-size: 3em;
}
.portfolio-modal .modal-content img {
margin-bottom: 30px;
}
.portfolio-modal .modal-content .item-details {
margin: 30px 0;
}
.portfolio-modal .close-modal {
position: absolute;
top: 25px;
right: 25px;
width: 75px;
height: 75px;
background-color: transparent;
cursor: pointer;
}
.portfolio-modal .close-modal:hover {
opacity: .3;
}
.portfolio-modal .close-modal .lr {
z-index: 1051;
width: 1px;
height: 75px;
margin-left: 35px;
background-color: #2c3e50;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.portfolio-modal .close-modal .lr .rl {
z-index: 1052;
width: 1px;
height: 75px;
background-color: #2c3e50;
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.portfolio-modal .modal-backdrop {
display: none;
opacity: 0;
}
|
apache-2.0
|
tthomas48/databean
|
BuyPlayTix/DataBean/ObjectAdapter.php
|
19538
|
<?php
namespace BuyPlayTix\DataBean;
class ObjectAdapter implements IAdapter
{
public static $DB_DIR;
private $tables = [];
private $queries = [];
public function __construct()
{}
function load($databean, $param = "")
{
$table = $databean->getTable();
$pk = $databean->getPk();
if (! array_key_exists($table, $this->tables)) {
$this->tables[$table] = [];
}
$b = $this->tables[$table];
if (is_array($param)) {
foreach ($b as $bean) {
if (array_key_exists($param[0], $bean) && $bean[$param[0]] == $param[1]) {
$databean->fields = $bean;
$databean->setNew(false);
return $databean;
}
}
} elseif (strlen($param) > 0) {
foreach ($b as $bean) {
if (array_key_exists($pk, $bean) && $bean[$pk] == $param) {
$databean->fields = $bean;
$databean->setNew(false);
return $databean;
}
}
}
$uuid = UUID::get();
$databean->fields[$pk] = $uuid;
$databean->setNew(true);
return $databean;
}
function loadAll($databean, $field = "", $param = "", $andClause = "")
{
if (strlen($field) > 0) {
if (is_array($param) && count($param) == 1) {
$whereClause = ' where ' . $field . ' = ' . $param[0];
} else {
$valList = $this->_parseList($param);
$whereClause = ' where ' . $field . ' in ' . $valList;
}
} elseif (is_array($param) && count($param) > 0) {
if (is_array($param) && count($param) == 1) {
$whereClause = ' where ' . $databean->getPk() . ' = ' . $param[0];
} else {
$valList = $this->_parseList($param);
$whereClause = ' where ' . $databean->getPk() . ' in ' . $valList;
}
} else {
$whereClause = "";
}
$group_by = "";
$order_by = "";
$where = array();
$clause = $whereClause . " " . $andClause;
$chunks = preg_split("/\s*GROUP\s+BY\s*/i", $clause);
if (count($chunks) == 2) {
$clause = $chunks[0];
$group_by = $chunks[1];
}
$chunks = preg_split("/\s*ORDER\s+BY\s*/i", $clause);
if (count($chunks) == 2) {
$clause = $chunks[0];
$order_by = $chunks[1];
}
$clause = preg_replace("/\s*WHERE\s*/i", "", $clause);
$chunks = preg_split("/\s*AND\s*/i", $clause);
foreach ($chunks as $chunk) {
$where_chunks = preg_split("/\s*!=\s*/i", $chunk);
if (count($where_chunks) == 2) {
$field = strtoupper(trim($where_chunks[0]));
$value = trim($where_chunks[1], ' \'');
$where[$field] = array(
"v" => $value,
"condition" => "!="
);
continue;
}
$where_chunks = preg_split("/\s*=\s*/i", $chunk);
if (count($where_chunks) == 2) {
$field = strtoupper(trim($where_chunks[0]));
$value = trim($where_chunks[1], ' \'');
$where[$field] = array(
"v" => $value,
"condition" => "="
);
continue;
}
$where_chunks = preg_split("/\s+in\s*/i", $chunk);
if (count($where_chunks) == 2) {
$field = strtoupper(trim($where_chunks[0]));
$value = str_replace(')', '', str_replace('(', '', $where_chunks[1]));
$values = explode(',', $value);
for ($i = 0; $i < count($values); $i ++) {
$values[$i] = trim($values[$i], ' \'');
}
$where[$field] = array(
"v" => $values,
"condition" => "="
);
continue;
}
}
$databeans = array();
$table = $databean->getTable();
$pk = $databean->getPk();
$b = $this->tables[$table];
foreach ($b as $bean) {
$bean_matches = true;
foreach ($where as $field => $predicate) {
$value = $predicate["v"];
$condition = $predicate["condition"];
if (is_array($value)) {
$found_match = false;
foreach ($value as $v) {
if (array_key_exists($field, $bean) && $this->isMatch($bean[$field], $condition, $v)) {
$found_match = true;
}
}
if (! $found_match) {
$bean_matches = false;
}
} elseif (!array_key_exists($field, $bean) || ($this->isMatch($bean[$field], $condition, $value) === false)) {
$bean_matches = false;
}
}
if ($bean_matches) {
$className = get_class($databean);
$newBean = new $className($bean[$pk]);
$databeans[] = $newBean;
}
}
return $databeans;
}
private function isMatch($beanValue, $condition, $value)
{
if ($condition === '=') {
return $beanValue === $value;
}
if ($condition === '!=') {
return $beanValue !== $value;
}
return false;
}
function update($databean)
{
$table = $databean->getTable();
$pk = $databean->getPk();
if (array_key_exists($table, $this->tables) === false) {
$this->tables[$table] = [];
}
$existingRowKey = null;
for($index = 0; $index < count($this->tables[$table]); $index++) {
$row = $this->tables[$table][$index];
if (array_key_exists($pk, $row) && $row[$pk] === $databean->$pk) {
$existingRowKey = $index;
break;
}
}
$databean->setNew(false);
if ($existingRowKey === null) {
$this->tables[$table][] = $databean->getFields();
return $databean;
}
foreach ($databean->getFields() as $key => $value) {
$this->tables[$table][$existingRowKey][$key] = $value;
}
return $databean;
}
function delete($databean)
{
$table = $databean->getTable();
$pk = $databean->getPk();
if (! array_key_exists($table, $this->tables)) {
return $databean;
}
foreach ($this->tables[$table] as $index => $row) {
if (array_key_exists($pk, $row) && $row[$pk] === $databean->$pk) {
unset($this->tables[$table][$index]);
return $databean;
}
}
}
private function get_pk_value($databean)
{
$pk_value = $databean->get($databean->getPk());
if ($pk_value != NULL) {
return $pk_value;
}
return UUID::get();
}
function raw_delete($table, $where_fields = array())
{
if (array_key_exists($table, $this->tables) === false) {
$this->tables[$table] = [];
return;
}
$t = $this->tables[$table];
foreach ($t as $index => $row) {
$found_match = false;
foreach ($where_fields as $name => $v) {
// print $row[$name] . "\n";
// $v = 1, $row[$name] = 2
$value = $v;
if (is_array($v)) {
$condition = $v['condition'];
$value = $v['value'];
switch ($condition) {
case '<>':
case '!=':
if ($row[$name] == $value) {
$found_match = true;
}
break;
case '>':
if ($row[$name] > $value) {
$found_match = true;
}
break;
case '<':
if ($row[$name] < $value) {
$found_match = true;
}
break;
case 'in':
if (! in_array($row[$name], $value)) {
$found_match = true;
}
break;
case '=':
default:
if ($row[$name] != $value) {
$found_match = true;
}
break;
}
} elseif ($row[$name] === $value) {
$found_match = true;
}
}
if ($found_match) {
unset($t[$index]);
}
}
$this->tables[$table] = $t;
}
function raw_insert($table, $fields = array())
{
if (! isset($this->tables[$table])) {
$this->tables[$table] = array();
}
$t = $this->tables[$table];
foreach ($t as $index => $row) {
$found_match = true;
foreach ($fields as $name => $value) {
if ($row[$name] != $value) {
$found_match = false;
}
}
if ($found_match) {
throw new Exception("Unique constraint failure.");
}
}
$this->tables[$table][] = $fields;
}
function raw_replace($table, $fields = []) {
if (! isset($this->tables[$table])) {
return $this->raw_insert($table, $fields);
}
$pk = "UID";
if (array_key_exists("ID", $fields)) {
$pk = "ID";
}
$foundRow = false;
$t = $this->tables[$table];
foreach ($t as $index => $row) {
if ($row[$pk] === $fields[$pk]) {
$foundRow = true;
foreach($fields as $key => $value) {
$this->tables[$table][$index][$key] = $value;
}
}
}
if (!$foundRow) {
return $this->raw_insert($table, $fields);
}
}
// TODO: Add order and grouping, aggregate
function raw_select($table, $fields = array(), $where_fields = array(), $cast_class = NULL, $order = array(), $group = array())
{
if (array_key_exists($table, $this->tables) === false) {
$this->tables[$table] = array();
}
$results = array();
$t = $this->tables[$table];
foreach ($t as $index => $row) {
$found_match = true;
foreach ($where_fields as $name => $v) {
$value = $v;
if (is_array($v)) {
$condition = $v['condition'];
$value = $v['value'];
switch ($condition) {
case '<>':
case '!=':
if ($row[$name] == $value) {
$found_match = false;
}
break;
case '>':
if ($row[$name] <= $value) {
$found_match = false;
}
break;
case '<':
if ($row[$name] < $value) {
$found_match >= false;
}
break;
case 'in':
if (! in_array($row[$name], $value)) {
$found_match = false;
}
break;
case '=':
default:
if ($row[$name] != $value) {
$found_match = false;
}
break;
}
} elseif (!array_key_exists($name, $row) || $row[$name] != $value) {
$found_match = false;
}
}
if ($found_match) {
if ($cast_class != NULL) {
$class = new \ReflectionClass($cast_class);
$results[] = $class->newInstanceArgs(array(
$row[$fields[0]]
));
} else {
$ret_row = array();
$aggregation = array();
foreach ($fields as $field) {
if (is_array($field)) {
$field_name = $field['name'];
$field_alias = $field['alias'];
if (empty($field_alias)) {
$field_alias = $field_name;
}
switch ($field['aggregation']) {
case 'count':
if (isset($aggregation[$field_alias])) {
$aggregation[$field_alias] = $aggregation[$field_alias]++;
break;
}
$aggregation[$field_alias] = 1;
break;
case 'sum':
if (isset($aggregation[$field_alias])) {
$aggregation[$field_alias] = $aggregation[$field_alias] += $row[$field_name];
break;
}
$aggregation[$field_alias] = $row[$field_name];
break;
default:
throw new \Exception("Unknown aggregation type for field $field_name.");
}
} else {
if (array_key_exists($field, $row)) {
$ret_row[$field] = $row[$field];
} else {
$ret_row[$field] = null;
}
}
}
foreach ($aggregation as $field_name => $field_value) {
$ret_row[$field_name] = $field_value;
}
$results[] = $ret_row;
}
}
}
return $results;
}
function raw_update($table, $fields = array(), $where_fields = array())
{
if (array_key_exists($table, $this->tables) === false) {
$this->tables[$table] = array();
}
$t = $this->tables[$table];
foreach ($t as $index => $row) {
$found_match = true;
foreach ($where_fields as $name => $v) {
$value = $v;
if (is_array($v)) {
switch ($v['condition']) {
case '<>':
case '!=':
if ($row[$name] == $value) {
$found_match = false;
}
break;
case '>':
if ($row[$name] > $value) {
$found_match = false;
}
break;
case '<':
if ($row[$name] < $value) {
$found_match = false;
}
break;
case 'in':
if (! in_array($row[$name], $value)) {
$found_match = false;
}
break;
case '=':
default:
if ($row[$name] != $value) {
$found_match = false;
}
break;
}
$condition = $v['condition'];
$value = $v['value'];
} else {
if ($row[$name] != $value) {
$found_match = false;
}
}
}
if ($found_match) {
foreach ($row as $row_name => $row_value) {
foreach ($fields as $field_name => $field_value) {
if ($row_name === $field_name) {
$this->tables[$table][$index][$row_name] = $field_value;
}
}
}
}
}
}
public function set_named_query_value($name, $value)
{
$this->queries[$name] = $value;
}
function named_query($name, $sql = "", $params = array(), $hash = true)
{
if (! array_key_exists($name, $this->queries)) {
throw new \Exception("No value set for named query: " . $name);
}
return $this->queries[$name];
}
private function _parseList($param = Array())
{
return "('" . implode("','", $param) . "')";
}
public function loadDatabase()
{
if (file_exists(ObjectAdapter::$DB_DIR . "tables.test.db")) {
$lock = fopen(ObjectAdapter::$DB_DIR . "tables.test.db", 'rb');
@flock($lock, LOCK_SH);
$this->tables = unserialize(file_get_contents(ObjectAdapter::$DB_DIR . "tables.test.db"));
@flock($lock, LOCK_UN);
fclose($lock);
}
if (file_exists(ObjectAdapter::$DB_DIR . "queries.test.db")) {
$lock = fopen(ObjectAdapter::$DB_DIR . "queries.test.db", 'rb');
@flock($lock, LOCK_SH);
$this->queries = unserialize(file_get_contents(ObjectAdapter::$DB_DIR . "queries.test.db"));
@flock($lock, LOCK_UN);
fclose($lock);
}
}
public function saveDatabase()
{
file_put_contents(ObjectAdapter::$DB_DIR . "tables.test.db", serialize($this->tables), LOCK_EX);
file_put_contents(ObjectAdapter::$DB_DIR . "queries.test.db", serialize($this->queries), LOCK_EX);
if ((fileperms(ObjectAdapter::$DB_DIR . "tables.test.db") & 0777) !== 0766) {
chmod(ObjectAdapter::$DB_DIR . "tables.test.db", 0766);
}
if ((fileperms(ObjectAdapter::$DB_DIR . "queries.test.db") & 0777) !== 0766) {
chmod(ObjectAdapter::$DB_DIR . "queries.test.db", 0766);
}
}
public function printDatabase()
{
print "Queries: \n";
print_r($this->queries);
print "Tables: \n";
print_r($this->tables);
}
public function clearDatabase()
{
$this->tables = [];
$this->queries = [];
$this->saveDatabase();
}
}
|
apache-2.0
|
seattlepublicrecords/seattlepublicrecords.github.io
|
information/agencies/city_of_seattle/seattle_police_department/copbook/5336/index.md
|
194
|
---
layout: page
title: Seattle Police Officer 5336 Suzanne M. Ross
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/5336/
---
**Age as of Feb. 24, 2016:** 55
|
apache-2.0
|
spark/photon-tinker-android
|
firmwareprotos/src/main/java/io/particle/firmwareprotos/ctrl/cloud/Cloud.java
|
42941
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: cloud.proto
package io.particle.firmwareprotos.ctrl.cloud;
public final class Cloud {
private Cloud() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
/**
* <pre>
* Make sure values of this enum match the values defined for the diagnostic info
* </pre>
*
* Protobuf enum {@code particle.ctrl.cloud.ConnectionStatus}
*/
public enum ConnectionStatus
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>DISCONNECTED = 0;</code>
*/
DISCONNECTED(0),
/**
* <code>CONNECTING = 1;</code>
*/
CONNECTING(1),
/**
* <code>CONNECTED = 2;</code>
*/
CONNECTED(2),
/**
* <code>DISCONNECTING = 3;</code>
*/
DISCONNECTING(3),
UNRECOGNIZED(-1),
;
/**
* <code>DISCONNECTED = 0;</code>
*/
public static final int DISCONNECTED_VALUE = 0;
/**
* <code>CONNECTING = 1;</code>
*/
public static final int CONNECTING_VALUE = 1;
/**
* <code>CONNECTED = 2;</code>
*/
public static final int CONNECTED_VALUE = 2;
/**
* <code>DISCONNECTING = 3;</code>
*/
public static final int DISCONNECTING_VALUE = 3;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static ConnectionStatus valueOf(int value) {
return forNumber(value);
}
public static ConnectionStatus forNumber(int value) {
switch (value) {
case 0: return DISCONNECTED;
case 1: return CONNECTING;
case 2: return CONNECTED;
case 3: return DISCONNECTING;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<ConnectionStatus>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
ConnectionStatus> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<ConnectionStatus>() {
public ConnectionStatus findValueByNumber(int number) {
return ConnectionStatus.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.getDescriptor().getEnumTypes().get(0);
}
private static final ConnectionStatus[] VALUES = values();
public static ConnectionStatus valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private ConnectionStatus(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:particle.ctrl.cloud.ConnectionStatus)
}
public interface GetConnectionStatusRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:particle.ctrl.cloud.GetConnectionStatusRequest)
com.google.protobuf.MessageOrBuilder {
}
/**
* <pre>
* Get the cloud connection status
* </pre>
*
* Protobuf type {@code particle.ctrl.cloud.GetConnectionStatusRequest}
*/
public static final class GetConnectionStatusRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:particle.ctrl.cloud.GetConnectionStatusRequest)
GetConnectionStatusRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetConnectionStatusRequest.newBuilder() to construct.
private GetConnectionStatusRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetConnectionStatusRequest() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private GetConnectionStatusRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.class, io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.Builder.class);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest)) {
return super.equals(obj);
}
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest other = (io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest) obj;
boolean result = true;
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Get the cloud connection status
* </pre>
*
* Protobuf type {@code particle.ctrl.cloud.GetConnectionStatusRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:particle.ctrl.cloud.GetConnectionStatusRequest)
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.class, io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.Builder.class);
}
// Construct using io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest getDefaultInstanceForType() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.getDefaultInstance();
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest build() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest buildPartial() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest result = new io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest(this);
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest) {
return mergeFrom((io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest other) {
if (other == io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.getDefaultInstance()) return this;
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:particle.ctrl.cloud.GetConnectionStatusRequest)
}
// @@protoc_insertion_point(class_scope:particle.ctrl.cloud.GetConnectionStatusRequest)
private static final io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest();
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetConnectionStatusRequest>
PARSER = new com.google.protobuf.AbstractParser<GetConnectionStatusRequest>() {
public GetConnectionStatusRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetConnectionStatusRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetConnectionStatusRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetConnectionStatusRequest> getParserForType() {
return PARSER;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface GetConnectionStatusReplyOrBuilder extends
// @@protoc_insertion_point(interface_extends:particle.ctrl.cloud.GetConnectionStatusReply)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
int getStatusValue();
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus getStatus();
}
/**
* Protobuf type {@code particle.ctrl.cloud.GetConnectionStatusReply}
*/
public static final class GetConnectionStatusReply extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:particle.ctrl.cloud.GetConnectionStatusReply)
GetConnectionStatusReplyOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetConnectionStatusReply.newBuilder() to construct.
private GetConnectionStatusReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetConnectionStatusReply() {
status_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private GetConnectionStatusReply(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
int rawValue = input.readEnum();
status_ = rawValue;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.class, io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.Builder.class);
}
public static final int STATUS_FIELD_NUMBER = 1;
private int status_;
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public int getStatusValue() {
return status_;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus getStatus() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus result = io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.valueOf(status_);
return result == null ? io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (status_ != io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.DISCONNECTED.getNumber()) {
output.writeEnum(1, status_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (status_ != io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.DISCONNECTED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, status_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply)) {
return super.equals(obj);
}
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply other = (io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply) obj;
boolean result = true;
result = result && status_ == other.status_;
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + status_;
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code particle.ctrl.cloud.GetConnectionStatusReply}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:particle.ctrl.cloud.GetConnectionStatusReply)
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReplyOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.class, io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.Builder.class);
}
// Construct using io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
status_ = 0;
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply getDefaultInstanceForType() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.getDefaultInstance();
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply build() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply buildPartial() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply result = new io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply(this);
result.status_ = status_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply) {
return mergeFrom((io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply other) {
if (other == io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.getDefaultInstance()) return this;
if (other.status_ != 0) {
setStatusValue(other.getStatusValue());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int status_ = 0;
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public int getStatusValue() {
return status_;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public Builder setStatusValue(int value) {
status_ = value;
onChanged();
return this;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus getStatus() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus result = io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.valueOf(status_);
return result == null ? io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.UNRECOGNIZED : result;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public Builder setStatus(io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus value) {
if (value == null) {
throw new NullPointerException();
}
status_ = value.getNumber();
onChanged();
return this;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public Builder clearStatus() {
status_ = 0;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:particle.ctrl.cloud.GetConnectionStatusReply)
}
// @@protoc_insertion_point(class_scope:particle.ctrl.cloud.GetConnectionStatusReply)
private static final io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply();
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetConnectionStatusReply>
PARSER = new com.google.protobuf.AbstractParser<GetConnectionStatusReply>() {
public GetConnectionStatusReply parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetConnectionStatusReply(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetConnectionStatusReply> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetConnectionStatusReply> getParserForType() {
return PARSER;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\013cloud.proto\022\023particle.ctrl.cloud\032\020exte" +
"nsions.proto\"#\n\032GetConnectionStatusReque" +
"st:\005\210\265\030\254\002\"Q\n\030GetConnectionStatusReply\0225\n" +
"\006status\030\001 \001(\0162%.particle.ctrl.cloud.Conn" +
"ectionStatus*V\n\020ConnectionStatus\022\020\n\014DISC" +
"ONNECTED\020\000\022\016\n\nCONNECTING\020\001\022\r\n\tCONNECTED\020" +
"\002\022\021\n\rDISCONNECTING\020\003B\'\n%io.particle.firm" +
"wareprotos.ctrl.cloudb\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
io.particle.firmwareprotos.ctrl.Extensions.getDescriptor(),
}, assigner);
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor,
new java.lang.String[] { });
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor,
new java.lang.String[] { "Status", });
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(io.particle.firmwareprotos.ctrl.Extensions.typeId);
com.google.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
io.particle.firmwareprotos.ctrl.Extensions.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Ranunculaceae/Delphinium/README.md
|
169
|
# Delphinium L. GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
dtgm/chocolatey-packages
|
automatic/_output/cyberduck.install/6.2.4.26305/tools/chocolateyInstall.ps1
|
656
|
$packageName = 'cyberduck.install'
$installerType = 'exe'
$silentArgs = '/S'
$url = 'https://update.cyberduck.io/windows/Cyberduck-Installer-6.2.4.26305.exe'
$checksum = '8710700d0fb30a44606c7b68699c0b5b003019a754db22cb715c7aa2240feed0'
$checksumType = 'sha256'
$validExitCodes = @(0)
Install-ChocolateyPackage -PackageName "$packageName" `
-FileType "$installerType" `
-SilentArgs "$silentArgs" `
-Url "$url" `
-ValidExitCodes $validExitCodes `
-Checksum "$checksum" `
-ChecksumType "$checksumType"
|
apache-2.0
|
thbonk/electron-openui5-boilerplate
|
libs/openui5-runtime/resources/sap/m/PDFViewer-dbg.js
|
19266
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
/* global ActiveXObject:false */
// Provides control sap.m.PDFViewer.
sap.ui.define([
"jquery.sap.global",
"./library",
"sap/ui/core/Control",
"sap/ui/Device",
"sap/m/PDFViewerRenderManager",
"sap/m/MessageBox"
],
function (jQuery, library, Control, Device, PDFViewerRenderManager, MessageBox) {
"use strict";
var aAllowedMimeTypes = Object.freeze([
"application/pdf",
"application/x-google-chrome-pdf"
]);
function isSupportedMimeType(sMimeType) {
var iFoundIndex = aAllowedMimeTypes.indexOf(sMimeType);
return iFoundIndex > -1;
}
/**
* Definition of PDFViewer control
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* This control enables you to display PDF documents within your app.
* It can be embedded in your user interface layout, or you can set it to open in a popup dialog.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.50.8
*
* @constructor
* @public
* @alias sap.m.PDFViewer
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var PDFViewer = Control.extend("sap.m.PDFViewer",
/** @lends sap.m.PDFViewer.prototype */
{
metadata: {
library: "sap.m",
properties: {
/**
* Defines the height of the PDF viewer control, respective to the height of
* the parent container. Can be set to a percent, pixel, or em value.
*/
height: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "100%"},
/**
* Defines the width of the PDF viewer control, respective to the width of the
* parent container. Can be set to a percent, pixel, or em value.
*/
width: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "100%"},
/**
* Specifies the path to the PDF file to display. Can be set to a relative or
* an absolute path.
*/
source: {type: "sap.ui.core.URI", group: "Misc", defaultValue: null},
/**
* A custom error message that is displayed when the PDF file cannot be loaded.
* @deprecated As of version 1.50.0, replaced by {@link sap.m.PDFViewer#getErrorPlaceholderMessage()}.
*/
errorMessage: {type: "string", group: "Misc", defaultValue: null, deprecated: true},
/**
* A custom text that is displayed instead of the PDF file content when the PDF
* file cannot be loaded.
*/
errorPlaceholderMessage: {type: "string", group: "Misc", defaultValue: null},
/**
* A custom title for the PDF viewer popup dialog. Works only if the PDF viewer
* is set to open in a popup dialog.
* @deprecated As of version 1.50.0, replaced by {@link sap.m.PDFViewer#getTitle()}.
*/
popupHeaderTitle: {type: "string", group: "Misc", defaultValue: null, deprecated: true},
/**
* A custom title for the PDF viewer.
*/
title: {type: "string", group: "Misc", defaultValue: null},
/**
* Shows or hides the download button.
*/
showDownloadButton: {type: "boolean", group: "Misc", defaultValue: true}
},
aggregations: {
/**
* A custom control that can be used instead of the error message specified by the
* errorPlaceholderMessage property.
*/
errorPlaceholder: {type: "sap.ui.core.Control", multiple: false},
/**
* A multiple aggregation for buttons that can be added to the footer of the popup
* dialog. Works only if the PDF viewer is set to open in a popup dialog.
*/
popupButtons: {type: "sap.m.Button", multiple: true, singularName: "popupButton"}
},
events: {
/**
* This event is fired when a PDF file is loaded. If the PDF is loaded in smaller chunks,
* this event is fired as often as defined by the browser's plugin. This may happen after
* a couple chunks are processed.
*/
loaded: {},
/**
* This event is fired when there is an error loading the PDF file.
*/
error: {},
/**
* This event is fired when the PDF viewer control cannot check the loaded content. For
* example, the default configuration of the Mozilla Firefox browser may not allow checking
* the loaded content. This may also happen when the source PDF file is stored in a different
* domain.
* If you want no error message to be displayed when this event is fired, call the
* preventDefault() method inside the event handler.
*/
sourceValidationFailed: {}
}
}
});
/**
* @returns {boolean}
* @private
*/
PDFViewer._isPdfPluginEnabled = function () {
var bIsEnabled = true;
if (Device.browser.firefox) {
// https://bugzilla.mozilla.org/show_bug.cgi?id=1293406
// mimeType is missing for firefox even though it is enabled
return bIsEnabled;
}
if (Device.browser.internet_explorer) {
// hacky code how to recognize that pdf plugin is installed and enabled
try {
/* eslint-disable no-new */
new ActiveXObject("AcroPDF.PDF");
/* eslint-enable no-new */
} catch (e) {
bIsEnabled = false;
}
return bIsEnabled;
}
var aMimeTypes = navigator.mimeTypes;
bIsEnabled = aAllowedMimeTypes.some(function (sAllowedMimeType) {
var oMimeTypeItem = aMimeTypes.namedItem(sAllowedMimeType);
return oMimeTypeItem !== null;
});
return bIsEnabled;
};
/**
* Lifecycle method
*
* @private
*/
PDFViewer.prototype.init = function () {
// helper object that holds the references of nested objects
this._objectsRegister = {};
// state variable that shows the state of popup (rendering of pdf in popup requires it)
this._bIsPopupOpen = false;
this._initPopupControl();
this._initPopupDownloadButtonControl();
this._initPlaceholderMessagePageControl();
this._initToolbarDownloadButtonControl();
this._initOverflowToolbarControl();
this._initControlState();
};
/**
* Setup state variables to default state
*
* @private
*/
PDFViewer.prototype._initControlState = function () {
// state property that control if the embedded pdf should or should not rendered.
this._bRenderPdfContent = true;
// detect that beforeunload was fired (IE only)
this._bOnBeforeUnloadFired = false;
};
PDFViewer.prototype.setWidth = function (sWidth) {
this.setProperty("width", sWidth, true);
var oDomRef = this.$();
if (oDomRef === null) {
return this;
}
oDomRef.css("width", this._getRenderWidth());
return this;
};
PDFViewer.prototype.setHeight = function (sHeight) {
this.setProperty("height", sHeight, true);
var oDomRef = this.$();
if (oDomRef === null) {
return this;
}
oDomRef.css("height", this._getRenderHeight());
return this;
};
PDFViewer.prototype.onBeforeRendering = function () {
// IE things
// because of the detecting error state in IE (double call of unload listener)
// it is important to reset the flag before each render
// otherwise it wrongly detects error state (the unload listener is called once even in valid use case)
this._bOnBeforeUnloadFired = false;
};
/**
* Lifecycle method
*
* @private
*/
PDFViewer.prototype.onAfterRendering = function () {
var fnInitIframeElement = function () {
// cant use attachBrowserEvent because it attach event to component root node (this.$())
// load event does not bubble so it has to be bind directly to iframe element
var oIframeElement = this._getIframeDOMElement();
var oIframeContentWindow = jQuery(oIframeElement.get(0).contentWindow);
if (Device.browser.internet_explorer) {
// being special does not mean useful
// https://connect.microsoft.com/IE/feedback/details/809377/ie-11-load-event-doesnt-fired-for-pdf-in-iframe
// onerror does not works on IE. Therefore readyonstatechange and unload events are used for error detection.
// When invalid response is received (404, etc.), readystatechange is not fired but unload is.
// When valid response is received, then readystatechange and 'complete' state of target's element is received.
oIframeContentWindow.on("beforeunload", this._onBeforeUnloadListener.bind(this));
oIframeContentWindow.on("readystatechange", this._onReadyStateChangeListener.bind(this));
// some error codes load html file and fires loadEvent
oIframeElement.on("load", this._onLoadIEListener.bind(this));
} else {
// normal browsers supports load events as specification said
oIframeElement.on("load", this._onLoadListener.bind(this));
}
oIframeElement.on("error", this._onErrorListener.bind(this));
var sParametrizedSource = this.getSource();
var iCrossPosition = this.getSource().indexOf("#");
if (iCrossPosition > -1) {
sParametrizedSource = sParametrizedSource.substr(0, iCrossPosition);
}
sParametrizedSource += "#view=FitH";
if (jQuery.sap.validateUrl(sParametrizedSource)) {
oIframeElement.attr("src", encodeURI(sParametrizedSource));
} else {
this._fireErrorEvent();
}
}.bind(this);
try {
this.setBusy(true);
fnInitIframeElement();
} catch (error) {
this.setBusy(false);
}
};
/**
* @private
*/
PDFViewer.prototype._fireErrorEvent = function () {
this._renderErrorState();
this.fireEvent("error", {}, true);
};
/**
* @private
*/
PDFViewer.prototype._renderErrorState = function () {
var oDownloadButton = this._objectsRegister.getToolbarDownloadButtonControl();
oDownloadButton.setEnabled(false);
var oDownloadButton = this._objectsRegister.getPopupDownloadButtonControl();
oDownloadButton.setEnabled(false);
this.setBusy(false);
this._bRenderPdfContent = false;
// calls controls invalidate because the error state should be render.
// It is controlled by the state variable called _bRenderPdfContent
// The main invalidate set the state of the control to the default and tries to load and render pdf
Control.prototype.invalidate.call(this);
};
/**
* @private
*/
PDFViewer.prototype._fireLoadedEvent = function () {
this._bRenderPdfContent = true;
this.setBusy(false);
try {
this._getIframeDOMElement().removeClass("sapMPDFViewerLoading");
} catch (err) {
jQuery.log.fatal("Iframe not founded in loaded event");
jQuery.log.fatal(err);
}
this.fireEvent("loaded");
};
/**
* @param oEvent
* @private
*/
PDFViewer.prototype._onLoadListener = function (oEvent) {
try {
var oTarget = jQuery(oEvent.target),
bContinue = true;
// Firefox
// https://bugzilla.mozilla.org/show_bug.cgi?id=911444
// because of the embedded pdf plugin in firefox it is not possible to check contentType of the iframe document
// if the content is pdf. If the content is not a pdf and it is from the same origin, it can be accessed.
// Other browsers allow access to the mimeType of the iframe's document if the content is from the same origin.
var sCurrentContentType = "application/pdf";
try {
// browsers render pdf in iframe as html page with embed tag
var aEmbeds = oTarget[0].contentWindow.document.embeds;
bContinue = !!aEmbeds && aEmbeds.length === 1;
if (bContinue) {
sCurrentContentType = aEmbeds[0].attributes.getNamedItem("type").value;
}
} catch (error) {
// even though the sourceValidationFailed event is fired, the default behaviour is to continue.
// when preventDefault is on event object is called, the rendering ends up with error
if (!Device.browser.firefox && this.fireEvent("sourceValidationFailed", {}, true)) {
this._showMessageBox();
return;
}
}
if (bContinue && isSupportedMimeType(sCurrentContentType)) {
this._fireLoadedEvent();
} else {
this._fireErrorEvent();
}
} catch (error) {
jQuery.sap.log.fatal(false, "Fatal error during the handling of load event happened.");
jQuery.sap.log.fatal(false, error.message);
}
};
/**
* @private
*/
PDFViewer.prototype._onErrorListener = function () {
this._fireErrorEvent();
};
/**
* @private
*/
PDFViewer.prototype._onReadyStateChangeListener = function (oEvent) {
var INTERACTIVE_READY_STATE = "interactive";
var COMPLETE_READY_STATE = "complete";
switch (oEvent.target.readyState) {
case INTERACTIVE_READY_STATE: // IE11 only fires interactive
case COMPLETE_READY_STATE:
// iframe content is not loaded when interactive ready state is fired
// even though complete ready state should be fired. We were not able to simulate firing complete ready state
// on IE. Therefore the validation of source is not possible.
this._fireLoadedEvent();
break;
}
};
/**
* @private
*/
PDFViewer.prototype._onBeforeUnloadListener = function () {
// IE problems
// when invalid response is received (404), beforeunload is fired twice
if (this._bOnBeforeUnloadFired) {
this._fireErrorEvent();
return;
}
this._bOnBeforeUnloadFired = true;
};
/**
* @param oEvent
* @private
*/
PDFViewer.prototype._onLoadIEListener = function (oEvent) {
try {
// because of asynchronity of events, IE sometimes fires load event even after it unloads the content.
// The contentWindow does not exists in these moments. On the other hand, the error state is already handled
// by onBeforeUnloadListener, so we only need catch for catching the error and then return.
// The problem is not with null reference. The access of the contentWindow sometimes fires 'access denied' error
// which is not detectable otherwise.
var sCurrentContentType = oEvent.currentTarget.contentWindow.document.mimeType;
} catch (err) {
return;
}
if (!isSupportedMimeType(sCurrentContentType)) {
this._fireErrorEvent();
}
};
/**
* Downloads the PDF file.
*
* @public
*/
PDFViewer.prototype.downloadPDF = function () {
var oWindow = window.open(this.getSource());
oWindow.focus();
};
/**
* @param string oClickedButtonId
* @private
*/
PDFViewer.prototype._onSourceValidationErrorMessageBoxCloseListener = function (oClickedButtonId) {
if (oClickedButtonId === MessageBox.Action.CANCEL) {
this._renderErrorState();
} else {
this._fireLoadedEvent();
}
};
/**
* @param oEvent
* @private
*/
PDFViewer.prototype._onAfterPopupClose = function (oEvent) {
var oPopup = this._objectsRegister.getPopup();
// content has to be cleared from dom
oPopup.removeAllContent();
this._bIsPopupOpen = false;
};
/**
* @returns {boolean}
* @private
*/
PDFViewer.prototype._shouldRenderPdfContent = function () {
return PDFViewer._isPdfPluginEnabled() && this._bRenderPdfContent && this.getSource() !== null;
};
/**
* @returns {boolean}
* @private
*/
PDFViewer.prototype._isSourceValidToDisplay = function () {
var sSource = this.getSource();
return sSource !== null && sSource !== "" && typeof sSource !== "undefined";
};
/**
* Triggers rerendering of this element and its children.
*
* @param {sap.ui.base.ManagedObject} [oOrigin] Child control for which the method was called
*
* @public
*/
PDFViewer.prototype.invalidate = function (oOrigin) {
this._initControlState();
Control.prototype.invalidate.call(this, oOrigin);
};
/**
* Opens the PDF viewer in a popup dialog.
*
* @public
*/
PDFViewer.prototype.open = function () {
if (!this._isSourceValidToDisplay()) {
jQuery.sap.assert(false, "The PDF file cannot be opened with the given source. Given source: " + this.getSource());
return;
}
if (this._isEmbeddedModeAllowed()) {
this._openOnDesktop();
} else {
this._openOnMobile();
}
};
/**
* Handles opening on desktop devices
* @private
*/
PDFViewer.prototype._openOnDesktop = function () {
var oPopup = this._objectsRegister.getPopup();
if (this._bIsPopupOpen) {
return;
}
this._initControlState();
this._preparePopup(oPopup);
oPopup.addContent(this);
this._bIsPopupOpen = true;
oPopup.open();
};
/**
* Handles opening on mobile/tablet devices
* @private
*/
PDFViewer.prototype._openOnMobile = function () {
var oWindow = window.open(this.getSource());
oWindow.focus();
};
/**
* Gets the iframe element from rendered DOM
* @returns {*} jQuery object of iframe
* @private
*/
PDFViewer.prototype._getIframeDOMElement = function () {
var oIframeElement = this.$().find("iframe");
if (oIframeElement.length === 0) {
throw Error("Underlying iframe was not found in DOM.");
}
if (oIframeElement.length > 1) {
jQuery.sap.log.fatal("Initialization of iframe fails. Reason: the control somehow renders multiple iframes");
}
return oIframeElement;
};
/**
* @private
*/
PDFViewer.prototype._isEmbeddedModeAllowed = function () {
return Device.system.desktop;
};
/**
* @returns {jQuery.sap.util.ResourceBundle}
* @private
*/
PDFViewer.prototype._getLibraryResourceBundle = function () {
return sap.ui.getCore().getLibraryResourceBundle("sap.m");
};
/**
* @returns {string}
* @private
*/
PDFViewer.prototype._getMessagePageErrorMessage = function () {
return this.getErrorPlaceholderMessage() ? this.getErrorPlaceholderMessage() :
this._getLibraryResourceBundle().getText("PDF_VIEWER_PLACEHOLDER_ERROR_TEXT");
};
/**
* @returns {string}
* @private
*/
PDFViewer.prototype._getRenderWidth = function () {
return this._bIsPopupOpen ? '100%' : this.getWidth();
};
/**
* @returns {string}
* @private
*/
PDFViewer.prototype._getRenderHeight = function () {
return this._bIsPopupOpen ? '100%' : this.getHeight();
};
/**
* @private
*/
PDFViewer.prototype._showMessageBox = function () {
MessageBox.show(this._getLibraryResourceBundle().getText("PDF_VIEWER_SOURCE_VALIDATION_MESSAGE_TEXT"), {
icon: MessageBox.Icon.WARNING,
title: this._getLibraryResourceBundle().getText("PDF_VIEWER_SOURCE_VALIDATION_MESSAGE_HEADER"),
actions: [MessageBox.Action.OK, MessageBox.Action.CANCEL],
defaultAction: MessageBox.Action.CANCEL,
id: this.getId() + "-validationErrorSourceMessageBox",
styleClass: "sapUiSizeCompact",
contentWidth: '100px',
onClose: this._onSourceValidationErrorMessageBoxCloseListener.bind(this)
});
};
/**
* Lifecycle method
* @private
*/
PDFViewer.prototype.exit = function () {
jQuery.each(this._objectsRegister, function (iIndex, fnGetObject) {
var oObject = fnGetObject(true);
if (oObject) {
oObject.destroy();
}
});
};
PDFViewerRenderManager.extendPdfViewer(PDFViewer);
return PDFViewer;
}, /* bExport= */ true);
|
apache-2.0
|
arash16/madson
|
src/index.js
|
901
|
var madson = (function () {
import "nxutils/generic/base";
import "./utils";
import "./write";
import "./read";
import "./preset";
function mEncode(input, options) {
var encoder = new EncodeBuffer(options);
encode(encoder, cloneDecycle(input));
return encoder.read();
}
function mDecode(input, options) {
var decoder = new DecodeBuffer(options);
decoder.append(input);
return retroCycle(decode(decoder));
}
function packer(input) {
return Buffer.isBuffer(input) ? mDecode(input) : mEncode(input);
}
var madson = extend(packer, {
createCodec: Codec,
codec: { preset: preset },
encode: mEncode,
decode: mDecode
});
if ("isServer") {
if (typeof module == 'object')
module.exports = madson;
}
else global.madson = madson;
return madson;
})();
|
apache-2.0
|
dahlstrom-g/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowsPane.java
|
40236
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl;
import com.intellij.ide.RemoteDesktopService;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.UISettingsListener;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.ThreeComponentsSplitter;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.openapi.util.registry.RegistryValueListener;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowType;
import com.intellij.openapi.wm.WindowInfo;
import com.intellij.openapi.wm.ex.ToolWindowEx;
import com.intellij.reference.SoftReference;
import com.intellij.ui.OnePixelSplitter;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.ui.paint.PaintUtil;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.ui.scale.ScaleContext;
import com.intellij.util.IJSwingUtilities;
import com.intellij.util.ui.ImageUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import static com.intellij.util.ui.UIUtil.useSafely;
/**
* This panel contains all tool stripes and JLayeredPane at the center area. All tool windows are
* located inside this layered pane.
*
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class ToolWindowsPane extends JBLayeredPane implements UISettingsListener {
private static final Logger LOG = Logger.getInstance(ToolWindowsPane.class);
@NonNls public static final String TEMPORARY_ADDED = "TEMPORARY_ADDED";
private final JFrame frame;
private ToolWindowPaneState state = new ToolWindowPaneState();
/**
* This panel is the layered pane where all sliding tool windows are located. The DEFAULT
* layer contains splitters. The PALETTE layer contains all sliding tool windows.
*/
private final MyLayeredPane layeredPane;
/*
* Splitters.
*/
private final ThreeComponentsSplitter verticalSplitter;
private final ThreeComponentsSplitter horizontalSplitter;
/*
* Tool stripes.
*/
private final Stripe leftStripe;
private final Stripe rightStripe;
private final Stripe bottomStripe;
private final Stripe topStripe;
private final List<Stripe> stripes = new ArrayList<>(4);
private boolean isWideScreen;
private boolean leftHorizontalSplit;
private boolean rightHorizontalSplit;
private List<String> myDefaultRightButtons = new ArrayList<>();
private List<String> myDefaultLeftButtons = new ArrayList<>();
private List<String> myDefaultBottomButtons = new ArrayList<>();
@Nullable private final ToolwindowToolbar myLeftToolbar;
@Nullable private final ToolwindowToolbar myRightToolbar;
ToolWindowsPane(@NotNull JFrame frame,
@NotNull Disposable parentDisposable,
@Nullable ToolwindowToolbar leftSidebar,
@Nullable ToolwindowToolbar rightSidebar) {
myLeftToolbar = leftSidebar;
myRightToolbar = rightSidebar;
setOpaque(false);
this.frame = frame;
// splitters
verticalSplitter = new ThreeComponentsSplitter(true, parentDisposable);
RegistryValue registryValue = Registry.get("ide.mainSplitter.min.size");
registryValue.addListener(new RegistryValueListener() {
@Override
public void afterValueChanged(@NotNull RegistryValue value) {
updateInnerMinSize(value);
}
}, parentDisposable);
verticalSplitter.setDividerWidth(0);
verticalSplitter.setDividerMouseZoneSize(Registry.intValue("ide.splitter.mouseZone"));
verticalSplitter.setBackground(Color.gray);
horizontalSplitter = new ThreeComponentsSplitter(false, parentDisposable);
horizontalSplitter.setDividerWidth(0);
horizontalSplitter.setDividerMouseZoneSize(Registry.intValue("ide.splitter.mouseZone"));
horizontalSplitter.setBackground(Color.gray);
updateInnerMinSize(registryValue);
UISettings uiSettings = UISettings.getInstance();
isWideScreen = uiSettings.getWideScreenSupport();
leftHorizontalSplit = uiSettings.getLeftHorizontalSplit();
rightHorizontalSplit = uiSettings.getRightHorizontalSplit();
if (isWideScreen) {
horizontalSplitter.setInnerComponent(verticalSplitter);
}
else {
verticalSplitter.setInnerComponent(horizontalSplitter);
}
// tool stripes
topStripe = new Stripe(SwingConstants.TOP);
stripes.add(topStripe);
leftStripe = new Stripe(SwingConstants.LEFT);
stripes.add(leftStripe);
bottomStripe = new Stripe(SwingConstants.BOTTOM);
stripes.add(bottomStripe);
rightStripe = new Stripe(SwingConstants.RIGHT);
stripes.add(rightStripe);
updateToolStripesVisibility(uiSettings);
// layered pane
layeredPane = new MyLayeredPane(isWideScreen ? horizontalSplitter : verticalSplitter);
// compose layout
add(topStripe, JLayeredPane.POPUP_LAYER);
add(leftStripe, JLayeredPane.POPUP_LAYER);
add(bottomStripe, JLayeredPane.POPUP_LAYER);
add(rightStripe, JLayeredPane.POPUP_LAYER);
add(layeredPane, JLayeredPane.DEFAULT_LAYER);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicy());
}
void initDocumentComponent(@NotNull Project project) {
JComponent editorComponent = FileEditorManagerEx.getInstanceEx(project).getComponent();
editorComponent.setFocusable(false);
setDocumentComponent(editorComponent);
}
private void updateInnerMinSize(@NotNull RegistryValue value) {
int minSize = Math.max(0, Math.min(100, value.asInteger()));
verticalSplitter.setMinSize(JBUIScale.scale(minSize));
horizontalSplitter.setMinSize(JBUIScale.scale(minSize));
}
@Override
public void doLayout() {
Dimension size = getSize();
if (!topStripe.isVisible()) {
topStripe.setBounds(0, 0, 0, 0);
bottomStripe.setBounds(0, 0, 0, 0);
leftStripe.setBounds(0, 0, 0, 0);
rightStripe.setBounds(0, 0, 0, 0);
layeredPane.setBounds(0, 0, getWidth(), getHeight());
}
else {
Dimension topSize = topStripe.getPreferredSize();
Dimension bottomSize = bottomStripe.getPreferredSize();
Dimension leftSize = leftStripe.getPreferredSize();
Dimension rightSize = rightStripe.getPreferredSize();
topStripe.setBounds(0, 0, size.width, topSize.height);
int height = size.height - topSize.height - bottomSize.height;
leftStripe.setBounds(0, topSize.height, leftSize.width, height);
rightStripe.setBounds(size.width - rightSize.width, topSize.height, rightSize.width, height);
bottomStripe.setBounds(0, size.height - bottomSize.height, size.width, bottomSize.height);
UISettings uiSettings = UISettings.getInstance();
if (uiSettings.getHideToolStripes() || uiSettings.getPresentationMode()) {
if (isSquareStripeUI()) {
updateSquareStripes(false);
} else {
layeredPane.setBounds(0, 0, size.width, size.height);
}
}
else {
int width = size.width - leftSize.width - rightSize.width;
layeredPane.setBounds(leftSize.width, topSize.height, width, height);
}
}
}
private static boolean isSquareStripeUI() {
return Registry.is("ide.new.stripes.ui");
}
@Override
public void uiSettingsChanged(@NotNull UISettings uiSettings) {
updateToolStripesVisibility(uiSettings);
updateLayout(uiSettings);
}
/**
* @param dirtyMode if {@code true} then JRootPane will not be validated and repainted after adding
* the decorator. Moreover in this (dirty) mode animation doesn't work.
*/
final void addDecorator(@NotNull JComponent decorator, @NotNull WindowInfo info, boolean dirtyMode, @NotNull ToolWindowManagerImpl manager) {
if (info.isDocked()) {
boolean side = !info.isSplit();
WindowInfo sideInfo = manager.getDockedInfoAt(info.getAnchor(), side);
if (sideInfo == null) {
ToolWindowAnchor anchor = info.getAnchor();
setComponent(decorator, anchor, normalizeWeigh(info.getWeight()));
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
else {
addAndSplitDockedComponentCmd(decorator, info, dirtyMode, manager);
}
}
else if (info.getType() == ToolWindowType.SLIDING) {
addSlidingComponent(decorator, info, dirtyMode);
}
else {
throw new IllegalArgumentException("Unknown window type: " + info.getType());
}
}
void removeDecorator(@NotNull WindowInfo info, @Nullable JComponent component, boolean dirtyMode, @NotNull ToolWindowManagerImpl manager) {
if (info.getType() == ToolWindowType.DOCKED) {
WindowInfo sideInfo = manager.getDockedInfoAt(info.getAnchor(), !info.isSplit());
if (sideInfo == null) {
setComponent(null, info.getAnchor(), 0);
}
else {
ToolWindowAnchor anchor = info.getAnchor();
JComponent c = getComponentAt(anchor);
if (c instanceof Splitter) {
Splitter splitter = (Splitter)c;
InternalDecoratorImpl component1 = (InternalDecoratorImpl)(info.isSplit() ? splitter.getFirstComponent() : splitter.getSecondComponent());
state.addSplitProportion(info, component1, splitter);
setComponent(component1, anchor,
component1 == null ? 0 : ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError(component1).getWeight());
}
else {
setComponent(null, anchor, 0);
}
}
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
else if (info.getType() == ToolWindowType.SLIDING) {
if (component != null) {
removeSlidingComponent(component, info, dirtyMode);
}
}
}
public final @NotNull JComponent getLayeredPane() {
return layeredPane;
}
public void validateAndRepaint() {
layeredPane.validate();
layeredPane.repaint();
for (Stripe stripe : stripes) {
stripe.revalidate();
stripe.repaint();
}
}
public void revalidateNotEmptyStripes() {
for (Stripe stripe : stripes) {
if (!stripe.isEmpty()) {
stripe.revalidate();
}
}
}
private void setComponent(@Nullable JComponent component, @NotNull ToolWindowAnchor anchor, float weight) {
Dimension size = getSize();
if (ToolWindowAnchor.TOP == anchor) {
verticalSplitter.setFirstComponent(component);
verticalSplitter.setFirstSize((int)(size.getHeight() * weight));
}
else if (ToolWindowAnchor.LEFT == anchor) {
horizontalSplitter.setFirstComponent(component);
horizontalSplitter.setFirstSize((int)(size.getWidth() * weight));
}
else if (ToolWindowAnchor.BOTTOM == anchor) {
verticalSplitter.setLastComponent(component);
verticalSplitter.setLastSize((int)(size.getHeight() * weight));
}
else if (ToolWindowAnchor.RIGHT == anchor) {
horizontalSplitter.setLastComponent(component);
horizontalSplitter.setLastSize((int)(size.getWidth() * weight));
}
else {
LOG.error("unknown anchor: " + anchor);
}
}
private JComponent getComponentAt(@NotNull ToolWindowAnchor anchor) {
if (ToolWindowAnchor.TOP == anchor) {
return verticalSplitter.getFirstComponent();
}
else if (ToolWindowAnchor.LEFT == anchor) {
return horizontalSplitter.getFirstComponent();
}
else if (ToolWindowAnchor.BOTTOM == anchor) {
return verticalSplitter.getLastComponent();
}
else if (ToolWindowAnchor.RIGHT == anchor) {
return horizontalSplitter.getLastComponent();
}
else {
LOG.error("unknown anchor: " + anchor);
return null;
}
}
private void setDocumentComponent(@Nullable JComponent component) {
(isWideScreen ? verticalSplitter : horizontalSplitter).setInnerComponent(component);
}
private void updateToolStripesVisibility(@NotNull UISettings uiSettings) {
boolean oldVisible = leftStripe.isVisible();
boolean showButtons = !uiSettings.getHideToolStripes() && !uiSettings.getPresentationMode();
boolean visible = (showButtons || state.isStripesOverlaid()) && !isSquareStripeUI();
leftStripe.setVisible(visible);
rightStripe.setVisible(visible);
topStripe.setVisible(visible);
bottomStripe.setVisible(visible);
if (myLeftToolbar != null && myRightToolbar != null) {
boolean oldSquareVisible = myLeftToolbar.isVisible() && myRightToolbar.isVisible();
boolean squareStripesVisible = isSquareStripeUI() && showButtons;
updateSquareStripes(squareStripesVisible);
if (isSquareStripeUI() && oldSquareVisible != squareStripesVisible) {
revalidate();
repaint();
}
}
boolean overlayed = !showButtons && state.isStripesOverlaid();
leftStripe.setOverlayed(overlayed);
rightStripe.setOverlayed(overlayed);
topStripe.setOverlayed(overlayed);
bottomStripe.setOverlayed(overlayed);
if (oldVisible != visible) {
revalidate();
repaint();
}
}
private void updateSquareStripes(boolean squareStripesVisible) {
if (myLeftToolbar != null && myRightToolbar != null) {
myLeftToolbar.setVisible(squareStripesVisible);
myRightToolbar.setVisible(squareStripesVisible);
}
}
public int getBottomHeight() {
return bottomStripe.isVisible() ? bottomStripe.getHeight() : 0;
}
public boolean isBottomSideToolWindowsVisible() {
return getComponentAt(ToolWindowAnchor.BOTTOM) != null;
}
@NotNull
Stripe getStripeFor(@NotNull ToolWindowAnchor anchor) {
if (ToolWindowAnchor.TOP == anchor) {
return topStripe;
}
if (ToolWindowAnchor.BOTTOM == anchor) {
return bottomStripe;
}
if (ToolWindowAnchor.LEFT == anchor) {
return leftStripe;
}
if (ToolWindowAnchor.RIGHT == anchor) {
return rightStripe;
}
throw new IllegalArgumentException("Anchor=" + anchor);
}
@Nullable
Stripe getStripeFor(@NotNull Rectangle screenRectangle, @NotNull Stripe preferred) {
if (preferred.containsScreen(screenRectangle)) {
return preferred;
}
for (Stripe stripe : stripes) {
if (stripe.containsScreen(screenRectangle)) {
return stripe;
}
}
return null;
}
@Nullable
ToolwindowToolbar getSquareStripeFor(@NotNull ToolWindowAnchor anchor) {
if (ToolWindowAnchor.TOP == anchor || ToolWindowAnchor.RIGHT == anchor) return myRightToolbar;
if (ToolWindowAnchor.BOTTOM == anchor || ToolWindowAnchor.LEFT == anchor) return myLeftToolbar;
throw new IllegalArgumentException("Anchor=" + anchor);
}
void startDrag() {
for (Stripe each : stripes) {
each.startDrag();
}
}
void stopDrag() {
for (Stripe stripe : stripes) {
stripe.stopDrag();
}
}
void stretchWidth(@NotNull ToolWindow window, int value) {
stretch(window, value);
}
void stretchHeight(@NotNull ToolWindow window, int value) {
stretch(window, value);
}
private void stretch(@NotNull ToolWindow wnd, int value) {
Pair<Resizer, Component> pair = findResizerAndComponent(wnd);
if (pair == null) return;
boolean vertical = wnd.getAnchor() == ToolWindowAnchor.TOP || wnd.getAnchor() == ToolWindowAnchor.BOTTOM;
int actualSize = (vertical ? pair.second.getHeight() : pair.second.getWidth()) + value;
boolean first = wnd.getAnchor() == ToolWindowAnchor.LEFT || wnd.getAnchor() == ToolWindowAnchor.TOP;
int maxValue = vertical ? verticalSplitter.getMaxSize(first) : horizontalSplitter.getMaxSize(first);
int minValue = vertical ? verticalSplitter.getMinSize(first) : horizontalSplitter.getMinSize(first);
pair.first.setSize(Math.max(minValue, Math.min(maxValue, actualSize)));
}
private @Nullable Pair<Resizer, Component> findResizerAndComponent(@NotNull ToolWindow window) {
if (!window.isVisible()) return null;
Resizer resizer = null;
Component component = null;
if (window.getType() == ToolWindowType.DOCKED) {
component = getComponentAt(window.getAnchor());
if (component != null) {
if (window.getAnchor().isHorizontal()) {
resizer = verticalSplitter.getFirstComponent() == component
? new Resizer.Splitter.FirstComponent(verticalSplitter)
: new Resizer.Splitter.LastComponent(verticalSplitter);
}
else {
resizer = horizontalSplitter.getFirstComponent() == component
? new Resizer.Splitter.FirstComponent(horizontalSplitter)
: new Resizer.Splitter.LastComponent(horizontalSplitter);
}
}
}
else if (window.getType() == ToolWindowType.SLIDING) {
component = window.getComponent();
while (component != null) {
if (component.getParent() == layeredPane) break;
component = component.getParent();
}
if (component != null) {
if (window.getAnchor() == ToolWindowAnchor.TOP) {
resizer = new Resizer.LayeredPane.Top(component);
}
else if (window.getAnchor() == ToolWindowAnchor.BOTTOM) {
resizer = new Resizer.LayeredPane.Bottom(component);
}
else if (window.getAnchor() == ToolWindowAnchor.LEFT) {
resizer = new Resizer.LayeredPane.Left(component);
}
else if (window.getAnchor() == ToolWindowAnchor.RIGHT) {
resizer = new Resizer.LayeredPane.Right(component);
}
}
}
return resizer != null ? Pair.create(resizer, component) : null;
}
private void updateLayout(@NotNull UISettings uiSettings) {
if (isWideScreen != uiSettings.getWideScreenSupport()) {
JComponent documentComponent = (isWideScreen ? verticalSplitter : horizontalSplitter).getInnerComponent();
isWideScreen = uiSettings.getWideScreenSupport();
if (isWideScreen) {
verticalSplitter.setInnerComponent(null);
horizontalSplitter.setInnerComponent(verticalSplitter);
}
else {
horizontalSplitter.setInnerComponent(null);
verticalSplitter.setInnerComponent(horizontalSplitter);
}
layeredPane.remove(isWideScreen ? verticalSplitter : horizontalSplitter);
layeredPane.add(isWideScreen ? horizontalSplitter : verticalSplitter, DEFAULT_LAYER);
setDocumentComponent(documentComponent);
}
if (leftHorizontalSplit != uiSettings.getLeftHorizontalSplit()) {
JComponent component = getComponentAt(ToolWindowAnchor.LEFT);
if (component instanceof Splitter) {
Splitter splitter = (Splitter)component;
WindowInfoImpl firstInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError((InternalDecoratorImpl)splitter.getFirstComponent());
WindowInfoImpl secondInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError((InternalDecoratorImpl)splitter.getSecondComponent());
setComponent(splitter, ToolWindowAnchor.LEFT, ToolWindowAnchor.LEFT.isSplitVertically()
? firstInfo.getWeight()
: firstInfo.getWeight() + secondInfo.getWeight());
}
leftHorizontalSplit = uiSettings.getLeftHorizontalSplit();
}
if (rightHorizontalSplit != uiSettings.getRightHorizontalSplit()) {
JComponent component = getComponentAt(ToolWindowAnchor.RIGHT);
if (component instanceof Splitter) {
Splitter splitter = (Splitter)component;
WindowInfoImpl firstInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError((InternalDecoratorImpl)splitter.getFirstComponent());
WindowInfoImpl secondInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError((InternalDecoratorImpl)splitter.getSecondComponent());
setComponent(splitter, ToolWindowAnchor.RIGHT, ToolWindowAnchor.RIGHT.isSplitVertically()
? firstInfo.getWeight()
: firstInfo.getWeight() + secondInfo.getWeight());
}
rightHorizontalSplit = uiSettings.getRightHorizontalSplit();
}
}
public boolean isMaximized(@NotNull ToolWindow window) {
return state.isMaximized(window);
}
void setMaximized(@NotNull ToolWindow toolWindow, boolean maximized) {
Pair<Resizer, Component> resizerAndComponent = findResizerAndComponent(toolWindow);
if (resizerAndComponent == null) {
return;
}
if (maximized) {
int size = toolWindow.getAnchor().isHorizontal() ? resizerAndComponent.second.getHeight() : resizerAndComponent.second.getWidth();
stretch(toolWindow, Short.MAX_VALUE);
state.setMaximizedProportion(Pair.create(toolWindow, size));
}
else {
Pair<ToolWindow, Integer> maximizedProportion = state.getMaximizedProportion();
LOG.assertTrue(maximizedProportion != null);
ToolWindow maximizedWindow = maximizedProportion.first;
assert maximizedWindow == toolWindow;
resizerAndComponent.first.setSize(maximizedProportion.second);
state.setMaximizedProportion(null);
}
doLayout();
}
void reset() {
for (Stripe stripe : stripes) {
stripe.reset();
}
state = new ToolWindowPaneState();
revalidate();
}
void onStripeButtonRemoved(@NotNull Project project, @NotNull ToolWindow toolWindow) {
if (!isSquareStripeUI()) return;
if (myLeftToolbar == null || myRightToolbar == null) return;
if (!toolWindow.isAvailable() || toolWindow.getIcon() == null) return;
toolWindow.setVisibleOnLargeStripe(false);
ToolWindowAnchor anchor = toolWindow.getLargeStripeAnchor();
if (ToolWindowAnchor.LEFT.equals(anchor) || ToolWindowAnchor.BOTTOM.equals(anchor)) {
myLeftToolbar.removeStripeButton(project, toolWindow, anchor);
}
else if (ToolWindowAnchor.RIGHT.equals(anchor)) {
myRightToolbar.removeStripeButton(project, toolWindow, anchor);
}
}
void onStripeButtonAdded(@NotNull Project project,
@NotNull ToolWindow toolWindow,
@NotNull ToolWindowAnchor actualAnchor,
@NotNull Comparator<ToolWindow> comparator) {
if (!isSquareStripeUI()) return;
if (myLeftToolbar == null || myRightToolbar == null) return;
ensureDefaultInitialized(project);
ToolWindowAnchor toolWindowAnchor = toolWindow.getAnchor();
if (toolWindowAnchor == ToolWindowAnchor.LEFT && myDefaultLeftButtons.contains(toolWindow.getId())
|| toolWindowAnchor == ToolWindowAnchor.RIGHT && myDefaultRightButtons.contains(toolWindow.getId())
|| toolWindowAnchor == ToolWindowAnchor.BOTTOM && myDefaultBottomButtons.contains(toolWindow.getId())) {
toolWindow.setVisibleOnLargeStripe(true);
actualAnchor = toolWindowAnchor;
}
toolWindow.setLargeStripeAnchor(actualAnchor);
if (!toolWindow.isAvailable() || toolWindow.getIcon() == null || !toolWindow.isVisibleOnLargeStripe()) return;
if (ToolWindowAnchor.LEFT.equals(actualAnchor) || ToolWindowAnchor.BOTTOM.equals(actualAnchor)) {
myLeftToolbar.addStripeButton(project, actualAnchor, comparator, toolWindow);
}
else if (ToolWindowAnchor.RIGHT.equals(actualAnchor)) {
myRightToolbar.addStripeButton(project, actualAnchor, comparator, toolWindow);
}
}
private void ensureDefaultInitialized(@NotNull Project project) {
String key = "NEW_TOOLWINDOW_STRIPE_DEFAULTS";
if (PropertiesComponent.getInstance(project).isTrueValue(key)) {
return;
}
myDefaultLeftButtons = ToolWindowToolbarProvider.getInstance().defaultBottomToolwindows(project, ToolWindowAnchor.LEFT);
myDefaultRightButtons = ToolWindowToolbarProvider.getInstance().defaultBottomToolwindows(project, ToolWindowAnchor.RIGHT);
myDefaultBottomButtons = ToolWindowToolbarProvider.getInstance().defaultBottomToolwindows(project, ToolWindowAnchor.BOTTOM);
PropertiesComponent.getInstance(project).setValue(key, true);
}
@FunctionalInterface
interface Resizer {
void setSize(int size);
abstract class Splitter implements Resizer {
ThreeComponentsSplitter mySplitter;
Splitter(@NotNull ThreeComponentsSplitter splitter) {
mySplitter = splitter;
}
static final class FirstComponent extends Splitter {
FirstComponent(@NotNull ThreeComponentsSplitter splitter) {
super(splitter);
}
@Override
public void setSize(int size) {
mySplitter.setFirstSize(size);
}
}
static final class LastComponent extends Splitter {
LastComponent(@NotNull ThreeComponentsSplitter splitter) {
super(splitter);
}
@Override
public void setSize(int size) {
mySplitter.setLastSize(size);
}
}
}
abstract class LayeredPane implements Resizer {
Component myComponent;
LayeredPane(@NotNull Component component) {
myComponent = component;
}
@Override
public final void setSize(int size) {
_setSize(size);
if (myComponent.getParent() instanceof JComponent) {
JComponent parent = (JComponent)myComponent;
parent.revalidate();
parent.repaint();
}
}
abstract void _setSize(int size);
static final class Left extends LayeredPane {
Left(@NotNull Component component) {
super(component);
}
@Override
public void _setSize(int size) {
myComponent.setSize(size, myComponent.getHeight());
}
}
static final class Right extends LayeredPane {
Right(@NotNull Component component) {
super(component);
}
@Override
public void _setSize(int size) {
Rectangle bounds = myComponent.getBounds();
int delta = size - bounds.width;
bounds.x -= delta;
bounds.width += delta;
myComponent.setBounds(bounds);
}
}
static class Top extends LayeredPane {
Top(@NotNull Component component) {
super(component);
}
@Override
public void _setSize(int size) {
myComponent.setSize(myComponent.getWidth(), size);
}
}
static class Bottom extends LayeredPane {
Bottom(@NotNull Component component) {
super(component);
}
@Override
public void _setSize(int size) {
Rectangle bounds = myComponent.getBounds();
int delta = size - bounds.height;
bounds.y -= delta;
bounds.height += delta;
myComponent.setBounds(bounds);
}
}
}
}
private void addAndSplitDockedComponentCmd(@NotNull JComponent newComponent,
@NotNull WindowInfo info,
boolean dirtyMode,
@NotNull ToolWindowManagerImpl manager) {
ToolWindowAnchor anchor = info.getAnchor();
final class MySplitter extends OnePixelSplitter implements UISettingsListener {
@Override
public void uiSettingsChanged(@NotNull UISettings uiSettings) {
if (anchor == ToolWindowAnchor.LEFT) {
setOrientation(!uiSettings.getLeftHorizontalSplit());
}
else if (anchor == ToolWindowAnchor.RIGHT) {
setOrientation(!uiSettings.getRightHorizontalSplit());
}
}
@Override
public String toString() {
return "[" + getFirstComponent() + "|" + getSecondComponent() + "]";
}
}
Splitter splitter = new MySplitter();
splitter.setOrientation(anchor.isSplitVertically());
if (!anchor.isHorizontal()) {
splitter.setAllowSwitchOrientationByMouseClick(true);
splitter.addPropertyChangeListener(evt -> {
if (!Splitter.PROP_ORIENTATION.equals(evt.getPropertyName())) return;
boolean isSplitterHorizontalNow = !splitter.isVertical();
UISettings settings = UISettings.getInstance();
if (anchor == ToolWindowAnchor.LEFT) {
if (settings.getLeftHorizontalSplit() != isSplitterHorizontalNow) {
settings.setLeftHorizontalSplit(isSplitterHorizontalNow);
settings.fireUISettingsChanged();
}
}
if (anchor == ToolWindowAnchor.RIGHT) {
if (settings.getRightHorizontalSplit() != isSplitterHorizontalNow) {
settings.setRightHorizontalSplit(isSplitterHorizontalNow);
settings.fireUISettingsChanged();
}
}
});
}
JComponent c = getComponentAt(anchor);
// if all components are hidden for anchor we should find the second component to put in a splitter
// otherwise we add empty splitter
if (c == null) {
List<ToolWindowEx> toolWindows = manager.getToolWindowsOn(anchor, Objects.requireNonNull(info.getId()));
toolWindows.removeIf(window -> window == null || window.isSplitMode() == info.isSplit() || !window.isVisible());
if (!toolWindows.isEmpty()) {
c = ((ToolWindowImpl)toolWindows.get(0)).getDecoratorComponent();
}
if (c == null) {
LOG.error("Empty splitter @ " + anchor + " during AddAndSplitDockedComponentCmd for " + info.getId());
}
}
float newWeight;
if (c instanceof InternalDecoratorImpl) {
InternalDecoratorImpl oldComponent = (InternalDecoratorImpl)c;
WindowInfoImpl oldInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError(oldComponent);
IJSwingUtilities.updateComponentTreeUI(oldComponent);
IJSwingUtilities.updateComponentTreeUI(newComponent);
if (info.isSplit()) {
splitter.setFirstComponent(oldComponent);
splitter.setSecondComponent(newComponent);
float proportion = state.getPreferredSplitProportion(Objects.requireNonNull(oldInfo.getId()), normalizeWeigh(
oldInfo.getSideWeight() / (oldInfo.getSideWeight() + info.getSideWeight())));
splitter.setProportion(proportion);
if (!anchor.isHorizontal() && !anchor.isSplitVertically()) {
newWeight = normalizeWeigh(oldInfo.getWeight() + info.getWeight());
}
else {
newWeight = normalizeWeigh(oldInfo.getWeight());
}
}
else {
splitter.setFirstComponent(newComponent);
splitter.setSecondComponent(oldComponent);
splitter.setProportion(normalizeWeigh(info.getSideWeight()));
if (!anchor.isHorizontal() && !anchor.isSplitVertically()) {
newWeight = normalizeWeigh(oldInfo.getWeight() + info.getWeight());
}
else {
newWeight = normalizeWeigh(info.getWeight());
}
}
}
else {
newWeight = normalizeWeigh(info.getWeight());
}
setComponent(splitter, anchor, newWeight);
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
private void addSlidingComponent(@NotNull JComponent component, @NotNull WindowInfo info, boolean dirtyMode) {
if (dirtyMode || !UISettings.getInstance().getAnimateWindows() || RemoteDesktopService.isRemoteSession()) {
// not animated
layeredPane.add(component, JLayeredPane.PALETTE_LAYER);
layeredPane.setBoundsInPaletteLayer(component, info.getAnchor(), info.getWeight());
}
else {
// Prepare top image. This image is scrolling over bottom image.
Image topImage = layeredPane.getTopImage();
Rectangle bounds = component.getBounds();
useSafely(topImage.getGraphics(), topGraphics -> {
component.putClientProperty(TEMPORARY_ADDED, Boolean.TRUE);
try {
layeredPane.add(component, JLayeredPane.PALETTE_LAYER);
layeredPane.moveToFront(component);
layeredPane.setBoundsInPaletteLayer(component, info.getAnchor(), info.getWeight());
component.paint(topGraphics);
layeredPane.remove(component);
}
finally {
component.putClientProperty(TEMPORARY_ADDED, null);
}
});
// prepare bottom image
Image bottomImage = layeredPane.getBottomImage();
Point2D bottomImageOffset = PaintUtil.getFractOffsetInRootPane(layeredPane);
useSafely(bottomImage.getGraphics(), bottomGraphics -> {
bottomGraphics.setClip(0, 0, bounds.width, bounds.height);
bottomGraphics.translate(bottomImageOffset.getX() - bounds.x, bottomImageOffset.getY() - bounds.y);
layeredPane.paint(bottomGraphics);
});
// start animation.
Surface surface = new Surface(topImage, bottomImage, PaintUtil.negate(bottomImageOffset), 1, info.getAnchor(), UISettings.ANIMATION_DURATION);
layeredPane.add(surface, JLayeredPane.PALETTE_LAYER);
surface.setBounds(bounds);
layeredPane.validate();
layeredPane.repaint();
surface.runMovement();
layeredPane.remove(surface);
layeredPane.add(component, JLayeredPane.PALETTE_LAYER);
}
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
private void removeSlidingComponent(@NotNull Component component, @NotNull WindowInfo info, boolean dirtyMode) {
UISettings uiSettings = UISettings.getInstance();
if (!dirtyMode && uiSettings.getAnimateWindows() && !RemoteDesktopService.isRemoteSession()) {
Rectangle bounds = component.getBounds();
// Prepare top image. This image is scrolling over bottom image. It contains
// picture of component is being removed.
Image topImage = layeredPane.getTopImage();
useSafely(topImage.getGraphics(), component::paint);
// Prepare bottom image. This image contains picture of component that is located
// under the component to is being removed.
Image bottomImage = layeredPane.getBottomImage();
Point2D bottomImageOffset = PaintUtil.getFractOffsetInRootPane(layeredPane);
useSafely(bottomImage.getGraphics(), bottomGraphics -> {
layeredPane.remove(component);
bottomGraphics.clipRect(0, 0, bounds.width, bounds.height);
bottomGraphics.translate(bottomImageOffset.getX() - bounds.x, bottomImageOffset.getY() - bounds.y);
layeredPane.paint(bottomGraphics);
});
// Remove component from the layered pane and start animation.
Surface surface = new Surface(topImage, bottomImage, PaintUtil.negate(bottomImageOffset), -1, info.getAnchor(), UISettings.ANIMATION_DURATION);
layeredPane.add(surface, JLayeredPane.PALETTE_LAYER);
surface.setBounds(bounds);
layeredPane.validate();
layeredPane.repaint();
surface.runMovement();
layeredPane.remove(surface);
}
else {
// not animated
layeredPane.remove(component);
}
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
private static final class ImageRef extends SoftReference<BufferedImage> {
private @Nullable BufferedImage myStrongRef;
ImageRef(@NotNull BufferedImage image) {
super(image);
myStrongRef = image;
}
@Override
public BufferedImage get() {
if (myStrongRef != null) {
BufferedImage img = myStrongRef;
myStrongRef = null; // drop on first request
return img;
}
return super.get();
}
}
private static class ImageCache extends ScaleContext.Cache<ImageRef> {
ImageCache(@NotNull Function<? super ScaleContext, ImageRef> imageProvider) {
super(imageProvider);
}
public BufferedImage get(@NotNull ScaleContext ctx) {
ImageRef ref = getOrProvide(ctx);
BufferedImage image = SoftReference.dereference(ref);
if (image != null) return image;
clear(); // clear to recalculate the image
return get(ctx); // first recalculated image will be non-null
}
}
private final class MyLayeredPane extends JBLayeredPane {
private final Function<ScaleContext, ImageRef> myImageProvider = __ -> {
int width = Math.max(Math.max(1, getWidth()), frame.getWidth());
int height = Math.max(Math.max(1, getHeight()), frame.getHeight());
return new ImageRef(ImageUtil.createImage(getGraphicsConfiguration(), width, height, BufferedImage.TYPE_INT_RGB));
};
/*
* These images are used to perform animated showing and hiding of components.
* They are the member for performance reason.
*/
private final ImageCache myBottomImageCache = new ImageCache(myImageProvider);
private final ImageCache myTopImageCache = new ImageCache(myImageProvider);
MyLayeredPane(@NotNull JComponent splitter) {
setOpaque(false);
add(splitter, JLayeredPane.DEFAULT_LAYER);
}
final Image getBottomImage() {
return myBottomImageCache.get(ScaleContext.create(this));
}
final Image getTopImage() {
return myTopImageCache.get(ScaleContext.create(this));
}
/**
* When component size becomes larger then bottom and top images should be enlarged.
*/
@Override
public void doLayout() {
final int width = getWidth();
final int height = getHeight();
if (width < 0 || height < 0) {
return;
}
// Resize component at the DEFAULT layer. It should be only on component in that layer
Component[] components = getComponentsInLayer(JLayeredPane.DEFAULT_LAYER);
LOG.assertTrue(components.length <= 1);
for (Component component : components) {
component.setBounds(0, 0, getWidth(), getHeight());
}
// Resize components at the PALETTE layer
components = getComponentsInLayer(JLayeredPane.PALETTE_LAYER);
for (Component component : components) {
if (!(component instanceof InternalDecoratorImpl)) {
continue;
}
WindowInfo info = (((InternalDecoratorImpl)component)).getToolWindow().getWindowInfo();
float weight = info.getAnchor().isHorizontal()
? (float)component.getHeight() / getHeight()
: (float)component.getWidth() / getWidth();
setBoundsInPaletteLayer(component, info.getAnchor(), weight);
}
}
final void setBoundsInPaletteLayer(@NotNull Component component, @NotNull ToolWindowAnchor anchor, float weight) {
if (weight < .0f) {
weight = WindowInfoImpl.DEFAULT_WEIGHT;
}
else if (weight > 1.0f) {
weight = 1.0f;
}
if (ToolWindowAnchor.TOP == anchor) {
component.setBounds(0, 0, getWidth(), (int)(getHeight() * weight + .5f));
}
else if (ToolWindowAnchor.LEFT == anchor) {
component.setBounds(0, 0, (int)(getWidth() * weight + .5f), getHeight());
}
else if (ToolWindowAnchor.BOTTOM == anchor) {
final int height = (int)(getHeight() * weight + .5f);
component.setBounds(0, getHeight() - height, getWidth(), height);
}
else if (ToolWindowAnchor.RIGHT == anchor) {
final int width = (int)(getWidth() * weight + .5f);
component.setBounds(getWidth() - width, 0, width, getHeight());
}
else {
LOG.error("unknown anchor " + anchor);
}
}
}
void setStripesOverlayed(boolean value) {
state.setStripesOverlaid(value);
updateToolStripesVisibility(UISettings.getInstance());
}
private static float normalizeWeigh(final float weight) {
if (weight <= 0) return WindowInfoImpl.DEFAULT_WEIGHT;
if (weight >= 1) return 1 - WindowInfoImpl.DEFAULT_WEIGHT;
return weight;
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Cerastium/Cerastium arvense/ Syn. Cerastium subulatum/README.md
|
183
|
# Cerastium subulatum Greene SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Pertusariales/Pertusariaceae/Pertusaria/Pertusaria cinerella/README.md
|
193
|
# Pertusaria cinerella Müll. Arg. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Pertusaria cinerella Müll. Arg.
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Salicaceae/Salix/Salix arctica/Salix arctica arctica/README.md
|
174
|
# Salix arctica subvar. arctica SUBVARIETY
#### Status
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Magnoliales/Annonaceae/Uvaria/Uvaria cornuana/README.md
|
187
|
# Uvaria cornuana Engl. & Diels SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Leptosphaeriaceae/Ophiobolus/Ophiobolus arenarius/README.md
|
189
|
# Ophiobolus arenarius E. Bommer, M. Rousseau, Sacc. SPECIES
#### Status
ACCEPTED
#### According to
Belgian Species List
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Vernonia/Vernonia pulchella/README.md
|
182
|
# Vernonia pulchella Small SPECIES
#### Status
ACCEPTED
#### According to
Integrated Taxonomic Information System
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Physciaceae/Physcia/Physcia tricolor/README.md
|
212
|
# Physcia tricolor (Zahlbr.) Yoshim. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Lobaria tricolor Zahlbr.
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Bacteria/Proteobacteria/Alphaproteobacteria/Caulobacterales/Caulobacteraceae/Caulobacter/Caulobacter segnis/README.md
|
220
|
# Caulobacter segnis (Urakami et al., 1990) Abraham et al., 1999 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.