code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* Copyright 2008 Nicolas Cochard
* 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 rocfox.rdf2xml.utilities.xml;
import java.util.Stack;
/**
*
* @author Nicolas
*/
public class XmlNamespaceContextStack
{
private Stack<XmlNamespaceContext> contexts = new Stack<XmlNamespaceContext>();
public XmlNamespaceContextStack()
{
contexts.push(new XmlNamespaceContext());
}
public XmlNamespaceContext getCurrent()
{
return contexts.peek();
}
public XmlNamespaceContext moveToNext()
{
XmlNamespaceContext current = contexts.peek();
XmlNamespaceContext next = current.clone();
contexts.push(next);
return next;
}
public void moveBack()
{
contexts.pop();
}
}
|
MondecaLabs/rdf2xml
|
src/rocfox/rdf2xml/utilities/xml/XmlNamespaceContextStack.java
|
Java
|
apache-2.0
| 1,217
|
//
// NSMutableArray+LoggingAddObject.h
// MethodSwizzling
//
// Created by tarena on 16/5/19.
// Copyright © 2016年 tarena. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSMutableArray (LoggingAddObject)
-(void)logAddObject:(id)object;
@end
|
zhangyonguu/myuu
|
MethodSwizzling/MethodSwizzling/NSMutableArray+LoggingAddObject.h
|
C
|
apache-2.0
| 298
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_144) on Tue Jul 03 11:45:08 CDT 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WordCapAdapter</title>
<meta name="date" content="2018-07-03">
<meta name="keywords" content="edu.umn.biomedicus.tnt.WordCapAdapter class">
<meta name="keywords" content="apply()">
<meta name="keywords" content="isToLowercase()">
<meta name="keywords" content="setToLowercase()">
<meta name="keywords" content="isIgnoreCapitalization()">
<meta name="keywords" content="setIgnoreCapitalization()">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="WordCapAdapter";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="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="../../../../edu/umn/biomedicus/tnt/TntPosTagger.html" title="class in edu.umn.biomedicus.tnt"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../edu/umn/biomedicus/tnt/WordCapFilter.html" title="class in edu.umn.biomedicus.tnt"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?edu/umn/biomedicus/tnt/WordCapAdapter.html" target="_top">Frames</a></li>
<li><a href="WordCapAdapter.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><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </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">edu.umn.biomedicus.tnt</div>
<h2 title="Class WordCapAdapter" class="title">Class WordCapAdapter</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>edu.umn.biomedicus.tnt.WordCapAdapter</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">WordCapAdapter</span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../edu/umn/biomedicus/tnt/WordCapAdapter.html#WordCapAdapter--">WordCapAdapter</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../edu/umn/biomedicus/tnt/WordCapAdapter.html#WordCapAdapter--">WordCapAdapter</a></span>()</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="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../edu/umn/biomedicus/common/tuples/WordCap.html" title="type parameter in WordCap">WordCap</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/umn/biomedicus/tnt/WordCapAdapter.html#apply--">apply</a></span>()</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/umn/biomedicus/tnt/WordCapAdapter.html#isIgnoreCapitalization--">isIgnoreCapitalization</a></span>()</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/umn/biomedicus/tnt/WordCapAdapter.html#isToLowercase--">isToLowercase</a></span>()</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/umn/biomedicus/tnt/WordCapAdapter.html#setIgnoreCapitalization--">setIgnoreCapitalization</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../edu/umn/biomedicus/tnt/WordCapAdapter.html#setToLowercase--">setToLowercase</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="WordCapAdapter--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>WordCapAdapter</h4>
<pre>public WordCapAdapter()</pre>
</li>
</ul>
<a name="WordCapAdapter--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>WordCapAdapter</h4>
<pre>public WordCapAdapter()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="apply--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>apply</h4>
<pre>public <a href="../../../../edu/umn/biomedicus/common/tuples/WordCap.html" title="type parameter in WordCap">WordCap</a> apply()</pre>
</li>
</ul>
<a name="isToLowercase--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isToLowercase</h4>
<pre>public boolean isToLowercase()</pre>
</li>
</ul>
<a name="setToLowercase--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setToLowercase</h4>
<pre>public void setToLowercase()</pre>
</li>
</ul>
<a name="isIgnoreCapitalization--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isIgnoreCapitalization</h4>
<pre>public boolean isIgnoreCapitalization()</pre>
</li>
</ul>
<a name="setIgnoreCapitalization--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setIgnoreCapitalization</h4>
<pre>public void setIgnoreCapitalization()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="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="../../../../edu/umn/biomedicus/tnt/TntPosTagger.html" title="class in edu.umn.biomedicus.tnt"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../edu/umn/biomedicus/tnt/WordCapFilter.html" title="class in edu.umn.biomedicus.tnt"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?edu/umn/biomedicus/tnt/WordCapAdapter.html" target="_top">Frames</a></li>
<li><a href="WordCapAdapter.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><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
NLPIE/BioMedICUS
|
doc/javadoc/biomedicus-core/edu/umn/biomedicus/tnt/WordCapAdapter.html
|
HTML
|
apache-2.0
| 11,459
|
# Polyangium septatum Thaxter, 1904 SPECIES
#### Status
SYNONYM
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Bacteria/Proteobacteria/Deltaproteobacteria/Myxococcales/Polyangiaceae/Polyangium/Polyangium sorediatum/ Syn. Polyangium septatum/README.md
|
Markdown
|
apache-2.0
| 198
|
package co.weeby.service;
import co.weeby.event.MessageEvent;
/**
* Message looper for handle Message.<br>
* All messages should come from {@link co.weeby.connector.Connector} .
*
* @see co.weeby.connector.Connector
* @see co.weeby.connector.SelectorConnector
*
* @author jiangzhen
*/
public interface ServiceLooper {
/**
* Handle Message which from connector API
* @param evt
*/
public void handleMessage(MessageEvent evt);
}
|
jiangzhen1984/ChatServer
|
source/src/main/java/co/weeby/service/ServiceLooper.java
|
Java
|
apache-2.0
| 455
|
<strong>Who should approve that damn thing?</strong>
<input form-field type="string" name="approver" />
<small>*must be a valid user</small>
|
clintmanning/new-empty
|
webapps/camunda-webapp/webapp/src/main/webapp/develop/invoice/assign-approver.html
|
HTML
|
apache-2.0
| 142
|
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package app does all of the work necessary to create a Kubernetes
// APIServer by binding together the API, master and APIServer infrastructure.
// It can be configured and called directly or via the hyperkube framework.
package app
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"k8s.io/kubernetes/openshift-kube-apiserver/admission/admissionenablement"
"k8s.io/kubernetes/openshift-kube-apiserver/enablement"
"k8s.io/kubernetes/openshift-kube-apiserver/openshiftkubeapiserver"
"github.com/go-openapi/spec"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
extensionsapiserver "k8s.io/apiextensions-apiserver/pkg/apiserver"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/sets"
utilwait "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authorization/authorizer"
openapinamer "k8s.io/apiserver/pkg/endpoints/openapi"
"k8s.io/apiserver/pkg/endpoints/request"
genericapiserver "k8s.io/apiserver/pkg/server"
"k8s.io/apiserver/pkg/server/filters"
serveroptions "k8s.io/apiserver/pkg/server/options"
serverstorage "k8s.io/apiserver/pkg/server/storage"
"k8s.io/apiserver/pkg/storage/etcd3/preflight"
"k8s.io/apiserver/pkg/util/feature"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/apiserver/pkg/util/term"
"k8s.io/apiserver/pkg/util/webhook"
clientgoinformers "k8s.io/client-go/informers"
clientgoclientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/keyutil"
cloudprovider "k8s.io/cloud-provider"
cliflag "k8s.io/component-base/cli/flag"
"k8s.io/component-base/cli/globalflag"
"k8s.io/component-base/metrics"
_ "k8s.io/component-base/metrics/prometheus/workqueue" // for workqueue metric registration
"k8s.io/component-base/version"
"k8s.io/component-base/version/verflag"
"k8s.io/klog"
aggregatorapiserver "k8s.io/kube-aggregator/pkg/apiserver"
aggregatorscheme "k8s.io/kube-aggregator/pkg/apiserver/scheme"
"k8s.io/kubernetes/cmd/kube-apiserver/app/options"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/apis/core"
v1 "k8s.io/kubernetes/pkg/apis/core/v1"
"k8s.io/kubernetes/pkg/capabilities"
serviceaccountcontroller "k8s.io/kubernetes/pkg/controller/serviceaccount"
"k8s.io/kubernetes/pkg/features"
generatedopenapi "k8s.io/kubernetes/pkg/generated/openapi"
"k8s.io/kubernetes/pkg/kubeapiserver"
kubeapiserveradmission "k8s.io/kubernetes/pkg/kubeapiserver/admission"
kubeauthenticator "k8s.io/kubernetes/pkg/kubeapiserver/authenticator"
"k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes"
kubeoptions "k8s.io/kubernetes/pkg/kubeapiserver/options"
kubeserver "k8s.io/kubernetes/pkg/kubeapiserver/server"
"k8s.io/kubernetes/pkg/master"
"k8s.io/kubernetes/pkg/master/reconcilers"
"k8s.io/kubernetes/pkg/master/tunneler"
"k8s.io/kubernetes/pkg/registry/cachesize"
eventstorage "k8s.io/kubernetes/pkg/registry/core/event/storage"
rbacrest "k8s.io/kubernetes/pkg/registry/rbac/rest"
"k8s.io/kubernetes/pkg/serviceaccount"
utilflag "k8s.io/kubernetes/pkg/util/flag"
"k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/bootstrap"
)
const (
etcdRetryLimit = 60
etcdRetryInterval = 1 * time.Second
)
// NewAPIServerCommand creates a *cobra.Command object with default parameters
func NewAPIServerCommand() *cobra.Command {
s := options.NewServerRunOptions()
cmd := &cobra.Command{
Use: "kube-apiserver",
Long: `The Kubernetes API server validates and configures data
for the api objects which include pods, services, replicationcontrollers, and
others. The API Server services REST operations and provides the frontend to the
cluster's shared state through which all other components interact.`,
RunE: func(cmd *cobra.Command, args []string) error {
verflag.PrintAndExitIfRequested()
if len(s.OpenShiftConfig) > 0 {
openshiftConfig, err := enablement.GetOpenshiftConfig(s.OpenShiftConfig)
if err != nil {
klog.Fatal(err)
}
enablement.ForceOpenShift(openshiftConfig)
// this forces a patch to be called
// TODO we're going to try to remove bits of the patching.
configPatchFn := openshiftkubeapiserver.NewOpenShiftKubeAPIServerConfigPatch(openshiftConfig)
OpenShiftKubeAPIServerConfigPatch = configPatchFn
args, err := openshiftkubeapiserver.ConfigToFlags(openshiftConfig)
if err != nil {
return err
}
// hopefully this resets the flags?
if err := cmd.ParseFlags(args); err != nil {
return err
}
// print merged flags (merged from OpenshiftConfig)
utilflag.PrintFlags(cmd.Flags())
enablement.ForceGlobalInitializationForOpenShift()
admissionenablement.InstallOpenShiftAdmissionPlugins(s)
} else {
// print default flags
utilflag.PrintFlags(cmd.Flags())
}
// set default options
completedOptions, err := Complete(s)
if err != nil {
return err
}
// validate options
if errs := completedOptions.Validate(); len(errs) != 0 {
return utilerrors.NewAggregate(errs)
}
return Run(completedOptions, genericapiserver.SetupSignalHandler())
},
}
fs := cmd.Flags()
namedFlagSets := s.Flags()
verflag.AddFlags(namedFlagSets.FlagSet("global"))
globalflag.AddGlobalFlags(namedFlagSets.FlagSet("global"), cmd.Name())
options.AddCustomGlobalFlags(namedFlagSets.FlagSet("generic"))
for _, f := range namedFlagSets.FlagSets {
fs.AddFlagSet(f)
}
usageFmt := "Usage:\n %s\n"
cols, _, _ := term.TerminalSize(cmd.OutOrStdout())
cmd.SetUsageFunc(func(cmd *cobra.Command) error {
fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())
cliflag.PrintSections(cmd.OutOrStderr(), namedFlagSets, cols)
return nil
})
cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine())
cliflag.PrintSections(cmd.OutOrStdout(), namedFlagSets, cols)
})
return cmd
}
// Run runs the specified APIServer. This should never exit.
func Run(completeOptions completedServerRunOptions, stopCh <-chan struct{}) error {
// To help debugging, immediately log version
klog.Infof("Version: %+v", version.Get())
server, err := CreateServerChain(completeOptions, stopCh)
if err != nil {
return err
}
prepared, err := server.PrepareRun()
if err != nil {
return err
}
return prepared.Run(stopCh)
}
// CreateServerChain creates the apiservers connected via delegation.
func CreateServerChain(completedOptions completedServerRunOptions, stopCh <-chan struct{}) (*aggregatorapiserver.APIAggregator, error) {
nodeTunneler, proxyTransport, err := CreateNodeDialer(completedOptions)
if err != nil {
return nil, err
}
kubeAPIServerConfig, insecureServingInfo, serviceResolver, pluginInitializer, err := CreateKubeAPIServerConfig(completedOptions, nodeTunneler, proxyTransport)
if err != nil {
return nil, err
}
// If additional API servers are added, they should be gated.
apiExtensionsConfig, err := createAPIExtensionsConfig(*kubeAPIServerConfig.GenericConfig, kubeAPIServerConfig.ExtraConfig.VersionedInformers, pluginInitializer, completedOptions.ServerRunOptions, completedOptions.MasterCount,
serviceResolver, webhook.NewDefaultAuthenticationInfoResolverWrapper(proxyTransport, kubeAPIServerConfig.GenericConfig.LoopbackClientConfig))
if err != nil {
return nil, err
}
apiExtensionsServer, err := createAPIExtensionsServer(apiExtensionsConfig, genericapiserver.NewEmptyDelegate())
if err != nil {
return nil, err
}
kubeAPIServer, err := CreateKubeAPIServer(kubeAPIServerConfig, apiExtensionsServer.GenericAPIServer)
if err != nil {
return nil, err
}
// aggregator comes last in the chain
aggregatorConfig, err := createAggregatorConfig(*kubeAPIServerConfig.GenericConfig, completedOptions.ServerRunOptions, kubeAPIServerConfig.ExtraConfig.VersionedInformers, serviceResolver, proxyTransport, pluginInitializer)
if err != nil {
return nil, err
}
aggregatorServer, err := createAggregatorServer(aggregatorConfig, kubeAPIServer.GenericAPIServer, apiExtensionsServer.Informers)
if err != nil {
// we don't need special handling for innerStopCh because the aggregator server doesn't create any go routines
return nil, err
}
if insecureServingInfo != nil {
insecureHandlerChain := kubeserver.BuildInsecureHandlerChain(aggregatorServer.GenericAPIServer.UnprotectedHandler(), kubeAPIServerConfig.GenericConfig)
if err := insecureServingInfo.Serve(insecureHandlerChain, kubeAPIServerConfig.GenericConfig.RequestTimeout, stopCh); err != nil {
return nil, err
}
}
return aggregatorServer, nil
}
// CreateKubeAPIServer creates and wires a workable kube-apiserver
func CreateKubeAPIServer(kubeAPIServerConfig *master.Config, delegateAPIServer genericapiserver.DelegationTarget) (*master.Master, error) {
kubeAPIServer, err := kubeAPIServerConfig.Complete().New(delegateAPIServer)
if err != nil {
return nil, err
}
return kubeAPIServer, nil
}
// CreateNodeDialer creates the dialer infrastructure to connect to the nodes.
func CreateNodeDialer(s completedServerRunOptions) (tunneler.Tunneler, *http.Transport, error) {
// Setup nodeTunneler if needed
var nodeTunneler tunneler.Tunneler
var proxyDialerFn utilnet.DialFunc
if len(s.SSHUser) > 0 {
// Get ssh key distribution func, if supported
var installSSHKey tunneler.InstallSSHKey
cloud, err := cloudprovider.InitCloudProvider(s.CloudProvider.CloudProvider, s.CloudProvider.CloudConfigFile)
if err != nil {
return nil, nil, fmt.Errorf("cloud provider could not be initialized: %v", err)
}
if cloud != nil {
if instances, supported := cloud.Instances(); supported {
installSSHKey = instances.AddSSHKeyToAllInstances
}
}
if s.KubeletConfig.Port == 0 {
return nil, nil, fmt.Errorf("must enable kubelet port if proxy ssh-tunneling is specified")
}
if s.KubeletConfig.ReadOnlyPort == 0 {
return nil, nil, fmt.Errorf("must enable kubelet readonly port if proxy ssh-tunneling is specified")
}
// Set up the nodeTunneler
// TODO(cjcullen): If we want this to handle per-kubelet ports or other
// kubelet listen-addresses, we need to plumb through options.
healthCheckPath := &url.URL{
Scheme: "http",
Host: net.JoinHostPort("127.0.0.1", strconv.FormatUint(uint64(s.KubeletConfig.ReadOnlyPort), 10)),
Path: "healthz",
}
nodeTunneler = tunneler.New(s.SSHUser, s.SSHKeyfile, healthCheckPath, installSSHKey)
// Use the nodeTunneler's dialer when proxying to pods, services, and nodes
proxyDialerFn = nodeTunneler.Dial
}
// Proxying to pods and services is IP-based... don't expect to be able to verify the hostname
proxyTLSClientConfig := &tls.Config{InsecureSkipVerify: true}
proxyTransport := utilnet.SetTransportDefaults(&http.Transport{
DialContext: proxyDialerFn,
TLSClientConfig: proxyTLSClientConfig,
})
return nodeTunneler, proxyTransport, nil
}
// CreateKubeAPIServerConfig creates all the resources for running the API server, but runs none of them
func CreateKubeAPIServerConfig(
s completedServerRunOptions,
nodeTunneler tunneler.Tunneler,
proxyTransport *http.Transport,
) (
*master.Config,
*genericapiserver.DeprecatedInsecureServingInfo,
aggregatorapiserver.ServiceResolver,
[]admission.PluginInitializer,
error,
) {
genericConfig, versionedInformers, insecureServingInfo, serviceResolver, pluginInitializers, admissionPostStartHook, storageFactory, err := buildGenericConfig(s.ServerRunOptions, proxyTransport)
if err != nil {
return nil, nil, nil, nil, err
}
if _, port, err := net.SplitHostPort(s.Etcd.StorageConfig.Transport.ServerList[0]); err == nil && port != "0" && len(port) != 0 {
if err := utilwait.PollImmediate(etcdRetryInterval, etcdRetryLimit*etcdRetryInterval, preflight.EtcdConnection{ServerList: s.Etcd.StorageConfig.Transport.ServerList}.CheckEtcdServers); err != nil {
return nil, nil, nil, nil, fmt.Errorf("error waiting for etcd connection: %v", err)
}
}
capabilities.Initialize(capabilities.Capabilities{
AllowPrivileged: s.AllowPrivileged,
// TODO(vmarmol): Implement support for HostNetworkSources.
PrivilegedSources: capabilities.PrivilegedSources{
HostNetworkSources: []string{},
HostPIDSources: []string{},
HostIPCSources: []string{},
},
PerConnectionBandwidthLimitBytesPerSec: s.MaxConnectionBytesPerSec,
})
if len(s.ShowHiddenMetricsForVersion) > 0 {
metrics.SetShowHidden()
}
serviceIPRange, apiServerServiceIP, err := master.ServiceIPRange(s.PrimaryServiceClusterIPRange)
if err != nil {
return nil, nil, nil, nil, err
}
// defaults to empty range and ip
var secondaryServiceIPRange net.IPNet
// process secondary range only if provided by user
if s.SecondaryServiceClusterIPRange.IP != nil {
secondaryServiceIPRange, _, err = master.ServiceIPRange(s.SecondaryServiceClusterIPRange)
if err != nil {
return nil, nil, nil, nil, err
}
}
var eventStorage *eventstorage.REST
eventStorage, err = eventstorage.NewREST(genericConfig.RESTOptionsGetter, uint64(s.EventTTL.Seconds()))
if err != nil {
return nil, nil, nil, nil, err
}
genericConfig.EventSink = eventRegistrySink{eventStorage}
config := &master.Config{
GenericConfig: genericConfig,
ExtraConfig: master.ExtraConfig{
APIResourceConfigSource: storageFactory.APIResourceConfigSource,
StorageFactory: storageFactory,
EventTTL: s.EventTTL,
KubeletClientConfig: s.KubeletConfig,
EnableLogsSupport: s.EnableLogsHandler,
ProxyTransport: proxyTransport,
Tunneler: nodeTunneler,
ServiceIPRange: serviceIPRange,
APIServerServiceIP: apiServerServiceIP,
SecondaryServiceIPRange: secondaryServiceIPRange,
APIServerServicePort: 443,
ServiceNodePortRange: s.ServiceNodePortRange,
KubernetesServiceNodePort: s.KubernetesServiceNodePort,
EndpointReconcilerType: reconcilers.Type(s.EndpointReconcilerType),
MasterCount: s.MasterCount,
ServiceAccountIssuer: s.ServiceAccountIssuer,
ServiceAccountMaxExpiration: s.ServiceAccountTokenMaxExpiration,
VersionedInformers: versionedInformers,
},
}
clientCAProvider, err := s.Authentication.ClientCert.GetClientCAContentProvider()
if err != nil {
return nil, nil, nil, nil, err
}
config.ExtraConfig.ClusterAuthenticationInfo.ClientCA = clientCAProvider
requestHeaderConfig, err := s.Authentication.RequestHeader.ToAuthenticationRequestHeaderConfig()
if err != nil {
return nil, nil, nil, nil, err
}
if requestHeaderConfig != nil {
config.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderCA = requestHeaderConfig.CAContentProvider
config.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderAllowedNames = requestHeaderConfig.AllowedClientNames
config.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderExtraHeaderPrefixes = requestHeaderConfig.ExtraHeaderPrefixes
config.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderGroupHeaders = requestHeaderConfig.GroupHeaders
config.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderUsernameHeaders = requestHeaderConfig.UsernameHeaders
}
if err := config.GenericConfig.AddPostStartHook("start-kube-apiserver-admission-initializer", admissionPostStartHook); err != nil {
return nil, nil, nil, nil, err
}
if nodeTunneler != nil {
// Use the nodeTunneler's dialer to connect to the kubelet
config.ExtraConfig.KubeletClientConfig.Dial = nodeTunneler.Dial
}
if config.GenericConfig.EgressSelector != nil {
// Use the config.GenericConfig.EgressSelector lookup to find the dialer to connect to the kubelet
config.ExtraConfig.KubeletClientConfig.Lookup = config.GenericConfig.EgressSelector.Lookup
}
return config, insecureServingInfo, serviceResolver, pluginInitializers, nil
}
// BuildGenericConfig takes the master server options and produces the genericapiserver.Config associated with it
func buildGenericConfig(
s *options.ServerRunOptions,
proxyTransport *http.Transport,
) (
genericConfig *genericapiserver.Config,
versionedInformers clientgoinformers.SharedInformerFactory,
insecureServingInfo *genericapiserver.DeprecatedInsecureServingInfo,
serviceResolver aggregatorapiserver.ServiceResolver,
pluginInitializers []admission.PluginInitializer,
admissionPostStartHook genericapiserver.PostStartHookFunc,
storageFactory *serverstorage.DefaultStorageFactory,
lastErr error,
) {
genericConfig = genericapiserver.NewConfig(legacyscheme.Codecs)
genericConfig.MergedResourceConfig = master.DefaultAPIResourceConfigSource()
if lastErr = s.GenericServerRunOptions.ApplyTo(genericConfig); lastErr != nil {
return
}
if lastErr = s.InsecureServing.ApplyTo(&insecureServingInfo, &genericConfig.LoopbackClientConfig); lastErr != nil {
return
}
if lastErr = s.SecureServing.ApplyTo(&genericConfig.SecureServing, &genericConfig.LoopbackClientConfig); lastErr != nil {
return
}
if lastErr = s.Authentication.ApplyTo(genericConfig); lastErr != nil {
return
}
if lastErr = s.Features.ApplyTo(genericConfig); lastErr != nil {
return
}
if lastErr = s.APIEnablement.ApplyTo(genericConfig, master.DefaultAPIResourceConfigSource(), legacyscheme.Scheme); lastErr != nil {
return
}
if lastErr = s.EgressSelector.ApplyTo(genericConfig); lastErr != nil {
return
}
genericConfig.OpenAPIConfig = genericapiserver.DefaultOpenAPIConfig(generatedopenapi.GetOpenAPIDefinitions, openapinamer.NewDefinitionNamer(legacyscheme.Scheme, extensionsapiserver.Scheme, aggregatorscheme.Scheme))
genericConfig.OpenAPIConfig.Info.Title = "Kubernetes"
genericConfig.LongRunningFunc = filters.BasicLongRunningRequestCheck(
sets.NewString("watch", "proxy"),
sets.NewString("attach", "exec", "proxy", "log", "portforward"),
)
kubeVersion := version.Get()
genericConfig.Version = &kubeVersion
storageFactoryConfig := kubeapiserver.NewStorageFactoryConfig()
storageFactoryConfig.APIResourceConfig = genericConfig.MergedResourceConfig
completedStorageFactoryConfig, err := storageFactoryConfig.Complete(s.Etcd)
if err != nil {
lastErr = err
return
}
storageFactory, lastErr = completedStorageFactoryConfig.New()
if lastErr != nil {
return
}
if genericConfig.EgressSelector != nil {
storageFactory.StorageConfig.Transport.EgressLookup = genericConfig.EgressSelector.Lookup
}
if lastErr = s.Etcd.ApplyWithStorageFactoryTo(storageFactory, genericConfig); lastErr != nil {
return
}
// Use protobufs for self-communication.
// Since not every generic apiserver has to support protobufs, we
// cannot default to it in generic apiserver and need to explicitly
// set it in kube-apiserver.
genericConfig.LoopbackClientConfig.ContentConfig.ContentType = "application/vnd.kubernetes.protobuf"
// Disable compression for self-communication, since we are going to be
// on a fast local network
genericConfig.LoopbackClientConfig.DisableCompression = true
enablement.SetLoopbackClientConfig(genericConfig.LoopbackClientConfig)
kubeClientConfig := genericConfig.LoopbackClientConfig
clientgoExternalClient, err := clientgoclientset.NewForConfig(kubeClientConfig)
if err != nil {
lastErr = fmt.Errorf("failed to create real external clientset: %v", err)
return
}
versionedInformers = clientgoinformers.NewSharedInformerFactory(clientgoExternalClient, 10*time.Minute)
genericConfig.Authentication.Authenticator, genericConfig.OpenAPIConfig.SecurityDefinitions, err = BuildAuthenticator(s, clientgoExternalClient, versionedInformers)
if err != nil {
lastErr = fmt.Errorf("invalid authentication config: %v", err)
return
}
genericConfig.Authorization.Authorizer, genericConfig.RuleResolver, err = BuildAuthorizer(s, versionedInformers)
if err != nil {
lastErr = fmt.Errorf("invalid authorization config: %v", err)
return
}
if !sets.NewString(s.Authorization.Modes...).Has(modes.ModeRBAC) {
genericConfig.DisabledPostStartHooks.Insert(rbacrest.PostStartHookName)
}
admissionConfig := &kubeapiserveradmission.Config{
ExternalInformers: versionedInformers,
LoopbackClientConfig: genericConfig.LoopbackClientConfig,
CloudConfigFile: s.CloudProvider.CloudConfigFile,
}
serviceResolver = buildServiceResolver(s.EnableAggregatorRouting, genericConfig.LoopbackClientConfig.Host, versionedInformers)
authInfoResolverWrapper := webhook.NewDefaultAuthenticationInfoResolverWrapper(proxyTransport, genericConfig.LoopbackClientConfig)
lastErr = s.Audit.ApplyTo(
genericConfig,
genericConfig.LoopbackClientConfig,
versionedInformers,
serveroptions.NewProcessInfo("kube-apiserver", "kube-system"),
&serveroptions.WebhookOptions{
AuthInfoResolverWrapper: authInfoResolverWrapper,
ServiceResolver: serviceResolver,
},
)
if lastErr != nil {
return
}
pluginInitializers, admissionPostStartHook, err = admissionConfig.New(proxyTransport, serviceResolver)
if err != nil {
lastErr = fmt.Errorf("failed to create admission plugin initializer: %v", err)
return
}
if err := PatchKubeAPIServerConfig(genericConfig, versionedInformers, &pluginInitializers); err != nil {
lastErr = fmt.Errorf("failed to patch: %v", err)
return
}
if enablement.IsOpenShift() {
admissionenablement.SetAdmissionDefaults(s, versionedInformers, clientgoExternalClient)
}
err = s.Admission.ApplyTo(
genericConfig,
versionedInformers,
kubeClientConfig,
feature.DefaultFeatureGate,
pluginInitializers...)
if err != nil {
lastErr = fmt.Errorf("failed to initialize admission: %v", err)
}
return
}
// BuildAuthenticator constructs the authenticator
func BuildAuthenticator(s *options.ServerRunOptions, extclient clientgoclientset.Interface, versionedInformer clientgoinformers.SharedInformerFactory) (authenticator.Request, *spec.SecurityDefinitions, error) {
authenticatorConfig, err := s.Authentication.ToAuthenticationConfig()
if err != nil {
return nil, nil, err
}
if s.Authentication.ServiceAccounts.Lookup || utilfeature.DefaultFeatureGate.Enabled(features.TokenRequest) {
authenticatorConfig.ServiceAccountTokenGetter = serviceaccountcontroller.NewGetterFromClient(
extclient,
versionedInformer.Core().V1().Secrets().Lister(),
versionedInformer.Core().V1().ServiceAccounts().Lister(),
versionedInformer.Core().V1().Pods().Lister(),
)
}
authenticatorConfig.BootstrapTokenAuthenticator = bootstrap.NewTokenAuthenticator(
versionedInformer.Core().V1().Secrets().Lister().Secrets(metav1.NamespaceSystem),
)
return authenticatorConfig.New()
}
// BuildAuthorizer constructs the authorizer
func BuildAuthorizer(s *options.ServerRunOptions, versionedInformers clientgoinformers.SharedInformerFactory) (authorizer.Authorizer, authorizer.RuleResolver, error) {
authorizationConfig := s.Authorization.ToAuthorizationConfig(versionedInformers)
return authorizationConfig.New()
}
// completedServerRunOptions is a private wrapper that enforces a call of Complete() before Run can be invoked.
type completedServerRunOptions struct {
*options.ServerRunOptions
}
// Complete set default ServerRunOptions.
// Should be called after kube-apiserver flags parsed.
func Complete(s *options.ServerRunOptions) (completedServerRunOptions, error) {
var options completedServerRunOptions
// set defaults
if err := s.GenericServerRunOptions.DefaultAdvertiseAddress(s.SecureServing.SecureServingOptions); err != nil {
return options, err
}
if err := kubeoptions.DefaultAdvertiseAddress(s.GenericServerRunOptions, s.InsecureServing.DeprecatedInsecureServingOptions); err != nil {
return options, err
}
// process s.ServiceClusterIPRange from list to Primary and Secondary
// we process secondary only if provided by user
serviceClusterIPRangeList := strings.Split(s.ServiceClusterIPRanges, ",")
var apiServerServiceIP net.IP
var serviceIPRange net.IPNet
var err error
// nothing provided by user, use default range (only applies to the Primary)
if len(serviceClusterIPRangeList) == 0 {
var primaryServiceClusterCIDR net.IPNet
serviceIPRange, apiServerServiceIP, err = master.ServiceIPRange(primaryServiceClusterCIDR)
if err != nil {
return options, fmt.Errorf("error determining service IP ranges: %v", err)
}
s.PrimaryServiceClusterIPRange = serviceIPRange
}
if len(serviceClusterIPRangeList) > 0 {
_, primaryServiceClusterCIDR, err := net.ParseCIDR(serviceClusterIPRangeList[0])
if err != nil {
return options, fmt.Errorf("service-cluster-ip-range[0] is not a valid cidr")
}
serviceIPRange, apiServerServiceIP, err = master.ServiceIPRange(*(primaryServiceClusterCIDR))
if err != nil {
return options, fmt.Errorf("error determining service IP ranges for primary service cidr: %v", err)
}
s.PrimaryServiceClusterIPRange = serviceIPRange
}
// user provided at least two entries
if len(serviceClusterIPRangeList) > 1 {
_, secondaryServiceClusterCIDR, err := net.ParseCIDR(serviceClusterIPRangeList[1])
if err != nil {
return options, fmt.Errorf("service-cluster-ip-range[1] is not an ip net")
}
s.SecondaryServiceClusterIPRange = *(secondaryServiceClusterCIDR)
}
//note: validation asserts that the list is max of two dual stack entries
if err := s.SecureServing.MaybeDefaultWithSelfSignedCerts(s.GenericServerRunOptions.AdvertiseAddress.String(), []string{"kubernetes.default.svc", "kubernetes.default", "kubernetes"}, []net.IP{apiServerServiceIP}); err != nil {
return options, fmt.Errorf("error creating self-signed certificates: %v", err)
}
if len(s.GenericServerRunOptions.ExternalHost) == 0 {
if len(s.GenericServerRunOptions.AdvertiseAddress) > 0 {
s.GenericServerRunOptions.ExternalHost = s.GenericServerRunOptions.AdvertiseAddress.String()
} else {
if hostname, err := os.Hostname(); err == nil {
s.GenericServerRunOptions.ExternalHost = hostname
} else {
return options, fmt.Errorf("error finding host name: %v", err)
}
}
klog.Infof("external host was not specified, using %v", s.GenericServerRunOptions.ExternalHost)
}
s.Authentication.ApplyAuthorization(s.Authorization)
// Use (ServiceAccountSigningKeyFile != "") as a proxy to the user enabling
// TokenRequest functionality. This defaulting was convenient, but messed up
// a lot of people when they rotated their serving cert with no idea it was
// connected to their service account keys. We are taking this opportunity to
// remove this problematic defaulting.
if s.ServiceAccountSigningKeyFile == "" {
// Default to the private server key for service account token signing
if len(s.Authentication.ServiceAccounts.KeyFiles) == 0 && s.SecureServing.ServerCert.CertKey.KeyFile != "" {
if kubeauthenticator.IsValidServiceAccountKeyFile(s.SecureServing.ServerCert.CertKey.KeyFile) {
s.Authentication.ServiceAccounts.KeyFiles = []string{s.SecureServing.ServerCert.CertKey.KeyFile}
} else {
klog.Warning("No TLS key provided, service account token authentication disabled")
}
}
}
if s.ServiceAccountSigningKeyFile != "" && s.Authentication.ServiceAccounts.Issuer != "" {
sk, err := keyutil.PrivateKeyFromFile(s.ServiceAccountSigningKeyFile)
if err != nil {
return options, fmt.Errorf("failed to parse service-account-issuer-key-file: %v", err)
}
if s.Authentication.ServiceAccounts.MaxExpiration != 0 {
lowBound := time.Hour
upBound := time.Duration(1<<32) * time.Second
if s.Authentication.ServiceAccounts.MaxExpiration < lowBound ||
s.Authentication.ServiceAccounts.MaxExpiration > upBound {
return options, fmt.Errorf("the serviceaccount max expiration must be between 1 hour to 2^32 seconds")
}
}
s.ServiceAccountIssuer, err = serviceaccount.JWTTokenGenerator(s.Authentication.ServiceAccounts.Issuer, sk)
if err != nil {
return options, fmt.Errorf("failed to build token generator: %v", err)
}
s.ServiceAccountTokenMaxExpiration = s.Authentication.ServiceAccounts.MaxExpiration
}
if s.Etcd.EnableWatchCache {
klog.V(2).Infof("Initializing cache sizes based on %dMB limit", s.GenericServerRunOptions.TargetRAMMB)
sizes := cachesize.NewHeuristicWatchCacheSizes(s.GenericServerRunOptions.TargetRAMMB)
if userSpecified, err := serveroptions.ParseWatchCacheSizes(s.Etcd.WatchCacheSizes); err == nil {
for resource, size := range userSpecified {
sizes[resource] = size
}
}
s.Etcd.WatchCacheSizes, err = serveroptions.WriteWatchCacheSizes(sizes)
if err != nil {
return options, err
}
}
if s.APIEnablement.RuntimeConfig != nil {
for key, value := range s.APIEnablement.RuntimeConfig {
if key == "v1" || strings.HasPrefix(key, "v1/") ||
key == "api/v1" || strings.HasPrefix(key, "api/v1/") {
delete(s.APIEnablement.RuntimeConfig, key)
s.APIEnablement.RuntimeConfig["/v1"] = value
}
if key == "api/legacy" {
delete(s.APIEnablement.RuntimeConfig, key)
}
}
}
options.ServerRunOptions = s
return options, nil
}
func buildServiceResolver(enabledAggregatorRouting bool, hostname string, informer clientgoinformers.SharedInformerFactory) webhook.ServiceResolver {
var serviceResolver webhook.ServiceResolver
if enabledAggregatorRouting {
serviceResolver = aggregatorapiserver.NewEndpointServiceResolver(
informer.Core().V1().Services().Lister(),
informer.Core().V1().Endpoints().Lister(),
)
} else {
serviceResolver = aggregatorapiserver.NewClusterIPServiceResolver(
informer.Core().V1().Services().Lister(),
)
}
// resolve kubernetes.default.svc locally
if localHost, err := url.Parse(hostname); err == nil {
serviceResolver = aggregatorapiserver.NewLoopbackServiceResolver(serviceResolver, localHost)
}
return serviceResolver
}
// eventRegistrySink wraps an event registry in order to be used as direct event sync, without going through the API.
type eventRegistrySink struct {
*eventstorage.REST
}
var _ genericapiserver.EventSink = eventRegistrySink{}
func (s eventRegistrySink) Create(v1event *corev1.Event) (*corev1.Event, error) {
ctx := request.WithNamespace(request.NewContext(), v1event.Namespace)
var event core.Event
if err := v1.Convert_v1_Event_To_core_Event(v1event, &event, nil); err != nil {
return nil, err
}
obj, err := s.REST.Create(ctx, &event, nil, &metav1.CreateOptions{})
if err != nil {
return nil, err
}
ret, ok := obj.(*core.Event)
if !ok {
return nil, fmt.Errorf("expected corev1.Event, got %T", obj)
}
var v1ret corev1.Event
if err := v1.Convert_core_Event_To_v1_Event(ret, &v1ret, nil); err != nil {
return nil, err
}
return &v1ret, nil
}
|
pecameron/origin
|
vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/server.go
|
GO
|
apache-2.0
| 31,140
|
/*
* Copyright (c) 2009-2020, Peter Abeles. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ejml.dense.row.decomposition.qr;
import org.ejml.data.DMatrixRMaj;
import org.ejml.dense.row.RandomMatrices_DDRM;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2)
@Measurement(iterations = 5)
@State(Scope.Benchmark)
@Fork(value = 2)
public class BenchmarkDecompositionQR_DDRM {
// @Param({"100", "500", "1000", "5000", "10000"})
@Param({"1000"})
public int size;
public DMatrixRMaj A, Q, R;
QRDecompositionHouseholderColumn_DDRM houseCol = new QRDecompositionHouseholderColumn_DDRM();
@Setup
public void setup() {
Random rand = new Random(234);
A = RandomMatrices_DDRM.rectangle(size*2, size/2, -1, 1, rand);
Q = new DMatrixRMaj(size, size);
R = new DMatrixRMaj(Q.numCols, Q.numCols);
}
@Benchmark
public void houseCol() {
houseCol.decompose(A);
houseCol.getQ(Q, true);
houseCol.getR(R, true);
}
@Benchmark
public void houseCol_decompose() {
houseCol.decompose(A);
}
public static void main( String[] args ) throws RunnerException {
Options opt = new OptionsBuilder()
.include(BenchmarkDecompositionQR_DDRM.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
|
lessthanoptimal/ejml
|
main/ejml-ddense/benchmarks/src/org/ejml/dense/row/decomposition/qr/BenchmarkDecompositionQR_DDRM.java
|
Java
|
apache-2.0
| 2,295
|
/*!
* CBBL®
* ______________________________________________________________
* Architecture and Code Handcrafted by Prabhat Kumar.
* Architectuur en Code handgemaakt door Prabhat Kumar.
* @author : Prabhat Kumar [http://prabhatkumar.org/]
* @copyright : Sequømics Corporation [http://sequomics.com/]
* ______________________________________________________________
* @date : 09-May-2016
* @license : Apache, version 2.0
* ______________________________________________________________
*/
|
CB2L/CB2L.github.io
|
cbbl.config.js
|
JavaScript
|
apache-2.0
| 511
|
echo three
pause
|
wolispace/cow_windows_server
|
oldcow_on_apache/test3.bat
|
Batchfile
|
apache-2.0
| 17
|
# Copyright 2015 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.
# ==============================================================================
# pylint: disable=line-too-long
"""This library provides a set of classes and functions that helps train models.
## Optimizers
The Optimizer base class provides methods to compute gradients for a loss and
apply gradients to variables. A collection of subclasses implement classic
optimization algorithms such as GradientDescent and Adagrad.
You never instantiate the Optimizer class itself, but instead instantiate one
of the subclasses.
@@Optimizer
@@GradientDescentOptimizer
@@AdadeltaOptimizer
@@AdagradOptimizer
@@MomentumOptimizer
@@AdamOptimizer
@@FtrlOptimizer
@@RMSPropOptimizer
## Gradient Computation
TensorFlow provides functions to compute the derivatives for a given
TensorFlow computation graph, adding operations to the graph. The
optimizer classes automatically compute derivatives on your graph, but
creators of new Optimizers or expert users can call the lower-level
functions below.
@@gradients
@@AggregationMethod
@@stop_gradient
## Gradient Clipping
TensorFlow provides several operations that you can use to add clipping
functions to your graph. You can use these functions to perform general data
clipping, but they're particularly useful for handling exploding or vanishing
gradients.
@@clip_by_value
@@clip_by_norm
@@clip_by_average_norm
@@clip_by_global_norm
@@global_norm
## Decaying the learning rate
@@exponential_decay
## Moving Averages
Some training algorithms, such as GradientDescent and Momentum often benefit
from maintaining a moving average of variables during optimization. Using the
moving averages for evaluations often improve results significantly.
@@ExponentialMovingAverage
## Coordinator and QueueRunner
See [Threading and Queues](../../how_tos/threading_and_queues/index.md)
for how to use threads and queues. For documentation on the Queue API,
see [Queues](../../api_docs/python/io_ops.md#queues).
@@Coordinator
@@QueueRunner
@@add_queue_runner
@@start_queue_runners
## Distributed execution
See [Distributed TensorFlow](../../how_tos/distributed/index.md) for
more information about how to configure a distributed TensorFlow program.
@@Server
@@Supervisor
@@SessionManager
@@ClusterSpec
@@replica_device_setter
## Summary Operations
The following ops output
[`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)
protocol buffers as serialized string tensors.
You can fetch the output of a summary op in a session, and pass it to
a [SummaryWriter](../../api_docs/python/train.md#SummaryWriter) to append it
to an event file. Event files contain
[`Event`](https://www.tensorflow.org/code/tensorflow/core/util/event.proto)
protos that can contain `Summary` protos along with the timestamp and
step. You can then use TensorBoard to visualize the contents of the
event files. See [TensorBoard and
Summaries](../../how_tos/summaries_and_tensorboard/index.md) for more
details.
@@scalar_summary
@@image_summary
@@audio_summary
@@histogram_summary
@@zero_fraction
@@merge_summary
@@merge_all_summaries
## Adding Summaries to Event Files
See [Summaries and
TensorBoard](../../how_tos/summaries_and_tensorboard/index.md) for an
overview of summaries, event files, and visualization in TensorBoard.
@@SummaryWriter
@@summary_iterator
## Training utilities
@@global_step
@@write_graph
"""
# pylint: enable=line-too-long
# Optimizers.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
# pylint: disable=g-bad-import-order,unused-import
from tensorflow.python.ops import gradients
from tensorflow.python.ops import io_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.training.adadelta import AdadeltaOptimizer
from tensorflow.python.training.adagrad import AdagradOptimizer
from tensorflow.python.training.proximal_adagrad import ProximalAdagradOptimizer
from tensorflow.python.training.adam import AdamOptimizer
from tensorflow.python.training.ftrl import FtrlOptimizer
from tensorflow.python.training.momentum import MomentumOptimizer
from tensorflow.python.training.moving_averages import ExponentialMovingAverage
from tensorflow.python.training.optimizer import Optimizer
from tensorflow.python.training.rmsprop import RMSPropOptimizer
from tensorflow.python.training.gradient_descent import GradientDescentOptimizer
from tensorflow.python.training.proximal_gradient_descent import ProximalGradientDescentOptimizer
from tensorflow.python.training.sync_replicas_optimizer import SyncReplicasOptimizer
# Utility classes for training.
from tensorflow.python.training.coordinator import Coordinator
from tensorflow.python.training.coordinator import LooperThread
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.training.queue_runner import *
# For the module level doc.
from tensorflow.python.training import input as _input
from tensorflow.python.training.input import *
from tensorflow.python.training.device_setter import replica_device_setter
from tensorflow.python.training.saver import generate_checkpoint_state_proto
from tensorflow.python.training.saver import get_checkpoint_state
from tensorflow.python.training.saver import latest_checkpoint
from tensorflow.python.training.saver import Saver
from tensorflow.python.training.saver import update_checkpoint_state
from tensorflow.python.training.saver import export_meta_graph
from tensorflow.python.training.saver import import_meta_graph
from tensorflow.python.training.session_manager import SessionManager
from tensorflow.python.training.summary_io import summary_iterator
from tensorflow.python.training.summary_io import SummaryWriter
from tensorflow.python.training.supervisor import Supervisor
from tensorflow.python.training.training_util import write_graph
from tensorflow.python.training.training_util import global_step
from tensorflow.python.pywrap_tensorflow import NewCheckpointReader
# Training data protos.
from tensorflow.core.example.example_pb2 import *
from tensorflow.core.example.feature_pb2 import *
from tensorflow.core.protobuf.saver_pb2 import *
# Utility op. Open Source. TODO(touts): move to nn?
from tensorflow.python.training.learning_rate_decay import exponential_decay
# Distributed computing support
from tensorflow.core.protobuf.tensorflow_server_pb2 import ClusterDef
from tensorflow.core.protobuf.tensorflow_server_pb2 import JobDef
from tensorflow.core.protobuf.tensorflow_server_pb2 import ServerDef
from tensorflow.python.training.server_lib import ClusterSpec
from tensorflow.python.training.server_lib import Server
from tensorflow.python.util.all_util import make_all
# Include extra modules for docstrings because:
# * Input methods in tf.train are documented in io_ops.
# * Saver methods in tf.train are documented in state_ops.
__all__ = make_all(__name__, [sys.modules[__name__], io_ops, state_ops])
# Symbols whitelisted for export without documentation.
# TODO(cwhipkey): review these and move to contrib or expose through
# documentation.
__all__.extend([
"BytesList",
"Example",
"Feature",
"FeatureList",
"FeatureLists",
"Features",
"FloatList",
"Int64List",
"LooperThread",
"SaverDef",
"SequenceExample",
"export_meta_graph",
"generate_checkpoint_state_proto",
"import_meta_graph",
"queue_runner",
])
|
TakayukiSakai/tensorflow
|
tensorflow/python/training/training.py
|
Python
|
apache-2.0
| 8,011
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.ha.HAServiceProtocol;
import org.apache.hadoop.ha.HAServiceStatus;
import org.apache.hadoop.ha.HealthCheckFailedException;
import org.apache.hadoop.ha.ServiceFailedException;
import org.apache.hadoop.ha.proto.HAServiceProtocolProtos;
import org.apache.hadoop.ha.protocolPB.HAServiceProtocolPB;
import org.apache.hadoop.ha.protocolPB.HAServiceProtocolServerSideTranslatorPB;
import org.apache.hadoop.ipc.ProtobufRpcEngine;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RPC.Server;
import org.apache.hadoop.ipc.StandbyException;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.Groups;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.security.authorize.PolicyProvider;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.apache.hadoop.service.CompositeService;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.ResourceOption;
import org.apache.hadoop.yarn.conf.HAUtil;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.ipc.RPCUtil;
import org.apache.hadoop.yarn.ipc.YarnRPC;
import org.apache.hadoop.yarn.security.ConfiguredYarnAuthorizer;
import org.apache.hadoop.yarn.security.YarnAuthorizationProvider;
import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol;
import org.apache.hadoop.yarn.server.api.protocolrecords.AddToClusterNodeLabelsRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.AddToClusterNodeLabelsResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshQueuesRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshQueuesResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshServiceAclsRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshServiceAclsResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshSuperUserGroupsConfigurationRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshSuperUserGroupsConfigurationResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshUserToGroupsMappingsRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshUserToGroupsMappingsResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RemoveFromClusterNodeLabelsRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RemoveFromClusterNodeLabelsResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.ReplaceLabelsOnNodeRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.ReplaceLabelsOnNodeResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.UpdateNodeResourceRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.UpdateNodeResourceResponse;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSystem;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeResourceUpdateEvent;
import org.apache.hadoop.yarn.server.resourcemanager.security.authorize.RMPolicyProvider;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.BlockingService;
public class AdminService extends CompositeService implements
HAServiceProtocol, ResourceManagerAdministrationProtocol {
private static final Log LOG = LogFactory.getLog(AdminService.class);
private final RMContext rmContext;
private final ResourceManager rm;
private String rmId;
private boolean autoFailoverEnabled;
private EmbeddedElectorService embeddedElector;
private Server server;
// Address to use for binding. May be a wildcard address.
private InetSocketAddress masterServiceBindAddress;
private YarnAuthorizationProvider authorizer;
private final RecordFactory recordFactory =
RecordFactoryProvider.getRecordFactory(null);
public AdminService(ResourceManager rm, RMContext rmContext) {
super(AdminService.class.getName());
this.rm = rm;
this.rmContext = rmContext;
}
@Override
public void serviceInit(Configuration conf) throws Exception {
if (rmContext.isHAEnabled()) {
autoFailoverEnabled = HAUtil.isAutomaticFailoverEnabled(conf);
if (autoFailoverEnabled) {
if (HAUtil.isAutomaticFailoverEmbedded(conf)) {
embeddedElector = createEmbeddedElectorService();
addIfService(embeddedElector);
}
}
}
masterServiceBindAddress = conf.getSocketAddr(
YarnConfiguration.RM_BIND_HOST,
YarnConfiguration.RM_ADMIN_ADDRESS,
YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS,
YarnConfiguration.DEFAULT_RM_ADMIN_PORT);
authorizer = YarnAuthorizationProvider.getInstance(conf);
authorizer.setAdmins(new AccessControlList(conf.get(
YarnConfiguration.YARN_ADMIN_ACL,
YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)), UserGroupInformation
.getCurrentUser());
rmId = conf.get(YarnConfiguration.RM_HA_ID);
super.serviceInit(conf);
}
@Override
protected void serviceStart() throws Exception {
startServer();
super.serviceStart();
}
@Override
protected void serviceStop() throws Exception {
stopServer();
super.serviceStop();
}
protected void startServer() throws Exception {
Configuration conf = getConfig();
YarnRPC rpc = YarnRPC.create(conf);
this.server = (Server) rpc.getServer(
ResourceManagerAdministrationProtocol.class, this, masterServiceBindAddress,
conf, null,
conf.getInt(YarnConfiguration.RM_ADMIN_CLIENT_THREAD_COUNT,
YarnConfiguration.DEFAULT_RM_ADMIN_CLIENT_THREAD_COUNT));
// Enable service authorization?
if (conf.getBoolean(
CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION,
false)) {
refreshServiceAcls(
getConfiguration(conf,
YarnConfiguration.HADOOP_POLICY_CONFIGURATION_FILE),
RMPolicyProvider.getInstance());
}
if (rmContext.isHAEnabled()) {
RPC.setProtocolEngine(conf, HAServiceProtocolPB.class,
ProtobufRpcEngine.class);
HAServiceProtocolServerSideTranslatorPB haServiceProtocolXlator =
new HAServiceProtocolServerSideTranslatorPB(this);
BlockingService haPbService =
HAServiceProtocolProtos.HAServiceProtocolService
.newReflectiveBlockingService(haServiceProtocolXlator);
server.addProtocol(RPC.RpcKind.RPC_PROTOCOL_BUFFER,
HAServiceProtocol.class, haPbService);
}
this.server.start();
conf.updateConnectAddr(YarnConfiguration.RM_BIND_HOST,
YarnConfiguration.RM_ADMIN_ADDRESS,
YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS,
server.getListenerAddress());
}
protected void stopServer() throws Exception {
if (this.server != null) {
this.server.stop();
}
}
protected EmbeddedElectorService createEmbeddedElectorService() {
return new EmbeddedElectorService(rmContext);
}
@InterfaceAudience.Private
void resetLeaderElection() {
if (embeddedElector != null) {
embeddedElector.resetLeaderElection();
}
}
private UserGroupInformation checkAccess(String method) throws IOException {
return RMServerUtils.verifyAdminAccess(authorizer, method, LOG);
}
private UserGroupInformation checkAcls(String method) throws YarnException {
try {
return checkAccess(method);
} catch (IOException ioe) {
throw RPCUtil.getRemoteException(ioe);
}
}
/**
* Check that a request to change this node's HA state is valid.
* In particular, verifies that, if auto failover is enabled, non-forced
* requests from the HAAdmin CLI are rejected, and vice versa.
*
* @param req the request to check
* @throws AccessControlException if the request is disallowed
*/
private void checkHaStateChange(StateChangeRequestInfo req)
throws AccessControlException {
switch (req.getSource()) {
case REQUEST_BY_USER:
if (autoFailoverEnabled) {
throw new AccessControlException(
"Manual failover for this ResourceManager is disallowed, " +
"because automatic failover is enabled.");
}
break;
case REQUEST_BY_USER_FORCED:
if (autoFailoverEnabled) {
LOG.warn("Allowing manual failover from " +
org.apache.hadoop.ipc.Server.getRemoteAddress() +
" even though automatic failover is enabled, because the user " +
"specified the force flag");
}
break;
case REQUEST_BY_ZKFC:
if (!autoFailoverEnabled) {
throw new AccessControlException(
"Request from ZK failover controller at " +
org.apache.hadoop.ipc.Server.getRemoteAddress() + " denied " +
"since automatic failover is not enabled");
}
break;
}
}
private synchronized boolean isRMActive() {
return HAServiceState.ACTIVE == rmContext.getHAServiceState();
}
private void throwStandbyException() throws StandbyException {
throw new StandbyException("ResourceManager " + rmId + " is not Active!");
}
@Override
public synchronized void monitorHealth()
throws IOException {
checkAccess("monitorHealth");
if (isRMActive() && !rm.areActiveServicesRunning()) {
throw new HealthCheckFailedException(
"Active ResourceManager services are not running!");
}
}
@Override
public synchronized void transitionToActive(
HAServiceProtocol.StateChangeRequestInfo reqInfo) throws IOException {
// call refreshAdminAcls before HA state transition
// for the case that adminAcls have been updated in previous active RM
try {
refreshAdminAcls(false);
} catch (YarnException ex) {
throw new ServiceFailedException("Can not execute refreshAdminAcls", ex);
}
UserGroupInformation user = checkAccess("transitionToActive");
checkHaStateChange(reqInfo);
try {
rm.transitionToActive();
// call all refresh*s for active RM to get the updated configurations.
refreshAll();
RMAuditLogger.logSuccess(user.getShortUserName(),
"transitionToActive", "RMHAProtocolService");
} catch (Exception e) {
RMAuditLogger.logFailure(user.getShortUserName(), "transitionToActive",
"", "RMHAProtocolService",
"Exception transitioning to active");
throw new ServiceFailedException(
"Error when transitioning to Active mode", e);
}
}
@Override
public synchronized void transitionToStandby(
HAServiceProtocol.StateChangeRequestInfo reqInfo) throws IOException {
// call refreshAdminAcls before HA state transition
// for the case that adminAcls have been updated in previous active RM
try {
refreshAdminAcls(false);
} catch (YarnException ex) {
throw new ServiceFailedException("Can not execute refreshAdminAcls", ex);
}
UserGroupInformation user = checkAccess("transitionToStandby");
checkHaStateChange(reqInfo);
try {
rm.transitionToStandby(true);
RMAuditLogger.logSuccess(user.getShortUserName(),
"transitionToStandby", "RMHAProtocolService");
} catch (Exception e) {
RMAuditLogger.logFailure(user.getShortUserName(), "transitionToStandby",
"", "RMHAProtocolService",
"Exception transitioning to standby");
throw new ServiceFailedException(
"Error when transitioning to Standby mode", e);
}
}
@Override
public synchronized HAServiceStatus getServiceStatus() throws IOException {
checkAccess("getServiceState");
HAServiceState haState = rmContext.getHAServiceState();
HAServiceStatus ret = new HAServiceStatus(haState);
if (isRMActive() || haState == HAServiceProtocol.HAServiceState.STANDBY) {
ret.setReadyToBecomeActive();
} else {
ret.setNotReadyToBecomeActive("State is " + haState);
}
return ret;
}
@Override
public RefreshQueuesResponse refreshQueues(RefreshQueuesRequest request)
throws YarnException, StandbyException {
String argName = "refreshQueues";
final String msg = "refresh queues.";
UserGroupInformation user = checkAcls(argName);
checkRMStatus(user.getShortUserName(), argName, msg);
RefreshQueuesResponse response =
recordFactory.newRecordInstance(RefreshQueuesResponse.class);
try {
rmContext.getScheduler().reinitialize(getConfig(), this.rmContext);
// refresh the reservation system
ReservationSystem rSystem = rmContext.getReservationSystem();
if (rSystem != null) {
rSystem.reinitialize(getConfig(), rmContext);
}
RMAuditLogger.logSuccess(user.getShortUserName(), argName,
"AdminService");
return response;
} catch (IOException ioe) {
throw logAndWrapException(ioe, user.getShortUserName(), argName, msg);
}
}
@Override
public RefreshNodesResponse refreshNodes(RefreshNodesRequest request)
throws YarnException, StandbyException {
String argName = "refreshNodes";
final String msg = "refresh nodes.";
UserGroupInformation user = checkAcls("refreshNodes");
checkRMStatus(user.getShortUserName(), argName, msg);
try {
Configuration conf =
getConfiguration(new Configuration(false),
YarnConfiguration.YARN_SITE_CONFIGURATION_FILE);
rmContext.getNodesListManager().refreshNodes(conf);
RMAuditLogger.logSuccess(user.getShortUserName(), argName,
"AdminService");
return recordFactory.newRecordInstance(RefreshNodesResponse.class);
} catch (IOException ioe) {
throw logAndWrapException(ioe, user.getShortUserName(), argName, msg);
}
}
@Override
public RefreshSuperUserGroupsConfigurationResponse refreshSuperUserGroupsConfiguration(
RefreshSuperUserGroupsConfigurationRequest request)
throws YarnException, IOException {
String argName = "refreshSuperUserGroupsConfiguration";
UserGroupInformation user = checkAcls(argName);
checkRMStatus(user.getShortUserName(), argName, "refresh super-user-groups.");
// Accept hadoop common configs in core-site.xml as well as RM specific
// configurations in yarn-site.xml
Configuration conf =
getConfiguration(new Configuration(false),
YarnConfiguration.CORE_SITE_CONFIGURATION_FILE,
YarnConfiguration.YARN_SITE_CONFIGURATION_FILE);
RMServerUtils.processRMProxyUsersConf(conf);
ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
RMAuditLogger.logSuccess(user.getShortUserName(),
argName, "AdminService");
return recordFactory.newRecordInstance(
RefreshSuperUserGroupsConfigurationResponse.class);
}
@Override
public RefreshUserToGroupsMappingsResponse refreshUserToGroupsMappings(
RefreshUserToGroupsMappingsRequest request)
throws YarnException, IOException {
String argName = "refreshUserToGroupsMappings";
UserGroupInformation user = checkAcls(argName);
checkRMStatus(user.getShortUserName(), argName, "refresh user-groups.");
Groups.getUserToGroupsMappingService(
getConfiguration(new Configuration(false),
YarnConfiguration.CORE_SITE_CONFIGURATION_FILE)).refresh();
RMAuditLogger.logSuccess(user.getShortUserName(), argName, "AdminService");
return recordFactory.newRecordInstance(
RefreshUserToGroupsMappingsResponse.class);
}
@Override
public RefreshAdminAclsResponse refreshAdminAcls(
RefreshAdminAclsRequest request) throws YarnException, IOException {
return refreshAdminAcls(true);
}
private RefreshAdminAclsResponse refreshAdminAcls(boolean checkRMHAState)
throws YarnException, IOException {
String argName = "refreshAdminAcls";
UserGroupInformation user = checkAcls(argName);
if (checkRMHAState) {
checkRMStatus(user.getShortUserName(), argName, "refresh Admin ACLs.");
}
Configuration conf =
getConfiguration(new Configuration(false),
YarnConfiguration.YARN_SITE_CONFIGURATION_FILE);
authorizer.setAdmins(new AccessControlList(conf.get(
YarnConfiguration.YARN_ADMIN_ACL,
YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)), UserGroupInformation
.getCurrentUser());
RMAuditLogger.logSuccess(user.getShortUserName(), argName,
"AdminService");
return recordFactory.newRecordInstance(RefreshAdminAclsResponse.class);
}
@Override
public RefreshServiceAclsResponse refreshServiceAcls(
RefreshServiceAclsRequest request) throws YarnException, IOException {
if (!getConfig().getBoolean(
CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION,
false)) {
throw RPCUtil.getRemoteException(
new IOException("Service Authorization (" +
CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION +
") not enabled."));
}
String argName = "refreshServiceAcls";
UserGroupInformation user = checkAcls(argName);
checkRMStatus(user.getShortUserName(), argName, "refresh Service ACLs.");
PolicyProvider policyProvider = RMPolicyProvider.getInstance();
Configuration conf =
getConfiguration(new Configuration(false),
YarnConfiguration.HADOOP_POLICY_CONFIGURATION_FILE);
refreshServiceAcls(conf, policyProvider);
rmContext.getClientRMService().refreshServiceAcls(conf, policyProvider);
rmContext.getApplicationMasterService().refreshServiceAcls(
conf, policyProvider);
rmContext.getResourceTrackerService().refreshServiceAcls(
conf, policyProvider);
RMAuditLogger.logSuccess(user.getShortUserName(), argName, "AdminService");
return recordFactory.newRecordInstance(RefreshServiceAclsResponse.class);
}
private synchronized void refreshServiceAcls(Configuration configuration,
PolicyProvider policyProvider) {
this.server.refreshServiceAclWithLoadedConfiguration(configuration,
policyProvider);
}
@Override
public String[] getGroupsForUser(String user) throws IOException {
return UserGroupInformation.createRemoteUser(user).getGroupNames();
}
@SuppressWarnings("unchecked")
@Override
public UpdateNodeResourceResponse updateNodeResource(
UpdateNodeResourceRequest request) throws YarnException, IOException {
String argName = "updateNodeResource";
UserGroupInformation user = checkAcls(argName);
checkRMStatus(user.getShortUserName(), argName, "update node resource.");
Map<NodeId, ResourceOption> nodeResourceMap = request.getNodeResourceMap();
Set<NodeId> nodeIds = nodeResourceMap.keySet();
// verify nodes are all valid first.
// if any invalid nodes, throw exception instead of partially updating
// valid nodes.
for (NodeId nodeId : nodeIds) {
RMNode node = this.rmContext.getRMNodes().get(nodeId);
if (node == null) {
LOG.error("Resource update get failed on all nodes due to change "
+ "resource on an unrecognized node: " + nodeId);
throw RPCUtil.getRemoteException(
"Resource update get failed on all nodes due to change resource "
+ "on an unrecognized node: " + nodeId);
}
}
// do resource update on each node.
// Notice: it is still possible to have invalid NodeIDs as nodes decommission
// may happen just at the same time. This time, only log and skip absent
// nodes without throwing any exceptions.
boolean allSuccess = true;
for (Map.Entry<NodeId, ResourceOption> entry : nodeResourceMap.entrySet()) {
ResourceOption newResourceOption = entry.getValue();
NodeId nodeId = entry.getKey();
RMNode node = this.rmContext.getRMNodes().get(nodeId);
if (node == null) {
LOG.warn("Resource update get failed on an unrecognized node: " + nodeId);
allSuccess = false;
} else {
// update resource to RMNode
this.rmContext.getDispatcher().getEventHandler()
.handle(new RMNodeResourceUpdateEvent(nodeId, newResourceOption));
LOG.info("Update resource on node(" + node.getNodeID()
+ ") with resource(" + newResourceOption.toString() + ")");
}
}
if (allSuccess) {
RMAuditLogger.logSuccess(user.getShortUserName(), argName,
"AdminService");
}
UpdateNodeResourceResponse response =
UpdateNodeResourceResponse.newInstance();
return response;
}
private synchronized Configuration getConfiguration(Configuration conf,
String... confFileNames) throws YarnException, IOException {
for (String confFileName : confFileNames) {
InputStream confFileInputStream = this.rmContext.getConfigurationProvider()
.getConfigurationInputStream(conf, confFileName);
if (confFileInputStream != null) {
conf.addResource(confFileInputStream);
}
}
return conf;
}
private void refreshAll() throws ServiceFailedException {
try {
refreshQueues(RefreshQueuesRequest.newInstance());
refreshNodes(RefreshNodesRequest.newInstance());
refreshSuperUserGroupsConfiguration(
RefreshSuperUserGroupsConfigurationRequest.newInstance());
refreshUserToGroupsMappings(
RefreshUserToGroupsMappingsRequest.newInstance());
if (getConfig().getBoolean(
CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION,
false)) {
refreshServiceAcls(RefreshServiceAclsRequest.newInstance());
}
} catch (Exception ex) {
throw new ServiceFailedException(ex.getMessage());
}
}
// only for testing
@VisibleForTesting
public AccessControlList getAccessControlList() {
return ((ConfiguredYarnAuthorizer)authorizer).getAdminAcls();
}
@VisibleForTesting
public Server getServer() {
return this.server;
}
@Override
public AddToClusterNodeLabelsResponse addToClusterNodeLabels(AddToClusterNodeLabelsRequest request)
throws YarnException, IOException {
String argName = "addToClusterNodeLabels";
final String msg = "add labels.";
UserGroupInformation user = checkAcls(argName);
checkRMStatus(user.getShortUserName(), argName, msg);
AddToClusterNodeLabelsResponse response =
recordFactory.newRecordInstance(AddToClusterNodeLabelsResponse.class);
try {
rmContext.getNodeLabelManager().addToCluserNodeLabels(request.getNodeLabels());
RMAuditLogger
.logSuccess(user.getShortUserName(), argName, "AdminService");
return response;
} catch (IOException ioe) {
throw logAndWrapException(ioe, user.getShortUserName(), argName, msg);
}
}
@Override
public RemoveFromClusterNodeLabelsResponse removeFromClusterNodeLabels(
RemoveFromClusterNodeLabelsRequest request) throws YarnException, IOException {
String argName = "removeFromClusterNodeLabels";
final String msg = "remove labels.";
UserGroupInformation user = checkAcls(argName);
checkRMStatus(user.getShortUserName(), argName, msg);
RemoveFromClusterNodeLabelsResponse response =
recordFactory.newRecordInstance(RemoveFromClusterNodeLabelsResponse.class);
try {
rmContext.getNodeLabelManager().removeFromClusterNodeLabels(request.getNodeLabels());
RMAuditLogger
.logSuccess(user.getShortUserName(), argName, "AdminService");
return response;
} catch (IOException ioe) {
throw logAndWrapException(ioe, user.getShortUserName(), argName, msg);
}
}
@Override
public ReplaceLabelsOnNodeResponse replaceLabelsOnNode(
ReplaceLabelsOnNodeRequest request) throws YarnException, IOException {
String argName = "replaceLabelsOnNode";
final String msg = "set node to labels.";
UserGroupInformation user = checkAcls(argName);
checkRMStatus(user.getShortUserName(), argName, msg);
ReplaceLabelsOnNodeResponse response =
recordFactory.newRecordInstance(ReplaceLabelsOnNodeResponse.class);
try {
rmContext.getNodeLabelManager().replaceLabelsOnNode(
request.getNodeToLabels());
RMAuditLogger
.logSuccess(user.getShortUserName(), argName, "AdminService");
return response;
} catch (IOException ioe) {
throw logAndWrapException(ioe, user.getShortUserName(), argName, msg);
}
}
private void checkRMStatus(String user, String argName, String msg)
throws StandbyException {
if (!isRMActive()) {
RMAuditLogger.logFailure(user, argName, "",
"AdminService", "ResourceManager is not active. Can not " + msg);
throwStandbyException();
}
}
private YarnException logAndWrapException(IOException ioe, String user,
String argName, String msg) throws YarnException {
LOG.info("Exception " + msg, ioe);
RMAuditLogger.logFailure(user, argName, "",
"AdminService", "Exception " + msg);
return RPCUtil.getRemoteException(ioe);
}
}
|
zjshen/hadoop-in-docker
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java
|
Java
|
apache-2.0
| 26,917
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id: SimplePlanDrawer.java 627367 2008-02-13 12:03:30Z maxberger $ */
package org.apache.fop.plan;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.fop.svg.SVGUtilities;
/**
* Simple plan drawer implementation.
*/
public class SimplePlanDrawer implements PlanDrawer {
private static final String SVG_NAMESPACE = SVGDOMImplementation.SVG_NAMESPACE_URI;
private float fontSize;
private HashMap hints;
private java.awt.Font font = null;
private boolean bord = false;
private float lSpace = 15;
private float width;
private float height;
private float topEdge;
private float rightEdge;
private String[] colours;
private String[] darkcolours;
private Date startDate;
private Date endDate;
/**
* Sets the start date.
* @param sd start date
*/
public void setStartDate(Date sd) {
startDate = sd;
}
/**
* Sets the end date.
* @param ed end date
*/
public void setEndDate(Date ed) {
endDate = ed;
}
/**
* @see org.apache.fop.plan.PlanDrawer#createDocument(EventList, float, float, HashMap)
*/
public Document createDocument(EventList data, float w, float h,
HashMap hints) {
this.width = w;
this.height = h;
this.hints = hints;
fontSize = ((Float) hints.get(PlanHints.FONT_SIZE)).floatValue();
bord = ((Boolean) hints.get(PlanHints.PLAN_BORDER)).booleanValue();
String title = "";
DOMImplementation impl =
SVGDOMImplementation.getDOMImplementation();
Document doc = impl.createDocument(SVG_NAMESPACE, "svg", null);
Element svgRoot = doc.getDocumentElement();
svgRoot.setAttributeNS(null, "width", "" + width);
svgRoot.setAttributeNS(null, "height", "" + height);
svgRoot.setAttributeNS(null, "style",
"font-size:" + 8
+ ";font-family:"
+ hints.get(PlanHints.FONT_FAMILY));
font = new java.awt.Font((String)hints.get(PlanHints.FONT_FAMILY),
java.awt.Font.PLAIN, (int)fontSize);
if (bord) {
Element border =
SVGUtilities.createRect(doc, 0, 0, width, height);
border.setAttributeNS(null, "style", "stroke:black;fill:none");
svgRoot.appendChild(border);
}
float strwidth = SVGUtilities.getStringWidth(title, font);
Element text;
float pos = (float)(80 - strwidth / 2.0);
if (pos < 5) {
pos = 5;
}
text = SVGUtilities.createText(doc, pos, 18, title);
text.setAttributeNS(null, "style", "font-size:14");
svgRoot.appendChild(text);
topEdge = SVGUtilities.getStringHeight(title, font) + 5;
// add the actual pie chart
addPlan(doc, svgRoot, data);
//addLegend(doc, svgRoot, data);
return doc;
}
protected void addPlan(Document doc, Element svgRoot, EventList data) {
Date currentDate = new Date();
Date lastWeek = startDate;
Date future = endDate;
Calendar lw = Calendar.getInstance();
if (lastWeek == null || future == null) {
int dow = lw.get(Calendar.DAY_OF_WEEK);
lw.add(Calendar.DATE, -dow - 6);
lastWeek = lw.getTime();
lw.add(Calendar.DATE, 5 * 7);
future = lw.getTime();
}
long totalDays = (long)((future.getTime() - lastWeek.getTime() + 43200000) / 86400000);
lw.setTime(lastWeek);
int startDay = lw.get(Calendar.DAY_OF_WEEK);
float graphTop = topEdge;
Element g;
Element line;
line = SVGUtilities.createLine(doc, 0, topEdge, width, topEdge);
line.setAttributeNS(null, "style", "fill:none;stroke:black");
svgRoot.appendChild(line);
Element clip1 = SVGUtilities.createClip(doc,
SVGUtilities.createPath(doc,
"m0 0l126 0l0 " + height + "l-126 0z"), "clip1");
Element clip2 = SVGUtilities.createClip(doc,
SVGUtilities.createPath(doc,
"m130 0l66 0l0 " + height + "l-66 0z"), "clip2");
Element clip3 = SVGUtilities.createClip(doc,
SVGUtilities.createPath(doc,
"m200 0l" + (width - 200) + " 0l0 " + height + "l-"
+ (width - 200) + " 0z"), "clip3");
svgRoot.appendChild(clip1);
svgRoot.appendChild(clip2);
svgRoot.appendChild(clip3);
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Element text;
text = SVGUtilities.createText(doc, 201, topEdge - 1,
df.format(lastWeek));
svgRoot.appendChild(text);
text = SVGUtilities.createText(doc, width, topEdge - 1,
df.format(future));
text.setAttributeNS(null, "text-anchor", "end");
svgRoot.appendChild(text);
line = SVGUtilities.createLine(doc, 128, topEdge, 128, height);
line.setAttributeNS(null, "style", "fill:none;stroke:rgb(150,150,150)");
svgRoot.appendChild(line);
int offset = 0;
for (int count = startDay; count < startDay + totalDays - 1; count++) {
offset++;
if (count % 7 == 0 || count % 7 == 1) {
Element rect = SVGUtilities.createRect(doc,
200 + (offset - 1) * (width - 200) / (totalDays - 2),
(float)(topEdge + 0.5),
(width - 200) / (totalDays - 3),
height - 1 - topEdge);
rect.setAttributeNS(null, "style", "stroke:none;fill:rgb(230,230,230)");
svgRoot.appendChild(rect);
}
line = SVGUtilities.createLine(doc,
200 + (offset - 1) * (width - 200) / (totalDays - 2),
(float)(topEdge + 0.5),
200 + (offset - 1) * (width - 200) / (totalDays - 2),
(float)(height - 0.5));
line.setAttributeNS(null, "style", "fill:none;stroke:rgb(200,200,200)");
svgRoot.appendChild(line);
}
for (int count = 0; count < data.getSize(); count++) {
GroupInfo gi = data.getGroupInfo(count);
g = SVGUtilities.createG(doc);
text = SVGUtilities.createText(doc, 1, topEdge + 12,
gi.getName());
text.setAttributeNS(null, "style", "clip-path:url(#clip1)");
g.appendChild(text);
if (count > 0) {
line = SVGUtilities.createLine(doc, 0, topEdge + 2,
width, topEdge + 2);
line.setAttributeNS(null, "style", "fill:none;stroke:rgb(100,100,100)");
g.appendChild(line);
}
float lastTop = topEdge;
topEdge += 14;
boolean showing = false;
for (int count1 = 0; count1 < gi.getSize(); count1++) {
ActionInfo act = gi.getActionInfo(count1);
String name = act.getOwner();
String label = act.getLabel();
text = SVGUtilities.createText(doc, 8, topEdge + 12, label);
text.setAttributeNS(null, "style", "clip-path:url(#clip1)");
g.appendChild(text);
text = SVGUtilities.createText(doc, 130, topEdge + 12,
name);
text.setAttributeNS(null, "style", "clip-path:url(#clip2)");
g.appendChild(text);
int type = act.getType();
Date start = act.getStartDate();
Date end = act.getEndDate();
if (end.after(lastWeek) && start.before(future)) {
showing = true;
int left = 200;
int right = 500;
int daysToStart = (int)((start.getTime()
- lastWeek.getTime() + 43200000) / 86400000);
int days = (int)((end.getTime() - start.getTime()
+ 43200000) / 86400000);
int daysFromEnd =
(int)((future.getTime() - end.getTime()
+ 43200000) / 86400000);
Element taskGraphic;
switch (type) {
case ActionInfo.TASK:
taskGraphic = SVGUtilities.createRect(doc,
left + daysToStart * 300 / (totalDays - 2),
topEdge + 2, days * 300 / (totalDays - 2), 10);
taskGraphic.setAttributeNS(null,
"style",
"stroke:black;fill:blue;stroke-width:1;clip-path:url(#clip3)");
g.appendChild(taskGraphic);
break;
case ActionInfo.MILESTONE:
taskGraphic = SVGUtilities.createPath(doc,
"m " + (left
+ daysToStart * 300 / (totalDays - 2) - 6)
+ " " + (topEdge + 6) + "l6 6l6-6l-6-6z");
taskGraphic.setAttributeNS(null,
"style",
"stroke:black;fill:black;stroke-width:1;clip-path:url(#clip3)");
g.appendChild(taskGraphic);
text = SVGUtilities.createText(doc,
left + daysToStart * 300 / (totalDays - 2) + 8,
topEdge + 9, df.format(start));
g.appendChild(text);
break;
case ActionInfo.GROUPING:
taskGraphic = SVGUtilities.createPath(doc,
"m " + (left
+ daysToStart * 300 / (totalDays - 2) - 6)
+ " " + (topEdge + 6) + "l6 -6l"
+ (days * 300 / (totalDays - 2))
+ " 0l6 6l-6 6l-4-4l"
+ -(days * 300 / (totalDays - 2) - 8)
+ " 0l-4 4l-6-6z");
taskGraphic.setAttributeNS(null,
"style",
"stroke:black;fill:black;stroke-width:1;clip-path:url(#clip3)");
g.appendChild(taskGraphic);
break;
default:
break;
}
}
topEdge += 14;
}
if (showing) {
svgRoot.appendChild(g);
} else {
topEdge = lastTop;
}
}
int currentDays =
(int)((currentDate.getTime() - lastWeek.getTime()
+ 43200000) / 86400000);
text = SVGUtilities.createText(doc,
(float)(200 + (currentDays + 0.5) * 300 / 35),
graphTop - 1, df.format(currentDate));
text.setAttributeNS(null, "text-anchor", "middle");
text.setAttributeNS(null, "style", "stroke:rgb(100,100,100)");
svgRoot.appendChild(text);
line = SVGUtilities.createLine(doc,
(float)(200 + (currentDays + 0.5) * 300 / 35), graphTop,
(float)(200 + (currentDays + 0.5) * 300 / 35), height);
line.setAttributeNS(null, "style", "fill:none;stroke:rgb(200,50,50);stroke-dasharray:5,5");
svgRoot.appendChild(line);
}
}
|
tavultesoft/keymanweb
|
windows/src/ext/docbook/fop/fop-0.95/examples/plan/src/org/apache/fop/plan/SimplePlanDrawer.java
|
Java
|
apache-2.0
| 13,179
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
author: sanja7s
---------------
plot the distribution
"""
import os
import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from collections import defaultdict
from matplotlib import colors
from pylab import MaxNLocator
import pylab as pl
from mpl_toolkits.axes_grid import inset_locator
matplotlib.style.use('ggplot')
IN_DIR = "../../data/timelines"
os.chdir(IN_DIR)
font = {'family' : 'sans-serif',
'variant' : 'normal',
'weight' : 'light',
'size' : 14}
grid = {'color' : 'gray',
'alpha' : 0.5,
'linestyle' : '-.'}
lines = {'color' : 'gray'}
#xticks = {'color' : 'gray'}
matplotlib.rc('font', **font)
matplotlib.rc('grid', **grid)
matplotlib.rc('lines', **lines)
#matplotlib.rc('ticks', **ticks)
def read_in_plug_data(node):
f_in = 'node_' + node +'_plug.csv'
distr = defaultdict(int)
with open(f_in, 'r') as f:
for line in f:
# n are irrelevant
n, n, n, t, n, plug, n, n, n = line.strip().split('"')
t = dt.datetime.fromtimestamp(int(t))
plug = float(plug)
distr[t] = plug
return distr
def read_in_num_jobs_data(node):
f_in = 'node_' + node +'_plug.csv'
distr = defaultdict(int)
with open(f_in, 'r') as f:
for line in f:
n, n, n, t, n, n, n, jobs_list, n6 = line.strip().split('"')
t = dt.datetime.fromtimestamp(int(t))
jobs = jobs_list.split(',')
if jobs_list == "":
distr[t] = 0
else:
distr[t] = len(jobs)
return distr
def read_in_CPU_data(node):
f_in = 'node_' + node +'_CPUMEM.csv'
distr = defaultdict(int)
with open(f_in, 'r') as f:
for line in f:
n, n, n, t, n, n, n, CPU1, n, CPU2, n, n, n, n, n = line.strip().split('"')
t = dt.datetime.fromtimestamp(int(t))
CPU1 = float(CPU1)
CPU2 = float(CPU2)
distr[t] = (CPU1, CPU2)
return distr
def read_in_MEM_data(node):
f_in = 'node_' + node +'_CPUMEM.csv'
distr = defaultdict(int)
with open(f_in, 'r') as f:
for line in f:
n, n, n, t, n, n, n, n, n, n, n, MEM1, n, MEM2, n = line.strip().split('"')
t = dt.datetime.fromtimestamp(int(t))
MEM1 = float(MEM1)
MEM2 = float(MEM2)
distr[t] = (MEM1, MEM2)
return distr
def read_in_rb_data(node):
f_in = 'node_' + node +'_rb.csv'
distr = defaultdict(int)
with open(f_in, 'r') as f:
for line in f:
n, n, n, t, n, n, n, r, n, b, n = line.strip().split('"')
t = dt.datetime.fromtimestamp(int(t))
r = int(r)
b = int(b)
distr[t] = (r, b)
return distr
def plot_plug_timeline(node):
print 'Plotting plug values'
d = read_in_plug_data(node)
dates = d.keys()
X = pd.to_datetime(dates)
values = [v if v > 0 else 0 for v in d.values()]
start_time = min(dates)
end_time = max(dates)
print start_time, end_time
print min(values), max(values)
fig, ax = plt.subplots()
ax.scatter(X, values, marker='s', s=1)
#ax.plot(X, values)
fig.autofmt_xdate()
ax.set_xlabel('time')
ax.set_ylabel('plug value')
plt.xlim(pd.to_datetime(start_time), pd.to_datetime(end_time))
#plt.show()
plt.savefig('plug_timeline_node_' + node + '.png')
return fig, ax, plt
def plot_plug_timeline_v2(node):
print 'Plotting plug values'
d = read_in_plug_data(node)
dates = d.keys()
X = pd.to_datetime(dates)
values = [v if v > 0 else 0 for v in d.values()]
ts = pd.Series(values, index = X)
start_time = min(dates)
end_time = max(dates)
print start_time, end_time
print min(values), max(values)
fig, ax = plt.subplots()
ts.plot(color = 'darkblue')
for tl in ax.get_yticklabels():
tl.set_color('darkblue')
fig.autofmt_xdate()
ax.set_xlabel('time')
ax.set_ylabel('plug value', color='darkblue')
plt.xlim(pd.to_datetime(start_time), pd.to_datetime(end_time))
ymin = 240
ymax = 280
if min(values) < 160:
ymin = min(values) - 10
if max(values) > 250:
ymax = max(values) + 10
plt.ylim(ymin, ymax)
#plt.savefig(cwd + '/multiple_v2/plug_only/plug_timeline_node_' + node + '_v2.png')
return fig, ax, plt
def plot_plug_and_num_jobs_timeline(node):
print 'Plotting num of jobs values'
d = read_in_num_jobs_data(node)
dates = d.keys()
X = pd.to_datetime(dates)
values = d.values()
start_time = min(dates)
end_time = max(dates)
print start_time, end_time
print min(values), max(values)
fig, ax1, plt = plot_plug_timeline_v2(node)
ax2 = ax1.twinx()
ax2.scatter(X, values,
marker='s', color='red', s=7)
ax2.set_ylabel('# of jobs', color='red')
ya = ax2.get_yaxis()
ya.set_major_locator(MaxNLocator(integer=True))
plt.xlim(pd.to_datetime(start_time), pd.to_datetime(end_time))
for tl in ax2.get_yticklabels():
tl.set_color('r')
cwd = os.getcwd()
print cwd
plt.savefig(cwd + '/lowest_norm_stdev/SandyBridge/num_jobs_and_plug_timeline_node_' + node + '_v2.png')
def plot_plug_and_CPUs_timeline(node):
print 'Plotting CPUs values'
d = read_in_CPU_data(node)
dates = d.keys()
X = pd.to_datetime(dates)
values1 = []
values2 = []
for el in d.values():
if el[0] > 0:
v1 = el[0]
else:
v1 = 0
values1.append(v1)
if el[1] > 0:
v2 = el[1]
else:
v2 = 0
values2.append(v2)
start_time = min(dates)
end_time = max(dates)
print start_time, end_time
print 'Min and max CPU1 ', min(values1), max(values1)
print 'Min and max CPU2 ', min(values2), max(values2)
fig, ax1, plt = plot_plug_timeline_v2(node)
ax2 = ax1.twinx()
ts1 = pd.Series(values1, index = X)
ax2.scatter(X, values1, marker='s', color='red', s=4, label = 'CPU1')
#ts1.plot(color='red', label = 'CPU1')
ts2 = pd.Series(values2, index = X)
ax2.scatter(X, values2, marker='s', color='magenta', s=4, label = 'CPU2')
#ts2.plot(color='magenta', label = 'CPU2')
ax2.set_ylabel('CPU values', color='red')
ya = ax2.get_yaxis()
ya.set_major_locator(MaxNLocator(integer=True))
plt.xlim(pd.to_datetime(start_time), pd.to_datetime(end_time))
for tl in ax2.get_yticklabels():
tl.set_color('r')
handles, labels = ax2.get_legend_handles_labels()
l = ax2.legend(handles, labels, loc=3)
for text in l.get_texts():
text.set_color('gray')
plt.savefig('lowest_norm_stdev/SandyBridge/CPUs_plug_timeline_node_' + node + '.png')
def plot_plug_and_MEM_timeline(node):
print 'Plotting DRAM values'
d = read_in_MEM_data(node)
dates = d.keys()
X = pd.to_datetime(dates)
values1 = [v[0] if v[0] > -1 else -1 for v in d.values()]
values2 = [v[1] if v[1] > -1 else -1 for v in d.values()]
start_time = min(dates)
end_time = max(dates)
print start_time, end_time
print 'Min and max MEM1 ', min(values1), max(values1)
print 'Min and max MEM2 ', min(values2), max(values2)
fig, ax1, plt = plot_plug_timeline(node)
ax2 = ax1.twinx()
ax2.scatter(X, values1,
marker='s', color='darkgreen', s=4, label = 'DRAM1')
ax2.scatter(X, values2,
marker='s', color='olive', s=4, label = 'DRAM2')
ax2.set_ylabel('DRAM values', color='olive')
plt.xlim(pd.to_datetime(start_time), pd.to_datetime(end_time))
for tl in ax2.get_yticklabels():
tl.set_color('olive')
handles, labels = ax2.get_legend_handles_labels()
l = ax2.legend(handles, labels, loc=1)
for text in l.get_texts():
text.set_color('gray')
plt.savefig('MEM_plug_timeline_node_' + node + '.png')
def plot_plug_and_rb_timeline(node):
print 'Plotting r b values'
d = read_in_rb_data(node)
dates = d.keys()
X = pd.to_datetime(dates)
values1 = [v[0] if v[0] > 0 else 0 for v in d.values()]
values2 = [v[1] if v[1] > 0 else 0 for v in d.values()]
start_time = min(dates)
end_time = max(dates)
print start_time, end_time
print 'Min and max MEM1 ', min(values1), max(values1)
print 'Min and max MEM2 ', min(values2), max(values2)
fig, ax1, plt = plot_plug_timeline(node)
ax2 = ax1.twinx()
ax2.scatter(X, values1,
marker='s', color='tomato', s=3, label = 'r')
ax2.scatter(X, values2,
marker='s', color='sage', s=3, label = 'b')
ax2.set_ylabel('r and b values', color='sage')
ya = ax2.get_yaxis()
ya.set_major_locator(MaxNLocator(integer=True))
plt.xlim(pd.to_datetime(start_time), pd.to_datetime(end_time))
for tl in ax2.get_yticklabels():
tl.set_color('sage')
handles, labels = ax2.get_legend_handles_labels()
l = ax2.legend(handles, labels, loc=1)
for text in l.get_texts():
text.set_color('gray')
plt.savefig('rb_plug_timeline_node_' + node + '.png')
#plot_plug_and_num_jobs_timeline('c48')
#plot_plug_and_num_jobs_timeline('c578')
#plot_plug_and_num_jobs_timeline('c578')
#plot_plug_and_CPUs_timeline('c577')
"""
plot_plug_and_MEM_timeline('c48')
plot_plug_and_MEM_timeline('c577')
plot_plug_and_MEM_timeline('c31')
plot_plug_and_MEM_timeline('c63')
plot_plug_and_MEM_timeline('c750')
plot_plug_and_MEM_timeline('c34')
"""
"""
plot_plug_and_rb_timeline('c48')
plot_plug_and_rb_timeline('c577')
plot_plug_and_rb_timeline('c31')
plot_plug_and_rb_timeline('c63')
plot_plug_and_rb_timeline('c750')
plot_plug_and_rb_timeline('c34')
"""
"""
# for the nodes running only one job
plot_plug_timeline('c424')
plot_plug_and_num_jobs_timeline('c424')
"""
# this is for the only node that did not run any jobs
#plot_plug_and_num_jobs_timeline('c42')
#plot_plug_timeline_v2('c42')
"""
# for random nodes
for node in [ 'c31', 'c34', 'c42', 'c48', 'c63', 'c329', 'c424', \
'c577', 'c578', 'c604', 'c672', 'c735', 'c750']:
#plot_plug_timeline_v2(node)
plot_plug_and_num_jobs_timeline(node)
"""
# for the nodes running only one unique (same) job all the time
#plot_plug_timeline('c7')
#plot_plug_and_num_jobs_timeline('c7')
"""
for node in ['c9', 'c10', 'c11', 'c12', 'c13', 'c16', 'c18', 'c19', 'c20']:
#plot_plug_timeline_v2(node)
#plot_plug_and_num_jobs_timeline(node)
plot_plug_and_CPUs_timeline(node)
"""
#plot_plug_and_CPUs_timeline('c4')
"""
# these nodes have the highest normalized stdev of plug
for node in ['c849', 'c666', 'c747', 'c908', 'c658', 'c620', 'c85', 'c364']:
#plot_plug_timeline_v2(node)
plot_plug_and_num_jobs_timeline(node)
plot_plug_and_CPUs_timeline(node)
"""
"""
# these are some of the nodes that have the smallest normalized stdev of plug
# SandyBridge
for node in ['c423']:
#plot_plug_timeline_v2(node)
plot_plug_and_num_jobs_timeline(node)
plot_plug_and_CPUs_timeline(node)
"""
|
sanja7s/EEDC
|
src/timelines/node_plug_timeline.py
|
Python
|
apache-2.0
| 10,157
|
/*
* Copyright 2008 Philip van Oosten (Mentoring Systems BVBA)
*
* 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 longbow.core;
import static junit.framework.Assert.*;
import static org.easymock.EasyMock.*;
import longbow.*;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Philip van Oosten
*
*/
public class DefaultLongbowFactoryTest {
private LongbowFactory factory;
@Before
public void setUp() {
factory = new DefaultLongbowFactory();
}
@Test
public void testCreateDataNode() {
final Metadata metadata = createMock(Metadata.class);
replay(metadata);
final DataNode node = factory.createDataNode(metadata);
assertTrue(node instanceof DefaultDataNode);
}
@Test
public void testCreateDataWrapper() {
final DataWrapper wrapper = factory.createDataWrapper();
assertTrue(wrapper instanceof DefaultDataWrapper);
assertNull(wrapper.getData());
}
@Test
public void testCreateInput() {
final TransformationContext context = createMock(TransformationContext.class);
final Metadata metadata = createMock(Metadata.class);
replay(context, metadata);
final Input input = factory.createInput(context, metadata);
assertTrue(input instanceof DefaultInput);
assertNull(input.getConnection());
assertSame(metadata, input.getMetadata());
assertSame(context, input.getTransformationContext());
assertFalse(input.isConnected());
assertFalse(input.isOptional());
verify(context, metadata);
}
@Test
public void testCreateOutput() {
final TransformationContext context = createMock(TransformationContext.class);
final Metadata metadata = createMock(Metadata.class);
replay(context, metadata);
final Output output = factory.createOutput(context, metadata);
assertTrue(output instanceof DefaultOutput);
assertNull(output.getConnection());
assertSame(metadata, output.getMetadata());
assertSame(context, output.getTransformationContext());
assertFalse(output.isConnected());
assertFalse(output.isOptional());
verify(context, metadata);
}
@Test
public void testCreateRunner() {
final Workflow workflow = createMock(Workflow.class);
replay(workflow);
final Runner runner = factory.createRunner(workflow);
assertTrue(runner instanceof DefaultRunner);
verify(workflow);
}
@Test
public void testCreateTransformationContext() {
// factory.createTransformationContext(workflow)
}
@Test
public void testCreateWorkflow() {
final Workflow workflow = factory.createWorkflow();
assertEquals(0, workflow.size());
assertTrue(workflow.isEmpty());
assertTrue(workflow instanceof DefaultWorkflow);
}
@Test
public void testEquals() {
}
@Test
public void testToString() {
}
}
|
pvoosten/Longbow
|
test/longbow/core/DefaultLongbowFactoryTest.java
|
Java
|
apache-2.0
| 3,205
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_32) on Tue Jun 18 11:08:46 PDT 2013 -->
<TITLE>
DeleteUserRequest (AWS SDK for Java - 1.4.7)
</TITLE>
<META NAME="date" CONTENT="2013-06-18">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../JavaDoc.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DeleteUserRequest (AWS SDK for Java - 1.4.7)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<span id="feedback_section"><h3>Did this page help you?</h3> <a id="feedback_yes" target="_blank">Yes</a> <a id="feedback_no" target="_blank">No</a> <a id="go_cti" target="_blank">Tell us about it...</a></span>
<script type="text/javascript">
var javadoc_root_name = "/javadoc/";
var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length);
var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length);
var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id=";
var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id=";
var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name=";
if(file_path != "overview-frame.html") {
var file_name = file_path.replace(/[/.]/g, '_');
document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name);
document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name);
document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name);
} else {
// hide the header in overview-frame page
document.getElementById("feedback_section").innerHTML = "";
}
</script>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserPolicyRequest.html" title="class in com.amazonaws.services.identitymanagement.model"><B>PREV CLASS</B></A>
<A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteVirtualMFADeviceRequest.html" title="class in com.amazonaws.services.identitymanagement.model"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html" target="_top"><B>FRAMES</B></A>
<A HREF="DeleteUserRequest.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
com.amazonaws.services.identitymanagement.model</FONT>
<BR>
Class DeleteUserRequest</H2>
<PRE>
<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html" title="class in com.amazonaws">com.amazonaws.AmazonWebServiceRequest</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>com.amazonaws.services.identitymanagement.model.DeleteUserRequest</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>DeleteUserRequest</B><DT>extends <A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html" title="class in com.amazonaws">AmazonWebServiceRequest</A><DT>implements <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A></DL>
</PRE>
<P>
Container for the parameters to the <A HREF="../../../../../com/amazonaws/services/identitymanagement/AmazonIdentityManagement.html#deleteUser(com.amazonaws.services.identitymanagement.model.DeleteUserRequest)"><CODE>DeleteUser operation</CODE></A>.
<p>
Deletes the specified user. The user must not belong to any groups, have any keys or signing certificates, or have any attached policies.
</p>
<P>
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../../com/amazonaws/services/identitymanagement/AmazonIdentityManagement.html#deleteUser(com.amazonaws.services.identitymanagement.model.DeleteUserRequest)"><CODE>AmazonIdentityManagement.deleteUser(DeleteUserRequest)</CODE></A>,
<A HREF="../../../../../serialized-form.html#com.amazonaws.services.identitymanagement.model.DeleteUserRequest">Serialized Form</A></DL>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html#DeleteUserRequest()">DeleteUserRequest</A></B>()</CODE>
<BR>
Default constructor for a new DeleteUserRequest object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html#DeleteUserRequest(java.lang.String)">DeleteUserRequest</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> userName)</CODE>
<BR>
Constructs a new DeleteUserRequest object.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html#equals(java.lang.Object)">equals</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> obj)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html#getUserName()">getUserName</A></B>()</CODE>
<BR>
Name of the user to delete.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html#hashCode()">hashCode</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html#setUserName(java.lang.String)">setUserName</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> userName)</CODE>
<BR>
Name of the user to delete.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html#toString()">toString</A></B>()</CODE>
<BR>
Returns a string representation of this object; useful for testing and
debugging.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html" title="class in com.amazonaws.services.identitymanagement.model">DeleteUserRequest</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html#withUserName(java.lang.String)">withUserName</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> userName)</CODE>
<BR>
Name of the user to delete.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_com.amazonaws.AmazonWebServiceRequest"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class com.amazonaws.<A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html" title="class in com.amazonaws">AmazonWebServiceRequest</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html#copyPrivateRequestParameters()">copyPrivateRequestParameters</A>, <A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html#getRequestClientOptions()">getRequestClientOptions</A>, <A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html#getRequestCredentials()">getRequestCredentials</A>, <A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html#setRequestCredentials(com.amazonaws.auth.AWSCredentials)">setRequestCredentials</A></CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#getClass()" title="class or interface in java.lang">getClass</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#notify()" title="class or interface in java.lang">notify</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#notifyAll()" title="class or interface in java.lang">notifyAll</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait()" title="class or interface in java.lang">wait</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait(long)" title="class or interface in java.lang">wait</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait(long, int)" title="class or interface in java.lang">wait</A></CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="DeleteUserRequest()"><!-- --></A><H3>
DeleteUserRequest</H3>
<PRE>
public <B>DeleteUserRequest</B>()</PRE>
<DL>
<DD>Default constructor for a new DeleteUserRequest object. Callers should use the
setter or fluent setter (with...) methods to initialize this object after creating it.
<P>
</DL>
<HR>
<A NAME="DeleteUserRequest(java.lang.String)"><!-- --></A><H3>
DeleteUserRequest</H3>
<PRE>
public <B>DeleteUserRequest</B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> userName)</PRE>
<DL>
<DD>Constructs a new DeleteUserRequest object.
Callers should use the setter or fluent setter (with...) methods to
initialize any additional object members.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>userName</CODE> - Name of the user to delete.</DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getUserName()"><!-- --></A><H3>
getUserName</H3>
<PRE>
public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getUserName</B>()</PRE>
<DL>
<DD>Name of the user to delete.
<p>
<b>Constraints:</b><br/>
<b>Length: </b>1 - 128<br/>
<b>Pattern: </b>[\w+=,.@-]*<br/>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>Name of the user to delete.</DL>
</DD>
</DL>
<HR>
<A NAME="setUserName(java.lang.String)"><!-- --></A><H3>
setUserName</H3>
<PRE>
public void <B>setUserName</B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> userName)</PRE>
<DL>
<DD>Name of the user to delete.
<p>
<b>Constraints:</b><br/>
<b>Length: </b>1 - 128<br/>
<b>Pattern: </b>[\w+=,.@-]*<br/>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>userName</CODE> - Name of the user to delete.</DL>
</DD>
</DL>
<HR>
<A NAME="withUserName(java.lang.String)"><!-- --></A><H3>
withUserName</H3>
<PRE>
public <A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html" title="class in com.amazonaws.services.identitymanagement.model">DeleteUserRequest</A> <B>withUserName</B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> userName)</PRE>
<DL>
<DD>Name of the user to delete.
<p>
Returns a reference to this object so that method calls can be chained together.
<p>
<b>Constraints:</b><br/>
<b>Length: </b>1 - 128<br/>
<b>Pattern: </b>[\w+=,.@-]*<br/>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>userName</CODE> - Name of the user to delete.
<DT><B>Returns:</B><DD>A reference to this updated object so that method calls can be chained
together.</DL>
</DD>
</DL>
<HR>
<A NAME="toString()"><!-- --></A><H3>
toString</H3>
<PRE>
public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>toString</B>()</PRE>
<DL>
<DD>Returns a string representation of this object; useful for testing and
debugging.
<P>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang">toString</A></CODE> in class <CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>A string representation of this object.<DT><B>See Also:</B><DD><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang"><CODE>Object.toString()</CODE></A></DL>
</DD>
</DL>
<HR>
<A NAME="hashCode()"><!-- --></A><H3>
hashCode</H3>
<PRE>
public int <B>hashCode</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#hashCode()" title="class or interface in java.lang">hashCode</A></CODE> in class <CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="equals(java.lang.Object)"><!-- --></A><H3>
equals</H3>
<PRE>
public boolean <B>equals</B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> obj)</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#equals(java.lang.Object)" title="class or interface in java.lang">equals</A></CODE> in class <CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<script src="http://aws.amazon.com/js/urchin.js" type="text/javascript"></script>
<script type="text/javascript">urchinTracker();</script>
<!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved.
More info available at http://www.omniture.com -->
<script language="JavaScript" type="text/javascript" src="https://d36cz9buwru1tt.cloudfront.net/js/sitecatalyst/s_code.min.js (view-source:https://d36cz9buwru1tt.cloudfront.net/js/sitecatalyst/s_code.min.js)" />
<script language="JavaScript" type="text/javascript">
<!--
// Documentation Service Name
s.prop66='AWS SDK for Java';
s.eVar66='D=c66';
// Documentation Guide Name
s.prop65='API Reference';
s.eVar65='D=c65';
var s_code=s.t();if(s_code)document.write(s_code)
//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-')
//-->
</script>
<noscript>
<img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" />
</noscript>
<!--/DO NOT REMOVE/-->
<!-- End SiteCatalyst code version: H.25.2. -->
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteUserPolicyRequest.html" title="class in com.amazonaws.services.identitymanagement.model"><B>PREV CLASS</B></A>
<A HREF="../../../../../com/amazonaws/services/identitymanagement/model/DeleteVirtualMFADeviceRequest.html" title="class in com.amazonaws.services.identitymanagement.model"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html" target="_top"><B>FRAMES</B></A>
<A HREF="DeleteUserRequest.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2010 Amazon Web Services, Inc. All Rights Reserved.
</BODY>
</HTML>
|
hobinyoon/aws-java-sdk-1.4.7
|
documentation/javadoc/com/amazonaws/services/identitymanagement/model/DeleteUserRequest.html
|
HTML
|
apache-2.0
| 24,717
|
/// <reference path="../_references.ts"/>
namespace demo.device {
'use strict';
interface IDeviceViewModel {
available:boolean;
cordova:string;
model:string;
platform:string;
uuid:string;
version:string;
}
export class DeviceController {
public vm:IDeviceViewModel;
static $inject:Array<string> = ["$ionicPlatform", "$cordovaDevice"];
constructor($ionicPlatform:ionic.platform.IonicPlatformService, $cordovaDevice:ngCordova.IDeviceService) {
$ionicPlatform.ready(() => {
this.vm = {
available : $cordovaDevice.getDevice().available,
cordova : $cordovaDevice.getCordova(),
model : $cordovaDevice.getModel(),
platform : $cordovaDevice.getPlatform(),
uuid : $cordovaDevice.getUUID(),
version : $cordovaDevice.getVersion()
};
});
}
}
angular.module("demo.device").controller("DeviceController", DeviceController);
}
|
ksachdeva/ngCordova-typescript-demo
|
www/app/device/device.controller.ts
|
TypeScript
|
apache-2.0
| 939
|
---
license: 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.
---
compass.clearWatch
========================
Stop watching the compass referenced by the watch ID parameter.
navigator.compass.clearWatch(watchID);
- __watchID__: The ID returned by `compass.watchHeading`.
Supported Platforms
-------------------
- Android
- iOS
- Windows Phone 7 and 8 ( if available in hardware )
- Bada 1.2 & 2.x
- webOS
- Tizen
- Windows 8
Quick Example
-------------
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
// ... later on ...
navigator.compass.clearWatch(watchID);
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>Compass Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchHeading`
var watchID = null;
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
startWatch();
}
// Start watching the compass
//
function startWatch() {
// Update compass every 3 seconds
var options = { frequency: 3000 };
watchID = navigator.compass.watchHeading(onSuccess, onError, options);
}
// Stop watching the compass
//
function stopWatch() {
if (watchID) {
navigator.compass.clearWatch(watchID);
watchID = null;
}
}
// onSuccess: Get the current heading
//
function onSuccess(heading) {
var element = document.getElementById('heading');
element.innerHTML = 'Heading: ' + heading.magneticHeading;
}
// onError: Failed to get the heading
//
function onError(compassError) {
alert('Compass error: ' + compassError.code);
}
</script>
</head>
<body>
<div id="heading">Waiting for heading...</div>
<button onclick="startWatch();">Start Watching</button>
<button onclick="stopWatch();">Stop Watching</button>
</body>
</html>
|
maveriklko9719/Coffee-Spills
|
docs/en/2.9.0rc1/cordova/compass/compass.clearWatch.md
|
Markdown
|
apache-2.0
| 3,184
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.v2.jobhistory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
/**
* Stores Job History configuration keys that can be set by administrators of
* the Job History server.
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class JHAdminConfig {
/** The prefix to all Job History configuration properties.*/
public static final String MR_HISTORY_PREFIX = "mapreduce.jobhistory.";
/** host:port address for History Server API.*/
public static final String MR_HISTORY_ADDRESS = MR_HISTORY_PREFIX + "address";
public static final int DEFAULT_MR_HISTORY_PORT = 10020;
public static final String DEFAULT_MR_HISTORY_ADDRESS = "0.0.0.0:" +
DEFAULT_MR_HISTORY_PORT;
/** If history cleaning should be enabled or not.*/
public static final String MR_HISTORY_CLEANER_ENABLE =
MR_HISTORY_PREFIX + "cleaner.enable";
/** Run the History Cleaner every X ms.*/
public static final String MR_HISTORY_CLEANER_INTERVAL_MS =
MR_HISTORY_PREFIX + "cleaner.interval-ms";
public static final long DEFAULT_MR_HISTORY_CLEANER_INTERVAL_MS =
1 * 24 * 60 * 60 * 1000l; //1 day
/** The number of threads to handle client API requests.*/
public static final String MR_HISTORY_CLIENT_THREAD_COUNT =
MR_HISTORY_PREFIX + "client.thread-count";
public static final int DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT = 10;
/**
* Size of the date string cache. Effects the number of directories
* which will be scanned to find a job.
*/
public static final String MR_HISTORY_DATESTRING_CACHE_SIZE =
MR_HISTORY_PREFIX + "datestring.cache.size";
public static final int DEFAULT_MR_HISTORY_DATESTRING_CACHE_SIZE = 200000;
//TODO REMOVE debug-mode
/** Equivalent to 0.20 mapreduce.jobhistory.debug.mode */
public static final String MR_HISTORY_DEBUG_MODE =
MR_HISTORY_PREFIX + "debug-mode";
/** Path where history files should be stored for DONE jobs. **/
public static final String MR_HISTORY_DONE_DIR =
MR_HISTORY_PREFIX + "done-dir";
/**
* Path where history files should be stored after a job finished and before
* they are pulled into the job history server.
**/
public static final String MR_HISTORY_INTERMEDIATE_DONE_DIR =
MR_HISTORY_PREFIX + "intermediate-done-dir";
/** Size of the job list cache.*/
public static final String MR_HISTORY_JOBLIST_CACHE_SIZE =
MR_HISTORY_PREFIX + "joblist.cache.size";
public static final int DEFAULT_MR_HISTORY_JOBLIST_CACHE_SIZE = 20000;
/** The location of the Kerberos keytab file.*/
public static final String MR_HISTORY_KEYTAB = MR_HISTORY_PREFIX + "keytab";
/** Size of the loaded job cache.*/
public static final String MR_HISTORY_LOADED_JOB_CACHE_SIZE =
MR_HISTORY_PREFIX + "loadedjobs.cache.size";
public static final int DEFAULT_MR_HISTORY_LOADED_JOB_CACHE_SIZE = 5;
/**
* The maximum age of a job history file before it is deleted from the history
* server.
*/
public static final String MR_HISTORY_MAX_AGE_MS =
MR_HISTORY_PREFIX + "max-age-ms";
public static final long DEFAULT_MR_HISTORY_MAX_AGE =
7 * 24 * 60 * 60 * 1000L; //1 week
/**
* Scan for history files to more from intermediate done dir to done dir
* every X ms.
*/
public static final String MR_HISTORY_MOVE_INTERVAL_MS =
MR_HISTORY_PREFIX + "move.interval-ms";
public static final long DEFAULT_MR_HISTORY_MOVE_INTERVAL_MS =
3 * 60 * 1000l; //3 minutes
/** The number of threads used to move files.*/
public static final String MR_HISTORY_MOVE_THREAD_COUNT =
MR_HISTORY_PREFIX + "move.thread-count";
public static final int DEFAULT_MR_HISTORY_MOVE_THREAD_COUNT = 3;
/** The Kerberos principal for the history server.*/
public static final String MR_HISTORY_PRINCIPAL =
MR_HISTORY_PREFIX + "principal";
/**The address the history server webapp is on.*/
public static final String MR_HISTORY_WEBAPP_ADDRESS =
MR_HISTORY_PREFIX + "webapp.address";
public static final int DEFAULT_MR_HISTORY_WEBAPP_PORT = 19888;
public static final String DEFAULT_MR_HISTORY_WEBAPP_ADDRESS =
"0.0.0.0:" + DEFAULT_MR_HISTORY_WEBAPP_PORT;
/*
* HS Service Authorization
*/
public static final String MR_HS_SECURITY_SERVICE_AUTHORIZATION =
"security.mrhs.client.protocol.acl";
/**
* The HistoryStorage class to use to cache history data.
*/
public static final String MR_HISTORY_STORAGE =
MR_HISTORY_PREFIX + "store.class";
/** Whether to use fixed ports with the minicluster. */
public static final String MR_HISTORY_MINICLUSTER_FIXED_PORTS = MR_HISTORY_PREFIX
+ "minicluster.fixed.ports";
/**
* Default is false to be able to run tests concurrently without port
* conflicts.
*/
public static boolean DEFAULT_MR_HISTORY_MINICLUSTER_FIXED_PORTS = false;
}
|
moreus/hadoop
|
hadoop-0.23.10/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/jobhistory/JHAdminConfig.java
|
Java
|
apache-2.0
| 5,746
|
package com.talentica.androidkotlin.customcamera.dagger.landing;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Retention(RetentionPolicy.RUNTIME)
@Scope
public @interface LandingActivityScope {
}
|
Talentica/AndroidWithKotlin
|
customcamera/src/main/java/com/talentica/androidkotlin/customcamera/dagger/landing/LandingActivityScope.java
|
Java
|
apache-2.0
| 265
|
# DevOps1-CM
This project automates the launch of Puppet as CM tool, performs initial server setup, and creates both Linux and Windows-based Puppet agents within an Amazon VPC.
|
mb-reantest/DevOps1-CM
|
README.md
|
Markdown
|
apache-2.0
| 177
|
/**
* Copyright 2006-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.generator.api.dom.java;
import static org.mybatis.generator.api.dom.OutputUtilities.javaIndent;
import static org.mybatis.generator.api.dom.OutputUtilities.newLine;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.mybatis.generator.api.dom.OutputUtilities;
/**
* The Class Interface.
*
* @author Jeff Butler
*/
public class InnerInterface extends JavaElement {
private List<Field> fields;
/** The type. */
private FullyQualifiedJavaType type;
/** The inner interfaces. */
private List<InnerInterface> innerInterfaces;
/** The super interface types. */
private Set<FullyQualifiedJavaType> superInterfaceTypes;
/** The methods. */
private List<Method> methods;
/**
* Instantiates a new interface.
*
* @param type
* the type
*/
public InnerInterface(FullyQualifiedJavaType type) {
super();
this.type = type;
innerInterfaces = new ArrayList<InnerInterface>();
superInterfaceTypes = new LinkedHashSet<FullyQualifiedJavaType>();
methods = new ArrayList<Method>();
fields = new ArrayList<Field>();
}
/**
* Instantiates a new interface.
*
* @param type
* the type
*/
public InnerInterface(String type) {
this(new FullyQualifiedJavaType(type));
}
public List<Field> getFields() {
return fields;
}
public void addField(Field field) {
fields.add(field);
}
/**
* Gets the formatted content.
*
* @param indentLevel
* the indent level
* @param compilationUnit the compilation unit
* @return the formatted content
*/
public String getFormattedContent(int indentLevel, CompilationUnit compilationUnit) {
StringBuilder sb = new StringBuilder();
addFormattedJavadoc(sb, indentLevel);
addFormattedAnnotations(sb, indentLevel);
javaIndent(sb, indentLevel);
sb.append(getVisibility().getValue());
if (isStatic()) {
sb.append("static "); //$NON-NLS-1$
}
if (isFinal()) {
sb.append("final "); //$NON-NLS-1$
}
sb.append("interface "); //$NON-NLS-1$
sb.append(getType().getShortName());
if (getSuperInterfaceTypes().size() > 0) {
sb.append(" extends "); //$NON-NLS-1$
boolean comma = false;
for (FullyQualifiedJavaType fqjt : getSuperInterfaceTypes()) {
if (comma) {
sb.append(", "); //$NON-NLS-1$
} else {
comma = true;
}
sb.append(JavaDomUtils.calculateTypeName(compilationUnit, fqjt));
}
}
sb.append(" {"); //$NON-NLS-1$
indentLevel++;
Iterator<Field> fldIter = fields.iterator();
while (fldIter.hasNext()) {
OutputUtilities.newLine(sb);
Field field = fldIter.next();
sb.append(field.getFormattedContent(indentLevel, compilationUnit));
}
if (fields.size() > 0 && methods.size() > 0) {
OutputUtilities.newLine(sb);
}
Iterator<Method> mtdIter = getMethods().iterator();
while (mtdIter.hasNext()) {
newLine(sb);
Method method = mtdIter.next();
sb.append(method.getFormattedContent(indentLevel, true, compilationUnit));
if (mtdIter.hasNext()) {
newLine(sb);
}
}
if (innerInterfaces.size() > 0) {
newLine(sb);
}
Iterator<InnerInterface> iiIter = innerInterfaces.iterator();
while (iiIter.hasNext()) {
newLine(sb);
InnerInterface innerInterface = iiIter.next();
sb.append(innerInterface.getFormattedContent(indentLevel, compilationUnit));
if (iiIter.hasNext()) {
newLine(sb);
}
}
indentLevel--;
newLine(sb);
javaIndent(sb, indentLevel);
sb.append('}');
return sb.toString();
}
/**
* Adds the super interface.
*
* @param superInterface
* the super interface
*/
public void addSuperInterface(FullyQualifiedJavaType superInterface) {
superInterfaceTypes.add(superInterface);
}
/**
* Gets the methods.
*
* @return Returns the methods.
*/
public List<Method> getMethods() {
return methods;
}
/**
* Adds the method.
*
* @param method
* the method
*/
public void addMethod(Method method) {
methods.add(method);
}
/**
* Gets the type.
*
* @return Returns the type.
*/
public FullyQualifiedJavaType getType() {
return type;
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.dom.java.CompilationUnit#getSuperClass()
*/
public FullyQualifiedJavaType getSuperClass() {
// interfaces do not have superclasses
return null;
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.dom.java.CompilationUnit#getSuperInterfaceTypes()
*/
public Set<FullyQualifiedJavaType> getSuperInterfaceTypes() {
return superInterfaceTypes;
}
/**
* Gets the inner interface.
*
* @return Returns the innerInterfaces.
*/
public List<InnerInterface> getInnerInterfaces() {
return innerInterfaces;
}
/**
* Adds the inner interface.
*
* @param innerInterface
* the inner interface
*/
public void addInnerInterfaces(InnerInterface innerInterface) {
innerInterfaces.add(innerInterface);
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.dom.java.CompilationUnit#isJavaInterface()
*/
public boolean isJavaInterface() {
return true;
}
/* (non-Javadoc)
* @see org.mybatis.generator.api.dom.java.CompilationUnit#isJavaEnumeration()
*/
public boolean isJavaEnumeration() {
return false;
}
}
|
pnoker/mybatisGenerator
|
src/main/java/org/mybatis/generator/api/dom/java/InnerInterface.java
|
Java
|
apache-2.0
| 6,871
|
/*
* Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
// This file was generated by NxParameterized/scripts/GenParameterized.pl
// Created: 2015.10.22 17:26:23
#include "EmitterGeomCylinderParams.h"
#include <string.h>
#include <stdlib.h>
using namespace NxParameterized;
namespace physx
{
namespace apex
{
namespace emitter
{
using namespace EmitterGeomCylinderParamsNS;
const char* const EmitterGeomCylinderParamsFactory::vptr =
NxParameterized::getVptr<EmitterGeomCylinderParams, EmitterGeomCylinderParams::ClassAlignment>();
const physx::PxU32 NumParamDefs = 4;
static NxParameterized::DefinitionImpl* ParamDefTable; // now allocated in buildTree [NumParamDefs];
static const size_t ParamLookupChildrenTable[] =
{
1, 2, 3,
};
#define TENUM(type) physx::##type
#define CHILDREN(index) &ParamLookupChildrenTable[index]
static const NxParameterized::ParamLookupNode ParamLookupTable[NumParamDefs] =
{
{ TYPE_STRUCT, false, 0, CHILDREN(0), 3 },
{ TYPE_ENUM, false, (size_t)(&((ParametersStruct*)0)->emitterType), NULL, 0 }, // emitterType
{ TYPE_F32, false, (size_t)(&((ParametersStruct*)0)->radius), NULL, 0 }, // radius
{ TYPE_F32, false, (size_t)(&((ParametersStruct*)0)->height), NULL, 0 }, // height
};
bool EmitterGeomCylinderParams::mBuiltFlag = false;
NxParameterized::MutexType EmitterGeomCylinderParams::mBuiltFlagMutex;
EmitterGeomCylinderParams::EmitterGeomCylinderParams(NxParameterized::Traits* traits, void* buf, PxI32* refCount) :
NxParameters(traits, buf, refCount)
{
//mParameterizedTraits->registerFactory(className(), &EmitterGeomCylinderParamsFactoryInst);
if (!buf) //Do not init data if it is inplace-deserialized
{
initDynamicArrays();
initStrings();
initReferences();
initDefaults();
}
}
EmitterGeomCylinderParams::~EmitterGeomCylinderParams()
{
freeStrings();
freeReferences();
freeDynamicArrays();
}
void EmitterGeomCylinderParams::destroy()
{
// We cache these fields here to avoid overwrite in destructor
bool doDeallocateSelf = mDoDeallocateSelf;
NxParameterized::Traits* traits = mParameterizedTraits;
physx::PxI32* refCount = mRefCount;
void* buf = mBuffer;
this->~EmitterGeomCylinderParams();
NxParameters::destroy(this, traits, doDeallocateSelf, refCount, buf);
}
const NxParameterized::DefinitionImpl* EmitterGeomCylinderParams::getParameterDefinitionTree(void)
{
if (!mBuiltFlag) // Double-checked lock
{
NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
buildTree();
}
}
return(&ParamDefTable[0]);
}
const NxParameterized::DefinitionImpl* EmitterGeomCylinderParams::getParameterDefinitionTree(void) const
{
EmitterGeomCylinderParams* tmpParam = const_cast<EmitterGeomCylinderParams*>(this);
if (!mBuiltFlag) // Double-checked lock
{
NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
tmpParam->buildTree();
}
}
return(&ParamDefTable[0]);
}
NxParameterized::ErrorType EmitterGeomCylinderParams::getParameterHandle(const char* long_name, Handle& handle) const
{
ErrorType Ret = NxParameters::getParameterHandle(long_name, handle);
if (Ret != ERROR_NONE)
{
return(Ret);
}
size_t offset;
void* ptr;
getVarPtr(handle, ptr, offset);
if (ptr == NULL)
{
return(ERROR_INDEX_OUT_OF_RANGE);
}
return(ERROR_NONE);
}
NxParameterized::ErrorType EmitterGeomCylinderParams::getParameterHandle(const char* long_name, Handle& handle)
{
ErrorType Ret = NxParameters::getParameterHandle(long_name, handle);
if (Ret != ERROR_NONE)
{
return(Ret);
}
size_t offset;
void* ptr;
getVarPtr(handle, ptr, offset);
if (ptr == NULL)
{
return(ERROR_INDEX_OUT_OF_RANGE);
}
return(ERROR_NONE);
}
void EmitterGeomCylinderParams::getVarPtr(const Handle& handle, void*& ptr, size_t& offset) const
{
ptr = getVarPtrHelper(&ParamLookupTable[0], const_cast<EmitterGeomCylinderParams::ParametersStruct*>(¶meters()), handle, offset);
}
/* Dynamic Handle Indices */
void EmitterGeomCylinderParams::freeParameterDefinitionTable(NxParameterized::Traits* traits)
{
if (!traits)
{
return;
}
if (!mBuiltFlag) // Double-checked lock
{
return;
}
NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
return;
}
for (physx::PxU32 i = 0; i < NumParamDefs; ++i)
{
ParamDefTable[i].~DefinitionImpl();
}
traits->free(ParamDefTable);
mBuiltFlag = false;
}
#define PDEF_PTR(index) (&ParamDefTable[index])
void EmitterGeomCylinderParams::buildTree(void)
{
physx::PxU32 allocSize = sizeof(NxParameterized::DefinitionImpl) * NumParamDefs;
ParamDefTable = (NxParameterized::DefinitionImpl*)(mParameterizedTraits->alloc(allocSize));
memset(static_cast<void*>(ParamDefTable), 0, allocSize);
for (physx::PxU32 i = 0; i < NumParamDefs; ++i)
{
NX_PARAM_PLACEMENT_NEW(ParamDefTable + i, NxParameterized::DefinitionImpl)(*mParameterizedTraits);
}
// Initialize DefinitionImpl node: nodeIndex=0, longName=""
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[0];
ParamDef->init("", TYPE_STRUCT, "STRUCT", true);
}
// Initialize DefinitionImpl node: nodeIndex=1, longName="emitterType"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[1];
ParamDef->init("emitterType", TYPE_ENUM, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("defaultValue", "rate", true);
ParamDefTable[1].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", "rate", true);
HintTable[1].init("longDescription", "rate - The emitter will emit at the rate specified by the asset's rateRange\\n\ndensityOnce - The emitter will fill the geometry according to the asset's densityRange\\n\ndensityBrush - As the emitter moves, the emitter will fill the volume that is not already covered by the previous position\\n\nfill - The emitter will fill the volume with particles based on the particle size\\n\n", true);
HintTable[2].init("shortDescription", "Emitter Type", true);
ParamDefTable[1].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
static const char* const EnumVals[] = { "rate", "densityOnce", "densityBrush", "fill" };
ParamDefTable[1].setEnumVals((const char**)EnumVals, 4);
}
// Initialize DefinitionImpl node: nodeIndex=2, longName="radius"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[2];
ParamDef->init("radius", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", physx::PxU64(1), true);
HintTable[1].init("gameScale", "true", true);
HintTable[2].init("min", physx::PxU64(0), true);
ParamDefTable[2].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("defaultValue", physx::PxU64(1), true);
HintTable[1].init("gameScale", "true", true);
HintTable[2].init("min", physx::PxU64(0), true);
HintTable[3].init("shortDescription", "Cylinder Radius", true);
ParamDefTable[2].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=3, longName="height"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[3];
ParamDef->init("height", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", physx::PxU64(1), true);
HintTable[1].init("gameScale", "true", true);
HintTable[2].init("min", physx::PxU64(0), true);
ParamDefTable[3].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("defaultValue", physx::PxU64(1), true);
HintTable[1].init("gameScale", "true", true);
HintTable[2].init("min", physx::PxU64(0), true);
HintTable[3].init("shortDescription", "Cylinder Height", true);
ParamDefTable[3].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// SetChildren for: nodeIndex=0, longName=""
{
static Definition* Children[3];
Children[0] = PDEF_PTR(1);
Children[1] = PDEF_PTR(2);
Children[2] = PDEF_PTR(3);
ParamDefTable[0].setChildren(Children, 3);
}
mBuiltFlag = true;
}
void EmitterGeomCylinderParams::initStrings(void)
{
}
void EmitterGeomCylinderParams::initDynamicArrays(void)
{
}
void EmitterGeomCylinderParams::initDefaults(void)
{
freeStrings();
freeReferences();
freeDynamicArrays();
emitterType = (const char*)"rate";
radius = physx::PxF32(1.0f);
height = physx::PxF32(1.0f);
initDynamicArrays();
initStrings();
initReferences();
}
void EmitterGeomCylinderParams::initReferences(void)
{
}
void EmitterGeomCylinderParams::freeDynamicArrays(void)
{
}
void EmitterGeomCylinderParams::freeStrings(void)
{
}
void EmitterGeomCylinderParams::freeReferences(void)
{
}
} // namespace emitter
} // namespace apex
} // namespace physx
|
LiangYue1981816/CrossEngine
|
PhysX-3.3/APEXSDK/module/emitter/src/EmitterGeomCylinderParams.cpp
|
C++
|
apache-2.0
| 9,950
|
/*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.nakamura.user.lite.servlet;
import com.google.common.collect.Lists;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceNotFoundException;
import org.apache.sling.api.servlets.HtmlResponse;
import org.apache.sling.servlets.post.Modification;
import org.sakaiproject.nakamura.api.doc.BindingType;
import org.sakaiproject.nakamura.api.doc.ServiceBinding;
import org.sakaiproject.nakamura.api.doc.ServiceDocumentation;
import org.sakaiproject.nakamura.api.doc.ServiceExtension;
import org.sakaiproject.nakamura.api.doc.ServiceMethod;
import org.sakaiproject.nakamura.api.doc.ServiceParameter;
import org.sakaiproject.nakamura.api.doc.ServiceResponse;
import org.sakaiproject.nakamura.api.doc.ServiceSelector;
import org.sakaiproject.nakamura.api.lite.Session;
import org.sakaiproject.nakamura.api.lite.StorageClientException;
import org.sakaiproject.nakamura.api.lite.StorageClientUtils;
import org.sakaiproject.nakamura.api.lite.accesscontrol.AccessControlManager;
import org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException;
import org.sakaiproject.nakamura.api.lite.accesscontrol.AclModification;
import org.sakaiproject.nakamura.api.lite.accesscontrol.Permission;
import org.sakaiproject.nakamura.api.lite.accesscontrol.Permissions;
import org.sakaiproject.nakamura.api.lite.accesscontrol.Security;
import org.sakaiproject.nakamura.api.lite.authorizable.Authorizable;
import org.sakaiproject.nakamura.api.user.UserConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Enumeration;
import java.util.List;
@ServiceDocumentation(name = "Update User ACE Servlet", okForVersion = "1.2",
description = "Updates a user's Access Control Entry (ACE). Maps on to nodes of resourceType sparse/user " +
"with the modifyAce selector. This servlet responds at " +
"/system/userManager/user/suzy.modifyAce.html",
shortDescription = "Update a user ACE",
bindings = @ServiceBinding(type = BindingType.TYPE, bindings = {"sparse/user"},
selectors = @ServiceSelector(name = "update", description = "Updates the ACE of a user"),
extensions = @ServiceExtension(name = "html", description = "Posts produce html containing the update status")),
methods = @ServiceMethod(name = "POST",
description = {"Updates a user ACE",
"Example<br>" +
"<pre>curl -FprincipalId=everyone -Fprivilege@jcr:read=granted http://localhost:8080/system/userManager/user/suzy.modifyAce.html</pre>"},
parameters = {
@ServiceParameter(name = "principalId", description = "The principalId that will receive the specified privilege"),
@ServiceParameter(name = "privilege", description = "The privilege to grant, one of: <br>" +
"@jcr:read=granted|denied|none <br> " +
"@jcr:write=granted|denied|none <br>" +
"@jcr:delete=granted|denied|none <br>"
)
},
response = {
@ServiceResponse(code = 200, description = "Success, HTML describing status is returned."),
@ServiceResponse(code = 404, description = "User was not found."),
@ServiceResponse(code = 500, description = "Failure with HTML explanation.")}
))
@SlingServlet(resourceTypes = {"sparse/user"}, methods = {"POST"}, selectors = {"modifyAce"})
public class LiteModifyUserAceServlet extends LiteAbstractUserPostServlet {
private static final long serialVersionUID = 9154151078639439773L;
private static final Logger LOGGER = LoggerFactory.getLogger(LiteModifyUserAceServlet.class);
@SuppressWarnings({"deprecation"})
@Override
protected void handleOperation(SlingHttpServletRequest request,
HtmlResponse htmlResponse, List<Modification> changes)
throws StorageClientException, AccessDeniedException {
Authorizable authorizable = null;
Resource resource = request.getResource();
if (resource != null) {
authorizable = resource.adaptTo(Authorizable.class);
}
// check that the user was located.
if (authorizable == null) {
throw new ResourceNotFoundException(
"User to update could not be determined");
}
// get a session
Session session = StorageClientUtils.adaptToSession(request.getResourceResolver().adaptTo(javax.jcr.Session.class));
if (session == null) {
throw new StorageClientException("Sparse Session not found");
}
// get the principal that will get the specified privilege
String principalId = request.getParameter("principalId");
if (principalId == null) {
throw new StorageClientException("principalId was not submitted.");
}
// figure out the specified privilege
Enumeration<?> parameterNames = request.getParameterNames();
List<AclModification> aclModifications = Lists.newArrayList();
while (parameterNames.hasMoreElements()) {
Object nextElement = parameterNames.nextElement();
if (nextElement instanceof String) {
String paramName = (String) nextElement;
if (paramName.startsWith("privilege@")) {
String privilegeName = paramName.substring("privilege@".length());
Permission permission = getPermission(privilegeName);
String parameterValue = request.getParameter(paramName);
if (parameterValue != null && parameterValue.length() > 0) {
if ("granted".equals(parameterValue) && permission != null) {
LOGGER.info("{}:{}:{}:{}", new Object[]{authorizable.getId(), principalId, "granted", permission.getName()});
AclModification.addAcl(true, permission, principalId, aclModifications);
} else if ("denied".equals(parameterValue) && permission != null) {
LOGGER.info("{}:{}:{}:{}", new Object[]{authorizable.getId(), principalId, "denied", permission.getName()});
AclModification.addAcl(false, permission, principalId, aclModifications);
} else if ("none".equals(parameterValue)) {
LOGGER.info("{}:{}:{}:{}", new Object[]{authorizable.getId(), principalId, "cleared", "all"});
AclModification.removeAcl(true, Permissions.ALL, principalId, aclModifications);
AclModification.removeAcl(false, Permissions.ALL, principalId, aclModifications);
}
}
}
}
}
// save the changes
AccessControlManager accessControlManager = session.getAccessControlManager();
accessControlManager.setAcl(Security.ZONE_AUTHORIZABLES, authorizable.getId(),
aclModifications.toArray(new AclModification[aclModifications.size()]));
responseCache.invalidate(UserConstants.USER_RESPONSE_CACHE, authorizable.getId());
}
private Permission getPermission(String privilegeName) {
return Permissions.parse(privilegeName);
}
}
|
dylanswartz/nakamura
|
bundles/user/impl/src/main/java/org/sakaiproject/nakamura/user/lite/servlet/LiteModifyUserAceServlet.java
|
Java
|
apache-2.0
| 8,048
|
//
// Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// A copy of the License is located at
//
// http://aws.amazon.com/apache2.0
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
//
package org.jenkinsci.plugins.awsdevicefarm;
import com.amazonaws.services.devicefarm.model.ExecutionResult;
import com.amazonaws.services.devicefarm.model.Run;
import hudson.model.AbstractBuild;
import hudson.model.Result;
import hudson.tasks.test.TestObject;
import hudson.tasks.test.TestResult;
import hudson.util.ChartUtil;
import hudson.util.Graph;
import org.apache.commons.lang.WordUtils;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Result object which contains high level result information, pass/warn/fail counters, and performance
* stats for an AWS Device Farm run.
* <p>
* A "snapshot" of the results of an AWS Device Farm run at some point during its execution lifecycle.
* New result objects will be created periodically during active runs and a final object will be stored
* and attached to a Jenkins run, once it has completed.
*/
public class AWSDeviceFarmTestResult extends TestResult {
private static final HashMap<ExecutionResult, Result> resultMap = new HashMap<ExecutionResult, Result>();
private static final int DefaultTrendGraphSize = 3;
private String id = "";
private String status = "";
private ExecutionResult result;
private int passCount = 0;
private int warnCount = 0;
private int failCount = 0;
private int totalCount = 0;
private int errorCount = 0;
private int skipCount = 0;
private int stopCount = 0;
private int duration = 0;
private String url = "";
private String project = "";
private AbstractBuild<?, ?> build;
public AWSDeviceFarmTestResult(AbstractBuild<?, ?> build, Run run) {
this.build = build;
if (run != null) {
this.id = AWSDeviceFarmUtils.getRunIdFromArn(run.getArn());
this.status = run.getStatus();
this.result = ExecutionResult.fromValue(run.getResult());
this.passCount = run.getCounters().getPassed();
this.warnCount = run.getCounters().getWarned();
this.failCount = run.getCounters().getFailed();
this.totalCount = run.getCounters().getTotal();
this.errorCount = run.getCounters().getErrored();
this.skipCount = run.getCounters().getSkipped();
//this.duration =
try {
this.stopCount = run.getCounters().getStopped();
} catch (NullPointerException e) {
// Ignore this until the stopped bug is fixed.
}
this.url = AWSDeviceFarmUtils.getRunUrlFromArn(run.getArn());
}
}
/**
* Map Device Farm results to Jenkins results.
*/
static {
resultMap.put(ExecutionResult.PASSED, Result.SUCCESS);
resultMap.put(ExecutionResult.WARNED, Result.UNSTABLE);
resultMap.put(ExecutionResult.FAILED, Result.FAILURE);
resultMap.put(ExecutionResult.SKIPPED, Result.FAILURE);
resultMap.put(ExecutionResult.ERRORED, Result.FAILURE);
resultMap.put(ExecutionResult.STOPPED, Result.FAILURE);
}
/**
* Create the graph image for the number of pass/warn/fail results in a test run, for the previous three Jenkins runs.
*
* @param request
* @param response
* @throws IOException
*/
@SuppressWarnings("unused")
public void doGraph(StaplerRequest request, StaplerResponse response) throws IOException {
// Abort if having Java AWT issues.
if (ChartUtil.awtProblemCause != null) {
response.sendRedirect2(String.format("%s/images/headless.png", request.getContextPath()));
return;
}
// Check the "If-Modified-Since" header and abort if we don't need re-create the graph.
if (isCompleted()) {
Calendar timestamp = getOwner().getTimestamp();
if (request.checkIfModified(timestamp, response)) {
return;
}
}
// Create new graph for this AWS Device Farm result.
Graph graph = AWSDeviceFarmGraph.createResultTrendGraph(build, isCompleted(), getPreviousResults(DefaultTrendGraphSize));
graph.doPng(request, response);
}
/**
* Create the graph image for the number of device minutes used in a test run, for the previous three Jenkins runs.
*
* @param request
* @param response
* @throws IOException
*/
@SuppressWarnings("unused")
public void doDurationGraph(StaplerRequest request, StaplerResponse response) throws IOException {
// Abort if having Java AWT issues.
if (ChartUtil.awtProblemCause != null) {
response.sendRedirect2(String.format("%s/images/headless.png", request.getContextPath()));
return;
}
// Check the "If-Modified-Since" header and abort if we don't need re-create the graph.
if (isCompleted()) {
Calendar timestamp = getOwner().getTimestamp();
if (request.checkIfModified(timestamp, response)) {
return;
}
}
// Create new duration graph for this AWS Device Farm result.
Graph graph = AWSDeviceFarmGraph.createDurationTrendGraph(build, isCompleted(), getPreviousResults(DefaultTrendGraphSize));
graph.doPng(request, response);
}
/**
* Return the AWS Device Farm result of the most recent build which contained an AWS Device Farm run.
*
* @return
*/
@SuppressWarnings("unused")
public AWSDeviceFarmTestResult getPreviousResult() {
AWSDeviceFarmTestResultAction prev = AWSDeviceFarmUtils.previousAWSDeviceFarmBuildAction(build.getProject());
if (prev == null) {
return null;
}
return prev.getResult();
}
/**
* Return a list of up to (n) of the most recent/previous AWS Device Farm results.
*
* @param n
* @return
*/
@SuppressWarnings("unused")
protected List<AWSDeviceFarmTestResult> getPreviousResults(int n) {
List<AWSDeviceFarmTestResult> results = getPreviousResults();
return results.subList(Math.max(0, results.size() - n), results.size());
//return results.subList(0, Math.min(n, results.size()));
}
/**
* Return a list of all AWS Device Farm results from all builds previous to the build that this result is tied to.
* The list is return in increasing, sequential order.
*
* @return
*/
@SuppressWarnings("unused")
protected List<AWSDeviceFarmTestResult> getPreviousResults() {
ArrayList<AWSDeviceFarmTestResultAction> actions = AWSDeviceFarmUtils.previousAWSDeviceFarmBuilds(build.getProject());
ArrayList<AWSDeviceFarmTestResult> results = new ArrayList<AWSDeviceFarmTestResult>();
for (AWSDeviceFarmTestResultAction action : actions) {
AWSDeviceFarmTestResult result = action.getResult();
if (result == null) {
continue;
}
results.add(result);
}
Collections.reverse(results);
return results;
}
public String getReportUrl() {
return url;
}
public String getRunId() {
return id;
}
public String getBuildNumber() {
return "" + build.getNumber();
}
public String getStatus() {
return WordUtils.capitalizeFully(status);
}
public String getProject() {
return project;
}
/**
* Return true if this result is "completed". A completed result is a result
* who is both marked as completed and has had its results archived for download.
*
* @return
*/
public Boolean isCompleted() {
return status != null
&& status.equalsIgnoreCase("COMPLETED");
}
/**
* Return a Jenkins build result which matches the result status from AWS Device Farm.
*
* @return
*/
public Result getBuildResult(Boolean ignoreRunError) {
if (ignoreRunError != null && ignoreRunError && ExecutionResult.ERRORED.equals(result)) {
if (totalCount == skipCount) {
result = ExecutionResult.SKIPPED;
} else if (stopCount > 0) {
result = ExecutionResult.STOPPED;
} else if (errorCount > 0) {
result = ExecutionResult.ERRORED;
} else if (failCount > 0) {
result = ExecutionResult.FAILED;
} else if (warnCount > 0) {
result = ExecutionResult.WARNED;
} else {
result = ExecutionResult.PASSED;
}
}
return resultMap.get(result);
}
/**
* Returns the AWS Device Farm test result for the given id. The id will likely be the default
* value generated by Jenkins, which is usually just the human readable name. Return this
* test result the ID's match, otherwise scan our previous runs looking for a matching result.
* If no match is found, return null.
*
* @param id
* @return
*/
public TestResult findCorrespondingResult(String id) {
if (id == null || getId().equalsIgnoreCase(id)) {
return this;
}
ArrayList<AWSDeviceFarmTestResultAction> prevActions = AWSDeviceFarmUtils.previousAWSDeviceFarmBuilds(build.getProject());
if (prevActions == null || prevActions.isEmpty()) {
return null;
}
for (AWSDeviceFarmTestResultAction action : prevActions) {
AWSDeviceFarmTestResult prevResult = action.getResult();
if (prevResult == null) {
continue;
}
if (prevResult.getId().equalsIgnoreCase(id)) {
return prevResult;
}
}
return null;
}
/**
* Return number of test passes in this result.
*
* @return
*/
@Override
public int getPassCount() {
return passCount;
}
/**
* Return number of test warnings in this result.
*
* @return
*/
public int getWarnCount() {
return warnCount;
}
/**
* Return number of test failures in this result.
*
* @return
*/
@Override
public int getFailCount() {
return failCount;
}
/**
* Return number of test errors in this result.
*
* @return
*/
public int getStopCount() {
return stopCount;
}
/**
* Return number of test errors in this result.
*
* @return
*/
public int getErrorCount() {
return errorCount;
}
/**
* Return number of test errors in this result.
*
* @return
*/
@Override
public int getSkipCount() {
return skipCount;
}
/**
* Return total number of tests run in this result.
*
* @return
*/
@Override
public int getTotalCount() {
return totalCount;
}
/**
* Return total number of device minutes used by the run which generated this result.
*
* @return
*/
@Override
public float getDuration() {
return (float) duration;
}
/**
* Return true if there are no tests for this result, false otherwise.
*
* @return
*/
public Boolean isEmpty() {
return getTotalCount() == 0;
}
public TestObject getParent() {
return null;
}
public AbstractBuild<?, ?> getOwner() {
return build;
}
public String getDisplayName() {
return String.format("AWS Device Farm #%s", id);
}
@Override
public String getName() {
return String.format("AWSDeviceFarm%s", id);
}
@Override
public String getSearchUrl() {
return "aws-device-farm";
}
}
|
oonemo/aws-device-farm-jenkins-plugin
|
src/main/java/org/jenkinsci/plugins/awsdevicefarm/AWSDeviceFarmTestResult.java
|
Java
|
apache-2.0
| 12,493
|
package net.crofis.ui;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
Minitour/crofis-android-uikit
|
ui/src/androidTest/java/net/crofis/ui/ApplicationTest.java
|
Java
|
apache-2.0
| 344
|
"""
lexical chain module for text tiling
"""
from tile_reader import TileReader
from scoring import boundarize, depth_scoring, window_diff
# ======================================================================================================================
# Main
# ======================================================================================================================
class LexicalChains(object):
def __init__(self):
self.sentences = []
self.actives = {}
self.gap_scores = []
self.boundary_vector = []
def analyze(self, sents, window=4, pos_filter=('PUNCT', 'SYM', 'SPACE', 'DET'), boundary_type='liberal'):
"""
Set attributes
:param sents: (list) spacy-analyzed sentences
:param window: (int) distance threshold within which chains are considered active
:param boundary_type: (str) 'liberal' or 'conservative' boundary scoring
:param pos_filter: (tuple) spacy pos_ labels to exclude (i.e. a pos-based stoplist)
:return: void
"""
self.sentences = self._preproc(sents, pos_filter)
self.actives = self._get_actives(self.sentences, window)
self.gap_scores = [len(self.actives[k]) for k in self.actives.keys()]
self.boundary_vector = self._get_boundaries(self.gap_scores, boundary_type)
@staticmethod
def _preproc(sentences, pos_filter):
"""
Filters out stop POSs and lemmatizes sentences
:param sentences: list of tokenized sentences in doc
:param pos_filter: tuple of spacy pos_ labels to filter out
:return: list
"""
filtered = [[tok for tok in sent if tok.pos_ not in pos_filter] for sent in sentences]
lemmatized = [[tok.lemma_ for tok in sent] for sent in filtered]
return lemmatized
@staticmethod
def _get_actives(sents, window):
"""
Get active lexical chains for each gap between sentences
:param sents: list of tokenized sentences
:param window: difference threshold over which lexical chains are considered active
:return: dictionary containing active lexical chains for each sentence transition
"""
# initialize active chains dictionary
actives = {}
for i in xrange(len(sents)-1):
actives[i] = set()
# loop over all sentences
for sent in sents:
# get index and unique tokens from current sentence
i = sents.index(sent)
uniques_i = set(sent)
# loop over all sentences within dist thresh of current
for diff in xrange(window, 0, -1):
# back off diff when there are less sentences left than dist thresh
while not i + diff < len(sents):
diff -= 1
# find shared tokens between current sent[i] and sent[i+diff]
n = i + diff
uniques_n = set(sents[n])
intersection = uniques_i.intersection(uniques_n)
# add the intersections to all affected transitions between sent[i] and sent[i+diff]
for k in list(xrange(diff)):
[actives[i+k].add(word) for word in intersection]
return actives
@staticmethod
def _get_boundaries(scores, boundary_type):
"""
Calculate boundaries from gap scores
:param scores: list containing # of active chains across each sentence gap in doc
:param boundary_type: string indicating 'liberal' or 'conservative' boundary scoring
:return: list indicating which sentences in doc constitute beginnings of new topic tiles
"""
d_scores = depth_scoring(scores)
boundaries = boundarize(d_scores, type=boundary_type)
boundary_vector = [1] + [0 if i not in boundaries else 1 for i in xrange(len(scores))]
return boundary_vector
# ======================================================================================================================
# Test if invoked directly
# ======================================================================================================================
if __name__ == "__main__":
from decimal import Decimal
import matplotlib.pyplot as plt
import sys
import os
# set doc
try:
doc = sys.argv[1]
except IndexError:
sys.exit("ERROR: Expected 1 arg, got {}\nUsage: (python) lexical_chains.py <docname> <docpath>".format(
len(sys.argv)-1))
# get doc path
path = os.path.dirname(__file__)
if doc in ('coron','athens','chatham','cuba','merida'):
doc_path = os.path.join(path, os.path.join("data", "GUM_voyage_{}_noheads.txt".format(doc)))
else:
raise ValueError("unrecognized document: {}".format(doc))
# get gold
gold_file = os.path.join(path, os.path.join("data", "GUM_5_gold_tiles.txt"))
with open(gold_file) as f:
boundaries = [[int(x) for x in line.split(",")] for line in f.read().split()]
texts = ["athens", "chatham", "coron", "cuba", "merida"]
gold_dict = dict(zip(texts, boundaries))
gold = gold_dict[doc]
# Instantiate TileReader
reader = TileReader()
reader.read(doc_path, newline_tokenization=True)
sents = reader.sentences
# Instantiate Lexical Chains
chains = LexicalChains()
chains.analyze(sents)
# compare gold and predicted boundaries
print "GOLD: {}".format(gold)
print "MINE: {}".format(chains.boundary_vector)
# get window_diff
window_size = len(gold)/4
wdiff = window_diff(chains.boundary_vector, gold, window_size)
print "Window Diff: {}".format(wdiff)
# Plot scores
scores = [0] + chains.gap_scores
plt.plot([x for x in xrange(len(scores))], scores)
for index, grp in enumerate(zip(gold, chains.boundary_vector)):
if 1 == grp[0] == grp[1]:
plt.axvline(x=index, color = 'green', linewidth='2.0')
elif 1 == grp[0] != grp[1]:
plt.axvline(x=index, color = 'red')
elif 1 == grp[1] != grp[0]:
plt.axvline(x=index, color = 'gray')
ymin, ymax = plt.ylim()
xmin, xmax = plt.xlim()
wdiff_rounded = round(Decimal(wdiff), 3)
plt.text(xmax-(xmax-xmin)/4,ymax+0.5, "window diff: {}".format(wdiff_rounded))
plt.show()
|
cligu/compdisc
|
lexical_chains.py
|
Python
|
apache-2.0
| 6,335
|
/**
* Copyright 2014 Shape Security, 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.
*/
// FIXME: the code generated by 6to5 should not have to require ES6 shims.
if (typeof Map === "undefined")
require('es6-map/implement');
if (typeof Symbol === "undefined")
require('es6-symbol/implement');
import ScopeAnalyzer from "./scope-analyzer";
export {ScopeType} from "./scope";
export {DeclarationType} from "./declaration";
export {Accessibility} from "./reference";
export default function analyze(script) {
return ScopeAnalyzer.analyze(script);
}
|
sethmcl/shift-scope-js
|
src/index.js
|
JavaScript
|
apache-2.0
| 1,072
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_74) on Fri Apr 01 14:42:20 CDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>org.apache.solr.analytics.plugin Class Hierarchy (Solr 6.0.0 API)</title>
<meta name="date" content="2016-04-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.solr.analytics.plugin Class Hierarchy (Solr 6.0.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</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/analytics/expression/package-tree.html">Prev</a></li>
<li><a href="../../../../../org/apache/solr/analytics/request/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/analytics/plugin/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.apache.solr.analytics.plugin</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://download.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a>
<ul>
<li type="circle">org.apache.solr.analytics.plugin.<a href="../../../../../org/apache/solr/analytics/plugin/AnalyticsStatisticsCollector.html" title="class in org.apache.solr.analytics.plugin"><span class="typeNameLink">AnalyticsStatisticsCollector</span></a></li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</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/analytics/expression/package-tree.html">Prev</a></li>
<li><a href="../../../../../org/apache/solr/analytics/request/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/analytics/plugin/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2016 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>
|
Velaya/gbol_solr
|
docs/solr-analytics/org/apache/solr/analytics/plugin/package-tree.html
|
HTML
|
apache-2.0
| 5,612
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_07.html">Class Test_AbaRouteValidator_07</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_13699_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_07.html?line=30040#src-30040" >testAbaNumberCheck_13699_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:36:47
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_13699_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=43470#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_07_testAbaNumberCheck_13699_good_xji.html
|
HTML
|
apache-2.0
| 9,181
|
/**
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal;
import com.google.inject.Binding;
import com.google.inject.ProvisionException;
import com.google.inject.spi.DependencyAndSource;
import com.google.inject.spi.ProvisionListener;
import java.util.List;
/**
* Intercepts provisions with a stack of listeners.
*
* @author sameb@google.com (Sam Berlin)
*/
final class ProvisionListenerStackCallback<T> {
private static final ProvisionListener EMPTY_LISTENER[] = new ProvisionListener[0];
private final ProvisionListener[] listeners;
private final Binding<T> binding;
public ProvisionListenerStackCallback(Binding<T> binding, List<ProvisionListener> listeners) {
this.binding = binding;
if (listeners.isEmpty()) {
this.listeners = EMPTY_LISTENER;
} else {
this.listeners = listeners.toArray(new ProvisionListener[listeners.size()]);
}
}
public boolean hasListeners() {
return listeners.length > 0;
}
public T provision(Errors errors, InternalContext context, ProvisionCallback<T> callable)
throws ErrorsException {
Provision provision = new Provision(errors, context, callable);
RuntimeException caught = null;
try {
provision.provision();
} catch(RuntimeException t) {
caught = t;
}
if (provision.exceptionDuringProvision != null) {
throw provision.exceptionDuringProvision;
} else if (caught != null) {
Object listener = provision.erredListener != null ?
provision.erredListener.getClass() : "(unknown)";
throw errors
.errorInUserCode(caught, "Error notifying ProvisionListener %s of %s.%n"
+ " Reason: %s", listener, binding.getKey(), caught)
.toException();
} else {
return provision.result;
}
}
// TODO(sameb): Can this be more InternalFactory-like?
public interface ProvisionCallback<T> {
public T call() throws ErrorsException;
}
private class Provision extends ProvisionListener.ProvisionInvocation<T> {
final Errors errors;
final InternalContext context;
final ProvisionCallback<T> callable;
int index = -1;
T result;
ErrorsException exceptionDuringProvision;
ProvisionListener erredListener;
public Provision(Errors errors, InternalContext context, ProvisionCallback<T> callable) {
this.callable = callable;
this.context = context;
this.errors = errors;
}
@Override
public T provision() {
index++;
if (index == listeners.length) {
try {
result = callable.call();
} catch(ErrorsException ee) {
exceptionDuringProvision = ee;
throw new ProvisionException(errors.merge(ee.getErrors()).getMessages());
}
} else if (index < listeners.length) {
int currentIdx = index;
try {
listeners[index].onProvision(this);
} catch(RuntimeException re) {
erredListener = listeners[currentIdx];
throw re;
}
if (currentIdx == index) {
// Our listener didn't provision -- do it for them.
provision();
}
} else {
throw new IllegalStateException("Already provisioned in this listener.");
}
return result;
}
@Override
public Binding<T> getBinding() {
// TODO(sameb): Because so many places cast directly to BindingImpl & subclasses,
// we can't decorate this to prevent calling getProvider().get(), which means
// if someone calls that they'll get strange errors.
return binding;
}
@Override
public List<DependencyAndSource> getDependencyChain() {
return context.getDependencyChain();
}
}
}
|
julienwetterwald/guice-jit-providers
|
core/src/com/google/inject/internal/ProvisionListenerStackCallback.java
|
Java
|
apache-2.0
| 4,289
|
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (9-ea) on Sun Oct 30 18:53:05 UTC 2016 -->
<title>KHRCLEvent2 (LWJGL 3.1.0 - EGL)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2016-10-30">
<link rel="stylesheet" type="text/css" href="../../../javadoc.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
<script type="text/javascript" src="../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="KHRCLEvent2 (LWJGL 3.1.0 - EGL)";
}
}
catch(err) {
}
//-->
var methods = {"i0":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
var pathtoroot = "../../../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../org/lwjgl/egl/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/lwjgl/egl/IMGImagePlaneAttribs.html" title="class in org.lwjgl.egl"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../org/lwjgl/egl/KHRConfigAttribs.html" title="class in org.lwjgl.egl"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/lwjgl/egl/KHRCLEvent2.html" target="_top">Frames</a></li>
<li><a href="KHRCLEvent2.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>
<ul class="navListSearch">
<li><span>SEARCH: </span>
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">
</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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </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 id="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
</nav>
</header>
<!-- ======== START OF CLASS DATA ======== -->
<main role="main">
<div class="header">
<div class="subTitle"><span class="packageLabelInClass">Package</span> <a href="../../../org/lwjgl/egl/package-summary.html" target="classFrame">org.lwjgl.egl</a></div>
<h2 title="Class KHRCLEvent2" class="title">Class KHRCLEvent2</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.lwjgl.egl.KHRCLEvent2</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">KHRCLEvent2</span>
extends java.lang.Object</pre>
<div class="block">Native bindings to the <a href="https://www.khronos.org/registry/egl/extensions/KHR/EGL_KHR_cl_event2.txt">KHR_cl_event2</a> extension.
<p>This extension allows creating an EGL sync object linked to an OpenCL event object, potentially improving efficiency of sharing images between the two
APIs. The companion cl_khr_egl_event extension provides the complementary functionality of creating an OpenCL event object from an EGL sync object.</p>
<p>This extension is functionally identical to EGL_KHR_cl_event, but is intended to replace that extension. It exists only to address an implementation
issue on 64-bit platforms where passing OpenCL event handles in an EGLint attribute list value is impossible, because the implementations use a 32-bit
type for EGLint.</p>
<p>This extension also incorporates some required functionality from the EGL_KHR_fence_sync extension, similarly modified for 64-bit platforms.</p>
<p>Requires <a href="../../../org/lwjgl/egl/EGL14.html" title="class in org.lwjgl.egl"><code>EGL 1.4</code></a> and <a href="../../../org/lwjgl/egl/KHRFenceSync.html" title="class in org.lwjgl.egl"><code>KHR_fence_sync</code></a>.</p></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary">
<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 int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../org/lwjgl/egl/KHRCLEvent2.html#EGL_CL_EVENT_HANDLE_KHR">EGL_CL_EVENT_HANDLE_KHR</a>
<br><a href="../../../org/lwjgl/egl/KHRCLEvent2.html#EGL_SYNC_CL_EVENT_COMPLETE_KHR">EGL_SYNC_CL_EVENT_COMPLETE_KHR</a>
<br><a href="../../../org/lwjgl/egl/KHRCLEvent2.html#EGL_SYNC_CL_EVENT_KHR">EGL_SYNC_CL_EVENT_KHR</a></span></code> </td>
</tr>
</table>
</li>
</ul>
</section>
<!-- ========== METHOD SUMMARY =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static long</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../org/lwjgl/egl/KHRCLEvent2.html#eglCreateSync64KHR-long-int-org.lwjgl.PointerBuffer-">eglCreateSync64KHR</a></span>(long dpy,
int type,
org.lwjgl.PointerBuffer attrib_list)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a id="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</section>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a id="EGL_CL_EVENT_HANDLE_KHR">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EGL_CL_EVENT_HANDLE_KHR</h4>
<pre>public static final int EGL_CL_EVENT_HANDLE_KHR</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../constant-values.html#org.lwjgl.egl.KHRCLEvent2.EGL_CL_EVENT_HANDLE_KHR">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a id="EGL_SYNC_CL_EVENT_KHR">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EGL_SYNC_CL_EVENT_KHR</h4>
<pre>public static final int EGL_SYNC_CL_EVENT_KHR</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../constant-values.html#org.lwjgl.egl.KHRCLEvent2.EGL_SYNC_CL_EVENT_KHR">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a id="EGL_SYNC_CL_EVENT_COMPLETE_KHR">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>EGL_SYNC_CL_EVENT_COMPLETE_KHR</h4>
<pre>public static final int EGL_SYNC_CL_EVENT_COMPLETE_KHR</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../constant-values.html#org.lwjgl.egl.KHRCLEvent2.EGL_SYNC_CL_EVENT_COMPLETE_KHR">Constant Field Values</a></dd>
</dl>
</li>
</ul>
</li>
</ul>
</section>
<!-- ============ METHOD DETAIL ========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a id="eglCreateSync64KHR-long-int-org.lwjgl.PointerBuffer-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>eglCreateSync64KHR</h4>
<pre>public static long eglCreateSync64KHR(long dpy,
int type,
org.lwjgl.PointerBuffer attrib_list)</pre>
</li>
</ul>
</li>
</ul>
</section>
</li>
</ul>
</div>
</div>
</main>
<!-- ========= END OF CLASS DATA ========= -->
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../org/lwjgl/egl/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/lwjgl/egl/IMGImagePlaneAttribs.html" title="class in org.lwjgl.egl"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../org/lwjgl/egl/KHRConfigAttribs.html" title="class in org.lwjgl.egl"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/lwjgl/egl/KHRCLEvent2.html" target="_top">Frames</a></li>
<li><a href="KHRCLEvent2.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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </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 id="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small><i>Copyright LWJGL. All Rights Reserved. <a href="https://www.lwjgl.org/license">License terms</a>.</i></small></p>
</footer>
</body>
</html>
|
VirtualGamer/SnowEngine
|
Dependencies/egl/docs/javadoc/org/lwjgl/egl/KHRCLEvent2.html
|
HTML
|
apache-2.0
| 12,732
|
/*
* Copyright 2014 Mark Eschbach.
*
* 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.meschbach.onomate.tests.assembly.scenarios;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
/**
*
* @author Mark Eschbach <meschbach@gmail.com>
* @version 0.0.1
* @since 0.0.2
*/
public class OnomateAssembly {
private final WebDriver driver;
private final String deployBase;
public OnomateAssembly(WebDriver driver, String deployBase) {
this.driver = driver;
this.deployBase = deployBase;
}
public StatusResource gotoStatus() {
driver.get(deployBase + "/status");
return new StatusResource();
}
public class StatusResource {
public String status() {
String text = waitOnTextOf(By.id("system-status"));
return text;
}
}
private void waitOn(By selector) {
try {
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.presenceOfElementLocated(selector));
} catch (TimeoutException te) {
throw new WaitTimeoutException("Unable to locate " + selector.toString(), te);
}
}
private String waitOnTextOf(By selector) {
waitOn(selector);
WebElement element = driver.findElement(selector);
return element.getText();
}
public Landing gotoLanding() {
driver.get(deployBase);
return new Landing();
}
public class Landing {
public Dashboard authenticate() {
By entryLocator = By.linkText("Enter");
waitOn(entryLocator);
WebElement element = driver.findElement(entryLocator);
element.click();
return new Dashboard();
}
}
public class Dashboard {
public Dashboard newAuthority(String authorityName, String nameServer, String contactEmail) {
final By soaContainerSelector = By.id("new-zone");
waitOn(soaContainerSelector);
WebElement container = driver.findElement(soaContainerSelector);
container.findElement(By.xpath(".//input[@ng-model = 'fqdn']")).sendKeys(authorityName);
container.findElement(By.xpath(".//input[@ng-model = 'nameServer']")).sendKeys(nameServer);
container.findElement(By.xpath(".//input[@ng-model= 'administrator']")).sendKeys(contactEmail);
container.findElement(By.tagName("button")).click();
return this;
}
public Authority authorityByZone( final String zone ) {
final By selector = By.xpath("//div[ @id = 'zones']/descendant::tr[td[a[text()='"+zone+"']]]");
waitOnTextOf(selector);
WebElement container = driver.findElement(selector);
return new RowZoneAuthority(container);
}
}
public interface Authority {
public String zone() ;
public String nameServer() ;
public String administrator();
public Authority waitOnPersisted();
public Zone details();
}
public class RowZoneAuthority implements Authority{
final WebElement container;
public RowZoneAuthority(WebElement container) {
this.container = container;
}
public String zone() {
return container.findElements(By.tagName("td")).get(0).getText();
}
public String nameServer() {
return container.findElements(By.tagName("td")).get(1).getText();
}
public String administrator() {
return container.findElements(By.tagName("td")).get(2).getText();
}
public Authority waitOnPersisted(){
waitOn(By.xpath("./descendant::td[text() = 'Persisted']"));
return this;
}
public Zone details(){
container.findElement(By.linkText("Details")).click();
waitOn(By.id("resource-records"));
return new Zone();
}
}
public enum RecordType {
A,
NS,
CNAME
}
public class Zone {
public Zone createRecord( final String name, final RecordType type, final String data ){
WebElement wizard = driver.findElement(By.id("rr-wizard"));
wizard.findElement(By.className("rr-host")).sendKeys(name);
WebElement typeElement = wizard.findElement(By.className("rr-type"));
Select typeSelector = new Select(typeElement);
typeSelector.selectByVisibleText(type.name());
wizard.findElement(By.className("rr-data")).sendKeys(data);
wizard.findElement(By.name("create-rr")).click();
return this;
}
public ResourceRow getResource( final String name ){
String xpath = "//table[@id='resource-records']/descendant::tr[ td[contains(@class, 'rr-host') and text() = '"+name+"'] ]";
WebElement resourceRow = driver.findElement(By.xpath(xpath));
return new ResourceRow(resourceRow);
}
}
public class ResourceRow {
WebElement row;
public ResourceRow(WebElement row) {
this.row = row;
}
public String host(){
return row.findElement(By.className("rr-host")).getText();
}
public String type(){
return row.findElement(By.className("rr-type")).getText();
}
public String value(){
return row.findElement(By.className("rr-data")).getText();
}
}
static class WaitTimeoutException extends RuntimeException {
public WaitTimeoutException(String message) {
super(message);
}
public WaitTimeoutException(String message, Throwable cause) {
super(message, cause);
}
public WaitTimeoutException(Throwable cause) {
super(cause);
}
}
}
|
meschbach/onomate
|
tests/assembly/src/main/java/com/meschbach/onomate/tests/assembly/scenarios/OnomateAssembly.java
|
Java
|
apache-2.0
| 6,703
|
# Synsphaeridium catenarium Playford in Playford & Dring SPECIES
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Protozoa/Acritarcha/Synsphaeridium/Synsphaeridium catenarium/README.md
|
Markdown
|
apache-2.0
| 220
|
package gui;
import java.util.Stack;
/**
* Solver class, to be extended by a class that implements the algorithms
* Eduardo Fernandes
* Filipe Eiras
*/
abstract class Solver {
final GameBoard gameBoard;
Stack<GameMove> moveStack;
boolean hasRun;
boolean solutionFound;
Solver(GameBoard input) {
gameBoard = input;
hasRun = false;
solutionFound = false;
}
abstract public void searchSolution() throws Exception;
void initializeSolver() {
moveStack = new Stack<>();
hasRun = false;
solutionFound = gameBoard.isBoardSolved();
}
public Stack<GameMove> getSolution() {
if (hasRun && solutionFound) {
return moveStack;
} else {
return null;
}
}
public boolean getIsSolutionFound() {
return solutionFound;
}
@SuppressWarnings("UnusedDeclaration")
public void printSolutionStack() {
if (hasRun && solutionFound) {
for (GameMove aMoveStack : moveStack) {
System.out.println(aMoveStack);
}
}
if (hasRun && !solutionFound) {
System.out.println("No solution has found");
}
if (!hasRun && !solutionFound) {
System.out.println("You must run the algorithm first");
}
}
@SuppressWarnings("UnusedDeclaration")
abstract public void printStatistics();
}
|
edlf/auto-shot
|
src/gui/Solver.java
|
Java
|
apache-2.0
| 1,438
|
<?php
/*
* PHP QR Code encoder
*
* Image output of code using GD2
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
define('QR_IMAGE', true);
class weixin_qrcode_QRimage {
//----------------------------------------------------------------------
public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE)
{
$image = self::image($frame, $pixelPerPoint, $outerFrame);
if ($filename === false) {
Header("Content-type: image/png");
ImagePng($image);
} else {
if($saveandprint===TRUE){
ImagePng($image, $filename);
header("Content-type: image/png");
ImagePng($image);
}else{
ImagePng($image, $filename);
}
}
ImageDestroy($image);
}
//----------------------------------------------------------------------
public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85)
{
$image = self::image($frame, $pixelPerPoint, $outerFrame);
if ($filename === false) {
Header("Content-type: image/jpeg");
ImageJpeg($image, null, $q);
} else {
ImageJpeg($image, $filename, $q);
}
ImageDestroy($image);
}
//----------------------------------------------------------------------
private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4)
{
$h = count($frame);
$w = strlen($frame[0]);
$imgW = $w + 2*$outerFrame;
$imgH = $h + 2*$outerFrame;
$base_image =ImageCreate($imgW, $imgH);
$col[0] = ImageColorAllocate($base_image,255,255,255);
$col[1] = ImageColorAllocate($base_image,0,0,0);
imagefill($base_image, 0, 0, $col[0]);
for($y=0; $y<$h; $y++) {
for($x=0; $x<$w; $x++) {
if ($frame[$y][$x] == '1') {
ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]);
}
}
}
$target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint);
ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH);
ImageDestroy($base_image);
return $target_image;
}
}
|
liuguogen/Ecstore
|
app/weixin/lib/qrcode/QRimage.php
|
PHP
|
apache-2.0
| 3,278
|
//-----------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//
// THIS CODE AND INFORMATION ARE PROVIDED AS-IS WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//-----------------------------------------------------------------------
#include "pch.h"
#include "HttpRequest.h"
#include <robuffer.h>
#include <shcore.h>
using namespace concurrency;
using namespace Microsoft::WRL;
using namespace Platform;
using namespace std;
using namespace Web;
using namespace Windows::Foundation;
using namespace Windows::Storage::Streams;
// Implementation of IXMLHTTPRequest2Callback used when only the complete response is needed.
// When processing chunks of response data as they are received, use HttpRequestBuffersCallback instead.
class HttpRequestStringCallback
: public RuntimeClass<RuntimeClassFlags<ClassicCom>, IXMLHTTPRequest2Callback, FtmBase>
{
public:
HttpRequestStringCallback(IXMLHTTPRequest2* httpRequest,
cancellation_token ct = concurrency::cancellation_token::none()) :
request(httpRequest), cancellationToken(ct)
{
// Register a callback function that aborts the HTTP operation when
// the cancellation token is canceled.
if (cancellationToken != cancellation_token::none())
{
registrationToken = cancellationToken.register_callback([this]()
{
if (request != nullptr)
{
request->Abort();
}
});
}
}
// Called when the HTTP request is being redirected to a new URL.
IFACEMETHODIMP OnRedirect(IXMLHTTPRequest2*, PCWSTR)
{
return S_OK;
}
// Called when HTTP headers have been received and processed.
IFACEMETHODIMP OnHeadersAvailable(IXMLHTTPRequest2*, DWORD statusCode, PCWSTR reasonPhrase)
{
HRESULT hr = S_OK;
// We must not propagate exceptions back to IXHR2.
try
{
this->statusCode = statusCode;
this->reasonPhrase = reasonPhrase;
}
catch (std::bad_alloc&)
{
hr = E_OUTOFMEMORY;
}
return hr;
}
// Called when a portion of the entity body has been received.
IFACEMETHODIMP OnDataAvailable(IXMLHTTPRequest2*, ISequentialStream*)
{
return S_OK;
}
// Called when the entire entity response has been received.
IFACEMETHODIMP OnResponseReceived(IXMLHTTPRequest2*, ISequentialStream* responseStream)
{
wstring wstr;
HRESULT hr = ReadUtf8StringFromSequentialStream(responseStream, wstr);
// We must not propagate exceptions back to IXHR2.
try
{
completionEvent.set(make_tuple<HRESULT, wstring>(move(hr), move(wstr)));
}
catch (std::bad_alloc&)
{
hr = E_OUTOFMEMORY;
}
return hr;
}
// Simulate the functionality of DataReader.ReadString().
// This is needed because DataReader requires IRandomAccessStream and this
// code has an ISequentialStream that does not have a conversion to IRandomAccessStream like IStream does.
HRESULT ReadUtf8StringFromSequentialStream(ISequentialStream* readStream, wstring& str)
{
// Convert the response to Unicode wstring.
HRESULT hr;
// Holds the response as a Unicode string.
wstringstream ss;
while (true)
{
ULONG cb;
char buffer[4096];
// Read the response as a UTF-8 string. Since UTF-8 characters are 1-4 bytes long,
// we need to make sure we only read an integral number of characters. So we'll
// start with 4093 bytes.
hr = readStream->Read(buffer, sizeof(buffer) - 3, &cb);
if (FAILED(hr) || (cb == 0))
{
break; // Error or no more data to process, exit loop.
}
if (cb == sizeof(buffer) - 3)
{
ULONG subsequentBytesRead;
unsigned int i, cl;
// Find the first byte of the last UTF-8 character in the buffer.
for (i = cb - 1; (i >= 0) && ((buffer[i] & 0xC0) == 0x80); i--);
// Calculate the number of subsequent bytes in the UTF-8 character.
if (((unsigned char)buffer[i]) < 0x80)
{
cl = 1;
}
else if (((unsigned char)buffer[i]) < 0xE0)
{
cl = 2;
}
else if (((unsigned char)buffer[i]) < 0xF0)
{
cl = 3;
}
else
{
cl = 4;
}
// Read any remaining bytes.
if (cb < i + cl)
{
hr = readStream->Read(buffer + cb, i + cl - cb, &subsequentBytesRead);
if (FAILED(hr))
{
break; // Error, exit loop.
}
cb += subsequentBytesRead;
}
}
// First determine the size required to store the Unicode string.
int const sizeRequired = MultiByteToWideChar(CP_UTF8, 0, buffer, cb, nullptr, 0);
if (sizeRequired == 0)
{
// Invalid UTF-8.
hr = HRESULT_FROM_WIN32(GetLastError());
break;
}
unique_ptr<char16[]> wstr(new(std::nothrow) char16[sizeRequired + 1]);
if (wstr.get() == nullptr)
{
hr = E_OUTOFMEMORY;
break;
}
// Convert the string from UTF-8 to UTF-16LE. This can never fail, since
// the previous call above succeeded.
MultiByteToWideChar(CP_UTF8, 0, buffer, cb, wstr.get(), sizeRequired);
wstr[sizeRequired] = L'\0'; // Terminate the string.
ss << wstr.get(); // Write the string to the stream.
}
str = SUCCEEDED(hr) ? ss.str() : wstring();
return (SUCCEEDED(hr)) ? S_OK : hr; // Don't return S_FALSE.
}
// Called when an error occurs during the HTTP request.
IFACEMETHODIMP OnError(IXMLHTTPRequest2*, HRESULT hrError)
{
HRESULT hr = S_OK;
// We must not propagate exceptions back to IXHR2.
try
{
completionEvent.set(make_tuple<HRESULT, wstring>(move(hrError), wstring()));
}
catch (std::bad_alloc&)
{
hr = E_OUTOFMEMORY;
}
return hr;
}
// Retrieves the completion event for the HTTP operation.
task_completion_event<tuple<HRESULT, wstring>> const& GetCompletionEvent() const
{
return completionEvent;
}
int GetStatusCode() const
{
return statusCode;
}
wstring GetReasonPhrase() const
{
return reasonPhrase;
}
private:
~HttpRequestStringCallback()
{
// Unregister the callback.
if (cancellationToken != cancellation_token::none())
{
cancellationToken.deregister_callback(registrationToken);
}
}
// Signals that the download operation was canceled.
cancellation_token cancellationToken;
// Used to unregister the cancellation token callback.
cancellation_token_registration registrationToken;
// The IXMLHTTPRequest2 that processes the HTTP request.
ComPtr<IXMLHTTPRequest2> request;
// Task completion event that is set when the
// download operation completes.
task_completion_event<tuple<HRESULT, wstring>> completionEvent;
int statusCode;
wstring reasonPhrase;
};
// Copy bytes from the sequential stream into the buffer provided until
// we reach the end of one or the other.
unsigned int Web::Details::HttpRequestBuffersCallback::ReadData(
_Out_writes_(outputBufferSize) byte* outputBuffer,
unsigned int outputBufferSize)
{
// Lock the data event while doing the read, to ensure that any bytes we don't read will
// result in the correct event getting triggered.
concurrency::critical_section::scoped_lock lock(dataEventLock);
ULONG bytesRead;
CheckHResult(dataStream.Get()->Read(outputBuffer, outputBufferSize, &bytesRead));
if (bytesRead < outputBufferSize)
{
// We need to reset the data event, which we can only do by creating a new one.
dataEvent = task_completion_event<void>();
}
return bytesRead;
}
// Create a task that completes when data is available, in an exception-safe way.
task<void> Web::Details::HttpRequestBuffersCallback::CreateDataTask()
{
concurrency::critical_section::scoped_lock lock(dataEventLock);
return create_task(dataEvent, cancellationToken);
}
HttpRequest::HttpRequest() : responseComplete(true), statusCode(200)
{
}
// Start a download of the specified URI using the specified method. The returned task produces the
// HTTP response text. The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
task<wstring> HttpRequest::DownloadAsync(PCWSTR httpMethod, PCWSTR uri, cancellation_token cancellationToken,
PCWSTR contentType, IStream* postStream, uint64 postStreamSizeToSend)
{
// Create an IXMLHTTPRequest2 object.
ComPtr<IXMLHTTPRequest2> xhr;
CheckHResult(CoCreateInstance(CLSID_XmlHttpRequest, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&xhr)));
// Create callback.
auto stringCallback = Make<HttpRequestStringCallback>(xhr.Get(), cancellationToken);
CheckHResult(stringCallback ? S_OK : E_OUTOFMEMORY);
auto completionTask = create_task(stringCallback->GetCompletionEvent());
// Create a request.
CheckHResult(xhr->Open(httpMethod, uri, stringCallback.Get(), nullptr, nullptr, nullptr, nullptr));
if (postStream != nullptr && contentType != nullptr)
{
CheckHResult(xhr->SetRequestHeader(L"Content-Type", contentType));
}
// Send the request.
CheckHResult(xhr->Send(postStream, postStreamSizeToSend));
// Return a task that completes when the HTTP operation completes.
// We pass the callback to the continuation because the lifetime of the
// callback must exceed the operation to ensure that cancellation
// works correctly.
return completionTask.then([this, stringCallback](tuple<HRESULT, wstring> resultTuple)
{
// If the GET operation failed, throw an Exception.
CheckHResult(std::get<0>(resultTuple));
statusCode = stringCallback->GetStatusCode();
reasonPhrase = stringCallback->GetReasonPhrase();
return std::get<1>(resultTuple);
});
}
// Start an HTTP GET on the specified URI. The returned task completes once the entire response
// has been received, and the task produces the HTTP response text. The status code and reason
// can be read with GetStatusCode() and GetReasonPhrase().
task<wstring> HttpRequest::GetAsync(Uri^ uri, cancellation_token cancellationToken)
{
return DownloadAsync(L"GET",
uri->AbsoluteUri->Data(),
cancellationToken,
nullptr,
nullptr,
0);
}
void HttpRequest::CreateMemoryStream(IStream **stream)
{
auto randomAccessStream = ref new Windows::Storage::Streams::InMemoryRandomAccessStream();
CheckHResult(CreateStreamOverRandomAccessStream(randomAccessStream, IID_PPV_ARGS(stream)));
}
// Start an HTTP POST on the specified URI, using a string body. The returned task produces the
// HTTP response text. The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
task<wstring> HttpRequest::PostAsync(Uri^ uri, const wstring& body, cancellation_token cancellationToken)
{
int length = 0;
ComPtr<IStream> postStream;
CreateMemoryStream(&postStream);
if (body.length() > 0)
{
// Get the required buffer size.
int size = WideCharToMultiByte(CP_UTF8, // UTF-8
0, // Conversion type
body.c_str(), // Unicode string to convert
static_cast<int>(body.length()), // Size
nullptr, // Output buffer
0, // Output buffer size
nullptr,
nullptr);
CheckHResult((size != 0) ? S_OK : HRESULT_FROM_WIN32(GetLastError()));
std::unique_ptr<char[]> tempData(new char[size]);
length = WideCharToMultiByte(CP_UTF8, // UTF-8
0, // Conversion type
body.c_str(), // Unicode string to convert
static_cast<int>(body.length()), // Size
tempData.get(), // Output buffer
size, // Output buffer size
nullptr,
nullptr);
CheckHResult((length != 0) ? S_OK : HRESULT_FROM_WIN32(GetLastError()));
CheckHResult(postStream->Write(tempData.get(), length, nullptr));
}
return DownloadAsync(L"POST",
uri->AbsoluteUri->Data(),
cancellationToken,
L"text/plain;charset=utf-8",
postStream.Get(),
length);
}
// Start an HTTP POST on the specified URI, using a stream body. The returned task produces the
// HTTP response text. The status code and reason can be read with GetStatusCode() and GetReasonPhrase().
task<wstring> HttpRequest::PostAsync(Uri^ uri, PCWSTR contentType, IStream* postStream,
uint64 postStreamSizeToSend, cancellation_token cancellationToken)
{
return DownloadAsync(L"POST",
uri->AbsoluteUri->Data(),
cancellationToken,
contentType,
postStream,
postStreamSizeToSend);
}
// Send a request but don't return the response. Instead, let the caller read it with ReadAsync().
task<void> HttpRequest::SendAsync(const wstring& httpMethod, Uri^ uri, cancellation_token cancellationToken)
{
// Create an IXMLHTTPRequest2 object.
ComPtr<IXMLHTTPRequest2> xhr;
CheckHResult(CoCreateInstance(CLSID_XmlHttpRequest, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&xhr)));
// Create callback.
buffersCallback = Make<Web::Details::HttpRequestBuffersCallback>(xhr.Get(), cancellationToken);
CheckHResult(buffersCallback ? S_OK : E_OUTOFMEMORY);
ComPtr<IXMLHTTPRequest2Callback> xhrCallback;
CheckHResult(buffersCallback.As(&xhrCallback));
// Open and send the request.
CheckHResult(xhr->Open(httpMethod.c_str(),
uri->AbsoluteUri->Data(),
xhrCallback.Get(),
nullptr,
nullptr,
nullptr,
nullptr));
responseComplete = false;
CheckHResult(xhr->Send(nullptr, 0));
// Return a task that completes when the HTTP operation completes.
// Since buffersCallback holds a reference on the callback, the lifetime of the callback will exceed
// the operation and ensure that cancellation works correctly.
return buffersCallback->CreateDataTask().then([this]()
{
CheckHResult(buffersCallback->GetError());
statusCode = buffersCallback->GetStatusCode();
reasonPhrase = buffersCallback->GetReasonPhrase();
});
}
// Read a chunk of data from the HTTP response, up to a specified length or until we reach the end
// of the response, and store the value in the provided buffer. This is useful for large content,
// enabling the streaming of the result.
task<void> HttpRequest::ReadAsync(Windows::Storage::Streams::IBuffer^ readBuffer, unsigned int offsetInBuffer,
unsigned int requestedBytesToRead)
{
if (offsetInBuffer + requestedBytesToRead > readBuffer->Capacity)
{
throw ref new InvalidArgumentException();
}
// Return a task that completes when a read completes.
// We pass the callback to the continuation because the lifetime of the
// callback must exceed the operation to ensure that cancellation
// works correctly.
return buffersCallback->CreateDataTask().then([this, readBuffer, offsetInBuffer, requestedBytesToRead]()
{
CheckHResult(buffersCallback->GetError());
// Get a pointer to the location to copy data into.
ComPtr<IBufferByteAccess> bufferByteAccess;
CheckHResult(reinterpret_cast<IUnknown*>(readBuffer)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess)));
byte* outputBuffer; // Returned internal pointer, do not free this value.
CheckHResult(bufferByteAccess->Buffer(&outputBuffer));
// Copy bytes from the sequential stream into the buffer provided until
// we reach the end of one or the other.
readBuffer->Length = buffersCallback->ReadData(outputBuffer + offsetInBuffer, requestedBytesToRead);
if (buffersCallback->IsResponseReceived() && (readBuffer->Length < requestedBytesToRead))
{
responseComplete = true;
}
});
}
|
gisfromscratch/windowsappsamples
|
Windows account authorization sample/C++/Shared/HttpRequest.cpp
|
C++
|
apache-2.0
| 17,910
|
package com.fxt.model.vo.basic;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("serial")
public class AccountShowModel implements Serializable
{
/**
* 提示信息
*/
private String msgTip = "";
/**
* 系统数据
*/
@SuppressWarnings("rawtypes")
private Map<String,List> map = new HashMap<String,List>();
public String getMsgTip()
{
return msgTip;
}
public void setMsgTip(String msgTip)
{
this.msgTip = msgTip;
}
@SuppressWarnings("rawtypes")
public Map<String, List> getMap() {
return map;
}
@SuppressWarnings("rawtypes")
public void setMap(Map<String, List> map) {
this.map = map;
}
}
|
tycooc/ERP
|
src/main/java/com/fxt/model/vo/basic/AccountShowModel.java
|
Java
|
apache-2.0
| 790
|
/**
* Copyright (c) 2017 The original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cqrs.example;
import org.cqrs.core.CQRS;
import org.cqrs.example.domain.BankAccount;
import org.cqrs.example.handler.BankAccountHandler;
import org.cqrs.example.handler.BankAccountHandler.BankAccountCmd;
import com.google.common.collect.ImmutableMap;
public class BankAccountTest {
public static void main(String[] args) throws InterruptedException {
CQRS cqrs = CQRS.get();
new BankAccountHandler(BankAccount.class);
String id = cqrs.execute(BankAccountCmd.OPEN_ACCOUNT, ImmutableMap.of("name", "wrd", "balance", 100.00));
// for (int i = 0; i < 500; i++) {
// cqrs.execute(BankAccountCmd.DEPOSITE_MONEY, ImmutableMap.of("id", id, "amount", Math.random() * 100));
// }
cqrs.execute(BankAccountCmd.DEPOSITE_MONEY, ImmutableMap.of("id", id, "amount", Math.random() * 100));
// cqrs.execute(BankAccountCmd.WITHDRAWAL_MONEY, ImmutableMap.of("id", id, "amount", 101.00));
System.out.println("========================================");
System.out.println(cqrs.domain(BankAccount.class).aggregateRoot(id));
cqrs.shutdown();
}
}
|
linkeer8802/cqrs
|
cqrs-sample/src/main/java/org/cqrs/example/BankAccountTest.java
|
Java
|
apache-2.0
| 1,794
|
/*
* Copyright 2011 Objectos, Fábrica de Software LTDA.
*
* 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 br.com.objectos.jabuticava;
import java.math.BigDecimal;
/**
* @author marcio.endo@objectos.com.br (Marcio Endo)
*/
public interface Numero {
BigDecimal bigDecimalValue();
double doubleValue();
float floatValue();
int intValue();
long longValue();
Numero aplicarPercentual(Percentual percentual);
boolean maiorQue(Numero outro);
boolean maiorOuIgualA(Numero outro);
boolean menorQue(Numero outro);
boolean menorOuIgualA(Numero outro);
boolean isZero();
BigDecimal toBigDecimal();
}
|
objectos/jabuticava
|
financeiro/src/main/java/br/com/objectos/jabuticava/Numero.java
|
Java
|
apache-2.0
| 1,146
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_144) on Fri Apr 13 22:56:24 CEST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface se.litsec.eidas.opensaml.ext.attributes.address.PostName (eIDAS extension for OpenSAML 3.x - 1.1.1)</title>
<meta name="date" content="2018-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface se.litsec.eidas.opensaml.ext.attributes.address.PostName (eIDAS extension for OpenSAML 3.x - 1.1.1)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/PostName.html" title="interface in se.litsec.eidas.opensaml.ext.attributes.address">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?se/litsec/eidas/opensaml/ext/attributes/address/class-use/PostName.html" target="_top">Frames</a></li>
<li><a href="PostName.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface se.litsec.eidas.opensaml.ext.attributes.address.PostName" class="title">Uses of Interface<br>se.litsec.eidas.opensaml.ext.attributes.address.PostName</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/PostName.html" title="interface in se.litsec.eidas.opensaml.ext.attributes.address">PostName</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#se.litsec.eidas.opensaml.ext.attributes.address.impl">se.litsec.eidas.opensaml.ext.attributes.address.impl</a></td>
<td class="colLast">
<div class="block">Implementation classes for the supporting types of the eIDAS <code>CurrentAddressStructuredType</code>.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="se.litsec.eidas.opensaml.ext.attributes.address.impl">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/PostName.html" title="interface in se.litsec.eidas.opensaml.ext.attributes.address">PostName</a> in <a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/impl/package-summary.html">se.litsec.eidas.opensaml.ext.attributes.address.impl</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/impl/package-summary.html">se.litsec.eidas.opensaml.ext.attributes.address.impl</a> that implement <a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/PostName.html" title="interface in se.litsec.eidas.opensaml.ext.attributes.address">PostName</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/impl/PostNameImpl.html" title="class in se.litsec.eidas.opensaml.ext.attributes.address.impl">PostNameImpl</a></span></code>
<div class="block">Implementation of <code>PostName</code>.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/impl/package-summary.html">se.litsec.eidas.opensaml.ext.attributes.address.impl</a> that return <a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/PostName.html" title="interface in se.litsec.eidas.opensaml.ext.attributes.address">PostName</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/PostName.html" title="interface in se.litsec.eidas.opensaml.ext.attributes.address">PostName</a></code></td>
<td class="colLast"><span class="typeNameLabel">PostNameBuilder.</span><code><span class="memberNameLink"><a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/impl/PostNameBuilder.html#buildObject--">buildObject</a></span>()</code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/PostName.html" title="interface in se.litsec.eidas.opensaml.ext.attributes.address">PostName</a></code></td>
<td class="colLast"><span class="typeNameLabel">PostNameBuilder.</span><code><span class="memberNameLink"><a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/impl/PostNameBuilder.html#buildObject-java.lang.String-java.lang.String-java.lang.String-">buildObject</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> namespaceURI,
<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> localName,
<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> namespacePrefix)</code></td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../se/litsec/eidas/opensaml/ext/attributes/address/PostName.html" title="interface in se.litsec.eidas.opensaml.ext.attributes.address">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?se/litsec/eidas/opensaml/ext/attributes/address/class-use/PostName.html" target="_top">Frames</a></li>
<li><a href="PostName.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.litsec.se">Litsec AB</a>. All rights reserved.</small></p>
</body>
</html>
|
litsec/eidas-opensaml
|
docs/javadoc/opensaml3/1.1.1/se/litsec/eidas/opensaml/ext/attributes/address/class-use/PostName.html
|
HTML
|
apache-2.0
| 9,810
|
package br.senac.tads4.piiv.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.senac.tads4.piiv.model.Cliente;
import br.senac.tads4.piiv.model.Endereco;
import br.senac.tads4.piiv.model.enumerated.Sexo;
import br.senac.tads4.piiv.repository.ClienteRepository;
import br.senac.tads4.piiv.repository.TipoConsoleRepository;
import br.senac.tads4.piiv.security.UsuarioSistema;
import br.senac.tads4.piiv.service.ClienteService;
import br.senac.tads4.piiv.service.exception.CpfClienteJaCadastradoException;
import br.senac.tads4.piiv.service.exception.EmailClienteJaCadastradoException;
import br.senac.tads4.piiv.service.exception.EmailUsuarioJaCadastradoException;
import br.senac.tads4.piiv.service.exception.SenhaUsuarioObrigatoriaException;
@Controller
@RequestMapping("/clientes")
public class ClienteController {
@Autowired
private ClienteRepository clienteRepository;
@Autowired
private TipoConsoleRepository tipoConsoleRepository;
@Autowired
private ClienteService clienteService;
/**
* Exibe o formulário para cadastro de um novo cliente
*
* @param cliente
* @param endereco
* @return
*/
@RequestMapping(value = "/novo")
public ModelAndView novo(Cliente cliente, Endereco endereco) {
ModelAndView mv = new ModelAndView("site/cliente/CadastroCliente");
this.menu(mv);
mv.addObject("sexos", Sexo.values());
return mv;
}
/**
* Método que faz a inserção de um novo cliente e cria um usuário com perfíl de
* cliente para acessar o sistema. Antes de salvar um cliente o sistema dispara
* o evento para tentar criar o perfíl de usuário
*
* @param cliente
* @param result
* @param attributes
* @return
*/
@RequestMapping(value = "/novo", method = RequestMethod.POST)
public ModelAndView novo(@Valid Cliente cliente, BindingResult resultCliente, @Valid Endereco endereco,
BindingResult resultEndereco, RedirectAttributes attributes) {
if (resultCliente.hasErrors()) {
return novo(cliente, endereco);
}
if (resultEndereco.hasErrors()) {
resultCliente.rejectValue("enderecos", "", "Existem campos obrigatórios do endereço sem preenchimento");
return novo(cliente, endereco);
}
try {
clienteService.salvar(cliente, endereco);
} catch (CpfClienteJaCadastradoException e) {
resultCliente.rejectValue("cpf", e.getMessage(), e.getMessage());
return novo(cliente, endereco);
} catch (EmailClienteJaCadastradoException e) {
resultCliente.rejectValue("email", e.getMessage(), e.getMessage());
return novo(cliente, endereco);
} catch (EmailUsuarioJaCadastradoException e) {
resultCliente.rejectValue("email", e.getMessage(), e.getMessage());
return novo(cliente, endereco);
} catch (SenhaUsuarioObrigatoriaException e) {
resultCliente.rejectValue("senha", e.getMessage(), e.getMessage());
return novo(cliente, endereco);
}
attributes.addFlashAttribute("mensagem", "Bem vindo a The Code Games!");
return new ModelAndView("redirect:/login/site");
}
/**
* Exibe a page home do cliente
*
* @param id
* @return
*/
@RequestMapping(value = "/conta/index")
public ModelAndView conta(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("site/cliente/PainelCliente");
Cliente cliente = this.getUsuarioLogado(request);
cliente = clienteRepository.findOne(cliente.getId());
if (cliente == null) {
return new ModelAndView("redirect:/logout");
}
mv.addObject("cliente", cliente);
this.menu(mv);
return mv;
}
/**
* Exibe o formulário com os dados cadastrais do cliente
*
* @param id
* @return
*/
@RequestMapping(value = "/conta/editar/dados-cadastrais")
public ModelAndView editarDadosCadastrais(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("site/cliente/DadosCadastraisCliente");
Cliente cliente = this.getUsuarioLogado(request);
cliente = clienteRepository.findOne(cliente.getId());
if (cliente == null) {
return new ModelAndView("redirect:/logout");
}
mv.addObject("cliente", cliente);
mv.addObject("sexos", Sexo.values());
this.menu(mv);
return mv;
}
/**
* Exibe o formulário com os dados cadastrais do cliente quando existe erro no
* preenchimento
*
* @param cliente
* @return
*/
private ModelAndView editarDadosCadastrais(Cliente cliente) {
ModelAndView mv = new ModelAndView("site/cliente/DadosCadastraisCliente");
mv.addObject("cliente", cliente);
mv.addObject("sexos", Sexo.values());
this.menu(mv);
return mv;
}
/**
* Método para salvar as alterações dos dados cadastrais do cliente
*
* @param cliente
* @param result
* @param attributes
* @return
*/
@RequestMapping(value = "/conta/editar/dados-cadastrais", method = RequestMethod.POST)
public ModelAndView salvarDadosCadastrais(@Valid Cliente cliente, BindingResult result,
RedirectAttributes attributes) {
if (result.hasErrors()) {
return editarDadosCadastrais(cliente);
}
try {
clienteService.alterar(cliente);
} catch (Exception e) {
return editarDadosCadastrais(cliente);
}
attributes.addFlashAttribute("mensagem", "Dados cadastrais alterados com sucesso!");
return new ModelAndView("redirect:/clientes/conta/index");
}
/**
* Exibe o formulário com o endereço principal do cliente
*
* @param id
* @return
*/
@RequestMapping(value = "/conta/editar/endereco-principal")
public ModelAndView editarEnderecoPrincipal(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("site/cliente/EnderecoCliente");
Cliente cliente = this.getUsuarioLogado(request);
cliente = clienteRepository.findOne(cliente.getId());
if (cliente == null) {
return new ModelAndView("redirect:/logout");
}
mv.addObject("cliente", cliente);
mv.addObject("endereco", cliente.getEnderecos().get(0));
this.menu(mv);
return mv;
}
/**
* Exibe o formulário com o endereço principal do cliente quando existem erros
* de preenchimento
*
* @param endereco
* @return
*/
private ModelAndView editarEnderecoPrincipal(Endereco endereco) {
ModelAndView mv = new ModelAndView("site/cliente/EnderecoCliente");
Cliente cliente = clienteRepository.findOne(endereco.getCliente().getId());
mv.addObject("cliente", cliente);
mv.addObject("endereco", endereco);
this.menu(mv);
return mv;
}
/**
* Método para salvar as alterações no endereço principal do cliente
*
* @param endereco
* @param result
* @param attributes
* @return
*/
@RequestMapping(value = "/conta/editar/endereco-principal", method = RequestMethod.POST)
public ModelAndView salvarEnderecoPrincipal(@Valid Endereco endereco, BindingResult result,
RedirectAttributes attributes) {
if (result.hasErrors()) {
return editarEnderecoPrincipal(endereco);
}
try {
clienteService.alterarEnderecoPrincipal(endereco);
} catch (Exception e) {
return editarEnderecoPrincipal(endereco);
}
attributes.addFlashAttribute("mensagem", "Endereço principal alterado com sucesso!");
return new ModelAndView("redirect:/clientes/conta/index");
}
/**
* Exibe o formulário com endereço adicional do cliente
*
* @param id
* @param index
* @return
*/
@RequestMapping(value = "/conta/editar/endereco-adicional/{index}")
public ModelAndView editarEnderecoAdicional(@PathVariable Integer index, HttpServletRequest request) {
ModelAndView mv = new ModelAndView("site/cliente/EnderecoCliente");
Cliente cliente = this.getUsuarioLogado(request);
cliente = clienteRepository.findOne(cliente.getId());
if (cliente == null) {
return new ModelAndView("redirect:/logout");
}
mv.addObject("cliente", cliente);
mv.addObject("endereco", cliente.getEnderecos().get(index));
this.menu(mv);
return mv;
}
/**
* Exibe o formulário com endereço adicional do cliente quando existem erros de
* preenchimento
*
* @param endereco
* @param index
* @return
*/
private ModelAndView editarEnderecoAdicional(Endereco endereco, @RequestParam Integer index) {
ModelAndView mv = new ModelAndView("site/cliente/EnderecoCliente");
Cliente cliente = clienteRepository.findOne(endereco.getCliente().getId());
mv.addObject("cliente", cliente);
mv.addObject("endereco", endereco);
this.menu(mv);
return mv;
}
/**
* Método para salvar as alterações no endereço adicional do cliente
*
* @param endereco
* @param index
* @param result
* @param attributes
* @return
*/
@RequestMapping(value = "/conta/editar/endereco-adicional", method = RequestMethod.POST)
public ModelAndView salvarEnderecoAdicional(@Valid Endereco endereco, @RequestParam Integer index,
BindingResult result, RedirectAttributes attributes) {
if (result.hasErrors()) {
return editarEnderecoAdicional(endereco, index);
}
try {
clienteService.alterarEnderecoAdicional(endereco, index);
} catch (Exception e) {
return editarEnderecoAdicional(endereco, index);
}
attributes.addFlashAttribute("mensagem", "Endereço adicional alterado com sucesso!");
return new ModelAndView("redirect:/clientes/conta/index");
}
/**
* Método para excluir endereço adicional
*
* @param id
* @param index
* @return
*/
@DeleteMapping(value = "/conta/remover-endereco-adicional/{id}/{index}")
public @ResponseBody ResponseEntity<?> removerEnderecoAdicional(@PathVariable Long id,
@PathVariable Integer index, HttpServletRequest request) {
this.conferirId(id, request);
try {
clienteService.removerEnderecoAdicional(id, index);
} catch (Exception e) {
return ResponseEntity.badRequest().body("Não foi possível excluir o registro");
}
return ResponseEntity.ok().build();
}
/**
* Exibe o formulário para cadastrar um novo endereço para o cliente
*
* @param id
* @param index
* @return
*/
@RequestMapping(value = "/conta/cadastrar/endereco-adicional/{index}")
public ModelAndView cadastrarEnderecoAdicional(@PathVariable Integer index, HttpServletRequest request) {
ModelAndView mv = new ModelAndView("site/cliente/NovoEnderecoCliente");
Cliente cliente = this.getUsuarioLogado(request);
cliente = clienteRepository.findOne(cliente.getId());
if (cliente == null) {
return new ModelAndView("redirect:/logout");
}
Endereco endereco = new Endereco();
endereco.setCliente(cliente);
mv.addObject("cliente", cliente);
mv.addObject("endereco", endereco);
this.menu(mv);
return mv;
}
/**
* Exibe o formulário com o novo endereço adicional quando existem erros
*
* @param endereco
* @param index
* @return
*/
private ModelAndView cadastrarEnderecoAdicional(Endereco endereco, @RequestParam Integer index) {
ModelAndView mv = new ModelAndView("site/cliente/NovoEnderecoCliente");
Cliente cliente = clienteRepository.findOne(endereco.getCliente().getId());
mv.addObject("cliente", cliente);
mv.addObject("endereco", endereco);
this.menu(mv);
return mv;
}
/**
* Método para salvar o novo endereço adicional
*
* @param endereco
* @param index
* @param result
* @param attributes
* @return
*/
@RequestMapping(value = "/conta/cadastrar/endereco-adicional", method = RequestMethod.POST)
public ModelAndView cadastrarEnderecoAdicional(@Valid Endereco endereco, @RequestParam Integer index,
BindingResult result, RedirectAttributes attributes) {
if (result.hasErrors()) {
return cadastrarEnderecoAdicional(endereco, index);
}
try {
clienteService.salvarEnderecoAdicional(endereco);
} catch (Exception e) {
return cadastrarEnderecoAdicional(endereco, index);
}
attributes.addFlashAttribute("mensagem", "Endereço adicional adicionado com sucesso!");
return new ModelAndView("redirect:/clientes/conta/index");
}
/**
* Monta o menu superior
*
* @param mv
*/
private void menu(ModelAndView mv) {
mv.addObject("tiposConsole", tipoConsoleRepository.findAll());
}
/**
* Método para garantir que a manipulação dos dados do cliente sejam apenas para
* o cliente logado no sistema
*
* @param id
* @return
*/
private ModelAndView conferirId(Long id, HttpServletRequest request) {
Cliente cliente = this.getUsuarioLogado(request);
try {
if (id != cliente.getId()) {
return new ModelAndView("redirect:/logout");
}
} catch (Exception e) {
return null;
}
return null;
}
/**
* Retorna o usuário cliente logado
*
* @param request
* @return
*/
private Cliente getUsuarioLogado(HttpServletRequest request) {
try {
HttpSession session = (HttpSession) request.getSession();
UsuarioSistema usuarioSistema = (UsuarioSistema) session.getAttribute("usuarioLogado");
return usuarioSistema.getCliente();
} catch (Exception e) {
return null;
}
}
}
|
eltonsalles/lojagames
|
src/main/java/br/senac/tads4/piiv/controller/ClienteController.java
|
Java
|
apache-2.0
| 13,493
|
# scala-enum
<a href='https://travis-ci.org/jeffmay/scala-enum'>
<img src='https://travis-ci.org/jeffmay/scala-enum.svg' alt='Build Status' />
</a>
<a href='https://coveralls.io/github/jeffmay/scala-enum?branch=master'>
<img src='https://coveralls.io/repos/jeffmay/scala-enum/badge.svg?branch=master&service=github' alt='Coverage Status' />
</a>
</a>
<table>
<tr>
<th>scala-enum</th>
<th>scala-enum-json</th>
</tr>
<tr>
<td>
<a href='https://bintray.com/jeffmay/maven/scala-enum/_latestVersion'>
<img src='https://api.bintray.com/packages/jeffmay/maven/scala-enum/images/download.svg'>
</a>
</td>
<td>
<a href='https://bintray.com/jeffmay/maven/scala-enum-json/_latestVersion'>
<img src='https://api.bintray.com/packages/jeffmay/maven/scala-enum-json/images/download.svg'>
</a>
</td>
</tr>
</table>
A Scala Enumeration wrapper for an improved Scala interface when dealing with Scala Enumerations.
|
jeffmay/scala-enum
|
README.md
|
Markdown
|
apache-2.0
| 976
|
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cordvtn.rest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.onlab.packet.IpAddress;
import org.onlab.packet.MacAddress;
import org.onosproject.cordvtn.CordVtnService;
import org.onosproject.net.HostId;
import org.onosproject.rest.AbstractWebResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.Map;
/**
* Dummy Neutron ML2 mechanism driver.
* It just returns OK for ports resource requests except for the port update.
*/
@Path("ports")
public class NeutronMl2PortsWebResource extends AbstractWebResource {
protected final Logger log = LoggerFactory.getLogger(getClass());
private static final String PORTS_MESSAGE = "Received ports %s";
private static final String PORT = "port";
private static final String DEVICE_ID = "device_id";
private static final String NAME = "name";
private static final String MAC_ADDRESS = "mac_address";
private static final String ADDRESS_PAIRS = "allowed_address_pairs";
private static final String IP_ADDERSS = "ip_address";
private static final String STAG_PREFIX = "stag-";
private static final int STAG_BEGIN_INDEX = 5;
private final CordVtnService service = get(CordVtnService.class);
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createPorts(InputStream input) {
log.trace(String.format(PORTS_MESSAGE, "create"));
return Response.status(Response.Status.OK).build();
}
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updatePorts(@PathParam("id") String id, InputStream input) {
log.debug(String.format(PORTS_MESSAGE, "update"));
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(input).get(PORT);
log.trace("{}", jsonNode.toString());
String deviceId = jsonNode.path(DEVICE_ID).asText();
String name = jsonNode.path(NAME).asText();
if (deviceId.isEmpty() || name.isEmpty() || !name.startsWith(STAG_PREFIX)) {
// ignore all updates other than allowed address pairs
return Response.status(Response.Status.OK).build();
}
// this is allowed address pairs updates
MacAddress mac = MacAddress.valueOf(jsonNode.path(MAC_ADDRESS).asText());
Map<IpAddress, MacAddress> vSgs = Maps.newHashMap();
jsonNode.path(ADDRESS_PAIRS).forEach(addrPair -> {
IpAddress pairIp = IpAddress.valueOf(addrPair.path(IP_ADDERSS).asText());
MacAddress pairMac = MacAddress.valueOf(addrPair.path(MAC_ADDRESS).asText());
vSgs.put(pairIp, pairMac);
});
service.updateVirtualSubscriberGateways(
HostId.hostId(mac),
name.substring(STAG_BEGIN_INDEX),
vSgs);
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.OK).build();
}
@Path("{id}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response deletePorts(@PathParam("id") String id) {
log.trace(String.format(PORTS_MESSAGE, "delete"));
return Response.status(Response.Status.OK).build();
}
}
|
sonu283304/onos
|
apps/cordvtn/src/main/java/org/onosproject/cordvtn/rest/NeutronMl2PortsWebResource.java
|
Java
|
apache-2.0
| 4,443
|
/*
* Copyright 2016 West Coast Informatics, LLC
*/
package com.wci.tt.jpa.infomodels;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.wci.tt.jpa.JpaSupport;
import com.wci.umls.server.helpers.CopyConstructorTester;
import com.wci.umls.server.helpers.EqualsHashcodeTester;
import com.wci.umls.server.helpers.GetterSetterTester;
import com.wci.umls.server.helpers.XmlSerializationTester;
/**
* Unit testing for {@link RxcuiModel}.
*/
public class RxcuiModelUnitTest extends JpaSupport {
/** The model object to test. */
private RxcuiModel object;
/** the test fixture l1. */
private List<?> l1;
/** the test fixture l2. */
private List<?> l2;
/**
* Setup class.
*/
@BeforeClass
public static void setupClass() {
// do nothing
}
/**
* Setup.
*
* @throws Exception the exception
*/
@Before
public void setup() throws Exception {
object = new RxcuiModel();
l1 = new ArrayList<>();
l1.add(null);
l2 = new ArrayList<>();
l2.add(null);
l2.add(null);
}
/**
* Test getter and setter methods of model object.
*
* @throws Exception the exception
*/
@Test
public void testModelGetSet() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
GetterSetterTester tester = new GetterSetterTester(object);
tester.test();
}
/**
* Test equals and hashcode methods.
*
* @throws Exception the exception
*/
@Test
public void testModelEqualsHashcode() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
EqualsHashcodeTester tester = new EqualsHashcodeTester(object);
tester.include("rxcui");
tester.include("rxcuiName");
tester.include("active");
tester.include("splSetIds");
tester.include("history");
tester.proxy(List.class, 1, l1);
tester.proxy(List.class, 2, l2);
assertTrue(tester.testIdentityFieldEquals());
assertTrue(tester.testNonIdentityFieldEquals());
assertTrue(tester.testIdentityFieldNotEquals());
assertTrue(tester.testIdentityFieldHashcode());
assertTrue(tester.testNonIdentityFieldHashcode());
assertTrue(tester.testIdentityFieldDifferentHashcode());
}
/**
* Test copy constructor.
*
* @throws Exception the exception
*/
@Test
public void testModelCopy() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
CopyConstructorTester tester = new CopyConstructorTester(object);
tester.proxy(List.class, 1, l1);
tester.proxy(List.class, 2, l2);
assertTrue(tester.testCopyConstructor(RxcuiModel.class));
}
/**
* Test XML serialization.
*
* @throws Exception the exception
*/
@Test
public void testModelXmlSerialization() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
XmlSerializationTester tester = new XmlSerializationTester(object);
tester.proxy(List.class, 1, l1);
tester.testXmlSerialization();
}
/**
* Test model in common.
*
* @throws Exception the exception
*/
@Test
public void testModelInCommon() throws Exception {
RxcuiModel m1 = new RxcuiModel();
RxcuiModel m2 = new RxcuiModel();
// should work, but be empty
RxcuiModel common = m1.getModelInCommon(m2, false);
assertNull(common);
// rxcui
m1.setRxcui("abc");
common = m1.getModelInCommon(m2, false);
assertNull(common);
m2.setRxcui("def");
common = m1.getModelInCommon(m2, false);
assertNull(common);
m2.setRxcui("abc");
common = m1.getModelInCommon(m2, false);
assertEquals("abc", common.getRxcui());
// rxcui name
m1 = new RxcuiModel();
m1.setRxcuiName("abc");
common = m1.getModelInCommon(m2, false);
assertNull(common);
m2.setRxcuiName("def");
common = m1.getModelInCommon(m2, false);
assertNull(common);
m2.setRxcuiName("abc");
common = m1.getModelInCommon(m2, false);
assertEquals("abc", common.getRxcuiName());
// History
m1.getHistory().add(new RxcuiNdcHistoryModel("abc", "def", "ghi"));
common = m1.getModelInCommon(m2, false);
assertEquals(0, common.getHistory().size());
m2.getHistory().add(new RxcuiNdcHistoryModel("def", "ghi", "jkl"));
common = m1.getModelInCommon(m2, false);
assertEquals(0, common.getHistory().size());
m2.getHistory().add(new RxcuiNdcHistoryModel("abc", "def", "ghi"));
common = m1.getModelInCommon(m2, false);
assertEquals(1, common.getHistory().size());
m1.getHistory().add(new RxcuiNdcHistoryModel("def", "ghi", "jkl"));
common = m1.getModelInCommon(m2, false);
assertEquals(2, common.getHistory().size());
// Spl Set ids
m1.getSplSetIds().add("abc");
common = m1.getModelInCommon(m2, false);
assertEquals(0, common.getSplSetIds().size());
m2.getSplSetIds().add("def");
common = m1.getModelInCommon(m2, false);
assertEquals(0, common.getSplSetIds().size());
m2.getSplSetIds().add("abc");
common = m1.getModelInCommon(m2, false);
assertEquals(1, common.getSplSetIds().size());
m1.getSplSetIds().add("def");
common = m1.getModelInCommon(m2, false);
assertEquals(2, common.getSplSetIds().size());
}
/**
* Teardown.
*/
@After
public void teardown() {
// do nothing
}
/**
* Teardown class.
*/
@AfterClass
public static void teardownClass() {
// do nothing
}
}
|
WestCoastInformatics/Terminology-Transformer
|
jpa-model/src/test/java/com/wci/tt/jpa/infomodels/RxcuiModelUnitTest.java
|
Java
|
apache-2.0
| 5,755
|
<p class="level0"><a name="NAME"></a><h2 class="nroffsh">NAME</h2>
<p class="level0">xwd - dump an image of an X window <a name="SYNOPSIS"></a><h2 class="nroffsh">SYNOPSIS</h2>
<p class="level0"><span Class="bold">xwd</span> [-debug] [-help] [-nobdrs] [-out <span Class="emphasis">file</span>] [-xy] [-frame] [-add <span Class="emphasis">value</span>] [-root | -id <span Class="emphasis">id</span> | -name <span Class="emphasis">name</span> ] [-icmap] [-screen] [-silent] [-display <span Class="emphasis">display</span>] <a name="DESCRIPTION"></a><h2 class="nroffsh">DESCRIPTION</h2>
<p class="level0">
<p class="level0"><span Class="emphasis">Xwd</span> is an X Window System window dumping utility. <span Class="emphasis">Xwd</span> allows X users to store window images in a specially formatted dump file. This file can then be read by various other X utilities for redisplay, printing, editing, formatting, archiving, image processing, etc. The target window is selected by clicking the pointer in the desired window. The keyboard bell is rung once at the beginning of the dump and twice when the dump is completed. <a name="OPTIONS"></a><h2 class="nroffsh">OPTIONS</h2>
<p class="level0">
<p class="level0">
<p class="level0"><span Class="bold">-display display</span> This argument allows you to specify the server to connect to; see <span Class="emphasis">X(7)</span>.
<p class="level0">
<p class="level0"><span Class="bold">-help</span> Print out the `Usage:' command syntax summary.
<p class="level0">
<p class="level0"><span Class="bold">-nobdrs</span> This argument specifies that the window dump should not include the pixels that compose the X window border. This is useful in situations where you may wish to include the window contents in a document as an illustration.
<p class="level0">
<p class="level0"><span Class="bold">-out file</span> This argument allows the user to explicitly specify the output file on the command line. The default is to output to standard out.
<p class="level0">
<p class="level0"><span Class="bold">-xy</span> This option applies to color displays only. It selects `XY' format dumping instead of the default `Z' format.
<p class="level0">
<p class="level0"><span Class="bold">-add value</span> This option specifies an signed value to be added to every pixel.
<p class="level0">
<p class="level0"><span Class="bold">-frame</span> This option indicates that the window manager frame should be included when manually selecting a window.
<p class="level0">
<p class="level0"><span Class="bold">-root</span> This option indicates that the root window should be selected for the window dump, without requiring the user to select a window with the pointer.
<p class="level0">
<p class="level0"><span Class="bold">-id id</span> This option indicates that the window with the specified resource id should be selected for the window dump, without requiring the user to select a window with the pointer.
<p class="level0">
<p class="level0"><span Class="bold">-name name</span> This option indicates that the window with the specified WM_NAME property should be selected for the window dump, without requiring the user to select a window with the pointer.
<p class="level0">
<p class="level0"><span Class="bold">-icmap</span> Normally the colormap of the chosen window is used to obtain RGB values. This option forces the first installed colormap of the screen to be used instead.
<p class="level0">
<p class="level0"><span Class="bold">-screen</span> This option indicates that the GetImage request used to obtain the image should be done on the root window, rather than directly on the specified window. In this way, you can obtain pieces of other windows that overlap the specified window, and more importantly, you can capture menus or other popups that are independent windows but appear over the specified window.
<p class="level0">
<p class="level0"><span Class="bold">-silent</span> Operate silently, i.e. don't ring any bells before and after dumping the window. <a name="ENVIRONMENT"></a><h2 class="nroffsh">ENVIRONMENT</h2>
<p class="level0">
<p class="level0">
<p class="level0"><span Class="bold">DISPLAY</span> To get default host and display number. <a name="FILES"></a><h2 class="nroffsh">FILES</h2>
<p class="level0">
<p class="level0">
<p class="level0"><span Class="bold">XWDFile.h</span> X Window Dump File format definition file. <a name="SEE"></a><h2 class="nroffsh">SEE ALSO</h2>
<p class="level0">xwud(1), X(7) <a name="AUTHORS"></a><h2 class="nroffsh">AUTHORS</h2>
<p class="level0">Tony Della Fera, Digital Equipment Corp., MIT Project Athena <br>William F. Wyatt, Smithsonian Astrophysical Observatory
|
loic-carbonne/Man-fulltext-search
|
Step2-Indexing/man_html/man1/xwd.1.html
|
HTML
|
apache-2.0
| 4,682
|
# Copyright 2017 AT&T Intellectual Property. All other 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.
"""Actions related to task commands."""
import time
from drydock_provisioner.cli.action import CliAction
from drydock_provisioner.cli.const import TaskStatus
class TaskList(CliAction): # pylint: disable=too-few-public-methods
"""Action to list tasks."""
def __init__(self, api_client):
"""Object initializer.
:param DrydockClient api_client: The api client used for invocation.
"""
super().__init__(api_client)
self.logger.debug('TaskList action initialized')
def invoke(self):
"""Invoke execution of this action."""
return self.api_client.get_tasks()
class TaskCreate(CliAction): # pylint: disable=too-few-public-methods
"""Action to create tasks against a design."""
def __init__(self,
api_client,
design_ref,
action_name=None,
node_names=None,
rack_names=None,
node_tags=None,
block=False,
poll_interval=15):
"""Object initializer.
:param DrydockClient api_client: The api client used for invocation.
:param string design_ref: The URI reference to design documents
:param string action_name: The name of the action being performed for this task
:param List node_names: The list of node names to restrict action application
:param List rack_names: The list of rack names to restrict action application
:param List node_tags: The list of node tags to restrict action application
:param bool block: Whether to block CLI exit until task completes
:param integer poll_interval: Polling interval to query task status
"""
super().__init__(api_client)
self.design_ref = design_ref
self.action_name = action_name
self.logger.debug('TaskCreate action initialized for design=%s',
design_ref)
self.logger.debug('Action is %s', action_name)
self.logger.debug("Node names = %s", node_names)
self.logger.debug("Rack names = %s", rack_names)
self.logger.debug("Node tags = %s", node_tags)
self.block = block
self.poll_interval = poll_interval
if any([node_names, rack_names, node_tags]):
filter_items = {'filter_type': 'union'}
if node_names is not None:
filter_items['node_names'] = node_names
if rack_names is not None:
filter_items['rack_names'] = rack_names
if node_tags is None:
filter_items['node_tags'] = node_tags
self.node_filter = {
'filter_set_type': 'intersection',
'filter_set': [filter_items]
}
else:
self.node_filter = None
def invoke(self):
"""Invoke execution of this action."""
task = self.api_client.create_task(
design_ref=self.design_ref,
task_action=self.action_name,
node_filter=self.node_filter)
if not self.block:
return task
task_id = task.get('task_id')
while True:
time.sleep(self.poll_interval)
task = self.api_client.get_task(task_id=task_id)
if task.get('status',
'') in [TaskStatus.Complete, TaskStatus.Terminated]:
return task
class TaskShow(CliAction): # pylint: disable=too-few-public-methods
"""Action to show a task's detial."""
def __init__(self, api_client, task_id, block=False, poll_interval=15):
"""Object initializer.
:param DrydockClient api_client: The api client used for invocation.
:param string task_id: the UUID of the task to retrieve
:param bool block: Whether to block CLI exit until task completes
:param integer poll_interval: Polling interval to query task status
"""
super().__init__(api_client)
self.task_id = task_id
self.logger.debug('TaskShow action initialized for task_id=%s,',
task_id)
self.block = block
self.poll_interval = poll_interval
def invoke(self):
"""Invoke execution of this action."""
task = self.api_client.get_task(task_id=self.task_id)
if not self.block:
return task
task_id = task.get('task_id')
while True:
time.sleep(self.poll_interval)
task = self.api_client.get_task(task_id=task_id)
if task.status in [TaskStatus.Complete, TaskStatus.Terminated]:
return task
|
att-comdev/drydock
|
drydock_provisioner/cli/task/actions.py
|
Python
|
apache-2.0
| 5,257
|
#
# Cookbook Name:: mariadb
# Attributes:: default
#
# Copyright 2008-2013, Opscode, 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.
#
default['mariadb']['version'] = '5.5'
|
paulczar/cookbook-mariadb
|
attributes/default.rb
|
Ruby
|
apache-2.0
| 677
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --expose-wasm
load('test/mjsunit/wasm/wasm-constants.js');
load('test/mjsunit/wasm/wasm-module-builder.js');
let k1MiB = 1 * 1024 * 1024;
let k1GiB = 1 * 1024 * 1024 * 1024;
let k4GiB = 4 * k1GiB;
let kMaxMemory = 2 * k1GiB - kPageSize; // TODO(titzer): raise this to 4GiB
(function Test() {
var memory;
function BuildAccessors(type, load_opcode, store_opcode) {
builder = new WasmModuleBuilder();
builder.addImportedMemory("i", "mem");
builder.addFunction("load", makeSig([kWasmI32], [type]))
.addBody([ // --
kExprGetLocal, 0, // --
load_opcode, 0, 0, // --
]) // --
.exportFunc();
builder.addFunction("store", makeSig([kWasmI32, type], []))
.addBody([ // --
kExprGetLocal, 0, // --
kExprGetLocal, 1, // --
store_opcode, 0, 0, // --
]) // --
.exportFunc();
let i = builder.instantiate({i: {mem: memory}});
return {load: i.exports.load, store: i.exports.store};
}
function probe(a, f) {
print("------------------------");
let stride = kPageSize;
let max = kMaxMemory;
for (let i = 0; i < max; i += stride) {
a.store(i, f(i));
}
for (let i = 0; i < max; i += stride) {
// print(`${i} = ${f(i)}`);
assertEquals(f(i), a.load(i));
}
}
try {
let kPages = kMaxMemory / kPageSize;
memory = new WebAssembly.Memory({initial: kPages, maximum: kPages});
} catch (e) {
print("OOM: sorry, best effort max memory size test.");
return;
}
assertEquals(kMaxMemory, memory.buffer.byteLength);
{
let a = BuildAccessors(kWasmI32, kExprI32LoadMem, kExprI32StoreMem);
probe(a, i => (0xaabbccee ^ ((i >> 11) * 0x110005)) | 0);
}
{
let a = BuildAccessors(kWasmI32, kExprI32LoadMem16U, kExprI32StoreMem16);
probe(a, i => (0xccee ^ ((i >> 11) * 0x110005)) & 0xFFFF);
}
{
let a = BuildAccessors(kWasmI32, kExprI32LoadMem8U, kExprI32StoreMem8);
probe(a, i => (0xee ^ ((i >> 11) * 0x05)) & 0xFF);
}
{
let a = BuildAccessors(kWasmF64, kExprF64LoadMem, kExprF64StoreMem);
probe(a, i => 0xaabbccee ^ ((i >> 11) * 0x110005));
}
{
let a = BuildAccessors(kWasmF32, kExprF32LoadMem, kExprF32StoreMem);
probe(a, i => Math.fround(0xaabbccee ^ ((i >> 11) * 0x110005)));
}
})();
|
fceller/arangodb
|
3rdParty/V8/v7.1.302.28/test/mjsunit/wasm/empirical_max_memory.js
|
JavaScript
|
apache-2.0
| 2,541
|
/* jshint esversion: 6 */
/* jslint node: true */
'use strict';
const cose = require('../');
const test = require('ava');
const jsonfile = require('jsonfile');
const base64url = require('base64url');
const cbor = require('cbor');
const deepEqual = require('./util.js').deepEqual;
test('ecdsa-examples verify ecdsa-01', async (t) => {
const example = jsonfile.readFileSync('test/Examples/ecdsa-examples/ecdsa-01.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('ecdsa-examples verify ecdsa-02', async (t) => {
const example = jsonfile.readFileSync('test/Examples/ecdsa-examples/ecdsa-02.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('create ecdsa-01', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/ecdsa-01.json');
const p = example.input.sign.protected;
const u = example.input.sign.unprotected;
const plaintext = Buffer.from(example.input.plaintext);
const signers = [{
key: {
d: base64url.toBuffer(example.input.sign.signers[0].key.d)
},
u: example.input.sign.signers[0].unprotected,
p: example.input.sign.signers[0].protected
}];
const header = { p: p, u: u };
const buf = await cose.sign.create(header, plaintext, signers);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
const actual = cbor.decodeFirstSync(buf);
const expected = cbor.decodeFirstSync(example.output.cbor);
t.true(deepEqual(actual, expected));
});
test('sign+verify rsa-pss-01', async (t) => {
const example = jsonfile.readFileSync('test/Examples/rsa-pss-examples/rsa-pss-01.json');
const p = example.input.sign.protected;
const u = example.input.sign.unprotected;
const plaintext = Buffer.from(example.input.plaintext);
const signers = [{
key: {
n: Buffer.from(example.input.sign.signers[0].key.n_hex, 'hex'),
d: Buffer.from(example.input.sign.signers[0].key.d_hex, 'hex'),
p: Buffer.from(example.input.sign.signers[0].key.p_hex, 'hex'),
q: Buffer.from(example.input.sign.signers[0].key.q_hex, 'hex'),
dp: Buffer.from(example.input.sign.signers[0].key.dP_hex, 'hex'),
dq: Buffer.from(example.input.sign.signers[0].key.dQ_hex, 'hex'),
qi: Buffer.from(example.input.sign.signers[0].key.qi_hex, 'hex'),
e: Buffer.from(example.input.sign.signers[0].key.e_hex, 'hex'),
kid: example.input.sign.signers[0].key.kid
},
u: example.input.sign.signers[0].unprotected,
p: example.input.sign.signers[0].protected
}];
signers[0].p.alg = 'PS256';
const header = { p: p, u: u };
const buf = await cose.sign.create(header, plaintext, signers);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
const verifiedBuf = await cose.sign.verify(buf, signers[0]);
t.true(Buffer.isBuffer(verifiedBuf));
t.true(verifiedBuf.length > 0);
t.is(verifiedBuf.toString('utf8'), example.input.plaintext);
});
test('sign+verify rsa-pss-02', async (t) => {
const example = jsonfile.readFileSync('test/Examples/rsa-pss-examples/rsa-pss-02.json');
const p = example.input.sign.protected;
const u = example.input.sign.unprotected;
const plaintext = Buffer.from(example.input.plaintext);
const signers = [{
key: {
n: Buffer.from(example.input.sign.signers[0].key.n_hex, 'hex'),
d: Buffer.from(example.input.sign.signers[0].key.d_hex, 'hex'),
p: Buffer.from(example.input.sign.signers[0].key.p_hex, 'hex'),
q: Buffer.from(example.input.sign.signers[0].key.q_hex, 'hex'),
dp: Buffer.from(example.input.sign.signers[0].key.dP_hex, 'hex'),
dq: Buffer.from(example.input.sign.signers[0].key.dQ_hex, 'hex'),
qi: Buffer.from(example.input.sign.signers[0].key.qi_hex, 'hex'),
e: Buffer.from(example.input.sign.signers[0].key.e_hex, 'hex'),
kid: example.input.sign.signers[0].key.kid
},
u: example.input.sign.signers[0].unprotected,
p: example.input.sign.signers[0].protected
}];
signers[0].p.alg = 'PS384';
const header = { p: p, u: u };
const buf = await cose.sign.create(header, plaintext, signers);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
const verifiedBuf = await cose.sign.verify(buf, signers[0]);
t.true(Buffer.isBuffer(buf));
t.true(verifiedBuf.length > 0);
t.is(verifiedBuf.toString('utf8'), example.input.plaintext);
});
test('sign+verify rsa-pss-03', async (t) => {
const example = jsonfile.readFileSync('test/Examples/rsa-pss-examples/rsa-pss-03.json');
const p = example.input.sign.protected;
const u = example.input.sign.unprotected;
const plaintext = Buffer.from(example.input.plaintext);
const signers = [{
key: {
n: Buffer.from(example.input.sign.signers[0].key.n_hex, 'hex'),
d: Buffer.from(example.input.sign.signers[0].key.d_hex, 'hex'),
p: Buffer.from(example.input.sign.signers[0].key.p_hex, 'hex'),
q: Buffer.from(example.input.sign.signers[0].key.q_hex, 'hex'),
dp: Buffer.from(example.input.sign.signers[0].key.dP_hex, 'hex'),
dq: Buffer.from(example.input.sign.signers[0].key.dQ_hex, 'hex'),
qi: Buffer.from(example.input.sign.signers[0].key.qi_hex, 'hex'),
e: Buffer.from(example.input.sign.signers[0].key.e_hex, 'hex'),
kid: example.input.sign.signers[0].key.kid
},
u: example.input.sign.signers[0].unprotected,
p: example.input.sign.signers[0].protected
}];
signers[0].p.alg = 'PS512';
const header = { p: p, u: u };
const buf = await cose.sign.create(header, plaintext, signers);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
const verifiedBuf = await cose.sign.verify(buf, signers[0]);
t.true(Buffer.isBuffer(verifiedBuf));
t.true(verifiedBuf.length > 0);
t.is(verifiedBuf.toString('utf8'), example.input.plaintext);
});
test('verify ecdsa-01', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/ecdsa-01.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('create sign-pass-01', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-pass-01.json');
const p = example.input.sign.protected;
const u = example.input.sign.unprotected;
const plaintext = Buffer.from(example.input.plaintext);
const signers = [{
key: {
d: base64url.toBuffer(example.input.sign.signers[0].key.d)
},
u: example.input.sign.signers[0].unprotected,
p: example.input.sign.signers[0].protected
}];
const header = { p: p, u: u };
const buf = await cose.sign.create(header, plaintext, signers);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
const actual = cbor.decodeFirstSync(buf);
const expected = cbor.decodeFirstSync(example.output.cbor);
t.true(deepEqual(actual, expected));
});
test('create sign-pass-01 Sync', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-pass-01.json');
const p = example.input.sign.protected;
const u = example.input.sign.unprotected;
const plaintext = Buffer.from(example.input.plaintext);
const signers = [{
key: {
d: base64url.toBuffer(example.input.sign.signers[0].key.d)
},
u: example.input.sign.signers[0].unprotected,
p: example.input.sign.signers[0].protected
}];
const header = { p: p, u: u };
const buf = await cose.sign.create(header, plaintext, signers);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
const actual = cbor.decodeFirstSync(buf);
const expected = cbor.decodeFirstSync(example.output.cbor);
t.true(deepEqual(actual, expected));
});
test('create sign-pass-02', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-pass-02.json');
const p = example.input.sign.protected;
const u = example.input.sign.unprotected;
const plaintext = Buffer.from(example.input.plaintext);
const signers = [{
key: { d: base64url.toBuffer(example.input.sign.signers[0].key.d) },
u: example.input.sign.signers[0].unprotected,
p: example.input.sign.signers[0].protected,
externalAAD: Buffer.from(example.input.sign.signers[0].external, 'hex')
}];
const header = { p: p, u: u };
const options = { encodep: 'empty' };
const buf = await cose.sign.create(header, plaintext, signers, options);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
const actual = cbor.decodeFirstSync(buf);
const expected = cbor.decodeFirstSync(example.output.cbor);
t.true(deepEqual(actual, expected));
});
test('create sign-pass-03', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-pass-03.json');
const p = example.input.sign.protected;
const u = example.input.sign.unprotected;
const plaintext = Buffer.from(example.input.plaintext);
const signers = [{
key: {
d: base64url.toBuffer(example.input.sign.signers[0].key.d)
},
u: example.input.sign.signers[0].unprotected,
p: example.input.sign.signers[0].protected
}];
const header = { p: p, u: u };
const options = { encodep: 'empty', excludetag: true };
const buf = await cose.sign.create(header, plaintext, signers, options);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
const actual = cbor.decodeFirstSync(buf);
const expected = cbor.decodeFirstSync(example.output.cbor);
t.true(deepEqual(actual, expected));
});
test('verify sign-pass-01', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-pass-01.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('verify sign-pass-01 Sync', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-pass-01.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('verify sign-pass-02', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-pass-02.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
},
externalAAD: Buffer.from(example.input.sign.signers[0].external, 'hex')
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('verify sign-pass-03', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-pass-03.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('verify sign-fail-01', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-fail-01.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
try {
await cose.sign.verify(signature, verifier);
t.fail('Unexpected cbor tag, \'998\'');
} catch (error) {
t.is(error.message, 'Unexpected cbor tag, \'998\'');
}
});
test('verify sign-fail-02', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-fail-02.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
try {
await cose.sign.verify(signature, verifier);
t.fail('Signature missmatch');
} catch (error) {
t.is(error.message, 'Signature missmatch');
}
});
test('verify sign-fail-03', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-fail-03.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
try {
await cose.sign.verify(signature, verifier);
t.fail('Unknown algorithm, -999');
} catch (error) {
t.is(error.message, 'Unknown algorithm, -999');
}
});
test('verify sign-fail-04', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-fail-04.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
try {
await cose.sign.verify(signature, verifier);
t.fail('Unknown algorithm, unknown');
} catch (error) {
t.is(error.message, 'Unknown algorithm, unknown');
}
});
test('verify sign-fail-06', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-fail-06.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
try {
await cose.sign.verify(signature, verifier);
t.fail('Signature missmatch');
} catch (error) {
t.is(error.message, 'Signature missmatch');
}
});
test('verify sign-fail-07', async (t) => {
const example = jsonfile.readFileSync('test/Examples/sign-tests/sign-fail-07.json');
const verifier = {
key: {
x: base64url.toBuffer(example.input.sign.signers[0].key.x),
y: base64url.toBuffer(example.input.sign.signers[0].key.y),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
try {
await cose.sign.verify(signature, verifier);
t.fail('Signature missmatch');
} catch (error) {
t.is(error.message, 'Signature missmatch');
}
});
test('verify rsa-pss-01', async (t) => {
const example = jsonfile.readFileSync('test/Examples/rsa-pss-examples/rsa-pss-01.json');
const verifier = {
key: {
n: Buffer.from(example.input.sign.signers[0].key.n_hex, 'hex'),
e: Buffer.from(example.input.sign.signers[0].key.e_hex, 'hex'),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('verify rsa-pss-02', async (t) => {
const example = jsonfile.readFileSync('test/Examples/rsa-pss-examples/rsa-pss-02.json');
const verifier = {
key: {
n: Buffer.from(example.input.sign.signers[0].key.n_hex, 'hex'),
e: Buffer.from(example.input.sign.signers[0].key.e_hex, 'hex'),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
test('verify rsa-pss-03', async (t) => {
const example = jsonfile.readFileSync('test/Examples/rsa-pss-examples/rsa-pss-03.json');
const verifier = {
key: {
n: Buffer.from(example.input.sign.signers[0].key.n_hex, 'hex'),
e: Buffer.from(example.input.sign.signers[0].key.e_hex, 'hex'),
kid: example.input.sign.signers[0].key.kid
}
};
const signature = Buffer.from(example.output.cbor, 'hex');
const buf = await cose.sign.verify(signature, verifier);
t.true(Buffer.isBuffer(buf));
t.true(buf.length > 0);
t.is(buf.toString('utf8'), example.input.plaintext);
});
|
erdtman/cose-js
|
test/sign-tests.js
|
JavaScript
|
apache-2.0
| 18,336
|
# Glochidion pulchellum Airy Shaw SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Phyllanthus/Phyllanthus stultitiae/ Syn. Glochidion pulchellum/README.md
|
Markdown
|
apache-2.0
| 188
|
package com.aries.library.fast.util;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityThread;
import android.app.AppGlobals;
import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.DrawableCompat;
import com.aries.library.fast.FastConstant;
import com.aries.ui.util.DrawableUtil;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Random;
/**
* @Author: AriesHoo on 2018/7/23 9:29
* @E-Mail: AriesHoo@126.com
* Function:app使用工具类
* Description:
* 1、将startActivity 参数Activity 改为Context
* 2、2018-7-23 09:29:55 新增获取App 应用名称方法
* 3、2019-2-15 11:28:53 修改startActivity 方法增加single tag设置方法{@link #setActivitySingleFlag(int)}
* 4、2019-2-22 13:49:12 修改{@link #getRootView(Activity)} 判断逻辑
* 5、2019-4-19 17:02:01 修改{@link #getTintDrawable(Drawable, int)}以支持5.0以下版本并增加{@link #getTintDrawable(Drawable, ColorStateList)}
* 6、2019-4-22 17:44:14 修改{@link #getTintDrawable(Drawable, int)}以支持5.0以下版本并增加{@link #getTintDrawable(Drawable, ColorStateList)}
*/
public class FastUtil {
private static int ACTIVITY_SINGLE_FLAG = Intent.FLAG_ACTIVITY_SINGLE_TOP;
/**
* 反射获取application对象
*
* @return application
*/
public static Application getApplication() {
try {
//兼容android P,直接调用@hide注解的方法来获取application对象
Application app = ActivityThread.currentApplication();
Log.e("FastUtil", "getApplication0:" + app);
if (app != null) {
return app;
}
} catch (Exception e) {
}
try {
//兼容android P,直接调用@hide注解的方法来获取application对象
Application app = AppGlobals.getInitialApplication();
Log.e("FastUtil", "getApplication1:" + app);
if (app != null) {
return app;
}
} catch (Exception e) {
}
return null;
}
/**
* 获取应用名称
*
* @param context
* @return
*/
public static CharSequence getAppName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return context.getResources().getText(labelRes);
} catch (PackageManager.NameNotFoundException e) {
Log.e("FastUtil", "getAppName:" + e.getMessage());
}
return null;
}
/**
* 获取 一定范围随机数
*
* @param max 最大值
* @param min 最小值
* @return
*/
public static int getRandom(int max, int min) {
// 定义随机类
Random random = new Random();
int result = random.nextInt(max) % (max - min + 1) + min;
return result;
}
/**
* 获取一定长度随机数
*
* @param length
* @return
*/
public static int getRandom(int length) {
return getRandom(length, 1);
}
/**
* 获取Activity 根布局
*
* @param activity
* @return
*/
public static View getRootView(Activity activity) {
if (activity == null) {
return null;
}
if (activity.findViewById(android.R.id.content) == null) {
return null;
}
try {
return ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
} catch (Exception e) {
return null;
}
}
/**
* 给一个Drawable变换线框颜色
* {@link DrawableUtil#setTintDrawable(Drawable, int)}
*
* @param drawable 需要变换颜色的drawable
* @param color 需要变换的颜色
* @return
*/
@Deprecated
public static Drawable getTintDrawable(Drawable drawable, @ColorInt int color) {
if (drawable != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
DrawableCompat.setTint(drawable, color);
} else {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}
}
return DrawableUtil.setTintDrawable(drawable, color);
}
/**
* {@link DrawableUtil#setTintDrawable(Drawable, ColorStateList)}
*
* @param drawable
* @param tint
* @return
*/
@Deprecated
public static Drawable getTintDrawable(Drawable drawable, @Nullable ColorStateList tint) {
return DrawableUtil.setTintDrawable(drawable, tint);
}
/**
* [获取应用程序版本名称信息]
*
* @param context
* @return 当前应用的版本名称
*/
public static String getVersionName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
if (null != packageManager) {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
if (null != packageInfo) {
return packageInfo.versionName;
}
}
} catch (PackageManager.NameNotFoundException e) {
Log.e("FastUtil", "getVersionName:" + e.getMessage());
}
return "";
}
/**
* @param context
* @return
*/
public static long getVersionCode(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
if (null != packageManager) {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
if (null != packageInfo) {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.P ? packageInfo.versionCode : packageInfo.getLongVersionCode();
}
}
} catch (PackageManager.NameNotFoundException e) {
Log.e("FastUtil", "getVersionCode:" + e.getMessage());
}
return -1;
}
/**
* 检查某个class是否存在
*
* @param className class的全路径包括包名+类名
* @return
*/
public static boolean isClassExist(String className) {
boolean isExit = false;
try {
Class<?> cls = Class.forName(className);
isExit = cls != null;
} catch (ClassNotFoundException e) {
}
return isExit;
}
/**
* {@link org.greenrobot.eventbus.EventBus} 要求注册之前, 订阅者必须含有一个或以上声明 {@link org.greenrobot.eventbus.Subscribe}
* 注解的方法, 否则会报错, 所以如果要想完成在基类中自动注册, 避免报错就要先检查是否符合注册资格
*
* @param subscriber 订阅者
* @return 返回 {@code true} 则表示含有 {@link org.greenrobot.eventbus.Subscribe} 注解, {@code false} 为不含有
*/
public static boolean haveEventBusAnnotation(Object subscriber) {
if (!FastUtil.isClassExist(FastConstant.EVENT_BUS_CLASS)) {
return false;
}
boolean skipSuperClasses = false;
Class<?> clazz = subscriber.getClass();
//查找类中符合注册要求的方法, 直到Object类
while (clazz != null && !isSystemClass(clazz.getName()) && !skipSuperClasses) {
Method[] allMethods;
try {
allMethods = clazz.getDeclaredMethods();
} catch (Throwable th) {
try {
allMethods = clazz.getMethods();
} catch (Throwable th2) {
continue;
} finally {
skipSuperClasses = true;
}
}
for (int i = 0; i < allMethods.length; i++) {
Method method = allMethods[i];
Class<?>[] parameterTypes = method.getParameterTypes();
//查看该方法是否含有 Subscribe 注解
if (method.isAnnotationPresent(org.greenrobot.eventbus.Subscribe.class) && parameterTypes.length == 1) {
return true;
}
} //end for
//获取父类, 以继续查找父类中符合要求的方法
clazz = clazz.getSuperclass();
}
return false;
}
private static boolean isSystemClass(String name) {
return name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.");
}
public static boolean isRunningForeground(Context context) {
return isRunningForeground(context, null);
}
/**
* 检查某个应用是否前台运行
*
* @param context
* @param packageName
* @return
*/
public static boolean isRunningForeground(Context context, String packageName) {
if (context == null) {
return false;
}
if (TextUtils.isEmpty(packageName)) {
packageName = context.getPackageName();
}
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName)) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
return false;
} else {
return true;
}
}
}
return false;
}
/**
* 判断当前设备是手机还是平板,代码来自 Google I/O App for Android
*
* @param context
* @return 平板返回 True,手机返回 False
*/
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
/**
* 判断App是否存在
*
* @param context 上下文
* @param packageName 包名
* @return
*/
public static boolean isAppInstall(Context context, String packageName) {
Context con = context == null ? getApplication() : context;
if (con == null) {
return false;
}
Intent launchIntent = con.getPackageManager().getLaunchIntentForPackage(packageName);
return launchIntent != null;
}
public static void jumpMarket(Context mContext) {
jumpMarket(mContext, null);
}
/**
* 跳转应用市场详情
*
* @param mContext
* @param packageName
*/
public static void jumpMarket(Context mContext, String packageName) {
if (mContext == null) {
return;
}
if (TextUtils.isEmpty(packageName)) {
packageName = mContext.getPackageName();
}
String mAddress = "market://details?id=" + packageName;
try {
Intent marketIntent = new Intent("android.intent.action.VIEW");
marketIntent.setData(Uri.parse(mAddress));
mContext.startActivity(marketIntent);
} catch (Exception e) {
Log.e("FastUtil", "jumpMarket:" + e.getMessage());
}
}
/**
* 设置Activity只启动一个Flag
*
* @param flag {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
* {@link Intent#FLAG_ACTIVITY_NEW_TASK}
* {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}
*/
public static void setActivitySingleFlag(int flag) {
ACTIVITY_SINGLE_FLAG = flag;
}
/**
* @param context
* @param activity 跳转Activity
* @param bundle
* @param isSingle
*/
public static void startActivity(Context context, Class<? extends Activity> activity, Bundle bundle, boolean isSingle) {
if (context == null) {
return;
}
Intent intent = new Intent(context, activity);
intent.setFlags(isSingle ? ACTIVITY_SINGLE_FLAG : Intent.FLAG_ACTIVITY_NEW_TASK);
if (!(context instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if (bundle != null) {
intent.putExtras(bundle);
}
context.startActivity(intent);
}
public static void startActivity(Context context, Class<? extends Activity> activity, Bundle bundle) {
startActivity(context, activity, bundle, true);
}
public static void startActivity(Context context, Class<? extends Activity> activity) {
startActivity(context, activity, null);
}
public static void startActivity(Context context, Class<? extends Activity> activity, boolean isSingle) {
startActivity(context, activity, null, isSingle);
}
/**
* 根据包名跳转应用
*
* @param context
* @param packageName
*/
public static void startApp(Context context, String packageName) {
Context con = context == null ? getApplication() : context;
if (!isAppInstall(con, packageName)) {
return;
}
Intent intent = con.getPackageManager().getLaunchIntentForPackage(packageName);
con.startActivity(intent);
}
/**
* @param context 上下文
* @param text 分享内容
* @param title 分享标题
*/
public static void startShareText(Context context, String text, CharSequence title) {
if (context == null) {
return;
}
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.setType("text/plain");
//设置分享列表的标题,并且每次都显示分享列表
context.startActivity(Intent.createChooser(shareIntent, title));
}
/**
* @param context 上下文
* @param url 分享文字
*/
public static void startShareText(Context context, String url) {
startShareText(context, url, null);
}
/**
* 拷贝到粘贴板
*
* @param context 上下文
* @param str 需要拷贝的文字
*/
public static void copyToClipboard(Context context, String str) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(str);
} else {
ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setPrimaryClip(ClipData.newPlainText("content", str));
}
}
}
|
AriesHoo/FastLib
|
library/src/main/java/com/aries/library/fast/util/FastUtil.java
|
Java
|
apache-2.0
| 15,668
|
/*
* Copyright 2016 - 2017 Aitu Software Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aitusoftware.flute.server.cache;
import com.aitusoftware.flute.config.HistogramConfig;
import com.aitusoftware.flute.server.dao.jdbc.HistogramRetrievalDao;
import com.aitusoftware.flute.server.http.CacheConfig;
public final class HistogramSourceProvider
{
private final HistogramQueryFunction queryFunction;
private final HistogramConfig histogramConfig;
private final HistogramRetrievalDao histogramRetrievalDao;
private final CacheConfig cacheConfig;
public HistogramSourceProvider(final HistogramQueryFunction queryFunction,
final HistogramConfig histogramConfig,
final HistogramRetrievalDao histogramRetrievalDao,
final CacheConfig cacheConfig)
{
this.queryFunction = queryFunction;
this.histogramConfig = histogramConfig;
this.histogramRetrievalDao = histogramRetrievalDao;
this.cacheConfig = cacheConfig;
}
public HistogramSource get()
{
if (cacheConfig.isCaching())
{
return new HistogramCache(cacheConfig.getCapacity(), histogramRetrievalDao,
System::currentTimeMillis, histogramConfig.asSupplier());
}
return new LiveHistogramSource(queryFunction, histogramConfig.asSupplier());
}
}
|
aitusoftware/flute
|
flute-server/src/main/java/com/aitusoftware/flute/server/cache/HistogramSourceProvider.java
|
Java
|
apache-2.0
| 1,957
|
# Cortinarius eburneus (Velen.) Rob. Henry ex Bon SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Docums Mycol. 15(no. 60): 38 (1985)
#### Original name
Phlegmacium eburneum Velen.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius eburneus/README.md
|
Markdown
|
apache-2.0
| 234
|
# Crowea macrantha "Hort." ex Henrincq SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Rutaceae/Crowea/Crowea macrantha/README.md
|
Markdown
|
apache-2.0
| 186
|
# Beilschmiedia dinklagei (Engl.) Robyns & Wilczek SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Beilschmiedia/Beilschmiedia dinklagei/README.md
|
Markdown
|
apache-2.0
| 198
|
# Apium laciniatum var. hispidulum H.Wolff VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Cyclospermum/Cyclospermum laciniatum/Apium laciniatum hispidulum/README.md
|
Markdown
|
apache-2.0
| 190
|
# Coelogyne confusa Ames SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Coelogyne/Coelogyne confusa/README.md
|
Markdown
|
apache-2.0
| 180
|
# Savia volubilis Raf. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Amphicarpaea/Amphicarpaea bracteata/ Syn. Savia volubilis/README.md
|
Markdown
|
apache-2.0
| 177
|
# Bulbine uncinata Moench SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Crinum/Crinum americanum/ Syn. Bulbine uncinata/README.md
|
Markdown
|
apache-2.0
| 180
|
# Zingiber yingjiangense S.Q.Tong SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Zingiberaceae/Zingiber/Zingiber yingjiangense/README.md
|
Markdown
|
apache-2.0
| 189
|
# Alchemilla isodonta Plocek SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Alchemilla/Alchemilla isodonta/README.md
|
Markdown
|
apache-2.0
| 176
|
# Pterula graminicola (Bourdot & Galzin) Singer, 1969 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Beih. Nova Hedwigia 29: 386 (1969)
#### Original name
Pistillaria graminicola Bourdot & Galzin, 1928
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Gomphales/Gomphaceae/Ceratellopsis/Ceratellopsis graminicola/ Syn. Pterula graminicola/README.md
|
Markdown
|
apache-2.0
| 280
|
# Polypodium minusculum Maxon SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Polypodiaceae/Polypodium/Polypodium minusculum/README.md
|
Markdown
|
apache-2.0
| 177
|
# Lactobacillus plantari (Orla-Jensen, 1919) Bergey et al., 1923 SPECIES
#### Status
SYNONYM
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Bacteria/Firmicutes/Bacilli/Lactobacillales/Lactobacillaceae/Lactobacillus/Lactobacillus plantarum/ Syn. Lactobacillus plantari/README.md
|
Markdown
|
apache-2.0
| 227
|
package org.apache.spark.sql.mleap
import ml.combust.mleap.core.types
import ml.combust.mleap.core.types.{BasicType, Casting}
import ml.combust.mleap.tensor.{DenseTensor, Tensor}
import org.apache.spark.ml.linalg.{Matrix, MatrixUDT, Vector, VectorUDT}
import ml.combust.mleap.core.util.VectorConverters._
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.types._
import scala.collection.mutable
import scala.language.implicitConversions
import scala.util.Try
/**
* Created by hollinwilkins on 10/22/16.
*/
trait TypeConverters {
private def getVectorSize(dataset: DataFrame, field: StructField): Int = {
val sizeInMeta = Try(field.metadata.getMetadata("ml_attr").getLong("num_attrs").toInt)
if (sizeInMeta.isSuccess) {
sizeInMeta.get
} else {
dataset.select(field.name).head().getAs[Vector](0).size
}
}
def sparkToMleapValue(dataType: DataType): (Any) => Any = dataType match {
case _: DecimalType =>
(v: Any) => v.asInstanceOf[java.math.BigDecimal].doubleValue()
case _: VectorUDT =>
(v: Any) =>
v.asInstanceOf[Vector]: Tensor[Double]
case _: MatrixUDT =>
(v: Any) =>
v.asInstanceOf[Matrix]: Tensor[Double]
case at: ArrayType if at.elementType == new VectorUDT =>
(v: Any) =>
val t = v.asInstanceOf[mutable.WrappedArray[Vector]]
val s = t.head.size
val values = t.flatMap(_.toArray).toArray
DenseTensor(values, Seq(t.size, s))
case _ => (v) => v
}
def sparkToMleapConverter(dataset: DataFrame,
field: StructField): (types.StructField, (Any) => Any) = {
(sparkFieldToMleapField(dataset, field), sparkToMleapValue(field.dataType))
}
def sparkFieldToMleapField(dataset: DataFrame,
field: StructField): types.StructField = {
val dt = field.dataType match {
case BooleanType => types.ScalarType.Boolean
case ByteType => types.ScalarType.Byte
case ShortType => types.ScalarType.Short
case IntegerType => types.ScalarType.Int
case LongType => types.ScalarType.Long
case FloatType => types.ScalarType.Float
case DoubleType => types.ScalarType.Double
case _: DecimalType => types.ScalarType.Double
case StringType => types.ScalarType.String.setNullable(field.nullable)
case ArrayType(ByteType, _) => types.ListType.Byte
case ArrayType(BooleanType, _) => types.ListType.Boolean
case ArrayType(ShortType, _) => types.ListType.Short
case ArrayType(IntegerType, _) => types.ListType.Int
case ArrayType(LongType, _) => types.ListType.Long
case ArrayType(FloatType, _) => types.ListType.Float
case ArrayType(DoubleType, _) => types.ListType.Double
case ArrayType(StringType, _) => types.ListType.String
case ArrayType(ArrayType(ByteType, _), _) => types.ListType.ByteString
case MapType(keyType, valueType, _) => types.MapType(sparkTypeToMleapBasicType(keyType), sparkTypeToMleapBasicType(valueType))
case _: VectorUDT =>
val size = getVectorSize(dataset, field)
types.TensorType.Double(size)
case _: MatrixUDT =>
val m = dataset.select(field.name).head.getAs[Matrix](0)
types.TensorType.Double(m.numRows, m.numCols)
case ArrayType(elementType, _) if elementType == new VectorUDT =>
val a = dataset.select(field.name).head.getAs[mutable.WrappedArray[Vector]](0)
types.TensorType.Double(a.length, a.head.size)
case _ => throw new UnsupportedOperationException(s"Cannot convert spark field $field to mleap")
}
types.StructField(field.name, dt.setNullable(field.nullable))
}
def sparkSchemaToMleapSchema(dataset: DataFrame): types.StructType = {
val fields = dataset.schema.fields.map(f => sparkFieldToMleapField(dataset, f))
types.StructType(fields).get
}
def sparkTypeToMleapBasicType(sparkType: DataType): types.BasicType = {
sparkType match{
case BooleanType => types.BasicType.Boolean
case ByteType => types.BasicType.Byte
case ShortType => types.BasicType.Short
case IntegerType => types.BasicType.Int
case LongType => types.BasicType.Long
case FloatType => types.BasicType.Float
case DoubleType => types.BasicType.Double
case _: DecimalType => types.BasicType.Double
case StringType => types.BasicType.String
case _ => throw new IllegalArgumentException(s"Can not convert spark $sparkType to mleap BasicType")
}
}
def mleapBasicTypeToSparkType(base: BasicType): DataType = base match {
case BasicType.Boolean => BooleanType
case BasicType.Byte => ByteType
case BasicType.Short => ShortType
case BasicType.Int => IntegerType
case BasicType.Long => LongType
case BasicType.Float => FloatType
case BasicType.Double => DoubleType
case BasicType.String => StringType
case BasicType.ByteString => ArrayType(ByteType, containsNull = false)
case _ => throw new UnsupportedOperationException(s"Cannot cast mleap type $base to spark DataType")
}
def mleapToSparkValue(dataType: types.DataType): (Any) => Any = dataType match {
case tt: types.TensorType =>
if(tt.dimensions.isEmpty) {
(v: Any) => v.asInstanceOf[Tensor[_]](0)
} else if(tt.dimensions.size == 1) {
if(tt.base == BasicType.Double) {
(v: Any) => v.asInstanceOf[Tensor[Double]]: Vector
} else {
val c = Casting.basicCast(tt.base, BasicType.Double).asInstanceOf[(Any) => Double]
(v: Any) => v.asInstanceOf[Tensor[_]].mapValues(c): Vector
}
} else if(tt.dimensions.size == 2) {
if(tt.base == BasicType.Double) {
(v: Any) => v.asInstanceOf[Tensor[Double]]: Matrix
} else {
val c = Casting.basicCast(tt.base, BasicType.Double).asInstanceOf[(Any) => Double]
(v: Any) => v.asInstanceOf[Tensor[_]].mapValues(c): Matrix
}
} else {
throw new IllegalArgumentException("cannot convert tensor for non-scalar, vector or matrix tensor")
}
case _ => (v: Any) => v
}
def mleapToSparkConverter(field: types.StructField): (StructField, (Any) => Any) = {
val dt = field.dataType match {
case types.ScalarType(base, _) => mleapBasicTypeToSparkType(base)
case types.ListType(base, _) => ArrayType(mleapBasicTypeToSparkType(base), containsNull = false)
case types.MapType(key, value, _) => MapType(mleapBasicTypeToSparkType(key), mleapBasicTypeToSparkType(value))
case tt: types.TensorType => mleapTensorToSpark(tt)
}
(StructField(field.name, dt, nullable = field.dataType.isNullable), mleapToSparkValue(field.dataType))
}
def mleapFieldToSparkField(field: types.StructField): StructField = {
val dt = field.dataType match {
case types.ScalarType(base, _) => mleapBasicTypeToSparkType(base)
case types.ListType(base, _) => ArrayType(mleapBasicTypeToSparkType(base), containsNull = false)
case types.MapType(key, value, _) => MapType(mleapBasicTypeToSparkType(key), mleapBasicTypeToSparkType(value))
case tt: types.TensorType => mleapTensorToSpark(tt)
}
StructField(field.name, dt, nullable = field.dataType.isNullable)
}
def mleapSchemaToSparkSchema(schema: types.StructType): StructType = {
val fields = schema.fields.map(mleapFieldToSparkField)
StructType(fields)
}
def mleapTensorToSpark(tt: types.TensorType): DataType = {
assert(TypeConverters.VECTOR_BASIC_TYPES.contains(tt.base),
s"cannot convert tensor with base ${tt.base} to vector")
assert(tt.dimensions.isDefined, "cannot convert tensor with undefined dimensions")
if(tt.dimensions.isEmpty) {
mleapBasicTypeToSparkType(tt.base)
} else if(tt.dimensions.size == 1) {
new VectorUDT
} else if(tt.dimensions.size == 2) {
new MatrixUDT
} else {
throw new IllegalArgumentException("cannot convert tensor for non-scalar, vector or matrix tensor")
}
}
def sparkToMleapDataShape(field: StructField,
dataset: DataFrame): types.DataShape = field.dataType match {
case BooleanType | ByteType | ShortType
| IntegerType | LongType | FloatType
| DoubleType | StringType => types.ScalarShape(field.nullable)
case _: DecimalType => types.ScalarShape(field.nullable)
case ArrayType(_, false) => types.ListShape(field.nullable)
case MapType(_, _, _) => types.ListShape(field.nullable)
case vu: VectorUDT =>
val size = getVectorSize(dataset, field)
types.TensorShape(Some(Seq(size)), field.nullable)
case mu: MatrixUDT =>
val m = dataset.select(field.name).head.getAs[Matrix](0)
types.TensorShape(Some(Seq(m.numRows, m.numCols)), field.nullable)
case _ => throw new IllegalArgumentException(s"invalid struct field for shape: $field")
}
}
object TypeConverters extends TypeConverters {
val VECTOR_BASIC_TYPES: Set[BasicType] = Set(
BasicType.Boolean,
BasicType.Byte,
BasicType.Short,
BasicType.Int,
BasicType.Long,
BasicType.Float,
BasicType.Double,
BasicType.String
)
}
|
combust/mleap
|
mleap-spark-base/src/main/scala/org/apache/spark/sql/mleap/TypeConverters.scala
|
Scala
|
apache-2.0
| 9,151
|
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.batch.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.batch.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateComputeEnvironmentRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateComputeEnvironmentRequestMarshaller {
private static final MarshallingInfo<String> COMPUTEENVIRONMENT_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("computeEnvironment").build();
private static final MarshallingInfo<String> STATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("state").build();
private static final MarshallingInfo<StructuredPojo> COMPUTERESOURCES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("computeResources").build();
private static final MarshallingInfo<String> SERVICEROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("serviceRole").build();
private static final UpdateComputeEnvironmentRequestMarshaller instance = new UpdateComputeEnvironmentRequestMarshaller();
public static UpdateComputeEnvironmentRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(UpdateComputeEnvironmentRequest updateComputeEnvironmentRequest, ProtocolMarshaller protocolMarshaller) {
if (updateComputeEnvironmentRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateComputeEnvironmentRequest.getComputeEnvironment(), COMPUTEENVIRONMENT_BINDING);
protocolMarshaller.marshall(updateComputeEnvironmentRequest.getState(), STATE_BINDING);
protocolMarshaller.marshall(updateComputeEnvironmentRequest.getComputeResources(), COMPUTERESOURCES_BINDING);
protocolMarshaller.marshall(updateComputeEnvironmentRequest.getServiceRole(), SERVICEROLE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
dagnir/aws-sdk-java
|
aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/transform/UpdateComputeEnvironmentRequestMarshaller.java
|
Java
|
apache-2.0
| 3,136
|
package ru.spb.kpit.kivan.Networking.AsyncCrawler.Proxy;
import ru.spb.kpit.kivan.General.DataStructures.HMCounter;
import ru.spb.kpit.kivan.Networking.AsyncCrawler.AsyncSiteRequestExecutor;
import ru.spb.kpit.kivan.Randomizer.SSRand;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
/**
* IntelliJ IDEA. Best IDE in entire Universe.
* CodeGod: Kivan
* ContinuumBreak: 23.09.13
* MomentOfSilence: 16:36
*/
public class ProxyPool {
/**
* String - name of prismer
*/
HashMap<String, ProxyPrismer> prismers = new HashMap<String, ProxyPrismer>();
/**
* List of o4erednostj of executions
*/
HashMap<AsyncSiteRequestExecutor, Set<ProxyPrismer>> o4erednostj = new HashMap<AsyncSiteRequestExecutor, Set<ProxyPrismer>>();
int maxBadCountForPrismer = 5;
HMCounter<ProxyPrismer> badPrismers = new HMCounter<ProxyPrismer>();
ReentrantLock lock = new ReentrantLock();
public ProxyPool(ProxyPrismer ... prismers) {
for (ProxyPrismer prismer : prismers) {
this.prismers.put(prismer.getInfo(), prismer);
}
}
public ProxyPool(int maxBadCountForPrismer, ProxyPrismer ... prismers) {
this.maxBadCountForPrismer = maxBadCountForPrismer;
for (ProxyPrismer prismer : prismers) {
this.prismers.put(prismer.getInfo(), prismer);
}
}
public ProxyPrismer getPrismer(AsyncSiteRequestExecutor executor){
try {
lock.lock();
Set<ProxyPrismer> proPri = o4erednostj.get(executor);
if(proPri==null || proPri.size()==0) {
proPri = new HashSet<ProxyPrismer>();
for (ProxyPrismer proxyPrismer : prismers.values()) {
proPri.add(proxyPrismer);
}
o4erednostj.put(executor, proPri);
}
ProxyPrismer pp = (ProxyPrismer) SSRand.thrdSf().randElFromCollection(proPri);
proPri.remove(pp);
return pp;
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
lock.unlock();
}
return null;
}
public void prismerDoneBad(ProxyPrismer prismer) {
try {
lock.lock();
badPrismers.put(prismer);
if(badPrismers.get(prismer)>maxBadCountForPrismer) {
prismers.remove(prismer.getInfo());
badPrismers.remove(prismer);
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
lock.unlock();
}
}
}
|
kivan-mih/generalLib
|
src/ru/spb/kpit/kivan/Networking/AsyncCrawler/Proxy/ProxyPool.java
|
Java
|
apache-2.0
| 2,735
|
"""
Helper functions for use by mac modules
.. versionadded:: 2016.3.0
"""
import logging
import os
import plistlib
import subprocess
import time
import xml.parsers.expat
import salt.grains.extra
import salt.modules.cmdmod
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.timed_subprocess
from salt.exceptions import (
CommandExecutionError,
SaltInvocationError,
TimedProcTimeoutError,
)
try:
import pwd
except ImportError:
# The pwd module is not available on all platforms
pass
DEFAULT_SHELL = salt.grains.extra.shell()["shell"]
# Set up logging
log = logging.getLogger(__name__)
__virtualname__ = "mac_utils"
__salt__ = {
"cmd.run_all": salt.modules.cmdmod._run_all_quiet,
"cmd.run": salt.modules.cmdmod._run_quiet,
}
def __virtual__():
"""
Load only on Mac OS
"""
if not salt.utils.platform.is_darwin():
return (
False,
"The mac_utils utility could not be loaded: "
"utility only works on MacOS systems.",
)
return __virtualname__
def _run_all(cmd):
"""
Args:
cmd:
Returns:
"""
if not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd, posix=False)
for idx, item in enumerate(cmd):
if not isinstance(cmd[idx], str):
cmd[idx] = str(cmd[idx])
cmd = " ".join(cmd)
run_env = os.environ.copy()
kwargs = {
"cwd": None,
"shell": DEFAULT_SHELL,
"env": run_env,
"stdin": None,
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"with_communicate": True,
"timeout": None,
"bg": False,
}
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **kwargs)
except OSError as exc:
raise CommandExecutionError(
"Unable to run command '{}' with the context '{}', reason: {}".format(
cmd, kwargs, exc
)
)
ret = {}
try:
proc.run()
except TimedProcTimeoutError as exc:
ret["stdout"] = str(exc)
ret["stderr"] = ""
ret["retcode"] = 1
ret["pid"] = proc.process.pid
return ret
out, err = proc.stdout, proc.stderr
if out is not None:
out = salt.utils.stringutils.to_str(out).rstrip()
if err is not None:
err = salt.utils.stringutils.to_str(err).rstrip()
ret["pid"] = proc.process.pid
ret["retcode"] = proc.process.returncode
ret["stdout"] = out
ret["stderr"] = err
return ret
def _check_launchctl_stderr(ret):
"""
helper class to check the launchctl stderr.
launchctl does not always return bad exit code
if there is a failure
"""
err = ret["stderr"].lower()
if "service is disabled" in err:
return True
return False
def execute_return_success(cmd):
"""
Executes the passed command. Returns True if successful
:param str cmd: The command to run
:return: True if successful, otherwise False
:rtype: bool
:raises: Error if command fails or is not supported
"""
ret = _run_all(cmd)
log.debug("Execute return success %s: %r", cmd, ret)
if ret["retcode"] != 0 or "not supported" in ret["stdout"].lower():
msg = "Command Failed: {}\n".format(cmd)
msg += "Return Code: {}\n".format(ret["retcode"])
msg += "Output: {}\n".format(ret["stdout"])
msg += "Error: {}\n".format(ret["stderr"])
raise CommandExecutionError(msg)
return True
def execute_return_result(cmd):
"""
Executes the passed command. Returns the standard out if successful
:param str cmd: The command to run
:return: The standard out of the command if successful, otherwise returns
an error
:rtype: str
:raises: Error if command fails or is not supported
"""
ret = _run_all(cmd)
if ret["retcode"] != 0 or "not supported" in ret["stdout"].lower():
msg = "Command Failed: {}\n".format(cmd)
msg += "Return Code: {}\n".format(ret["retcode"])
msg += "Output: {}\n".format(ret["stdout"])
msg += "Error: {}\n".format(ret["stderr"])
raise CommandExecutionError(msg)
return ret["stdout"]
def parse_return(data):
"""
Returns the data portion of a string that is colon separated.
:param str data: The string that contains the data to be parsed. Usually the
standard out from a command
For example:
``Time Zone: America/Denver``
will return:
``America/Denver``
"""
if ": " in data:
return data.split(": ")[1]
if ":\n" in data:
return data.split(":\n")[1]
else:
return data
def validate_enabled(enabled):
"""
Helper function to validate the enabled parameter. Boolean values are
converted to "on" and "off". String values are checked to make sure they are
either "on" or "off"/"yes" or "no". Integer ``0`` will return "off". All
other integers will return "on"
:param enabled: Enabled can be boolean True or False, Integers, or string
values "on" and "off"/"yes" and "no".
:type: str, int, bool
:return: "on" or "off" or errors
:rtype: str
"""
if isinstance(enabled, str):
if enabled.lower() not in ["on", "off", "yes", "no"]:
msg = (
"\nMac Power: Invalid String Value for Enabled.\n"
"String values must be 'on' or 'off'/'yes' or 'no'.\n"
"Passed: {}".format(enabled)
)
raise SaltInvocationError(msg)
return "on" if enabled.lower() in ["on", "yes"] else "off"
return "on" if bool(enabled) else "off"
def confirm_updated(value, check_fun, normalize_ret=False, wait=5):
"""
Wait up to ``wait`` seconds for a system parameter to be changed before
deciding it hasn't changed.
:param str value: The value indicating a successful change
:param function check_fun: The function whose return is compared with
``value``
:param bool normalize_ret: Whether to normalize the return from
``check_fun`` with ``validate_enabled``
:param int wait: The maximum amount of seconds to wait for a system
parameter to change
"""
for i in range(wait):
state = validate_enabled(check_fun()) if normalize_ret else check_fun()
log.debug(
"Confirm update try: %d func:%r state:%s value:%s",
i,
check_fun,
state,
value,
)
if value in state:
return True
time.sleep(1)
return False
def launchctl(sub_cmd, *args, **kwargs):
"""
Run a launchctl command and raise an error if it fails
Args: additional args are passed to launchctl
sub_cmd (str): Sub command supplied to launchctl
Kwargs: passed to ``cmd.run_all``
return_stdout (bool): A keyword argument. If true return the stdout of
the launchctl command
Returns:
bool: ``True`` if successful
str: The stdout of the launchctl command if requested
Raises:
CommandExecutionError: If command fails
CLI Example:
.. code-block:: bash
import salt.utils.mac_service
salt.utils.mac_service.launchctl('debug', 'org.cups.cupsd')
"""
# Get return type
return_stdout = kwargs.pop("return_stdout", False)
# Construct command
cmd = ["launchctl", sub_cmd]
cmd.extend(args)
# fix for https://github.com/saltstack/salt/issues/57436
if sub_cmd == "bootout":
kwargs["success_retcodes"] = [
36,
]
# Run command
kwargs["python_shell"] = False
kwargs = salt.utils.args.clean_kwargs(**kwargs)
ret = __salt__["cmd.run_all"](cmd, **kwargs)
error = _check_launchctl_stderr(ret)
# Raise an error or return successful result
if ret["retcode"] or error:
out = "Failed to {} service:\n".format(sub_cmd)
out += "stdout: {}\n".format(ret["stdout"])
out += "stderr: {}\n".format(ret["stderr"])
out += "retcode: {}".format(ret["retcode"])
raise CommandExecutionError(out)
else:
return ret["stdout"] if return_stdout else True
def _read_plist_file(root, file_name):
"""
:param root: The root path of the plist file
:param file_name: The name of the plist file
:return: An empty dictionary if the plist file was invalid, otherwise, a dictionary with plist data
"""
file_path = os.path.join(root, file_name)
log.debug("read_plist: Gathering service info for %s", file_path)
# Must be a plist file
if not file_path.lower().endswith(".plist"):
log.debug("read_plist: Not a plist file: %s", file_path)
return {}
# ignore broken symlinks
if not os.path.exists(os.path.realpath(file_path)):
log.warning("read_plist: Ignoring broken symlink: %s", file_path)
return {}
try:
with salt.utils.files.fopen(file_path, "rb") as handle:
plist = plistlib.load(handle)
except plistlib.InvalidFileException:
# Raised in python3 if the file is not XML.
# There's nothing we can do; move on to the next one.
log.warning(
'read_plist: Unable to parse "%s" as it is invalid XML: InvalidFileException.',
file_path,
)
return {}
except ValueError as err:
# fixes https://github.com/saltstack/salt/issues/58143
# choosing not to log a Warning as this would happen on BigSur+ machines.
log.debug(
"Caught ValueError: '%s', while trying to parse '%s'.", err, file_path
)
return {}
except xml.parsers.expat.ExpatError:
# Raised by py3 if the file is XML, but with errors.
log.warning(
'read_plist: Unable to parse "%s" as it is invalid XML: xml.parsers.expat.ExpatError.',
file_path,
)
return {}
if "Label" not in plist:
# not all launchd plists contain a Label key
log.debug(
"read_plist: Service does not contain a Label key. Skipping %s.", file_path
)
return {}
return {
"file_name": file_name,
"file_path": file_path,
"plist": plist,
}
def _available_services(refresh=False):
"""
This is a helper function for getting the available macOS services.
The strategy is to look through the known system locations for
launchd plist files, parse them, and use their information for
populating the list of services. Services can run without a plist
file present, but normally services which have an automated startup
will have a plist file, so this is a minor compromise.
"""
if "available_services" in __context__ and not refresh:
log.debug("Found context for available services.")
__context__["using_cached_services"] = True
return __context__["available_services"]
launchd_paths = {
"/Library/LaunchAgents",
"/Library/LaunchDaemons",
"/System/Library/LaunchAgents",
"/System/Library/LaunchDaemons",
}
agent_path = "/Users/{}/Library/LaunchAgents"
launchd_paths.update(
{
agent_path.format(user)
for user in os.listdir("/Users/")
if os.path.isdir(agent_path.format(user))
}
)
result = {}
for launch_dir in launchd_paths:
for root, dirs, files in salt.utils.path.os_walk(launch_dir):
for file_name in files:
data = _read_plist_file(root, file_name)
if data:
result[data["plist"]["Label"].lower()] = data
# put this in __context__ as this is a time consuming function.
# a fix for this issue. https://github.com/saltstack/salt/issues/48414
__context__["available_services"] = result
# this is a fresh gathering of services, set cached to false
__context__["using_cached_services"] = False
return result
def available_services(refresh=False):
"""
Return a dictionary of all available services on the system
:param bool refresh: If you wish to refresh the available services
as this data is cached on the first run.
Returns:
dict: All available services
CLI Example:
.. code-block:: bash
import salt.utils.mac_service
salt.utils.mac_service.available_services()
"""
log.debug("Loading available services")
return _available_services(refresh)
def console_user(username=False):
"""
Gets the UID or Username of the current console user.
:return: The uid or username of the console user.
:param bool username: Whether to return the username of the console
user instead of the UID. Defaults to False
:rtype: Interger of the UID, or a string of the username.
Raises:
CommandExecutionError: If we fail to get the UID.
CLI Example:
.. code-block:: bash
import salt.utils.mac_service
salt.utils.mac_service.console_user()
"""
try:
# returns the 'st_uid' stat from the /dev/console file.
uid = os.stat("/dev/console")[4]
except (OSError, IndexError):
# we should never get here but raise an error if so
raise CommandExecutionError("Failed to get a UID for the console user.")
if username:
return pwd.getpwuid(uid)[0]
return uid
def git_is_stub():
"""
Return whether macOS git is the standard OS stub or a real binary.
"""
# On a fresh macOS install, /usr/bin/git is a stub, which if
# accessed, triggers a UI dialog box prompting the user to install
# the developer command line tools. We don't want that! So instead,
# running the below command will return a path to the installed dev
# tools and retcode 0, or print a bunch of info to stderr and
# retcode 2.
try:
cmd = ["/usr/bin/xcode-select", "-p"]
_ = subprocess.check_call(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1
)
log.debug("Xcode command line tools present")
return False
except subprocess.CalledProcessError:
log.debug("Xcode command line tools not present")
return True
|
saltstack/salt
|
salt/utils/mac_utils.py
|
Python
|
apache-2.0
| 14,345
|
/*
Copyright 2021 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by injection-gen. DO NOT EDIT.
package filtered
import (
context "context"
apicorev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
v1 "k8s.io/client-go/informers/core/v1"
kubernetes "k8s.io/client-go/kubernetes"
corev1 "k8s.io/client-go/listers/core/v1"
cache "k8s.io/client-go/tools/cache"
client "knative.dev/pkg/client/injection/kube/client"
filtered "knative.dev/pkg/client/injection/kube/informers/factory/filtered"
controller "knative.dev/pkg/controller"
injection "knative.dev/pkg/injection"
logging "knative.dev/pkg/logging"
)
func init() {
injection.Default.RegisterFilteredInformers(withInformer)
injection.Dynamic.RegisterDynamicInformer(withDynamicInformer)
}
// Key is used for associating the Informer inside the context.Context.
type Key struct {
Selector string
}
func withInformer(ctx context.Context) (context.Context, []controller.Informer) {
untyped := ctx.Value(filtered.LabelKey{})
if untyped == nil {
logging.FromContext(ctx).Panic(
"Unable to fetch labelkey from context.")
}
labelSelectors := untyped.([]string)
infs := []controller.Informer{}
for _, selector := range labelSelectors {
f := filtered.Get(ctx, selector)
inf := f.Core().V1().ReplicationControllers()
ctx = context.WithValue(ctx, Key{Selector: selector}, inf)
infs = append(infs, inf.Informer())
}
return ctx, infs
}
func withDynamicInformer(ctx context.Context) context.Context {
untyped := ctx.Value(filtered.LabelKey{})
if untyped == nil {
logging.FromContext(ctx).Panic(
"Unable to fetch labelkey from context.")
}
labelSelectors := untyped.([]string)
for _, selector := range labelSelectors {
inf := &wrapper{client: client.Get(ctx), selector: selector}
ctx = context.WithValue(ctx, Key{Selector: selector}, inf)
}
return ctx
}
// Get extracts the typed informer from the context.
func Get(ctx context.Context, selector string) v1.ReplicationControllerInformer {
untyped := ctx.Value(Key{Selector: selector})
if untyped == nil {
logging.FromContext(ctx).Panicf(
"Unable to fetch k8s.io/client-go/informers/core/v1.ReplicationControllerInformer with selector %s from context.", selector)
}
return untyped.(v1.ReplicationControllerInformer)
}
type wrapper struct {
client kubernetes.Interface
namespace string
selector string
}
var _ v1.ReplicationControllerInformer = (*wrapper)(nil)
var _ corev1.ReplicationControllerLister = (*wrapper)(nil)
func (w *wrapper) Informer() cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(nil, &apicorev1.ReplicationController{}, 0, nil)
}
func (w *wrapper) Lister() corev1.ReplicationControllerLister {
return w
}
func (w *wrapper) ReplicationControllers(namespace string) corev1.ReplicationControllerNamespaceLister {
return &wrapper{client: w.client, namespace: namespace, selector: w.selector}
}
func (w *wrapper) List(selector labels.Selector) (ret []*apicorev1.ReplicationController, err error) {
reqs, err := labels.ParseToRequirements(w.selector)
if err != nil {
return nil, err
}
selector = selector.Add(reqs...)
lo, err := w.client.CoreV1().ReplicationControllers(w.namespace).List(context.TODO(), metav1.ListOptions{
LabelSelector: selector.String(),
// TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria.
})
if err != nil {
return nil, err
}
for idx := range lo.Items {
ret = append(ret, &lo.Items[idx])
}
return ret, nil
}
func (w *wrapper) Get(name string) (*apicorev1.ReplicationController, error) {
// TODO(mattmoor): Check that the fetched object matches the selector.
return w.client.CoreV1().ReplicationControllers(w.namespace).Get(context.TODO(), name, metav1.GetOptions{
// TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria.
})
}
|
knative/pkg
|
client/injection/kube/informers/core/v1/replicationcontroller/filtered/replicationcontroller.go
|
GO
|
apache-2.0
| 4,405
|
# Parduyna multiflora (R.Br.) Salisb. ex Dandy SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Liliales/Colchicaceae/Schelhammera/Schelhammera multiflora/ Syn. Parduyna multiflora/README.md
|
Markdown
|
apache-2.0
| 201
|
$packageName = '{{PackageName}}'
$installerType = 'exe'
$url = '{{DownloadUrl}}'
$checksum = '{{Checksum}}'
$checksumType = 'sha1'
$validExitCodes = @(0)
$binRoot = Get-BinRoot
$installPath = Join-Path $binRoot "Foldit"
$silentArgsBase = '/S /D='
$silentArgs = $($silentArgsBase + '"' + $installPath + '"')
Install-ChocolateyPackage -PackageName "$packageName" `
-FileType "$installerType" `
-SilentArgs "$silentArgs" `
-Url "$url" `
-ValidExitCodes $validExitCodes `
-Checksum "$checksum" `
-ChecksumType "$checksumType"
|
maharishi/chocolatey-packages
|
automatic/foldit/tools/chocolateyInstall.ps1
|
PowerShell
|
apache-2.0
| 681
|
//import java.net.*;
//import java.util.Scanner;
//import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* ShellProcess allows User to run external process
* managing input and ouputs streams in separated threads
*
* @author Xavier Bruhiere
*/
public class ShellProcess
{
private OutputStream out = null;
private OutputStream err = null;
private InputStream in = null;
private Process process;
private long timeout = 0L;
private boolean finished = false;
/** Constructors */
public ShellProcess() {
this(null, null, null, 0L);
}
public ShellProcess(OutputStream out, OutputStream err) {
this(out, err, null, 0L);
}
public ShellProcess(OutputStream out, OutputStream err, InputStream in) {
this(out, err, in, 0L);
}
public ShellProcess(OutputStream out, OutputStream err, long timeout) {
this(out, err, null, timeout);
}
/** @param out Outputstream vers lequel sera redirige la sortie standard (null pour ne pas rediriger).
* @param err Outputstream vers lequel sera redirige la sortie d'erreur
* @param in InputStream vers lequel sera redirige l'entree standard
* @param timeout temps en millisecondes avant de forcer l'arret (0 pour ne jamais forcer l'arret).*/
public ShellProcess(OutputStream out, OutputStream err, InputStream in, long timeout) {
this.out = out;
this.err = err;
this.in = in;
this.timeout = timeout < 0 ? 0L : timeout;
}
public int exec(String command) throws IOException {
process = Runtime.getRuntime().exec(command);
return execute();
}
public int exec(String[] cmdarray) throws IOException {
process = Runtime.getRuntime().exec(cmdarray);
return execute();
}
public int exec(String[] cmdarray, String[] envp) throws IOException {
process = Runtime.getRuntime().exec(cmdarray, envp);
return execute();
}
public int exec(String[] cmdarray, String[] envp, File dir) throws IOException {
process = Runtime.getRuntime().exec(cmdarray, envp, dir);
return execute();
}
public int exec(String command, String[] envp) throws IOException {
process = Runtime.getRuntime().exec(command, envp);
return execute();
}
/**
* Execute une ligne de commande dans un processus separe en specifiant des
* variables d'environnement et le repertoire de travail.
*
* @param command ligne de commande
* @param envp variables d'environnement
* @param dir repertoire de travail
* @return valeur de retour du processus
*/
public int exec(String command, String[] envp, File dir) throws IOException {
process = Runtime.getRuntime().exec(command, envp, dir);
return execute();
}
/** So told execution part */
private int execute() throws IOException {
int status = -1;
// Consommation des fluxs de sortie standard et d'erreur dans des threads separes.
if(err == null) {
process.getErrorStream().close();
} else {
createStreamThread(process.getErrorStream(), err);
}
if(out == null) {
process.getInputStream().close();
} else {
createStreamThread(process.getInputStream(), out);
}
// Mapping de l'entree standard de l'application si besoin est.
if(in != null) {
createStreamThread(in, process.getOutputStream());
}
if (timeout > 0L) {
Thread processThread = createProcessThread(process);
processThread.start();
try {
processThread.join(timeout);
try {
status = process.exitValue();
} catch (IllegalThreadStateException itse) {
process.destroy();
status = process.exitValue();
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
} else if (timeout == 0L) {
try {
status = process.waitFor();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
finished = true;
return status;
}
private void createStreamThread(final InputStream is, final OutputStream os) {
new Thread(new Runnable() {
public void run() {
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = null;
if(os != null) {
bos = new BufferedOutputStream(os);
}
byte[] data = new byte[2048];
int nbRead = 0;
try {
while((nbRead = bis.read(data)) > 0) {
if(bos != null) {
if(finished) {
break;
}
bos.write(data, 0, nbRead);
bos.flush();
}
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}).start();
}
private Thread createProcessThread(final Process process) {
return new Thread() {
public void run() {
try {
process.waitFor();
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
};
}
/** Accesseurs */
public OutputStream getErrorStream() {
return err;
}
public InputStream getInputStream() {
return in;
}
public OutputStream getOutputStream() {
return out;
}
public long getTimeout() {
return timeout;
}
public void setErrorStream(OutputStream err) {
this.err = err;
}
public void setInputStream(InputStream in) {
this.in = in;
}
public void setOutputStream(OutputStream out) {
this.out = out;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
/** Others */
public boolean isFinished() {
return finished;
}
}
|
hackliff/domobot
|
server/ipConnection/ShellProcess.java
|
Java
|
apache-2.0
| 5,564
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.IO.Pipelines
{
// Copied from https://github.com/dotnet/corefx/blob/de3902bb56f1254ec1af4bf7d092fc2c048734cc/src/System.IO.Pipelines/src/System/IO/Pipelines/BufferSegmentStack.cs
internal struct BufferSegmentStack
{
private SegmentAsValueType[] _array;
private int _size;
public BufferSegmentStack(int size)
{
_array = new SegmentAsValueType[size];
_size = 0;
}
public int Count => _size;
public bool TryPop([NotNullWhen(true)] out BufferSegment? result)
{
int size = _size - 1;
SegmentAsValueType[] array = _array;
if ((uint)size >= (uint)array.Length)
{
result = default;
return false;
}
_size = size;
result = array[size];
array[size] = default;
return true;
}
// Pushes an item to the top of the stack.
public void Push(BufferSegment item)
{
int size = _size;
SegmentAsValueType[] array = _array;
if ((uint)size < (uint)array.Length)
{
array[size] = item;
_size = size + 1;
}
else
{
PushWithResize(item);
}
}
// Non-inline from Stack.Push to improve its code quality as uncommon path
[MethodImpl(MethodImplOptions.NoInlining)]
private void PushWithResize(BufferSegment item)
{
Array.Resize(ref _array, 2 * _array.Length);
_array[_size] = item;
_size++;
}
/// <summary>
/// A simple struct we wrap reference types inside when storing in arrays to
/// bypass the CLR's covariant checks when writing to arrays.
/// </summary>
/// <remarks>
/// We use <see cref="SegmentAsValueType"/> as a wrapper to avoid paying the cost of covariant checks whenever
/// the underlying array that the <see cref="BufferSegmentStack"/> class uses is written to.
/// We've recognized this as a perf win in ETL traces for these stack frames:
/// clr!JIT_Stelem_Ref
/// clr!ArrayStoreCheck
/// clr!ObjIsInstanceOf
/// </remarks>
private readonly struct SegmentAsValueType
{
private readonly BufferSegment _value;
private SegmentAsValueType(BufferSegment value) => _value = value;
public static implicit operator SegmentAsValueType(BufferSegment s) => new SegmentAsValueType(s);
public static implicit operator BufferSegment(SegmentAsValueType s) => s._value;
}
}
}
|
aspnet/AspNetCore
|
src/Shared/Buffers/BufferSegmentStack.cs
|
C#
|
apache-2.0
| 2,966
|
# Contributing
Please take a moment to review this document in order to make the
contribution process easy and effective for everyone involved.
## Contributing code
Before doing any major changes, there are a couple things you should do:
1. Open an issue to discuss and potentially help if the team agrees
the changes will be for the best.
1. Familiarize yourself with the architecture and concepts by reading the
[contributor guide][contributor guide] and the projects
[pull request process][pr process].
1. Sign our [Contributor License Agreement][cla]
We thank you for following these tips!
## Code of Conduct
This project adheres to the [JS Foundation Code of
Conduct](https://js.foundation/community/code-of-conduct). We kindly
request that you read over our code of conduct before contributing.
<!-- Link labels -->
[cla]: https://cla.js.foundation/webhintio/hint
[contributor guide]: https://webhint.io/docs/contributor-guide/
[pr process]: https://webhint.io/docs/contributor-guide/getting-started/pull-requests/
|
sonarwhal/sonar
|
.github/CONTRIBUTING.md
|
Markdown
|
apache-2.0
| 1,039
|
---
author: admin
comments: true
date: 2013-05-16 10:07:00+00:00
layout: post
slug: '%e3%80%90%e8%bd%ac%e3%80%91%e6%ae%b5%e8%aa%89%e7%8e%8b%e8%af%ad%e5%ab%a3%e4%ba%95%e5%ba%95%e6%b7%b1%e6%83%85%e8%a1%a8%e7%99%bd%e4%b8%8d%e5%90%8c%e4%bd%9c%e5%ae%b6%e9%a3%8e%e6%a0%bc%e6%94%b9%ef%bf%bd'
title: 【转】段誉王语嫣井底深情表白(不同作家风格改写版)
permalink: /2013/05/16/180.html
wordpress_id: 180
categories:
- 天下杂侃
tags:
- 天下杂侃
---
【金庸原版】
直到午牌时分,井底三人才先后醒转。第一个醒的是王语嫣,她功力本浅,内力虽然全失,但原来并没多少,受损也就无几。她醒转后自然立时便想到段誉,其时虽是光天白日,深井之中仍是目不见物,她伸手一摸,碰到了段誉,叫道:“段郎,段郎,你……你……你怎么了?”不听得段誉的应声,只道他已被鸠摩智扼死,不禁抚“尸”痛哭,将他紧紧抱在胸前,哭道:“段郎,段郎,你对我这么情深意重,我却没有一天好言语、好颜色对你,我只盼日后丝萝得托乔木,好好的补报于你,哪知道……哪知道……我俩竟恁地命苦,今日你命丧恶僧之手……”
【古龙版】
王语嫣娇呼道:“段誉,段誉,你……你醒醒。”
她身旁一个声音冷冷道:“他不会醒来。”
这语声迟缓、冷漠,生涩,语调平板得没有一丝情感,像是坟墓里的死尸吐出的话语。
王语嫣却仿佛没有听见,嘶声道:“段誉,段誉,你快醒来……”
那语声冷冷道:“他已死了,你不知道么?”
王语嫣挺起胸膛,大声道:“哼,你怎知他死了?”
她虽然竭力摆出勇敢的样子,她的声音却微微颤抖,掩不住心里的害怕。
那语声狂笑道:“他是某家亲手杀死的,我怎不知?”
王语嫣突然放声痛哭起来,嘶声道:“你撒谎……,恶魔,你撒谎……”
黑暗肮脏的枯井底,一个绝美的女人,抱着一具尸体放声痛哭,构成了一幅惊心动魄、充满着血腥的诱惑的美丽画面!
【黄易版】
王语嫣只道段誉死了,抱着他的尸体,哀哀哭泣。
段誉的身体突然动了动,眼珠也转了转,出声笑道:“你哭什么?”
王语嫣又惊又喜,问他怎么会醒来。
原来段誉并没有被鸠摩智杀死,而是急中生智,屏住了呼吸,瞒过了鸠摩智,又点了他的穴道。
这清丽的美女听到这里,一双美目中泛起凄迷之色,香唇轻吐道:“幸好段郎你如此机智,方能制住了这恶僧,也使语嫣免于这恶僧的欺辱,人家真是对你感激不尽!”
段誉笑道:“你心中感激,该如何报答我呢?”
王语嫣如小绵羊般温顺地垂下了头,在段誉温柔的爱抚下,这端庄的美女青涩的情欲烈焰被他燃起,两人皆尝到了抵死缠绵的无穷快感。
【琼瑶版】
“语嫣!”鸠摩智炯炯的注视着她,含泪喊:“你难道看不出来吗?他,他已经死了!”
语嫣听到了他的话,整个人就震撼住了,久久的说不出话。她看着段誉的脸,那么年轻,那么俊秀……她茫然的摇着头,好小声好小声的说:
“不会的,不会的,不会的,他不会死的……”说着,就摇晃着他的身子,喊:
“段誉,你快醒醒,你快醒醒啊!”喊着喊着,泪水就滚了下来。
鸠摩智看着她这副模样,感到自己的心也仿佛被撕碎了,他握住她的手,真挚的、沉痛的喊:
“语嫣,你听我说一句话!他已经死了,不会回来了!可是——你还有我啊!”
【曹雪芹版】
那王语嫣见段誉不醒,已唬去了半个神儿,抱着他只哭骂:“你个狠心短命的小祖宗,你若死了,我可怎么过啊?”到伤心处,又唤起慕容复的名字来:“若有你在,死一百个他,我也不管了!”只哭得天昏地暗,两眼肿得只如桃子一般。
【明晓溪版】
晶莹的泪水。
透明璀璨的泪珠在她的脸上蔓延。
眼前白雾氤氲……
脑海中一片白茫茫……
……
恍若冬日最晶莹清澈的雪……
…………
……
“语嫣……”
……
“语嫣……”樱花般的唇角勾起一抹笑,呛咳出一串殷红的血沫,“我……喜欢你……”
……
…………
【鬼吹灯版】
不知过了多久,我才醒了过来,四周一片漆黑,看来这井深得很。正在绝望的时候,忽然感觉有丝阴风吹在脸上,不由心里一动,这井中既有空气流通,说明必和地下水脉相连,指不定就有一条秘道,通往皇宫的地下宝藏,毕竟这是西夏王朝剥削阶级的井。正胡思乱想着,忽然听到王语嫣在一边焦急地叫道:“老段,老段,你怎样了?”我刚想回答,猛听到身后一阵沉闷的异响,只觉得阴风更甚,不由毛骨悚然,忙压低了声音道:“嘘,别出声,有粽子。”
【韩寒版】
王姑娘先醒。这很奇怪,因为此人是先落下井去。段誉等人落下时必定要拿她当垫背。但是垫背居然还先醒来。我们只能理解为,王姑娘实在是人中极品,皮肉细嫩软和,故而充满弹力。用八戒的话说:
好大的棉花糖啊。
【郭敬明版】
直到午牌时分,井底三人才先后醒转。第一个醒的是王语嫣,她功力本浅,内力虽然全失,但原来并没多少,受损也就无几。她醒转后自然立时便想到段誉,其时虽是光天白日,深井之中仍是目不见物,她伸手一摸,碰到了段誉,叫道:“段郎,段郎,你……你……你怎么了?”不听得段誉的应声,只道他已被鸠摩智扼死,不禁抚“尸”痛哭,将他紧紧抱在胸前,哭道:“段郎,段郎,你对我这么情深意重,我却没有一天好言语、好颜色对你,我只盼日后丝萝得托乔木,好好的补报于你,哪知道……哪知道……我俩竟恁地命苦,今日你命丧恶僧之手……”
|
akmumu/akmumu.github.io
|
_posts/2013-05-16-180.markdown
|
Markdown
|
apache-2.0
| 6,713
|
/*
* 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.karaf.instance.command.completers;
import java.util.List;
import org.apache.karaf.instance.core.Instance;
import org.apache.karaf.instance.core.InstanceService;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import org.apache.karaf.shell.console.Completer;
/**
* Displays a list of configured server instances for the instance commands.
*
*/
public class InstanceCompleter implements Completer {
private InstanceService instanceService;
public void setInstanceService(InstanceService instanceService) {
this.instanceService = instanceService;
}
public int complete(String buffer, int cursor, List candidates) {
StringsCompleter delegate = new StringsCompleter();
for (Instance instance : instanceService.getInstances()) {
delegate.getStrings().add(instance.getName());
}
return delegate.complete(buffer, cursor, candidates);
}
}
|
soluvas/karaf
|
instance/command/src/main/java/org/apache/karaf/instance/command/completers/InstanceCompleter.java
|
Java
|
apache-2.0
| 1,752
|
# Atelophragma williamsii (Rydb.) Rydb. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Astragalus/Astragalus williamsii/ Syn. Atelophragma williamsii/README.md
|
Markdown
|
apache-2.0
| 194
|
/*
* This file is part of the PSL software.
* Copyright 2011-2013 University of Maryland
*
* 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.umd.cs.psl.application.inference;
import de.mathnbits.statistics.DoubleDist;
import edu.umd.cs.psl.application.ModelApplication;
import edu.umd.cs.psl.application.util.Grounding;
import edu.umd.cs.psl.config.ConfigBundle;
import edu.umd.cs.psl.config.ConfigManager;
import edu.umd.cs.psl.config.Factory;
import edu.umd.cs.psl.database.Database;
import edu.umd.cs.psl.database.DatabasePopulator;
import edu.umd.cs.psl.evaluation.result.FullConfidenceAnalysisResult;
import edu.umd.cs.psl.evaluation.result.memory.MemoryFullConfidenceAnalysisResult;
import edu.umd.cs.psl.model.ConfidenceValues;
import edu.umd.cs.psl.model.Model;
import edu.umd.cs.psl.model.atom.ObservedAtom;
import edu.umd.cs.psl.model.atom.PersistedAtomManager;
import edu.umd.cs.psl.model.atom.RandomVariableAtom;
import edu.umd.cs.psl.reasoner.Reasoner;
import edu.umd.cs.psl.reasoner.ReasonerFactory;
import edu.umd.cs.psl.reasoner.admm.ADMMReasonerFactory;
import edu.umd.cs.psl.sampler.MarginalSampler;
/**
* Infers the means and inverse standard deviations of the
* {@link RandomVariableAtom RandomVariableAtoms} persisted in a {@link Database},
* according to a {@link Model}, given the Database's {@link ObservedAtom ObservedAtoms}.
* <p>
* The set of RandomVariableAtoms is those persisted in the Database when {@link #mpeInference()}
* is called. This set must contain all RandomVariableAtoms the Model might access.
* ({@link DatabasePopulator} can help with this.)
*
* @author Matthias Broecheler
* @author Stephen Bach <bach@cs.umd.edu>
*/
public class ConfidenceAnalysis implements ModelApplication {
/**
* Prefix of property keys used by this class.
*
* @see ConfigManager
*/
public static final String CONFIG_PREFIX = "confidenceanalysis";
/**
* Positive integer key for the number of samples to collect for confidence
* analysis.
*/
public static final String NUM_SAMPLES_KEY = CONFIG_PREFIX + ".numsamples";
/** Default value for NUM_SAMPLES_KEY */
public static final int NUM_SAMPLES_DEFAULT = 1000;
/**
* Key for {@link Factory} or String property.
* <p>
* Should be set to a {@link ReasonerFactory} or the fully qualified
* name of one. Will be used to instantiate a {@link Reasoner}.
*/
public static final String REASONER_KEY = CONFIG_PREFIX + ".reasoner";
/**
* Default value for REASONER_KEY.
* <p>
* Value is instance of {@link ADMMReasonerFactory}.
*/
public static final ReasonerFactory REASONER_DEFAULT = new ADMMReasonerFactory();
private Model model;
private Database db;
private ConfigBundle config;
private final int numSamples;
public ConfidenceAnalysis(Model model, Database db, ConfigBundle config) {
this.model = model;
this.db = db;
this.config = config;
numSamples = config.getInt(NUM_SAMPLES_KEY, NUM_SAMPLES_DEFAULT);
if (numSamples <= 0)
throw new IllegalArgumentException("Number of samples must be positive.");
}
/**
* Infers the means and inverse standard deviations of the
* {@link RandomVariableAtom RandomVariableAtoms} persisted in a {@link Database},
* according to a {@link Model}, given the Database's {@link ObservedAtom ObservedAtoms},
* sets them as each Atom's truth values and confidence values, and commits
* them back to the Database.
* <p>
* The {@link RandomVariableAtom RandomVariableAtoms} to be inferred are those
* persisted in the Database when this method is called. All RandomVariableAtoms
* which the Model might access must be persisted in the Database.
*
* @return analysis results
* @see DatabasePopulator
*/
public FullConfidenceAnalysisResult runConfidenceAnalysis()
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Reasoner reasoner = ((ReasonerFactory) config.getFactory(REASONER_KEY, REASONER_DEFAULT)).getReasoner(config);
PersistedAtomManager atomManager = new PersistedAtomManager(db);
/* Builds the ground model */
Grounding.groundAll(model, atomManager, reasoner);
/* Starts in the MPE state */
reasoner.optimize();
/* Performs sampling */
MarginalSampler sampler = new MarginalSampler(numSamples);
sampler.sample(reasoner.getGroundKernels(), 1.0, 1);
/*
* Sets means and confidence scores and commits the RandomVariableAtoms
* back to the Database
*/
for (RandomVariableAtom atom : atomManager.getPersistedRVAtoms()) {
DoubleDist dist = sampler.getDistribution(atom.getVariable());
atom.setValue(dist.mean());
double conf = dist.stdDev();
conf = 1 / conf;
conf = Math.max(conf, ConfidenceValues.getMin());
conf = Math.min(conf, ConfidenceValues.getMax());
atom.setConfidenceValue(conf);
atom.commitToDB();
}
return new MemoryFullConfidenceAnalysisResult(sampler.getDistributions());
}
@Override
public void close() {
model=null;
db = null;
config = null;
}
}
|
JackSullivan/psl
|
psl-core/src/main/java/edu/umd/cs/psl/application/inference/ConfidenceAnalysis.java
|
Java
|
apache-2.0
| 5,512
|
package so.modernized.whip
import java.io._
import cc.factorie.app.chain.{LiteChainModelExample, SegmentEvaluation, ChainHelper}
import cc.factorie.app.nlp.load.LoadOntonotes5
import cc.factorie.app.nlp.{lexicon => lex, Document, Token}
import cc.factorie.app.nlp.lexicon.{LexiconsProvider, StaticLexicons}
import cc.factorie.app.nlp.ner._
import cc.factorie.la.{DenseTensor1, Tensor1}
import cc.factorie.optimize.{Trainer, ParameterAveraging, AdaGrad}
import cc.factorie.util._
import cc.factorie.variable._
import edu.umass.cs.iesl.entity_embeddings.EntityEmbeddingOpts
import edu.umass.cs.iesl.entity_embeddings.data_structures._
import edu.umass.cs.iesl.entity_embeddings.data_structures.data_stores.EmbeddingCollection
import scala.reflect.ClassTag
import scala.util.Random
/**
* @author johnsullivan
*/
abstract class EmbeddingChainNer[L <: NerTag](ld:CategoricalDomain[String] with SpanEncoding,
nl:(Token, String) => L,
ltt:L => Token,
modelIs:InputStream,
l:LexiconsProvider,
val embeddingColl:EmbeddingCollection)(implicit m:ClassTag[L])
extends ChainNer[L](ld, nl, ltt, modelIs, new StaticLexicons()(l))(m){
def lexiconMap(lp:LexiconsProvider) = {
Iterator(
lp.provide[lex.iesl.Month] -> "MONTH",
lp.provide[lex.iesl.Day] -> "DAY",
lp.provide[lex.iesl.PersonFirstHigh] -> "PERSON-FIRST-HIGH",
lp.provide[lex.iesl.PersonFirstHighest] -> "PERSON-FIRST-HIGHEST",
lp.provide[lex.iesl.PersonFirstMedium] -> "PERSON-FIRST-MEDIUM",
lp.provide[lex.iesl.PersonLastHigh] -> "PERSON-LAST-HIGH",
lp.provide[lex.iesl.PersonLastHighest] -> "PERSON-LAST-HIGHEST",
lp.provide[lex.iesl.PersonLastMedium] -> "PERSON-LAST-MEDIUM",
lp.provide[lex.iesl.PersonHonorific] -> "PERSON-HONORIFIC",
lp.provide[lex.iesl.Company] -> "COMPANY",
lp.provide[lex.iesl.JobTitle] -> "JOB-TITLE",
lp.provide[lex.iesl.OrgSuffix] -> "ORG-SUFFIX",
lp.provide[lex.iesl.Country] -> "COUNTRY",
lp.provide[lex.iesl.City] -> "CITY",
lp.provide[lex.iesl.PlaceSuffix] -> "PLACE-SUFFIX",
lp.provide[lex.iesl.UsState] -> "USSTATE",
lp.provide[lex.iesl.Continents] -> "CONTINENT",
lp.provide[lex.wikipedia.Person] -> "WIKI-PERSON",
lp.provide[lex.wikipedia.Event] -> "WIKI-EVENT",
lp.provide[lex.wikipedia.Location] -> "WIKI-LOCATION",
lp.provide[lex.wikipedia.Organization] -> "WIKI-ORG",
lp.provide[lex.wikipedia.ManMadeThing] -> "MANMADE",
lp.provide[lex.iesl.Demonym] -> "DEMONYM",
lp.provide[lex.wikipedia.Book] -> "WIKI-BOOK",
lp.provide[lex.wikipedia.Business] -> "WIKI-BUSINESS",
lp.provide[lex.wikipedia.Film] -> "WIKI-FILM"
).map{case (mp, n) => n -> EntitySlug(EnrichRedirectsAndVocab.fixName(mp.coordinates), English).normalizedSlug }.toMap
}
override def serialize(stream: OutputStream): Unit = {
import cc.factorie.util.CubbieConversions._
val is = new DataOutputStream(new BufferedOutputStream(stream))
BinarySerializer.serialize(ChainNERFeaturesDomain.dimensionDomain, is)
BinarySerializer.serialize(liteModel, is)
is.close()
}
override def deserialize(stream:InputStream): Unit = {
import cc.factorie.util.CubbieConversions._
val is = new DataInputStream(new BufferedInputStream(stream))
BinarySerializer.deserialize(ChainNERFeaturesDomain.dimensionDomain, is)
BinarySerializer.deserialize(liteModel, is)
is.close()
}
class ChainNerWithEmbeddingFeatures(val token:Token, val feats:ChainNERFeatures) extends TensorVar {
type Value = ImmutableConcatTensor1
val lexMap = lexiconMap(l)
lazy val embedding = {
(feats.activeCategories.flatMap(lexMap.get).map(embeddingColl.getEmbedding(_, Output, CoOccurringEntity)) ++
Seq(embeddingColl.getEmbedding(WordSlug(token.lemmaString, English).normalizedSlug, Output, CoOccurringEntity),
embeddingColl.getEmbedding(token.lemmaString, Output, CoOccurringEntity),
Some(new DenseTensor1(embeddingColl.outputDims))
)).flatten.reduce(_ + _)
}.asInstanceOf[Tensor1]
def value: Value = ImmutableConcatTensor1(feats.value, embedding)
}
val liteModel = new HybridChainModel[L](labelDomain, ChainNERFeaturesDomain.dimensionDomain, embeddingColl.outputDims, {label:L => label.token.attr[ChainNerWithEmbeddingFeatures].value.tuple})
override def addFeatures(document:Document, vf:Token => CategoricalVectorVar[String]): Unit = {
super.addFeatures(document, vf)
document.tokens foreach { t =>
t.attr += new ChainNerWithEmbeddingFeatures(t, t.attr[ChainNERFeatures])
}
}
override def process(document:Document) =
if(document.tokenCount > 0) {
if (!document.tokens.head.attr.contains(m.runtimeClass))
document.tokens.map(token => token.attr += newLabel(token, "O"))
if (!document.tokens.head.attr.contains(classOf[ChainNERFeatures])) {
document.tokens.map(token => {token.attr += new ChainNERFeatures(token)})
addFeatures(document, (t:Token)=>t.attr[ChainNERFeatures])
}
document.sentences.collect {
case sentence if sentence.nonEmpty =>
val vars = sentence.tokens.map(_.attr[L]).toSeq
val result = ChainHelper.viterbiFast(liteModel.potentials(sentence.tokens.map(_.attr[L]).toSeq))
vars.indices foreach (i => vars(i).set(result.mapValues(i))(null))
}
document
} else {
document
}
override def train(trainDocs: Seq[Document], testDocs: Seq[Document], rate: Double=0.18, delta: Double=0.066)(implicit random: scala.util.Random): Double = {
def labels(docs: Iterable[Document]): Iterable[L with LabeledMutableDiscreteVar] = {
docs.flatMap(doc => doc.tokens.map(_.attr[L with LabeledMutableDiscreteVar]))
}
println("initializing training features...")
(trainDocs ++ testDocs).foreach(_.tokens.map(token => token.attr += new ChainNERFeatures(token)))
trainDocs.foreach(addFeatures(_, (t:Token)=>t.attr[ChainNERFeatures]))
ChainNERFeaturesDomain.freeze()
println("initializing testing features...")
testDocs.foreach(addFeatures(_, (t:Token)=>t.attr[ChainNERFeatures]))
println(sampleOutputString(trainDocs.take(20).last.tokens.take(100)))
val trainLabels = labels(trainDocs).toIndexedSeq
val testLabels = labels(testDocs).toIndexedSeq
val labelDomain: CategoricalDomain[String] = trainLabels.head.domain.asInstanceOf[CategoricalDomain[String]]
(trainLabels ++ testLabels).foreach(_.setRandomly)
val examples = trainDocs.flatMap(_.sentences.filter(_.length > 1).map(sentence => new LiteChainModelExample[L](liteModel, sentence.tokens.map(_.attr[L with LabeledDiscreteVar]), y => y.value)))
val optimizer = new AdaGrad(rate=rate, delta=delta) with ParameterAveraging
def evaluate(){
val segmentEvaluation = new SegmentEvaluation[L with CategoricalLabeling[String]](
labelDomain.categories.filter(_.length > 2).map(_.substring(2)),
"(B|U)-", "(I|L)-"
)
trainDocs.foreach(doc => {
process(doc)
for (sentence <- doc.sentences) segmentEvaluation += sentence.tokens.map(_.attr[L with CategoricalLabeling[String]])
})
println(s"Train accuracy ${objective.accuracy(trainLabels)}")
println(segmentEvaluation)
if (testDocs.nonEmpty) {
val testSegmentEvaluation = new SegmentEvaluation[L with LabeledMutableCategoricalVar[String]](
labelDomain.categories.filter(_.length > 2).map(_.substring(2)),
"(B|U)-", "(I|L)-"
)
testDocs.foreach(doc => {
process(doc)
for (sentence <- doc.sentences) testSegmentEvaluation += sentence.tokens.map(_.attr[L with CategoricalLabeling[String]])
})
println(s"Test accuracy ${objective.accuracy(testLabels)}")
println(testSegmentEvaluation)
}
println(liteModel.parameters.tensors.map(t => t.toSeq.count(x => x == 0)).sum.toFloat/liteModel.parameters.tensors.map(_.length).sum +" sparsity")
}
println(s"training with ${examples.length} examples")
Trainer.onlineTrain(liteModel.parameters, examples, optimizer=optimizer, evaluate=evaluate, maxIterations = 5)
val finalEval = new SegmentEvaluation[L with LabeledMutableCategoricalVar[String]](labelDomain.categories.filter(_.length > 2).map(_.substring(2)), "(B|U)-", "(I|L)-")
val buf = new StringBuffer
buf.append(new LabeledDiscreteEvaluation(testDocs.flatMap(_.tokens.map(_.attr[L with LabeledMutableDiscreteVar]))))
for (doc <- testDocs; sentence <- doc.sentences) finalEval += sentence.tokens.map(_.attr[L with LabeledMutableCategoricalVar[String]])
println("final results:")
println(finalEval)
finalEval.f1
}
}
class OntonotesEmbeddingChainNer(mp:ModelProvider[OntonotesEmbeddingChainNer], lp:LexiconsProvider, embColl: EmbeddingCollection)
extends EmbeddingChainNer[BilouOntonotesNerTag](BilouOntonotesNerDomain, (t, s) => new BilouOntonotesNerTag(t, s), l => l.token, mp.provide, lp, embColl) {
def loadDocs(fn:String):Seq[Document] = LoadOntonotes5 fromFilename fn
}
object OntonotesEmbeddingNerTrainer extends HyperparameterMain {
def evaluateParameters(args: Array[String]): Double = {
val opts = new ChainNerOpts with EntityEmbeddingOpts
implicit val random = new Random(0)
opts parse args
val embColl = EmbeddingCollection fromCMDOptions opts
val ner = new OntonotesEmbeddingChainNer(ModelProvider.empty, opts.lexicons.value, embColl)
if (opts.brownClusFile.wasInvoked) {
println(s"Reading brown cluster file: ${opts.brownClusFile.value}")
for (line <- scala.io.Source.fromFile(opts.brownClusFile.value).getLines()) {
val splitLine = line.split("\t")
ner.clusters(splitLine(1)) = splitLine(0)
}
}
val trainPortionToTake = if(opts.trainPortion.wasInvoked) opts.trainPortion.value else 1.0
val testPortionToTake = if(opts.testPortion.wasInvoked) opts.testPortion.value else 1.0
val (trainDocsFull, testDocsFull) = if(opts.train.wasInvoked && opts.test.wasInvoked) {
opts.train.value.flatMap(f => ner.loadDocs(f.getAbsolutePath)).toSeq ->
opts.test.value.flatMap(f => ner.loadDocs(f.getAbsolutePath)).toSeq
} else if(opts.trainDir.wasInvoked && opts.testDir.wasInvoked) {
opts.trainDir.value.listFiles().flatMap(f => ner.loadDocs(f.getAbsolutePath)).toSeq ->
opts.testDir.value.listFiles().flatMap(f => ner.loadDocs(f.getAbsolutePath)).toSeq
} else {
throw new IllegalArgumentException("You must provide values for either --train and --test or --train-dir and --test-dir")
}
val trainDocs = trainDocsFull.take((trainDocsFull.length*trainPortionToTake).floor.toInt)
val testDocs = testDocsFull.take((testDocsFull.length*testPortionToTake).floor.toInt)
println(s"using training set: ${opts.train.value} ; test set: ${opts.test.value}")
println(s"$trainPortionToTake of training data; $testPortionToTake of test data:")
println(s"using ${trainDocs.length} / ${trainDocsFull.length} train docs, ${trainDocs.map(_.tokenCount).sum} tokens")
println(s"using ${testDocs.length} / ${testDocsFull.length} test docs, ${testDocs.map(_.tokenCount).sum} tokens")
val ret = ner.train(trainDocs, testDocs, opts.rate.value, opts.delta.value)
if (opts.serialize.value) {
println("serializing model to " + opts.saveModel.value)
ner.serialize(new FileOutputStream(opts.saveModel.value))
}
if(opts.targetAccuracy.wasInvoked) cc.factorie.assertMinimalAccuracy(ret,opts.targetAccuracy.value.toDouble)
ret
}
}
object OntonotesEmbeddingNerOptimizer {
val opts = new ChainNerOpts with EntityEmbeddingOpts
def main(args:Array[String]): Unit = {
opts parse args
opts.serialize.setValue(false)
import cc.factorie.util.LogUniformDoubleSampler
val rate = HyperParameter(opts.rate, new LogUniformDoubleSampler(1e-3, 1))
val delta = HyperParameter(opts.delta, new LogUniformDoubleSampler(0.01, 0.1))
val qs = new QSubExecutor(10, "cc.factorie.app.ner.OntonotesEmbeddingNerTrainer")
val optimizer = new HyperParameterSearcher(opts, Seq(rate, delta), qs.execute, 100, 90, 60)
val result = optimizer.optimize()
println("Got results: " + result.mkString(" "))
println("Best rate: " + opts.rate.value + " best delta: " + opts.delta.value)
println("Running best configuration...")
opts.serialize.setValue(true)
import scala.concurrent.Await
import scala.concurrent.duration._
Await.result(qs.execute(opts.values.flatMap(_.unParse).toArray), 1.hours)
println("Done.")
}
}
|
JackSullivan/whip
|
src/main/scala/so/modernized/whip/EmbeddingChainNer.scala
|
Scala
|
apache-2.0
| 12,849
|
/*
* Copyright 2000-2015 JetBrains s.r.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 org.jetbrains.plugins.gradle.execution.test.runner;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.actions.JavaRerunFailedTestsAction;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.testframework.TestTreeView;
import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil;
import com.intellij.execution.testframework.sm.runner.SMTestProxy;
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo;
import com.intellij.execution.testframework.sm.runner.ui.SMRootTestProxyFormatter;
import com.intellij.execution.testframework.sm.runner.ui.TestTreeRenderer;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.externalSystem.execution.ExternalSystemExecutionConsoleManager;
import com.intellij.openapi.externalSystem.model.DataNode;
import com.intellij.openapi.externalSystem.model.ExternalProjectInfo;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTask;
import com.intellij.openapi.externalSystem.model.task.TaskData;
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration;
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemExecuteTaskTask;
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.gradle.action.GradleRerunFailedTestsAction;
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil;
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames;
import org.jetbrains.plugins.gradle.util.GradleBundle;
import org.jetbrains.plugins.gradle.util.GradleConstants;
import java.io.File;
/**
* @author Vladislav.Soroka
* @since 2/18/14
*/
public class GradleTestsExecutionConsoleManager
implements ExternalSystemExecutionConsoleManager<ExternalSystemRunConfiguration, GradleTestsExecutionConsole, ProcessHandler> {
@NotNull
@Override
public ProjectSystemId getExternalSystemId() {
return GradleConstants.SYSTEM_ID;
}
@NotNull
@Override
public GradleTestsExecutionConsole attachExecutionConsole(@NotNull final ExternalSystemTask task,
@NotNull final Project project,
@NotNull final ExternalSystemRunConfiguration configuration,
@NotNull final Executor executor,
@NotNull final ExecutionEnvironment env,
@NotNull final ProcessHandler processHandler) {
final GradleConsoleProperties consoleProperties = new GradleConsoleProperties(configuration, executor);
String testFrameworkName = configuration.getSettings().getExternalSystemId().getReadableName();
String splitterPropertyName = SMTestRunnerConnectionUtil.getSplitterPropertyName(testFrameworkName);
final GradleTestsExecutionConsole consoleView = new GradleTestsExecutionConsole(consoleProperties, splitterPropertyName);
SMTestRunnerConnectionUtil.initConsoleView(consoleView, testFrameworkName);
final TestTreeView testTreeView = consoleView.getResultsViewer().getTreeView();
if (testTreeView != null) {
TestTreeRenderer originalRenderer = ObjectUtils.tryCast(testTreeView.getCellRenderer(), TestTreeRenderer.class);
if (originalRenderer != null) {
originalRenderer.setAdditionalRootFormatter(new SMRootTestProxyFormatter() {
@Override
public void format(@NotNull SMTestProxy.SMRootTestProxy testProxy, @NotNull TestTreeRenderer renderer) {
final TestStateInfo.Magnitude magnitude = testProxy.getMagnitudeInfo();
if (magnitude == TestStateInfo.Magnitude.RUNNING_INDEX) {
renderer.clear();
renderer.append(GradleBundle.message(
"gradle.test.runner.ui.tests.tree.presentation.labels.waiting.tests"),
SimpleTextAttributes.REGULAR_ATTRIBUTES
);
}
else if (!testProxy.isInProgress() && testProxy.isEmptySuite()) {
renderer.clear();
renderer.append(GradleBundle.message(
"gradle.test.runner.ui.tests.tree.presentation.labels.no.tests.were.found"),
SimpleTextAttributes.REGULAR_ATTRIBUTES
);
}
}
});
}
}
if (task instanceof ExternalSystemExecuteTaskTask) {
final ExternalSystemExecuteTaskTask executeTask = (ExternalSystemExecuteTaskTask)task;
if (executeTask.getArguments() == null || !StringUtil.contains(executeTask.getArguments(), "--tests")) {
executeTask.appendArguments("--tests *");
}
}
return consoleView;
}
@Override
public void onOutput(@NotNull GradleTestsExecutionConsole executionConsole,
@NotNull ProcessHandler processHandler,
@NotNull String text,
@NotNull Key processOutputType) {
GradleTestsExecutionConsoleOutputProcessor.onOutput(executionConsole, text, processOutputType);
}
@Override
public boolean isApplicableFor(@NotNull ExternalSystemTask task) {
if (task instanceof ExternalSystemExecuteTaskTask) {
final ExternalSystemExecuteTaskTask taskTask = (ExternalSystemExecuteTaskTask)task;
if (!StringUtil.equals(taskTask.getExternalSystemId().getId(), GradleConstants.SYSTEM_ID.getId())) return false;
return ContainerUtil.find(taskTask.getTasksToExecute(), taskToExecute -> {
String projectPath = taskTask.getExternalProjectPath();
File file = new File(projectPath);
if (file.isFile()) {
projectPath = StringUtil.trimEnd(projectPath, "/" + file.getName());
}
final ExternalProjectInfo externalProjectInfo =
ExternalSystemUtil.getExternalProjectInfo(taskTask.getIdeProject(), getExternalSystemId(), projectPath);
if (externalProjectInfo == null) return false;
final DataNode<TaskData> taskDataNode = GradleProjectResolverUtil.findTask(
externalProjectInfo.getExternalProjectStructure(), projectPath, taskToExecute);
return taskDataNode != null &&
(("check".equals(taskDataNode.getData().getName()) && "verification".equals(taskDataNode.getData().getGroup())
|| GradleCommonClassNames.GRADLE_API_TASKS_TESTING_TEST.equals(taskDataNode.getData().getType())));
}) != null;
}
return false;
}
@Override
public AnAction[] getRestartActions(@NotNull final GradleTestsExecutionConsole consoleView) {
JavaRerunFailedTestsAction rerunFailedTestsAction =
new GradleRerunFailedTestsAction(consoleView);
rerunFailedTestsAction.setModelProvider(() -> consoleView.getResultsViewer());
return new AnAction[]{rerunFailedTestsAction};
}
}
|
vvv1559/intellij-community
|
plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestsExecutionConsoleManager.java
|
Java
|
apache-2.0
| 8,044
|
package cn.jsprun.domain;
public class Rsscaches implements java.io.Serializable {
private static final long serialVersionUID = -6652621749680662070L;
private RsscachesId id;
public Rsscaches() {
}
public Rsscaches(RsscachesId id) {
this.id = id;
}
public RsscachesId getId() {
return this.id;
}
public void setId(RsscachesId id) {
this.id = id;
}
}
|
TinghuanWang/source
|
src/cn/jsprun/domain/Rsscaches.java
|
Java
|
apache-2.0
| 412
|
package org.roaringbitmap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
import static java.util.Arrays.copyOfRange;
@RunWith(Parameterized.class)
public class ContainerBatchIteratorTest {
@Parameterized.Parameters
public static Object[][] params() {
return new Object[][] {
{IntStream.range(0, 20000).toArray()},
{IntStream.range(0, 1 << 16).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> i < 500 || i > 2000).filter(i -> i < (1 << 15) || i > ((1 << 15) | (1 << 8))).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 12) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 11) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 10) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 9) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 8) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 7) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 6) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 5) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 4) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 3) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 2) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> ((i >>> 1) & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> (i & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> (i & 1) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> (i % 3) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> (i % 5) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> (i % 7) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> (i % 9) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> (i % 271) == 0).toArray()},
{IntStream.range(0, 1 << 16).filter(i -> (i % 1000) == 0).toArray()},
{IntStream.empty().toArray()},
{SeededTestData.sparseRegion().toArray()},
{SeededTestData.denseRegion().toArray()},
{SeededTestData.rleRegion().toArray()}
};
}
private final int[] expectedValues;
public ContainerBatchIteratorTest(int[] expectedValues) {
this.expectedValues = expectedValues;
}
@Test
public void shouldRecoverValues512() {
test(512);
}
@Test
public void shouldRecoverValues1024() {
test(1024);
}
@Test
public void shouldRecoverValues2048() {
test(2048);
}
@Test
public void shouldRecoverValues4096() {
test(4096);
}
@Test
public void shouldRecoverValues8192() {
test(8192);
}
@Test
public void shouldRecoverValues65536() {
test(65536);
}
@Test
public void shouldRecoverValuesRandomBatchSizes() {
IntStream.range(0, 100)
.forEach(i -> test(ThreadLocalRandom.current().nextInt(1, 65536)));
}
private void test(int batchSize) {
int[] buffer = new int[batchSize];
Container container = createContainer();
ContainerBatchIterator it = container.getBatchIterator();
int cardinality = 0;
while (it.hasNext()) {
int from = cardinality;
cardinality += it.next(0, buffer);
Assert.assertArrayEquals("Failure with batch size " + batchSize,
copyOfRange(expectedValues, from, cardinality), copyOfRange(buffer, 0, cardinality - from));
}
Assert.assertEquals(expectedValues.length, cardinality);
}
private Container createContainer() {
Container container = new ArrayContainer();
for (int value : expectedValues) {
container = container.add((short) value);
}
return container.runOptimize();
}
}
|
lemire/RoaringBitmap
|
RoaringBitmap/src/test/java/org/roaringbitmap/ContainerBatchIteratorTest.java
|
Java
|
apache-2.0
| 4,409
|
--[[
Copyright 2015 The Luvit 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.
--]]
local readline = require('readline')
local prettyPrint = require('pretty-print')
local Editor = readline.Editor
require('tap')(function(test)
test('readline Editor:onKey', function(expect)
-- If stdin is not a TTY, we can't run these tests.
if not prettyPrint.stdin.set_mode then return end
local editor = Editor.new({
stdin = prettyPrint.stdin,
stdout = prettyPrint.stdout
})
-- need to call readLine to initialize some variables
editor:readLine("", function() end)
-- but don't want to actually read anything
editor.stdin:read_stop()
editor.stdin:set_mode(0)
-- starting position
assert(#editor.line == 0)
assert(editor.position == 1)
-- single key
editor:onKey('a')
assert(editor.line == "a")
assert(editor.position == 2)
-- left arrow
editor:onKey('\027[D')
assert(editor.line == "a")
assert(editor.position == 1)
-- multiple keys
editor:onKey('abc')
assert(editor.line == "abca")
assert(editor.position == 4)
-- multiple control sequences (left arrows)
editor:onKey('\027[D\027[D\027[D')
assert(editor.line == "abca")
assert(editor.position == 1)
-- mixture of characters and control sequences
editor:onKey('a\027[Db\027[Dc\027[Dd')
assert(editor.line == "dcbaabca")
assert(editor.position == 2)
end)
end)
|
squeek502/luvit
|
tests/test-readline.lua
|
Lua
|
apache-2.0
| 1,958
|
/*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Replacements for frequently missing libm functions
*/
#ifndef AVUTIL_LIBM_H
#define AVUTIL_LIBM_H
#include <math.h>
#include "config.h"
#include "attributes.h"
#if !HAVE_EXP2
#undef exp2
#define exp2(x) exp((x) * 0.693147180559945)
#endif /* HAVE_EXP2 */
#if !HAVE_EXP2F
#undef exp2f
#define exp2f(x) ((float)exp2(x))
#endif /* HAVE_EXP2F */
#if !HAVE_LLRINT
#undef llrint
#define llrint(x) ((long long)rint(x))
#endif /* HAVE_LLRINT */
#if !HAVE_LLRINTF
#undef llrintf
#define llrintf(x) ((long long)rint(x))
#endif /* HAVE_LLRINT */
#if !HAVE_LOG2
#undef log2
#define log2(x) (log(x) * 1.44269504088896340736)
#endif /* HAVE_LOG2 */
#if !HAVE_LOG2F
#undef log2f
#define log2f(x) ((float)log2(x))
#endif /* HAVE_LOG2F */
#if !HAVE_LRINT
av_always_inline av_const long int lrint(double x)
{
return rint(x);
}
#endif /* HAVE_LRINT */
#if !HAVE_LRINTF
av_always_inline av_const long int lrintf(float x)
{
return (int)(rint(x));
}
#endif /* HAVE_LRINTF */
#if !HAVE_ROUND
av_always_inline av_const double round(double x)
{
return (x > 0) ? floor(x + 0.5) : ceil(x - 0.5);
}
#endif /* HAVE_ROUND */
#if !HAVE_ROUNDF
av_always_inline av_const float roundf(float x)
{
return (x > 0) ? floor(x + 0.5) : ceil(x - 0.5);
}
#endif /* HAVE_ROUNDF */
#if !HAVE_TRUNCF
av_always_inline av_const float truncf(float x)
{
return (x > 0) ? floor(x) : ceil(x);
}
#endif /* HAVE_TRUNCF */
#endif /* AVUTIL_LIBM_H */
|
dariorapisardi/flipdroid
|
jni/ffmpeg/libavutil/libm.h
|
C
|
apache-2.0
| 2,211
|
#!/usr/bin/env python3
import logging
from src import util
from src import etherscan
from src import messages
from crypto.prices import *
logger = logging.getLogger("node")
######
# Telegram command handler for adding nodes for the user who fired the command.
#
# Command: /node :address0;name0 ... :addressN;nameN
#
# Command parameter: :address0 - Address of the first node to add
# :name0 - Name of the first node
# :addressN - Address of the last node to add
# :nameN - Name of the last node
#
# Gets only called by the telegram bot api
######
def nodeAdd(bot, update, args):
response = "*Add*\n\n"
chatId = update.message.chat_id
logger.warning("add - args " + " ".join(args))
logger.warning("add - user: {}".format(update.message.from_user.id))
pool = bot.database.getPoolById(chatId)
if pool == None:
bot.create(bot,update,[])
if len(args) == 0:
response += ("Arguments required: address_0;name_0 ... address_n;name_n\n\n"
"Example: /add 0xFf2ED74286a5686Bc4F4896761718DE031680000;Node1 0xFf2ED74286a5686Bc4F4896761718DE031681111;Node2\n")
valid = False
else:
for arg in args:
valid = True
newNode = arg.split(";")
if len(newNode) != 2:
response += messages.invalidParameterError.format(arg)
valid = False
else:
if not util.validateTntAddress( newNode[0] ):
response += messages.invalidTntAddressError.format(newNode[0])
valid = False
if not util.validateName( newNode[1] ):
response += messages.invalidNameError.format(newNode[1])
valid = False
if valid:
address = newNode[0]
name = newNode[1]
if bot.database.addNode(update.message.chat_id, address, name, update.message.from_user.id,update.message.from_user.username):
response += "Added node {}!\n".format(address)
else:
response += messages.nodeExistsError.format(address)
bot.sendMessage(update.message.chat_id, response )
######
# Telegram command handler for updating nodes for the user who fired the command.
#
# Command: /add :address :newname
#
# Command parameter: :address - Address of the node to update
# :newname - New name for the node
#
# Gets only called by the telegram bot api
######
def nodeUpdate(bot, update, args):
response = "*Update*\n\n"
chatId = update.message.chat_id
logger.warning("update - args " + " ".join(args))
logger.warning("update - user: {}".format(update.message.from_user.id))
pool = bot.database.getPoolById(chatId)
user = bot.database.getUser(chatId, update.message.from_user.id)
if pool == None:
response+= messages.noPoolError
elif user == None:
response += messages.notActiveInPoolError
elif len(args) != 2:
response += ("Exactly 2 arguments required: :address :newname\n"
"Where :address is the address of the node to update and :newname the"
"new name of the node.\n\n"
"Example: /update 0xFf2ED74286a5686Bc4F4896761718DE031680000 MyNewNodeName\n")
else:
valid = True
if not util.validateTntAddress( args[0] ):
response += messages.invalidTntAddressError.format(args[0])
valid = False
elif not util.validateName( args[1] ):
response += messages.invalidNameError.format(args[1])
valid = False
if valid:
address = args[0]
name = args[1]
logger.info("update - {} {}".format(address, user['id']))
if bot.database.getNode(address, user['id']) == None:
response += messages.nodeNotExistsError.format(address)
else:
bot.database.updateNode(address,user['id'], name)
response += "Node successfully updated. {}\n".format(address)
bot.sendMessage(chatId, response )
######
# Telegram command handler for removing nodes for the user who fired the command.
#
# Command: /remove :address
#
# Command parameter: :address - Address of the node to remove
#
#
# Gets only called by the telegram bot api
######
def nodeRemove(bot, update, args):
response = "*Remove*\n\n"
chatId = update.message.chat_id
logger.warning("remove - " + " ".join(args))
logger.warning("remove - user: {}".format(update.message.from_user.id))
pool = bot.database.getPoolById(chatId)
user = bot.database.getUser(chatId, update.message.from_user.id)
if pool == None:
response+= messages.noPoolError
elif user == None:
response += messages.notActiveInPoolError
elif len(args) != 1:
response += ("Argument required: :address\n\n"
"Example: /remove 0xFf2ED74286a5686Bc4F4896761718DE031680000\n")
else:
address = args[0]
if not util.validateTntAddress( address ):
response += "ERROR: Invalid TNT-Address: {}\n".format(address)
else:
logger.info("remove - valid {}".format(address, ))
if bot.database.getNode(address, user['id']) == None:
response += "ERROR: Node {} does not exist!\n".format(address)
else:
bot.database.deleteNode(address,user['id'])
response += "Node {} successfully deleted.\n".format(address)
bot.sendMessage(chatId, response )
######
# Telegram command handler for reading the amounts of each node of the users
# in the pool
#
# Command: /nodes
#
# Gets only called by the telegram bot api
######
def nodes(bot, update):
response = ""
chatId = update.message.chat_id
nodesFound = False
pool = bot.database.getPoolById(chatId)
logger.warning("nodes - {}".format(chatId))
if pool == None:
response = "*Nodes*\n\n"
response += ("You need to create a pool with nodes first. "
"Type /help to show the list of commands.")
else:
tntPrice = liqui(Cryptos.TNT)
addresses = []
for user in bot.database.getUsers(pool['id']):
nodes = bot.database.getNodes(user['id'])
if len(nodes) == 0:
continue
for node in nodes:
addresses.append(node["address"])
amounts = etherscan.getTNTAmount(addresses, pool['api_key'])
for user in bot.database.getUsers(pool['id']):
nodes = bot.database.getNodes(user['id'])
if len(nodes) == 0:
continue
nodesFound = True
response += "*" + user['name'] + "*\n"
total = 0
for node in nodes:
tnt = amounts[node["address"]]
if tnt == -1:
response += node['name'] + " -> Sorry, there was an error.\n".format(tnt)
else:
total += int(tnt)
response += node['name'] + " -> {} TNT\n".format(tnt)
if tntPrice != None:
response += '\n*Total:\n TNT: {}\n USD: {}*\n\n'.format(total,int(total*tntPrice.usd))
else:
response += '\n*Total TNT: {}*\n\n'.format(total)
response += "\n\n"
if not nodesFound and pool:
response = "*Nodes*\n\n"
response += ("There are currently no nodes in this pool. You can create "
"nodes with /add.")
bot.sendMessage(chatId, response )
######
# Telegram command handler for reading the total amounts of all nodes of the users
# in the pool
#
# Command: /total
#
# Gets only called by the telegram bot api
######
def total(bot, update):
response = ""
chatId = update.message.chat_id
nodesFound = False
pool = bot.database.getPoolById(chatId)
logger.warning("total - {}".format(chatId))
if pool == None:
response = "*Total*\n\n"
response += ("You need to create a pool with nodes first. "
"Type /help to show the list of commands.")
else:
tntPrice = liqui(Cryptos.TNT)
addresses = []
for user in bot.database.getUsers(pool['id']):
nodes = bot.database.getNodes(user['id'])
if len(nodes) == 0:
continue
for node in nodes:
addresses.append(node["address"])
amounts = etherscan.getTNTAmount(addresses, pool['api_key'])
for user in bot.database.getUsers(chatId):
nodes = bot.database.getNodes(user['id'])
total = 0
if len(nodes) == 0:
continue
nodesFound = True
for node in bot.database.getNodes(user['id']):
total += amounts[node['address']]
if tntPrice != None:
response += '{} -> {} TNT | {} USD\n'.format(user['name'],total,int(total * tntPrice.usd))
else:
response += '{} -> {} TNT\n'.format(user['name'],total,int(total))
if not nodesFound:
response = "*Total*\n\n"
response += ("There are currently no nodes in this pool. You can create "
"nodes with /add.")
bot.sendMessage(chatId, response )
######
# Telegram command handler for reading the addresses of all nodes of the users
# in the pool
#
# Command: /addresses
#
# Gets only called by the telegram bot api
######
def addresses(bot, update):
response = ""
chatId = update.message.chat_id
nodesFound = False
pool = bot.database.getPoolById(chatId)
logger.warning("addresses - {}".format(chatId))
if pool == None:
response = "*Addresses*\n\n"
response += ("You need to create a pool with nodes first. "
"Type /help to show the list of commands.")
else:
for user in bot.database.getUsers(pool['id']):
nodes = bot.database.getNodes(user['id'])
if len(nodes) == 0:
continue
response += "*" + user['name'] + "*\n"
nodesFound = True
for node in nodes:
response += node['name'] + " -> " + node['address'] + "\n"
response += "\n\n"
if not nodesFound:
response = "*Addresses*\n\n"
response += ("There are currently no nodes in this pool. You can create "
"nodes with /add.")
bot.sendMessage(update.message.chat_id, response )
|
kevinrombach/TNTNodeMonitorBot
|
src/commandhandler/node.py
|
Python
|
apache-2.0
| 10,737
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""Tests for metadata utils."""
import os
import tensorflow.compat.v1 as tf
from explainable_ai_sdk.metadata.tf.v1 import utils
class UtilsTest(tf.test.TestCase):
def test_save_graph_model_explicit_session(self):
sess = tf.Session(graph=tf.Graph())
with sess.graph.as_default():
x = tf.placeholder(shape=[None, 10], dtype=tf.float32, name='inp')
weights = tf.constant(1., shape=(10, 2), name='weights')
model_path = os.path.join(tf.test.get_temp_dir(), 'explicit')
utils.save_graph_model(sess, model_path, {'x': x}, {'w': weights}, {'tag'})
self.assertTrue(os.path.isfile(os.path.join(model_path, 'saved_model.pb')))
tf.reset_default_graph()
loading_session = tf.Session(graph=tf.Graph())
with loading_session.graph.as_default():
tf.saved_model.loader.load(loading_session, ['tag'], model_path)
self.assertIn(x.op.name,
[n.name for n in loading_session.graph.as_graph_def().node])
self.assertIn(weights.op.name,
[n.name for n in loading_session.graph.as_graph_def().node])
def test_save_graph_model_default_session(self):
x = tf.placeholder(shape=[None, 10], dtype=tf.float32, name='inp')
weights = tf.constant(1., shape=(10, 2), name='weights')
model_path = os.path.join(tf.test.get_temp_dir(), 'default')
utils.save_graph_model(
tf.Session(), model_path, {'x': x}, {'w': weights}, {'tag'})
self.assertTrue(os.path.isfile(os.path.join(model_path, 'saved_model.pb')))
def test_save_graph_model_kwargs(self):
x = tf.placeholder(shape=[None, 10], dtype=tf.float32, name='inp')
weights = tf.constant(1., shape=(10, 2), name='weights')
model_path = os.path.join(tf.test.get_temp_dir(), 'kwargs')
utils.save_graph_model(
tf.Session(),
model_path, {'x': x}, {'w': weights}, {'tag'},
main_op=tf.tables_initializer(),
strip_default_attrs=False)
self.assertTrue(os.path.isfile(os.path.join(model_path, 'saved_model.pb')))
if __name__ == '__main__':
tf.test.main()
|
GoogleCloudPlatform/explainable_ai_sdk
|
explainable_ai_sdk/metadata/tf/v1/utils_test.py
|
Python
|
apache-2.0
| 2,629
|
#!/home/mjwtom/install/python/bin/python
# -*- coding: utf-8 -*-
import os
import subprocess
from nodes import storage_nodes as ips
def generate_rings():
print (os.environ["PATH"])
os.environ["PATH"] = '/home/mjwtom/install/python/bin' + ":" + os.environ["PATH"]
print (os.environ["PATH"])
dev = 'sdb1'
ETC_SWIFT='/etc/swift'
if not os.path.exists(ETC_SWIFT):
os.makedirs(ETC_SWIFT)
if os.path.exists(ETC_SWIFT+'/backups'):
cmd = ['rm',
'-rf',
'%s/backups' % ETC_SWIFT]
subprocess.call(cmd)
print 'current work path:%s' % os.getcwd()
os.chdir(ETC_SWIFT)
print 'change work path to:%s' % os.getcwd()
files = os.listdir(ETC_SWIFT)
for file in files:
path = ETC_SWIFT + '/' + file
if os.path.isdir(path):
continue
shotname, extentsion = os.path.splitext(file)
if (extentsion == '.builder') or (extentsion == '.gz'):
try:
os.remove(path)
except Exception as e:
print e
for builder, port in [('object.builder', 6000),
('object-1.builder', 6000),
('object-2.builder', 6000),
('container.builder', 6001),
('account.builder', 6002)]:
cmd = ['swift-ring-builder',
'%s' % builder,
'create',
'10',
'3',
'1']
subprocess.call(cmd)
i = 1
for ip in ips:
cmd = ['swift-ring-builder',
'%s' % builder,
'add',
'r%dz%d-%s:%d/%s' % (i, i, ip, port, dev),
'1']
subprocess.call(cmd)
i += 1
cmd = ['swift-ring-builder',
'%s' % builder,
'rebalance']
subprocess.call(cmd)
if __name__ == '__main__':
generate_rings()
|
mjwtom/swift
|
test/dedupe/bin/remakerings.py
|
Python
|
apache-2.0
| 1,973
|
#include "device/device.h"
#include "wrappers/channels/jni_mems_channel_wrap.h"
#include "saturation_cast.h"
#include "wrappers/channels/jni_channel_factory.h"
#include "wrappers/device/jni_device_wrap.h"
extern "C"
{
JNIEXPORT jlong JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_create(JNIEnv *env, jclass type,
jobject device) {
return createChannelFromDevice<JniMEMSChannelWrap>(env, device);
}
JNIEXPORT jobject
JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_info(JNIEnv *env, jobject instance) {
auto &memsChannelWrap = *extract_pointer<JniMEMSChannelWrap>(env, instance);
auto channelInfo = &memsChannelWrap->info();
return jni::java_object<decltype(channelInfo)>(channelInfo);
}
JNIEXPORT void
JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_init(JNIEnv *env, jobject instance) {
auto memsChannelWrap = extract_pointer<JniMEMSChannelWrap>(env, instance);
memsChannelWrap->subscribeLengthChanged(
find_notifier<decltype(memsChannelWrap)>(instance, "dataLengthChanged"));
}
JNIEXPORT void JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_deleteNative(JNIEnv *env, jobject instance) {
deleteNativeObject<JniMEMSChannelWrap>(env, instance);
}
JNIEXPORT jobject JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_underlyingDevice(JNIEnv *env, jobject instance) {
auto &memsChannelWrap = *extract_pointer<JniMEMSChannelWrap>(env, instance);
auto devicePtr = memsChannelWrap->underlyingDevice().lock();
if (!devicePtr){
return nullptr;
}
auto deviceWrap = new JniDeviceWrap(devicePtr);
return jni::java_object<decltype(deviceWrap)>(deviceWrap);
}
JNIEXPORT jfloat JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_samplingFrequency(JNIEnv *env,
jobject instance) {
auto &memsChannelWrap = *extract_pointer<JniMEMSChannelWrap>(env, instance);
return memsChannelWrap->samplingFrequency();
}
JNIEXPORT jlong JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_bufferSize(JNIEnv *env, jobject instance) {
auto &memsChannelWrap = *extract_pointer<JniMEMSChannelWrap>(env, instance);
return saturation_cast<jlong>(memsChannelWrap->bufferSize());
}
JNIEXPORT jlong JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_totalLength(JNIEnv *env, jobject instance) {
auto &memsChannelWrap = *extract_pointer<JniMEMSChannelWrap>(env, instance);
return saturation_cast<jlong>(memsChannelWrap->totalLength());
}
JNIEXPORT jobjectArray JNICALL
Java_com_neuromd_neurosdk_channels_MEMSChannel_readData(JNIEnv *env, jobject instance,
jlong offset, jlong length) {
try {
auto &memsChannelWrap = *extract_pointer<JniMEMSChannelWrap>(env, instance);
auto data = memsChannelWrap->readData(saturation_cast<Neuro::data_offset_t>(offset),
saturation_cast<Neuro::data_length_t>(length));
return jni::to_obj_array(env, data);
}
catch (std::exception &e){
jni::java_throw(env, "UnsupportedOperationException", e);
return nullptr;
}
}
}
void JniMEMSChannelWrap::subscribeLengthChanged(jobject stateChangedSubscriberRef) {
lengthChangedGlobalSubscriberRef = jni::make_global_ref_ptr(stateChangedSubscriberRef);
std::weak_ptr<jni::jobject_t> weakReference = lengthChangedGlobalSubscriberRef;
mListener = this->object->subscribeLengthChanged([weakReference](auto length){
jni::call_in_attached_thread([&weakReference, &length](auto env){
sendNotification<long>(env, weakReference, length);
});
});
}
template<>
template<>
jni::java_object<Neuro::MEMS>::java_object(const Neuro::MEMS &mems):
nativeObj(mems){
jni::call_in_attached_thread([=](JNIEnv* env){
auto objectClassConstructor = env->GetMethodID(object_class, "<init>",
constructor_signature<Neuro::MEMS>());
javaObj = make_global_ref_ptr(
env->NewObject(object_class,
objectClassConstructor,
mems.accelerometer.X,
mems.accelerometer.Y,
mems.accelerometer.Z,
mems.gyroscope.X,
mems.gyroscope.Y,
mems.gyroscope.Z));
});
}
|
NeurotechMRC/neuro-sdk
|
wrappers/android/android-neurosdk/src/main/cpp/wrappers/channels/jni_mems_channel_wrap.cpp
|
C++
|
apache-2.0
| 4,549
|
// Copyright 2006-2008 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/checks.h"
#if V8_LIBC_GLIBC || V8_OS_BSD
# include <cxxabi.h>
# include <execinfo.h>
#elif V8_OS_QNX
# include <backtrace.h>
#endif // V8_LIBC_GLIBC || V8_OS_BSD
#include <stdio.h>
#include "src/platform.h"
#include "src/v8.h"
namespace v8 {
namespace internal {
intptr_t HeapObjectTagMask() { return kHeapObjectTagMask; }
// Attempts to dump a backtrace (if supported).
void DumpBacktrace() {
#if V8_LIBC_GLIBC || V8_OS_BSD
void* trace[100];
int size = backtrace(trace, ARRAY_SIZE(trace));
char** symbols = backtrace_symbols(trace, size);
OS::PrintError("\n==== C stack trace ===============================\n\n");
if (size == 0) {
OS::PrintError("(empty)\n");
} else if (symbols == NULL) {
OS::PrintError("(no symbols)\n");
} else {
for (int i = 1; i < size; ++i) {
OS::PrintError("%2d: ", i);
char mangled[201];
if (sscanf(symbols[i], "%*[^(]%*[(]%200[^)+]", mangled) == 1) { // NOLINT
int status;
size_t length;
char* demangled = abi::__cxa_demangle(mangled, NULL, &length, &status);
OS::PrintError("%s\n", demangled != NULL ? demangled : mangled);
free(demangled);
} else {
OS::PrintError("??\n");
}
}
}
free(symbols);
#elif V8_OS_QNX
char out[1024];
bt_accessor_t acc;
bt_memmap_t memmap;
bt_init_accessor(&acc, BT_SELF);
bt_load_memmap(&acc, &memmap);
bt_sprn_memmap(&memmap, out, sizeof(out));
OS::PrintError(out);
bt_addr_t trace[100];
int size = bt_get_backtrace(&acc, trace, ARRAY_SIZE(trace));
OS::PrintError("\n==== C stack trace ===============================\n\n");
if (size == 0) {
OS::PrintError("(empty)\n");
} else {
bt_sprnf_addrs(&memmap, trace, size, const_cast<char*>("%a\n"),
out, sizeof(out), NULL);
OS::PrintError(out);
}
bt_unload_memmap(&memmap);
bt_release_accessor(&acc);
#endif // V8_LIBC_GLIBC || V8_OS_BSD
}
} } // namespace v8::internal
// Contains protection against recursive calls (faults while handling faults).
extern "C" void V8_Fatal(const char* file, int line, const char* format, ...) {
fflush(stdout);
fflush(stderr);
i::OS::PrintError("\n\n#\n# Fatal error in %s, line %d\n# ", file, line);
va_list arguments;
va_start(arguments, format);
i::OS::VPrintError(format, arguments);
va_end(arguments);
i::OS::PrintError("\n#\n");
v8::internal::DumpBacktrace();
fflush(stderr);
i::OS::Abort();
}
void CheckEqualsHelper(const char* file,
int line,
const char* expected_source,
v8::Handle<v8::Value> expected,
const char* value_source,
v8::Handle<v8::Value> value) {
if (!expected->Equals(value)) {
v8::String::Utf8Value value_str(value);
v8::String::Utf8Value expected_str(expected);
V8_Fatal(file, line,
"CHECK_EQ(%s, %s) failed\n# Expected: %s\n# Found: %s",
expected_source, value_source, *expected_str, *value_str);
}
}
void CheckNonEqualsHelper(const char* file,
int line,
const char* unexpected_source,
v8::Handle<v8::Value> unexpected,
const char* value_source,
v8::Handle<v8::Value> value) {
if (unexpected->Equals(value)) {
v8::String::Utf8Value value_str(value);
V8_Fatal(file, line, "CHECK_NE(%s, %s) failed\n# Value: %s",
unexpected_source, value_source, *value_str);
}
}
|
nextsmsversion/macchina.io
|
platform/JS/V8/v8-3.28.4/src/checks.cc
|
C++
|
apache-2.0
| 3,739
|
package com.verity.domain;
/**
* Created by Youjm on 2016/8/20.
*/
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MailAuthenticator extends Authenticator {
private String username;
private String password;
public MailAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
|
916742994/fts
|
verity/src/main/java/com/verity/domain/MailAuthenticator.java
|
Java
|
apache-2.0
| 865
|
webview-browser
===============
A basic implementation of a WebView based browser - intended for debugging purposes only.
|
gauntface/webview-browser
|
README.md
|
Markdown
|
apache-2.0
| 123
|
/*
* 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.translate.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.translate.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GetParallelDataResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetParallelDataResultJsonUnmarshaller implements Unmarshaller<GetParallelDataResult, JsonUnmarshallerContext> {
public GetParallelDataResult unmarshall(JsonUnmarshallerContext context) throws Exception {
GetParallelDataResult getParallelDataResult = new GetParallelDataResult();
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 getParallelDataResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("ParallelDataProperties", targetDepth)) {
context.nextToken();
getParallelDataResult.setParallelDataProperties(ParallelDataPropertiesJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("DataLocation", targetDepth)) {
context.nextToken();
getParallelDataResult.setDataLocation(ParallelDataDataLocationJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("AuxiliaryDataLocation", targetDepth)) {
context.nextToken();
getParallelDataResult.setAuxiliaryDataLocation(ParallelDataDataLocationJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("LatestUpdateAttemptAuxiliaryDataLocation", targetDepth)) {
context.nextToken();
getParallelDataResult.setLatestUpdateAttemptAuxiliaryDataLocation(ParallelDataDataLocationJsonUnmarshaller.getInstance()
.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 getParallelDataResult;
}
private static GetParallelDataResultJsonUnmarshaller instance;
public static GetParallelDataResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GetParallelDataResultJsonUnmarshaller();
return instance;
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-translate/src/main/java/com/amazonaws/services/translate/model/transform/GetParallelDataResultJsonUnmarshaller.java
|
Java
|
apache-2.0
| 3,782
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OTFN.Core.Errors
{
public class SymbolNotFoundException : NotFoundException
{
public SymbolNotFoundException(string message)
: base(message)
{
}
}
}
|
AndreyMav/OpenTradingFrameworkNet
|
OTFNCore/Errors/SymbolNotFoundException.cs
|
C#
|
apache-2.0
| 328
|
# Callicarpa loureiroi Hook. & Arn. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Callicarpa/Callicarpa loureiroi/README.md
|
Markdown
|
apache-2.0
| 183
|
from __future__ import absolute_import
from __future__ import print_function
from contextlib import contextmanager
from typing import (cast, Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional,
Sized, Tuple, Union, Text)
from django.core.urlresolvers import resolve
from django.conf import settings
from django.test import TestCase
from django.test.client import (
BOUNDARY, MULTIPART_CONTENT, encode_multipart,
)
from django.template import loader
from django.test.testcases import SerializeMixin
from django.http import HttpResponse
from django.db.utils import IntegrityError
from zerver.lib.initial_password import initial_password
from zerver.lib.db import TimeTrackingCursor
from zerver.lib.str_utils import force_text
from zerver.lib.utils import is_remote_server
from zerver.lib import cache
from zerver.tornado.handlers import allocate_handler_id
from zerver.worker import queue_processors
from zerver.lib.actions import (
check_send_message, create_stream_if_needed, bulk_add_subscriptions,
get_display_recipient, bulk_remove_subscriptions
)
from zerver.lib.test_helpers import (
instrument_url, find_key_by_email,
)
from zerver.models import (
get_stream,
get_user,
get_user_profile_by_email,
get_realm,
get_realm_by_email_domain,
Client,
Message,
Realm,
Recipient,
Stream,
Subscription,
UserMessage,
UserProfile,
)
from zerver.lib.request import JsonableError
from zilencer.models import get_remote_server_by_uuid
import base64
import mock
import os
import re
import time
import ujson
import unittest
from six.moves import urllib
from six import binary_type
from zerver.lib.str_utils import NonBinaryStr
from contextlib import contextmanager
import six
API_KEYS = {} # type: Dict[Text, Text]
def flush_caches_for_testing():
# type: () -> None
global API_KEYS
API_KEYS = {}
class UploadSerializeMixin(SerializeMixin):
"""
We cannot use override_settings to change upload directory because
because settings.LOCAL_UPLOADS_DIR is used in url pattern and urls
are compiled only once. Otherwise using a different upload directory
for conflicting test cases would have provided better performance
while providing the required isolation.
"""
lockfile = 'var/upload_lock'
@classmethod
def setUpClass(cls, *args, **kwargs):
# type: (*Any, **Any) -> None
if not os.path.exists(cls.lockfile):
with open(cls.lockfile, 'w'): # nocoverage - rare locking case
pass
super(UploadSerializeMixin, cls).setUpClass(*args, **kwargs)
class ZulipTestCase(TestCase):
# Ensure that the test system just shows us diffs
maxDiff = None # type: Optional[int]
'''
WRAPPER_COMMENT:
We wrap calls to self.client.{patch,put,get,post,delete} for various
reasons. Some of this has to do with fixing encodings before calling
into the Django code. Some of this has to do with providing a future
path for instrumentation. Some of it's just consistency.
The linter will prevent direct calls to self.client.foo, so the wrapper
functions have to fake out the linter by using a local variable called
django_client to fool the regext.
'''
def __init__(self, *args, **kwargs):
# type: (*Any, **Any) -> None
# This method should be removed when we migrate to version 3 of Python
import six
if six.PY2:
self.assertRaisesRegex = self.assertRaisesRegexp
super(ZulipTestCase, self).__init__(*args, **kwargs)
DEFAULT_REALM = Realm.objects.get(string_id='zulip')
@instrument_url
def client_patch(self, url, info={}, **kwargs):
# type: (Text, Dict[str, Any], **Any) -> HttpResponse
"""
We need to urlencode, since Django's function won't do it for us.
"""
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
return django_client.patch(url, encoded, **kwargs)
@instrument_url
def client_patch_multipart(self, url, info={}, **kwargs):
# type: (Text, Dict[str, Any], **Any) -> HttpResponse
"""
Use this for patch requests that have file uploads or
that need some sort of multi-part content. In the future
Django's test client may become a bit more flexible,
so we can hopefully eliminate this. (When you post
with the Django test client, it deals with MULTIPART_CONTENT
automatically, but not patch.)
"""
encoded = encode_multipart(BOUNDARY, info)
django_client = self.client # see WRAPPER_COMMENT
return django_client.patch(
url,
encoded,
content_type=MULTIPART_CONTENT,
**kwargs)
@instrument_url
def client_put(self, url, info={}, **kwargs):
# type: (Text, Dict[str, Any], **Any) -> HttpResponse
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
return django_client.put(url, encoded, **kwargs)
@instrument_url
def client_delete(self, url, info={}, **kwargs):
# type: (Text, Dict[str, Any], **Any) -> HttpResponse
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
return django_client.delete(url, encoded, **kwargs)
@instrument_url
def client_options(self, url, info={}, **kwargs):
# type: (Text, Dict[str, Any], **Any) -> HttpResponse
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
return django_client.options(url, encoded, **kwargs)
@instrument_url
def client_post(self, url, info={}, **kwargs):
# type: (Text, Dict[str, Any], **Any) -> HttpResponse
django_client = self.client # see WRAPPER_COMMENT
return django_client.post(url, info, **kwargs)
@instrument_url
def client_post_request(self, url, req):
# type: (Text, Any) -> HttpResponse
"""
We simulate hitting an endpoint here, although we
actually resolve the URL manually and hit the view
directly. We have this helper method to allow our
instrumentation to work for /notify_tornado and
future similar methods that require doing funny
things to a request object.
"""
match = resolve(url)
return match.func(req)
@instrument_url
def client_get(self, url, info={}, **kwargs):
# type: (Text, Dict[str, Any], **Any) -> HttpResponse
django_client = self.client # see WRAPPER_COMMENT
return django_client.get(url, info, **kwargs)
example_user_map = dict(
hamlet=u'hamlet@zulip.com',
cordelia=u'cordelia@zulip.com',
iago=u'iago@zulip.com',
prospero=u'prospero@zulip.com',
othello=u'othello@zulip.com',
AARON=u'AARON@zulip.com',
aaron=u'aaron@zulip.com',
ZOE=u'ZOE@zulip.com',
)
mit_user_map = dict(
sipbtest=u"sipbtest@mit.edu",
starnine=u"starnine@mit.edu",
espuser=u"espuser@mit.edu",
)
# Non-registered test users
nonreg_user_map = dict(
test=u'test@zulip.com',
test1=u'test1@zulip.com',
alice=u'alice@zulip.com',
newuser=u'newuser@zulip.com',
bob=u'bob@zulip.com',
cordelia=u'cordelia@zulip.com',
newguy=u'newguy@zulip.com',
me=u'me@zulip.com',
)
def nonreg_user(self, name):
# type: (str) -> UserProfile
email = self.nonreg_user_map[name]
return get_user(email, get_realm_by_email_domain(email))
def example_user(self, name):
# type: (str) -> UserProfile
email = self.example_user_map[name]
return get_user(email, get_realm('zulip'))
def mit_user(self, name):
# type: (str) -> UserProfile
email = self.mit_user_map[name]
return get_user(email, get_realm('zephyr'))
def nonreg_email(self, name):
# type: (str) -> Text
return self.nonreg_user_map[name]
def example_email(self, name):
# type: (str) -> Text
return self.example_user_map[name]
def mit_email(self, name):
# type: (str) -> Text
return self.mit_user_map[name]
def notification_bot(self):
# type: () -> UserProfile
return get_user('notification-bot@zulip.com', get_realm('zulip'))
def login_with_return(self, email, password=None):
# type: (Text, Optional[Text]) -> HttpResponse
if password is None:
password = initial_password(email)
return self.client_post('/accounts/login/',
{'username': email, 'password': password})
def login(self, email, password=None, fails=False):
# type: (Text, Optional[Text], bool) -> HttpResponse
if password is None:
password = initial_password(email)
if not fails:
self.assertTrue(self.client.login(username=email, password=password))
else:
self.assertFalse(self.client.login(username=email, password=password))
def logout(self):
# type: () -> None
self.client.logout()
def register(self, email, password):
# type: (Text, Text) -> HttpResponse
self.client_post('/accounts/home/', {'email': email})
return self.submit_reg_form_for_user(email, password)
def submit_reg_form_for_user(self, email, password, realm_name="Zulip Test",
realm_subdomain="zuliptest",
from_confirmation='', full_name=None, timezone=u'', **kwargs):
# type: (Text, Text, Optional[Text], Optional[Text], Optional[Text], Optional[Text], Optional[Text], **Any) -> HttpResponse
"""
Stage two of the two-step registration process.
If things are working correctly the account should be fully
registered after this call.
You can pass the HTTP_HOST variable for subdomains via kwargs.
"""
if full_name is None:
full_name = email.replace("@", "_")
return self.client_post('/accounts/register/',
{'full_name': full_name,
'password': password,
'realm_name': realm_name,
'realm_subdomain': realm_subdomain,
'key': find_key_by_email(email),
'timezone': timezone,
'terms': True,
'from_confirmation': from_confirmation},
**kwargs)
def get_confirmation_url_from_outbox(self, email_address, path_pattern="(\S+)>"):
# type: (Text, Text) -> Text
from django.core.mail import outbox
for message in reversed(outbox):
if email_address in message.to:
return re.search(settings.EXTERNAL_HOST + path_pattern,
message.body).groups()[0]
else:
raise AssertionError("Couldn't find a confirmation email.")
def get_api_key(self, email):
# type: (Text) -> Text
if email not in API_KEYS:
API_KEYS[email] = get_user_profile_by_email(email).api_key
return API_KEYS[email]
def get_server_api_key(self, server_uuid):
# type: (Text) -> Text
if server_uuid not in API_KEYS:
API_KEYS[server_uuid] = get_remote_server_by_uuid(server_uuid).api_key
return API_KEYS[server_uuid]
def api_auth(self, identifier):
# type: (Text) -> Dict[str, Text]
"""
identifier: Can be an email or a remote server uuid.
"""
if is_remote_server(identifier):
api_key = self.get_server_api_key(identifier)
else:
api_key = self.get_api_key(identifier)
credentials = u"%s:%s" % (identifier, api_key)
return {
'HTTP_AUTHORIZATION': u'Basic ' + base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
}
def get_streams(self, email, realm):
# type: (Text, Realm) -> List[Text]
"""
Helper function to get the stream names for a user
"""
user_profile = get_user(email, realm)
subs = Subscription.objects.filter(
user_profile=user_profile,
active=True,
recipient__type=Recipient.STREAM)
return [cast(Text, get_display_recipient(sub.recipient)) for sub in subs]
def send_message(self, sender_name, raw_recipients, message_type,
content=u"test content", subject=u"test", **kwargs):
# type: (Text, Union[Text, List[Text]], int, Text, Text, **Any) -> int
sender = get_user_profile_by_email(sender_name)
if message_type in [Recipient.PERSONAL, Recipient.HUDDLE]:
message_type_name = "private"
else:
message_type_name = "stream"
if isinstance(raw_recipients, six.string_types):
recipient_list = [raw_recipients]
else:
recipient_list = raw_recipients
(sending_client, _) = Client.objects.get_or_create(name="test suite")
return check_send_message(
sender, sending_client, message_type_name, recipient_list, subject,
content, forged=False, forged_timestamp=None,
forwarder_user_profile=sender, realm=sender.realm, **kwargs)
def get_messages(self, anchor=1, num_before=100, num_after=100,
use_first_unread_anchor=False):
# type: (int, int, int, bool) -> List[Dict[str, Any]]
post_params = {"anchor": anchor, "num_before": num_before,
"num_after": num_after,
"use_first_unread_anchor": ujson.dumps(use_first_unread_anchor)}
result = self.client_get("/json/messages", dict(post_params))
data = ujson.loads(result.content)
return data['messages']
def users_subscribed_to_stream(self, stream_name, realm):
# type: (Text, Realm) -> List[UserProfile]
stream = Stream.objects.get(name=stream_name, realm=realm)
recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM)
subscriptions = Subscription.objects.filter(recipient=recipient, active=True)
return [subscription.user_profile for subscription in subscriptions]
def assert_url_serves_contents_of_file(self, url, result):
# type: (str, bytes) -> None
response = self.client_get(url)
data = b"".join(response.streaming_content)
self.assertEqual(result, data)
def assert_json_success(self, result):
# type: (HttpResponse) -> Dict[str, Any]
"""
Successful POSTs return a 200 and JSON of the form {"result": "success",
"msg": ""}.
"""
self.assertEqual(result.status_code, 200, result)
json = ujson.loads(result.content)
self.assertEqual(json.get("result"), "success")
# We have a msg key for consistency with errors, but it typically has an
# empty value.
self.assertIn("msg", json)
return json
def get_json_error(self, result, status_code=400):
# type: (HttpResponse, int) -> Dict[str, Any]
self.assertEqual(result.status_code, status_code)
json = ujson.loads(result.content)
self.assertEqual(json.get("result"), "error")
return json['msg']
def assert_json_error(self, result, msg, status_code=400):
# type: (HttpResponse, Text, int) -> None
"""
Invalid POSTs return an error status code and JSON of the form
{"result": "error", "msg": "reason"}.
"""
self.assertEqual(self.get_json_error(result, status_code=status_code), msg)
def assert_length(self, queries, count):
# type: (Sized, int) -> None
actual_count = len(queries)
return self.assertTrue(actual_count == count,
"len(%s) == %s, != %s" % (queries, actual_count, count))
def assert_json_error_contains(self, result, msg_substring, status_code=400):
# type: (HttpResponse, Text, int) -> None
self.assertIn(msg_substring, self.get_json_error(result, status_code=status_code))
def assert_in_response(self, substring, response):
# type: (Text, HttpResponse) -> None
self.assertIn(substring, response.content.decode('utf-8'))
def assert_in_success_response(self, substrings, response):
# type: (List[Text], HttpResponse) -> None
self.assertEqual(response.status_code, 200)
decoded = response.content.decode('utf-8')
for substring in substrings:
self.assertIn(substring, decoded)
def assert_not_in_success_response(self, substrings, response):
# type: (List[Text], HttpResponse) -> None
self.assertEqual(response.status_code, 200)
decoded = response.content.decode('utf-8')
for substring in substrings:
self.assertNotIn(substring, decoded)
def fixture_data(self, type, action, file_type='json'):
# type: (Text, Text, Text) -> Text
return force_text(open(os.path.join(os.path.dirname(__file__),
"../webhooks/%s/fixtures/%s.%s" % (type, action, file_type))).read())
def make_stream(self, stream_name, realm=None, invite_only=False):
# type: (Text, Optional[Realm], Optional[bool]) -> Stream
if realm is None:
realm = self.DEFAULT_REALM
try:
stream = Stream.objects.create(
realm=realm,
name=stream_name,
invite_only=invite_only,
)
except IntegrityError: # nocoverage -- this is for bugs in the tests
raise Exception('''
%s already exists
Please call make_stream with a stream name
that is not already in use.''' % (stream_name,))
Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM)
return stream
# Subscribe to a stream directly
def subscribe_to_stream(self, email, stream_name, realm=None):
# type: (Text, Text, Optional[Realm]) -> Stream
if realm is None:
realm = get_realm_by_email_domain(email)
try:
stream = get_stream(stream_name, realm)
from_stream_creation = False
except Stream.DoesNotExist:
stream, from_stream_creation = create_stream_if_needed(realm, stream_name)
user_profile = get_user_profile_by_email(email)
bulk_add_subscriptions([stream], [user_profile], from_stream_creation=from_stream_creation)
return stream
def unsubscribe_from_stream(self, email, stream_name, realm):
# type: (Text, Text, Realm) -> None
user_profile = get_user(email, realm)
stream = get_stream(stream_name, realm)
bulk_remove_subscriptions([user_profile], [stream])
# Subscribe to a stream by making an API request
def common_subscribe_to_streams(self, email, streams, extra_post_data={}, invite_only=False):
# type: (Text, Iterable[Text], Dict[str, Any], bool) -> HttpResponse
post_data = {'subscriptions': ujson.dumps([{"name": stream} for stream in streams]),
'invite_only': ujson.dumps(invite_only)}
post_data.update(extra_post_data)
result = self.client_post("/api/v1/users/me/subscriptions", post_data, **self.api_auth(email))
return result
def send_json_payload(self, email, url, payload, stream_name=None, **post_params):
# type: (Text, Text, Union[Text, Dict[str, Any]], Optional[Text], **Any) -> Message
if stream_name is not None:
self.subscribe_to_stream(email, stream_name)
result = self.client_post(url, payload, **post_params)
self.assert_json_success(result)
# Check the correct message was sent
msg = self.get_last_message()
self.assertEqual(msg.sender.email, email)
if stream_name is not None:
self.assertEqual(get_display_recipient(msg.recipient), stream_name)
# TODO: should also validate recipient for private messages
return msg
def get_last_message(self):
# type: () -> Message
return Message.objects.latest('id')
def get_second_to_last_message(self):
# type: () -> Message
return Message.objects.all().order_by('-id')[1]
@contextmanager
def simulated_markdown_failure(self):
# type: () -> Iterator[None]
'''
This raises a failure inside of the try/except block of
bugdown.__init__.do_convert.
'''
with \
self.settings(ERROR_BOT=None), \
mock.patch('zerver.lib.bugdown.timeout', side_effect=KeyError('foo')), \
mock.patch('zerver.lib.bugdown.log_bugdown_error'):
yield
class WebhookTestCase(ZulipTestCase):
"""
Common for all webhooks tests
Override below class attributes and run send_and_test_message
If you create your url in uncommon way you can override build_webhook_url method
In case that you need modify body or create it without using fixture you can also override get_body method
"""
STREAM_NAME = None # type: Optional[Text]
TEST_USER_EMAIL = 'webhook-bot@zulip.com'
URL_TEMPLATE = None # type: Optional[Text]
FIXTURE_DIR_NAME = None # type: Optional[Text]
def setUp(self):
# type: () -> None
self.url = self.build_webhook_url()
def send_and_test_stream_message(self, fixture_name, expected_subject=None,
expected_message=None, content_type="application/json", **kwargs):
# type: (Text, Optional[Text], Optional[Text], Optional[Text], **Any) -> Message
payload = self.get_body(fixture_name)
if content_type is not None:
kwargs['content_type'] = content_type
msg = self.send_json_payload(self.TEST_USER_EMAIL, self.url, payload,
self.STREAM_NAME, **kwargs)
self.do_test_subject(msg, expected_subject)
self.do_test_message(msg, expected_message)
return msg
def send_and_test_private_message(self, fixture_name, expected_subject=None,
expected_message=None, content_type="application/json", **kwargs):
# type: (Text, Text, Text, str, **Any) -> Message
payload = self.get_body(fixture_name)
if content_type is not None:
kwargs['content_type'] = content_type
msg = self.send_json_payload(self.TEST_USER_EMAIL, self.url, payload,
stream_name=None, **kwargs)
self.do_test_message(msg, expected_message)
return msg
def build_webhook_url(self, *args, **kwargs):
# type: (*Any, **Any) -> Text
url = self.URL_TEMPLATE
if url.find("api_key") >= 0:
api_key = self.get_api_key(self.TEST_USER_EMAIL)
url = self.URL_TEMPLATE.format(api_key=api_key,
stream=self.STREAM_NAME)
else:
url = self.URL_TEMPLATE.format(stream=self.STREAM_NAME)
has_arguments = kwargs or args
if has_arguments and url.find('?') == -1:
url = "{}?".format(url)
else:
url = "{}&".format(url)
for key, value in kwargs.items():
url = "{}{}={}&".format(url, key, value)
for arg in args:
url = "{}{}&".format(url, arg)
return url[:-1] if has_arguments else url
def get_body(self, fixture_name):
# type: (Text) -> Union[Text, Dict[str, Text]]
"""Can be implemented either as returning a dictionary containing the
post parameters or as string containing the body of the request."""
return ujson.dumps(ujson.loads(self.fixture_data(self.FIXTURE_DIR_NAME, fixture_name)))
def do_test_subject(self, msg, expected_subject):
# type: (Message, Optional[Text]) -> None
if expected_subject is not None:
self.assertEqual(msg.topic_name(), expected_subject)
def do_test_message(self, msg, expected_message):
# type: (Message, Optional[Text]) -> None
if expected_message is not None:
self.assertEqual(msg.content, expected_message)
|
vabs22/zulip
|
zerver/lib/test_classes.py
|
Python
|
apache-2.0
| 24,636
|
import atexit
import sys
def all_done():
print('all_done()')
print('Registering')
atexit.register(all_done)
print('Registered')
print('Exiting...')
sys.exit()
|
jasonwee/asus-rt-n14uhp-mrtg
|
src/lesson_application_building_blocks/atexit_sys_exit.py
|
Python
|
apache-2.0
| 172
|
/*
* Copyright (C) 2010 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.android.settings.wifi;
import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
import static android.os.UserManager.DISALLOW_CONFIG_WIFI;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.UserManager;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.wifi.p2p.WifiP2pSettings;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Two types of UI are provided here.
*
* The first is for "usual Settings", appearing as any other Setup fragment.
*
* The second is for Setup Wizard, with a simplified interface that hides the action bar
* and menus.
*/
public class WifiSettings extends SettingsPreferenceFragment
implements DialogInterface.OnClickListener {
private static final String TAG = "WifiSettings";
private static final int MENU_ID_WPS_PBC = Menu.FIRST;
private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
private static final int MENU_ID_P2P = Menu.FIRST + 2;
private static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3;
private static final int MENU_ID_ADVANCED = Menu.FIRST + 4;
private static final int MENU_ID_SCAN = Menu.FIRST + 5;
private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
private static final int MENU_ID_FORGET = Menu.FIRST + 7;
private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
private static final int WIFI_DIALOG_ID = 1;
private static final int WPS_PBC_DIALOG_ID = 2;
private static final int WPS_PIN_DIALOG_ID = 3;
private static final int WIFI_SKIPPED_DIALOG_ID = 4;
private static final int WIFI_AND_MOBILE_SKIPPED_DIALOG_ID = 5;
// Combo scans can take 5-6s to complete - set to 10s.
private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000;
// Instance state keys
private static final String SAVE_DIALOG_EDIT_MODE = "edit_mode";
private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
// Activity result when pressing the Skip button
private static final int RESULT_SKIP = Activity.RESULT_FIRST_USER;
private final IntentFilter mFilter;
private final BroadcastReceiver mReceiver;
private final Scanner mScanner;
private WifiManager mWifiManager;
private WifiManager.ActionListener mConnectListener;
private WifiManager.ActionListener mSaveListener;
private WifiManager.ActionListener mForgetListener;
private boolean mP2pSupported;
private UserManager mUserManager;
private WifiEnabler mWifiEnabler;
// An access point being editted is stored here.
private AccessPoint mSelectedAccessPoint;
private DetailedState mLastState;
private WifiInfo mLastInfo;
private AtomicBoolean mConnected = new AtomicBoolean(false);
private WifiDialog mDialog;
private TextView mEmptyView;
/* Used in Wifi Setup context */
// this boolean extra specifies whether to disable the Next button when not connected
private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
// this boolean extra specifies whether to auto finish when connection is established
private static final String EXTRA_AUTO_FINISH_ON_CONNECT = "wifi_auto_finish_on_connect";
// this boolean extra shows a custom button that we can control
protected static final String EXTRA_SHOW_CUSTOM_BUTTON = "wifi_show_custom_button";
// show a text regarding data charges when wifi connection is required during setup wizard
protected static final String EXTRA_SHOW_WIFI_REQUIRED_INFO = "wifi_show_wifi_required_info";
// this boolean extra is set if we are being invoked by the Setup Wizard
private static final String EXTRA_IS_FIRST_RUN = "firstRun";
// should Next button only be enabled when we have a connection?
private boolean mEnableNextOnConnection;
// should activity finish once we have a connection?
private boolean mAutoFinishOnConnection;
// Save the dialog details
private boolean mDlgEdit;
private AccessPoint mDlgAccessPoint;
private Bundle mAccessPointSavedState;
// the action bar uses a different set of controls for Setup Wizard
private boolean mSetupWizardMode;
/* End of "used in Wifi Setup context" */
public WifiSettings() {
mFilter = new IntentFilter();
mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
handleEvent(context, intent);
}
};
mScanner = new Scanner();
}
@Override
public void onCreate(Bundle icicle) {
// Set this flag early, as it's needed by getHelpResource(), which is called by super
mSetupWizardMode = getActivity().getIntent().getBooleanExtra(EXTRA_IS_FIRST_RUN, false);
super.onCreate(icicle);
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (mSetupWizardMode) {
View view = inflater.inflate(R.layout.setup_preference, container, false);
View other = view.findViewById(R.id.other_network);
other.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mWifiManager.isWifiEnabled()) {
onAddNetworkPressed();
}
}
});
final ImageButton b = (ImageButton) view.findViewById(R.id.more);
if (b != null) {
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mWifiManager.isWifiEnabled()) {
PopupMenu pm = new PopupMenu(inflater.getContext(), b);
pm.inflate(R.menu.wifi_setup);
pm.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (R.id.wifi_wps == item.getItemId()) {
showDialog(WPS_PBC_DIALOG_ID);
return true;
}
return false;
}
});
pm.show();
}
}
});
}
Intent intent = getActivity().getIntent();
if (intent.getBooleanExtra(EXTRA_SHOW_CUSTOM_BUTTON, false)) {
view.findViewById(R.id.button_bar).setVisibility(View.VISIBLE);
view.findViewById(R.id.back_button).setVisibility(View.INVISIBLE);
view.findViewById(R.id.skip_button).setVisibility(View.INVISIBLE);
view.findViewById(R.id.next_button).setVisibility(View.INVISIBLE);
Button customButton = (Button) view.findViewById(R.id.custom_button);
customButton.setVisibility(View.VISIBLE);
customButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean isConnected = false;
Activity activity = getActivity();
final ConnectivityManager connectivity = (ConnectivityManager)
activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
final NetworkInfo info = connectivity.getActiveNetworkInfo();
isConnected = (info != null) && info.isConnected();
}
if (isConnected) {
// Warn of possible data charges
showDialog(WIFI_SKIPPED_DIALOG_ID);
} else {
// Warn of lack of updates
showDialog(WIFI_AND_MOBILE_SKIPPED_DIALOG_ID);
}
}
});
}
if (intent.getBooleanExtra(EXTRA_SHOW_WIFI_REQUIRED_INFO, false)) {
view.findViewById(R.id.wifi_required_info).setVisibility(View.VISIBLE);
}
return view;
} else {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mP2pSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);
mConnectListener = new WifiManager.ActionListener() {
@Override
public void onSuccess() {
}
@Override
public void onFailure(int reason) {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity,
R.string.wifi_failed_connect_message,
Toast.LENGTH_SHORT).show();
}
}
};
mSaveListener = new WifiManager.ActionListener() {
@Override
public void onSuccess() {
}
@Override
public void onFailure(int reason) {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity,
R.string.wifi_failed_save_message,
Toast.LENGTH_SHORT).show();
}
}
};
mForgetListener = new WifiManager.ActionListener() {
@Override
public void onSuccess() {
}
@Override
public void onFailure(int reason) {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity,
R.string.wifi_failed_forget_message,
Toast.LENGTH_SHORT).show();
}
}
};
if (savedInstanceState != null
&& savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE);
mAccessPointSavedState = savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
}
final Activity activity = getActivity();
final Intent intent = activity.getIntent();
// first if we're supposed to finish once we have a connection
mAutoFinishOnConnection = intent.getBooleanExtra(EXTRA_AUTO_FINISH_ON_CONNECT, false);
if (mAutoFinishOnConnection) {
// Hide the next button
if (hasNextButton()) {
getNextButton().setVisibility(View.GONE);
}
final ConnectivityManager connectivity = (ConnectivityManager)
activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null
&& connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
activity.setResult(Activity.RESULT_OK);
activity.finish();
return;
}
}
// if we're supposed to enable/disable the Next button based on our current connection
// state, start it off in the right state
mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
if (mEnableNextOnConnection) {
if (hasNextButton()) {
final ConnectivityManager connectivity = (ConnectivityManager)
activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getNetworkInfo(
ConnectivityManager.TYPE_WIFI);
changeNextButtonState(info.isConnected());
}
}
}
addPreferencesFromResource(R.xml.wifi_settings);
if (mSetupWizardMode) {
getView().setSystemUiVisibility(
// View.STATUS_BAR_DISABLE_BACK |
View.STATUS_BAR_DISABLE_HOME |
View.STATUS_BAR_DISABLE_RECENT |
View.STATUS_BAR_DISABLE_NOTIFICATION_ALERTS |
View.STATUS_BAR_DISABLE_CLOCK);
}
// On/off switch is hidden for Setup Wizard
if (!mSetupWizardMode) {
Switch actionBarSwitch = new Switch(activity);
if (activity instanceof PreferenceActivity) {
PreferenceActivity preferenceActivity = (PreferenceActivity) activity;
if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) {
final int padding = activity.getResources().getDimensionPixelSize(
R.dimen.action_bar_switch_padding);
actionBarSwitch.setPaddingRelative(0, 0, padding, 0);
activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
ActionBar.DISPLAY_SHOW_CUSTOM);
activity.getActionBar().setCustomView(actionBarSwitch, new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_VERTICAL | Gravity.END));
}
}
mWifiEnabler = new WifiEnabler(activity, actionBarSwitch);
}
mEmptyView = (TextView) getView().findViewById(android.R.id.empty);
getListView().setEmptyView(mEmptyView);
if (!mSetupWizardMode) {
registerForContextMenu(getListView());
}
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
if (mWifiEnabler != null) {
mWifiEnabler.resume();
}
getActivity().registerReceiver(mReceiver, mFilter);
updateAccessPoints();
}
@Override
public void onPause() {
super.onPause();
if (mWifiEnabler != null) {
mWifiEnabler.pause();
}
getActivity().unregisterReceiver(mReceiver);
mScanner.pause();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the user is not allowed to configure wifi, do not show the menu.
if (mUserManager.hasUserRestriction(DISALLOW_CONFIG_WIFI)) return;
final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
if (mSetupWizardMode) {
// FIXME: add setIcon() when graphics are available
menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
.setIcon(R.drawable.ic_wps)
.setEnabled(wifiIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
.setEnabled(wifiIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
} else {
menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
.setIcon(R.drawable.ic_wps)
.setEnabled(wifiIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
.setIcon(R.drawable.ic_menu_add)
.setEnabled(wifiIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan)
//.setIcon(R.drawable.ic_menu_scan_network)
.setEnabled(wifiIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin)
.setEnabled(wifiIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
if (mP2pSupported) {
menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p)
.setEnabled(wifiIsEnabled)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
}
menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
//.setIcon(android.R.drawable.ic_menu_manage)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// If the dialog is showing, save its state.
if (mDialog != null && mDialog.isShowing()) {
outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit);
if (mDlgAccessPoint != null) {
mAccessPointSavedState = new Bundle();
mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// If the user is not allowed to configure wifi, do not handle menu selections.
if (mUserManager.hasUserRestriction(DISALLOW_CONFIG_WIFI)) return false;
switch (item.getItemId()) {
case MENU_ID_WPS_PBC:
showDialog(WPS_PBC_DIALOG_ID);
return true;
case MENU_ID_P2P:
if (getActivity() instanceof PreferenceActivity) {
((PreferenceActivity) getActivity()).startPreferencePanel(
WifiP2pSettings.class.getCanonicalName(),
null,
R.string.wifi_p2p_settings_title, null,
this, 0);
} else {
startFragment(this, WifiP2pSettings.class.getCanonicalName(), -1, null);
}
return true;
case MENU_ID_WPS_PIN:
showDialog(WPS_PIN_DIALOG_ID);
return true;
case MENU_ID_SCAN:
if (mWifiManager.isWifiEnabled()) {
mScanner.forceScan();
}
return true;
case MENU_ID_ADD_NETWORK:
if (mWifiManager.isWifiEnabled()) {
onAddNetworkPressed();
}
return true;
case MENU_ID_ADVANCED:
if (getActivity() instanceof PreferenceActivity) {
((PreferenceActivity) getActivity()).startPreferencePanel(
AdvancedWifiSettings.class.getCanonicalName(),
null,
R.string.wifi_advanced_titlebar, null,
this, 0);
} else {
startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), -1, null);
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
if (info instanceof AdapterContextMenuInfo) {
Preference preference = (Preference) getListView().getItemAtPosition(
((AdapterContextMenuInfo) info).position);
if (preference instanceof AccessPoint) {
mSelectedAccessPoint = (AccessPoint) preference;
menu.setHeaderTitle(mSelectedAccessPoint.ssid);
if (mSelectedAccessPoint.getLevel() != -1
&& mSelectedAccessPoint.getState() == null) {
menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
}
if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
}
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (mSelectedAccessPoint == null) {
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case MENU_ID_CONNECT: {
if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
mWifiManager.connect(mSelectedAccessPoint.networkId,
mConnectListener);
} else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) {
/** Bypass dialog for unsecured networks */
mSelectedAccessPoint.generateOpenNetworkConfig();
mWifiManager.connect(mSelectedAccessPoint.getConfig(),
mConnectListener);
} else {
showDialog(mSelectedAccessPoint, true);
}
return true;
}
case MENU_ID_FORGET: {
mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener);
return true;
}
case MENU_ID_MODIFY: {
showDialog(mSelectedAccessPoint, true);
return true;
}
}
return super.onContextItemSelected(item);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
if (preference instanceof AccessPoint) {
mSelectedAccessPoint = (AccessPoint) preference;
/** Bypass dialog for unsecured, unsaved networks */
if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE &&
mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
mSelectedAccessPoint.generateOpenNetworkConfig();
mWifiManager.connect(mSelectedAccessPoint.getConfig(), mConnectListener);
} else {
showDialog(mSelectedAccessPoint, false);
}
} else {
return super.onPreferenceTreeClick(screen, preference);
}
return true;
}
private void showDialog(AccessPoint accessPoint, boolean edit) {
if (mDialog != null) {
removeDialog(WIFI_DIALOG_ID);
mDialog = null;
}
// Save the access point and edit mode
mDlgAccessPoint = accessPoint;
mDlgEdit = edit;
showDialog(WIFI_DIALOG_ID);
}
@Override
public Dialog onCreateDialog(int dialogId) {
switch (dialogId) {
case WIFI_DIALOG_ID:
AccessPoint ap = mDlgAccessPoint; // For manual launch
if (ap == null) { // For re-launch from saved state
if (mAccessPointSavedState != null) {
ap = new AccessPoint(getActivity(), mAccessPointSavedState);
// For repeated orientation changes
mDlgAccessPoint = ap;
}
}
// If it's still null, fine, it's for Add Network
mSelectedAccessPoint = ap;
mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit);
return mDialog;
case WPS_PBC_DIALOG_ID:
return new WpsDialog(getActivity(), WpsInfo.PBC);
case WPS_PIN_DIALOG_ID:
return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
case WIFI_SKIPPED_DIALOG_ID:
return new AlertDialog.Builder(getActivity())
.setMessage(R.string.wifi_skipped_message)
.setCancelable(false)
.setNegativeButton(R.string.wifi_skip_anyway,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
getActivity().setResult(RESULT_SKIP);
getActivity().finish();
}
})
.setPositiveButton(R.string.wifi_dont_skip,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
})
.create();
case WIFI_AND_MOBILE_SKIPPED_DIALOG_ID:
return new AlertDialog.Builder(getActivity())
.setMessage(R.string.wifi_and_mobile_skipped_message)
.setCancelable(false)
.setNegativeButton(R.string.wifi_skip_anyway,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
getActivity().setResult(RESULT_SKIP);
getActivity().finish();
}
})
.setPositiveButton(R.string.wifi_dont_skip,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
})
.create();
}
return super.onCreateDialog(dialogId);
}
/**
* Shows the latest access points available with supplimental information like
* the strength of network and the security for it.
*/
private void updateAccessPoints() {
// Safeguard from some delayed event handling
if (getActivity() == null) return;
if (mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI)) {
addMessagePreference(R.string.wifi_empty_list_user_restricted);
return;
}
final int wifiState = mWifiManager.getWifiState();
switch (wifiState) {
case WifiManager.WIFI_STATE_ENABLED:
// AccessPoints are automatically sorted with TreeSet.
final Collection<AccessPoint> accessPoints = constructAccessPoints();
getPreferenceScreen().removeAll();
if(accessPoints.size() == 0) {
addMessagePreference(R.string.wifi_empty_list_wifi_on);
}
for (AccessPoint accessPoint : accessPoints) {
getPreferenceScreen().addPreference(accessPoint);
}
break;
case WifiManager.WIFI_STATE_ENABLING:
getPreferenceScreen().removeAll();
break;
case WifiManager.WIFI_STATE_DISABLING:
addMessagePreference(R.string.wifi_stopping);
break;
case WifiManager.WIFI_STATE_DISABLED:
setOffMessage();
break;
}
}
private void setOffMessage() {
if (mEmptyView != null) {
mEmptyView.setText(R.string.wifi_empty_list_wifi_off);
if (Settings.Global.getInt(getActivity().getContentResolver(),
Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1) {
mEmptyView.append("\n\n");
int resId;
if (Settings.Secure.isLocationProviderEnabled(getActivity().getContentResolver(),
LocationManager.NETWORK_PROVIDER)) {
resId = R.string.wifi_scan_notify_text_location_on;
} else {
resId = R.string.wifi_scan_notify_text_location_off;
}
CharSequence charSeq = getText(resId);
mEmptyView.append(charSeq);
}
}
getPreferenceScreen().removeAll();
}
private void addMessagePreference(int messageId) {
if (mEmptyView != null) mEmptyView.setText(messageId);
getPreferenceScreen().removeAll();
}
/** Returns sorted list of access points */
private List<AccessPoint> constructAccessPoints() {
ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>();
/** Lookup table to more quickly update AccessPoints by only considering objects with the
* correct SSID. Maps SSID -> List of AccessPoints with the given SSID. */
Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>();
final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
if (configs != null) {
for (WifiConfiguration config : configs) {
AccessPoint accessPoint = new AccessPoint(getActivity(), config);
accessPoint.update(mLastInfo, mLastState);
accessPoints.add(accessPoint);
apMap.put(accessPoint.ssid, accessPoint);
}
}
final List<ScanResult> results = mWifiManager.getScanResults();
if (results != null) {
for (ScanResult result : results) {
// Ignore hidden and ad-hoc networks.
if (result.SSID == null || result.SSID.length() == 0 ||
result.capabilities.contains("[IBSS]")) {
continue;
}
boolean found = false;
for (AccessPoint accessPoint : apMap.getAll(result.SSID)) {
if (accessPoint.update(result))
found = true;
}
if (!found) {
AccessPoint accessPoint = new AccessPoint(getActivity(), result);
accessPoints.add(accessPoint);
apMap.put(accessPoint.ssid, accessPoint);
}
}
}
// Pre-sort accessPoints to speed preference insertion
Collections.sort(accessPoints);
return accessPoints;
}
/** A restricted multimap for use in constructAccessPoints */
private class Multimap<K,V> {
private HashMap<K,List<V>> store = new HashMap<K,List<V>>();
/** retrieve a non-null list of values with key K */
List<V> getAll(K key) {
List<V> values = store.get(key);
return values != null ? values : Collections.<V>emptyList();
}
void put(K key, V val) {
List<V> curVals = store.get(key);
if (curVals == null) {
curVals = new ArrayList<V>(3);
store.put(key, curVals);
}
curVals.add(val);
}
}
private void handleEvent(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN));
} else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) ||
WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) ||
WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) {
updateAccessPoints();
} else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
//Ignore supplicant state changes when network is connected
//TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and
//introduce a broadcast that combines the supplicant and network
//network state change events so the apps dont have to worry about
//ignoring supplicant state change when network is connected
//to get more fine grained information.
SupplicantState state = (SupplicantState) intent.getParcelableExtra(
WifiManager.EXTRA_NEW_STATE);
if (!mConnected.get() && SupplicantState.isHandshakeState(state)) {
updateConnectionState(WifiInfo.getDetailedStateOf(state));
} else {
// During a connect, we may have the supplicant
// state change affect the detailed network state.
// Make sure a lost connection is updated as well.
updateConnectionState(null);
}
} else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
WifiManager.EXTRA_NETWORK_INFO);
mConnected.set(info.isConnected());
changeNextButtonState(info.isConnected());
updateAccessPoints();
updateConnectionState(info.getDetailedState());
if (mAutoFinishOnConnection && info.isConnected()) {
Activity activity = getActivity();
if (activity != null) {
activity.setResult(Activity.RESULT_OK);
activity.finish();
}
return;
}
} else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
updateConnectionState(null);
}
}
private void updateConnectionState(DetailedState state) {
/* sticky broadcasts can call this when wifi is disabled */
if (!mWifiManager.isWifiEnabled()) {
mScanner.pause();
return;
}
if (state == DetailedState.OBTAINING_IPADDR) {
mScanner.pause();
} else {
mScanner.resume();
}
mLastInfo = mWifiManager.getConnectionInfo();
if (state != null) {
mLastState = state;
}
for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) {
// Maybe there's a WifiConfigPreference
Preference preference = getPreferenceScreen().getPreference(i);
if (preference instanceof AccessPoint) {
final AccessPoint accessPoint = (AccessPoint) preference;
accessPoint.update(mLastInfo, mLastState);
}
}
}
private void updateWifiState(int state) {
Activity activity = getActivity();
if (activity != null) {
activity.invalidateOptionsMenu();
}
switch (state) {
case WifiManager.WIFI_STATE_ENABLED:
mScanner.resume();
return; // not break, to avoid the call to pause() below
case WifiManager.WIFI_STATE_ENABLING:
addMessagePreference(R.string.wifi_starting);
break;
case WifiManager.WIFI_STATE_DISABLED:
setOffMessage();
break;
}
mLastInfo = null;
mLastState = null;
mScanner.pause();
}
private class Scanner extends Handler {
private int mRetry = 0;
void resume() {
if (!hasMessages(0)) {
sendEmptyMessage(0);
}
}
void forceScan() {
removeMessages(0);
sendEmptyMessage(0);
}
void pause() {
mRetry = 0;
removeMessages(0);
}
@Override
public void handleMessage(Message message) {
if (mWifiManager.startScan()) {
mRetry = 0;
} else if (++mRetry >= 3) {
mRetry = 0;
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, R.string.wifi_fail_to_scan,
Toast.LENGTH_LONG).show();
}
return;
}
sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS);
}
}
/**
* Renames/replaces "Next" button when appropriate. "Next" button usually exists in
* Wifi setup screens, not in usual wifi settings screen.
*
* @param connected true when the device is connected to a wifi network.
*/
private void changeNextButtonState(boolean connected) {
if (mEnableNextOnConnection && hasNextButton()) {
getNextButton().setEnabled(connected);
}
}
@Override
public void onClick(DialogInterface dialogInterface, int button) {
if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
forget();
} else if (button == WifiDialog.BUTTON_SUBMIT) {
if (mDialog != null) {
submit(mDialog.getController());
}
}
}
/* package */ void submit(WifiConfigController configController) {
final WifiConfiguration config = configController.getConfig();
if (config == null) {
if (mSelectedAccessPoint != null
&& mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
mWifiManager.connect(mSelectedAccessPoint.networkId,
mConnectListener);
}
} else if (config.networkId != INVALID_NETWORK_ID) {
if (mSelectedAccessPoint != null) {
mWifiManager.save(config, mSaveListener);
}
} else {
if (configController.isEdit()) {
mWifiManager.save(config, mSaveListener);
} else {
mWifiManager.connect(config, mConnectListener);
}
}
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
updateAccessPoints();
}
/* package */ void forget() {
if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
// Should not happen, but a monkey seems to triger it
Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
return;
}
mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener);
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
updateAccessPoints();
// We need to rename/replace "Next" button in wifi setup context.
changeNextButtonState(false);
}
/**
* Refreshes acccess points and ask Wifi module to scan networks again.
*/
/* package */ void refreshAccessPoints() {
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
getPreferenceScreen().removeAll();
}
/**
* Called when "add network" button is pressed.
*/
/* package */ void onAddNetworkPressed() {
// No exact access point is selected.
mSelectedAccessPoint = null;
showDialog(null, true);
}
/* package */ int getAccessPointsCount() {
final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
if (wifiIsEnabled) {
return getPreferenceScreen().getPreferenceCount();
} else {
return 0;
}
}
/**
* Requests wifi module to pause wifi scan. May be ignored when the module is disabled.
*/
/* package */ void pauseWifiScan() {
if (mWifiManager.isWifiEnabled()) {
mScanner.pause();
}
}
/**
* Requests wifi module to resume wifi scan. May be ignored when the module is disabled.
*/
/* package */ void resumeWifiScan() {
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
}
@Override
protected int getHelpResource() {
if (mSetupWizardMode) {
return 0;
}
return R.string.help_url_wifi;
}
/**
* Used as the outer frame of all setup wizard pages that need to adjust their margins based
* on the total size of the available display. (e.g. side margins set to 10% of total width.)
*/
public static class ProportionalOuterFrame extends RelativeLayout {
public ProportionalOuterFrame(Context context) {
super(context);
}
public ProportionalOuterFrame(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ProportionalOuterFrame(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Set our margins and title area height proportionally to the available display size
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
final Resources resources = getContext().getResources();
float titleHeight = resources.getFraction(R.dimen.setup_title_height, 1, 1);
float sideMargin = resources.getFraction(R.dimen.setup_border_width, 1, 1);
int bottom = resources.getDimensionPixelSize(R.dimen.setup_margin_bottom);
setPaddingRelative(
(int) (parentWidth * sideMargin),
0,
(int) (parentWidth * sideMargin),
bottom);
View title = findViewById(R.id.title_area);
if (title != null) {
title.setMinimumHeight((int) (parentHeight * titleHeight));
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
|
craigacgomez/flaming_monkey_packages_apps_Settings
|
src/com/android/settings/wifi/WifiSettings.java
|
Java
|
apache-2.0
| 46,198
|
/*
* Artifactory is a binaries repository manager.
* Copyright (C) 2012 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*/
package org.artifactory.webapp.wicket.util.validation;
import org.apache.wicket.validation.validator.RangeValidator;
/**
* The port number field wicket validator. Asserts the input is no lower than 1, and no higher than 65535 (the valid
* port range)
*
* @author Noam Y. Tenne
*/
public class PortNumberValidator extends RangeValidator<Integer> {
/**
* Default constructor
*/
public PortNumberValidator() {
super(1, 65535);
}
}
|
alancnet/artifactory
|
web/application/src/main/java/org/artifactory/webapp/wicket/util/validation/PortNumberValidator.java
|
Java
|
apache-2.0
| 1,223
|
<?php
namespace Oranges\MongoDbBundle\Helper;
/**
File Manager for storing files in the Ajent file system cloud.
@author R.J. Keller <rjkeller@pixonite.com>
*/
class FileUploadManager
{
/**
Stores the specified file upload in GridFS.
@param $upload_field_name - The name of the $_POST[] field where the user
uploaded the file to.
@param $database - The name of the MongoDB database to store the file in.
@param $metadata - Meta data to retrieve the file later.
@return $id - The ID # of the file uploaded.
*/
public static function storeUpload($upload_field_name, $database, $metadata)
{
$mongo = MongoDb::getMongo();
$db = $mongo->selectDB($database);
$grid = $db->getGridFS();
$id = $grid->storeUpload($upload_field_name, $metadata);
return $id;
}
/**
Stores the specified file in GridFS.
@param $upload_field_name - The name of the file to store in GridFS.
@param $database - The name of the MongoDB database to store the file in.
@param $metadata - Meta data to retrieve the file later.
@return $id - The ID # of the file uploaded.
*/
public static function storeFile($file_name, $database, $metadata)
{
$mongo = MongoDb::getMongo();
$db = $mongo->selectDB($database);
$grid = $db->getGridFS();
$id = $grid->storeFile($file_name, $metadata);
return $id;
}
/**
Uses the PHP GD library to resize an image file to the specified width
and height.
*/
public static function resizeImageUpload($upload_field_name, $max_width, $max_height)
{
$filename = $_FILES[$upload_field_name]['tmp_name'];
// Get new dimensions
list($width, $height) = getimagesize($filename);
$width_percent = $max_width / $width;
$height_percent = $max_height / $height;
$final_percent = 0.00;
if ($width_percent < $height_percent)
$final_percent = $width_percent;
else
$final_percent = $height_percent;
$new_width = $width * $final_percent;
$new_height = $height * $final_percent;
// Resample
$image_p = imagecreatetruecolor($max_width, $max_height);
$info = getimagesize($filename);
$image = null;
if ($info['mime'] == "image/png")
$image = imagecreatefrompng($filename);
else if ($info['mime'] == "image/gif")
$image = imagecreatefromgif($filename);
else
$image = imagecreatefromjpeg($filename);
imagefill($image_p, 0, 0, imagecolorallocate($image_p, 255,255,255));
imagecopyresampled($image_p, $image, ($max_width - $new_width) / 2, ($max_height - $new_height) / 2, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagepng($image_p, $filename, 0);
}
}
|
rjkeller/OrangesMongoDbBundle
|
Oranges/MongoDbBundle/Helper/FileUploadManager.php
|
PHP
|
apache-2.0
| 2,584
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.