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
|
|---|---|---|---|---|---|
class Category < ActiveRecord::Base
has_and_belongs_to_many :item
end
|
montehoover/homeventory
|
app/models/category.rb
|
Ruby
|
apache-2.0
| 73
|
<?php
/**
* Layer slider config.
*
* @package the7
* @since 1.0.0
*/
// File Security Check
if ( ! defined( 'ABSPATH' ) ) { exit; }
if ( ! class_exists( 'Presscore_Modules_Compatibility_LayerSlider', false ) ) :
class Presscore_Modules_Compatibility_LayerSlider {
public static function execute() {
if ( ! defined( 'LS_PLUGIN_VERSION' ) || ! class_exists( 'UniteBaseClassRev', false ) ) {
return;
}
add_action( 'admin_init', array( __CLASS__, 'set_default_slider_properties_action' ), 9 );
}
public static function set_default_slider_properties_action() {
if ( isset( $_POST['posted_add'] ) && strstr( $_SERVER['REQUEST_URI'], 'layerslider' ) && isset( $_POST['layerslider-slides'] ) ) {
$_POST['layerslider-slides']['properties']['bodyinclude'] = 'on';
}
}
}
Presscore_Modules_Compatibility_LayerSlider::execute();
endif;
|
ZloVolk/TQ
|
wp-content/themes/dt-the7/inc/mods/compatibility/class-compatibility-layerslider.php
|
PHP
|
apache-2.0
| 870
|
/*
* Copyright 2014 Netflix, 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.netflix.spinnaker.cats.redis.cluster;
import com.netflix.spinnaker.cats.agent.Agent;
import com.netflix.spinnaker.cats.agent.AgentExecution;
import com.netflix.spinnaker.cats.agent.AgentLock;
import com.netflix.spinnaker.cats.agent.AgentScheduler;
import com.netflix.spinnaker.cats.agent.AgentSchedulerAware;
import com.netflix.spinnaker.cats.agent.ExecutionInstrumentation;
import com.netflix.spinnaker.cats.module.CatsModuleAware;
import com.netflix.spinnaker.cats.redis.RedisClientDelegate;
import com.netflix.spinnaker.cats.thread.NamedThreadFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
@SuppressFBWarnings
public class ClusteredAgentScheduler extends CatsModuleAware implements AgentScheduler<AgentLock>, Runnable {
private static enum Status {
SUCCESS,
FAILURE
}
private static final Logger logger = LoggerFactory.getLogger(ClusteredAgentScheduler.class);
private final RedisClientDelegate redisClientDelegate;
private final NodeIdentity nodeIdentity;
private final AgentIntervalProvider intervalProvider;
private final ExecutorService agentExecutionPool;
private final Pattern enabledAgentPattern;
private final Map<String, AgentExecutionAction> agents = new ConcurrentHashMap<>();
private final Map<String, NextAttempt> activeAgents = new ConcurrentHashMap<>();
private final NodeStatusProvider nodeStatusProvider;
public ClusteredAgentScheduler(RedisClientDelegate redisClientDelegate,
NodeIdentity nodeIdentity,
AgentIntervalProvider intervalProvider,
NodeStatusProvider nodeStatusProvider,
String enabledAgentPattern) {
this(
redisClientDelegate,
nodeIdentity,
intervalProvider,
nodeStatusProvider,
Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(ClusteredAgentScheduler.class.getSimpleName())),
Executors.newCachedThreadPool(new NamedThreadFactory(AgentExecutionAction.class.getSimpleName())),
enabledAgentPattern
);
}
public ClusteredAgentScheduler(RedisClientDelegate redisClientDelegate,
NodeIdentity nodeIdentity,
AgentIntervalProvider intervalProvider,
NodeStatusProvider nodeStatusProvider,
ScheduledExecutorService lockPollingScheduler,
ExecutorService agentExecutionPool,
String enabledAgentPattern) {
this.redisClientDelegate = redisClientDelegate;
this.nodeIdentity = nodeIdentity;
this.intervalProvider = intervalProvider;
this.nodeStatusProvider = nodeStatusProvider;
this.agentExecutionPool = agentExecutionPool;
this.enabledAgentPattern = Pattern.compile(enabledAgentPattern);
lockPollingScheduler.scheduleAtFixedRate(this, 0, 1, TimeUnit.SECONDS);
}
private Map<String, NextAttempt> acquire() {
Map<String, NextAttempt> acquired = new HashMap<>(agents.size());
Set<String> skip = new HashSet<>(activeAgents.keySet());
for (Map.Entry<String, AgentExecutionAction> agent : agents.entrySet()) {
if (!skip.contains(agent.getKey())) {
final String agentType = agent.getKey();
AgentIntervalProvider.Interval interval = intervalProvider.getInterval(agent.getValue().getAgent());
if (acquireRunKey(agentType, interval.getTimeout())) {
acquired.put(agentType, new NextAttempt(System.currentTimeMillis(), interval.getInterval(), interval.getErrorInterval()));
}
}
}
return acquired;
}
@Override
public void run() {
if (!nodeStatusProvider.isNodeEnabled()) {
return;
}
try {
runAgents();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
private void runAgents() {
Map<String, NextAttempt> thisRun = acquire();
activeAgents.putAll(thisRun);
for (final Map.Entry<String, NextAttempt> toRun : thisRun.entrySet()) {
final AgentExecutionAction exec = agents.get(toRun.getKey());
agentExecutionPool.submit(new AgentJob(toRun.getValue(), exec, this));
}
}
private static final long MIN_TTL_THRESHOLD = 500L;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_EXPIRE_TIME_MILLIS = "PX";
private static final String SUCCESS_RESPONSE = "OK";
private static final Integer DEL_SUCCESS = 1;
private static final String DELETE_LOCK_KEY = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
private static final String TTL_LOCK_KEY = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'PX', ARGV[2], 'XX') else return nil end";
private boolean acquireRunKey(String agentType, long timeout) {
return redisClientDelegate.withCommandsClient(client -> {
String response = client.set(agentType, nodeIdentity.getNodeIdentity(), SET_IF_NOT_EXIST, SET_EXPIRE_TIME_MILLIS, timeout);
return SUCCESS_RESPONSE.equals(response);
});
}
private boolean deleteLock(String agentType) {
return redisClientDelegate.withScriptingClient(client -> {
Object response = client.eval(DELETE_LOCK_KEY, Arrays.asList(agentType), Arrays.asList(nodeIdentity.getNodeIdentity()));
return DEL_SUCCESS.equals(response);
});
}
private boolean ttlLock(String agentType, long newTtl) {
return redisClientDelegate.withScriptingClient(client -> {
Object response = client.eval(TTL_LOCK_KEY, Arrays.asList(agentType), Arrays.asList(nodeIdentity.getNodeIdentity(), Long.toString(newTtl)));
return SUCCESS_RESPONSE.equals(response);
});
}
private void releaseRunKey(String agentType, long when) {
final long newTtl = when - System.currentTimeMillis();
final boolean delete = newTtl < MIN_TTL_THRESHOLD;
if (delete) {
deleteLock(agentType);
} else {
ttlLock(agentType, newTtl);
}
}
private void agentCompleted(String agentType, long nextExecutionTime) {
try {
releaseRunKey(agentType, nextExecutionTime);
} finally {
activeAgents.remove(agentType);
}
}
@Override
public void schedule(Agent agent,
AgentExecution agentExecution,
ExecutionInstrumentation executionInstrumentation) {
if (!enabledAgentPattern.matcher(agent.getClass().getSimpleName().toLowerCase()).matches()) {
logger.debug(
"Agent is not enabled (agent: {}, agentType: {}, pattern: {})",
agent.getClass().getSimpleName(),
agent.getAgentType(),
enabledAgentPattern.pattern()
);
return;
}
if (agent instanceof AgentSchedulerAware) {
((AgentSchedulerAware)agent).setAgentScheduler(this);
}
AgentExecutionAction agentExecutionAction = new AgentExecutionAction(
agent, agentExecution, executionInstrumentation
);
agents.put(agent.getAgentType(), agentExecutionAction);
}
@Override
public void unschedule(Agent agent) {
releaseRunKey(agent.getAgentType(), 0); // Delete lock key now.
agents.remove(agent.getAgentType());
}
private static class NextAttempt {
private final long currentTime;
private final long successInterval;
private final long errorInterval;
public NextAttempt(long currentTime, long successInterval, long errorInterval) {
this.currentTime = currentTime;
this.successInterval = successInterval;
this.errorInterval = errorInterval;
}
public long getNextTime(Status status) {
if (status == Status.SUCCESS) {
return currentTime + successInterval;
}
return currentTime + errorInterval;
}
}
private static class AgentJob implements Runnable {
private final NextAttempt lockReleaseTime;
private final AgentExecutionAction action;
private final ClusteredAgentScheduler scheduler;
public AgentJob(NextAttempt times, AgentExecutionAction action, ClusteredAgentScheduler scheduler) {
this.lockReleaseTime = times;
this.action = action;
this.scheduler = scheduler;
}
@Override
public void run() {
Status status = Status.FAILURE;
try {
status = action.execute();
} finally {
scheduler.agentCompleted(action.getAgent().getAgentType(), lockReleaseTime.getNextTime(status));
}
}
}
private static class AgentExecutionAction {
private final Agent agent;
private final AgentExecution agentExecution;
private final ExecutionInstrumentation executionInstrumentation;
public AgentExecutionAction(Agent agent, AgentExecution agentExecution, ExecutionInstrumentation executionInstrumentation) {
this.agent = agent;
this.agentExecution = agentExecution;
this.executionInstrumentation = executionInstrumentation;
}
public Agent getAgent() {
return agent;
}
Status execute() {
try {
executionInstrumentation.executionStarted(agent);
long startTime = System.nanoTime();
agentExecution.executeAgent(agent);
executionInstrumentation.executionCompleted(agent, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
return Status.SUCCESS;
} catch (Throwable cause) {
executionInstrumentation.executionFailed(agent, cause);
return Status.FAILURE;
}
}
}
}
|
cfieber/clouddriver
|
cats/cats-redis/src/main/java/com/netflix/spinnaker/cats/redis/cluster/ClusteredAgentScheduler.java
|
Java
|
apache-2.0
| 11,353
|
/*
* The MIT License
*
* Copyright (c) 2011 Takahiro Hashimoto
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.taobao.api.internal.toplink.embedded.websocket.auth;
import com.taobao.api.internal.toplink.embedded.websocket.HttpHeader;
import com.taobao.api.internal.toplink.embedded.websocket.WebSocket;
import com.taobao.api.internal.toplink.embedded.websocket.exception.WebSocketException;
/**
* The Interface of ProxyCredentials.
*
* @author t-hashimoto
*/
public interface Authenticator {
/**
* Gets the credentials.
*
* @param method request method GET,POST,CONNECT(proxy)
* @param requestUri the request uri
* @param header http header
* @param authenticateHeaderName the authenticate header name
* @return the credentials
* @throws WebSocketException the web socket exception
*/
public String getCredentials(String method, String requestUri, HttpHeader header, String authenticateHeaderName) throws WebSocketException;
/**
* inits authenticator
*
* @param websocket the websocket
* @param credentials the credentials
*/
public void init(WebSocket websocket, Credentials credentials);
/**
* finish authenticate phase.
* if retry authenticate, need to create a new Authenticator instance.
*/
public void done();
public boolean isNeedAuthenticate();
public boolean isDone();
}
|
exercisecode/alidayu_demo
|
alidayu/src/main/java/com/taobao/api/internal/toplink/embedded/websocket/auth/Authenticator.java
|
Java
|
apache-2.0
| 2,469
|
/*
* 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.camel.component.seda;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.camel.AsyncCallback;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangeTimedOutException;
import org.apache.camel.ExtendedExchange;
import org.apache.camel.WaitForTaskToComplete;
import org.apache.camel.support.DefaultAsyncProducer;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.support.SynchronizationAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SedaProducer extends DefaultAsyncProducer {
private static final Logger LOG = LoggerFactory.getLogger(SedaProducer.class);
private final SedaEndpoint endpoint;
private final WaitForTaskToComplete waitForTaskToComplete;
private final long timeout;
private final boolean blockWhenFull;
private final boolean discardWhenFull;
private final long offerTimeout;
public SedaProducer(SedaEndpoint endpoint, WaitForTaskToComplete waitForTaskToComplete,
long timeout, boolean blockWhenFull, boolean discardWhenFull, long offerTimeout) {
super(endpoint);
this.endpoint = endpoint;
this.waitForTaskToComplete = waitForTaskToComplete;
this.timeout = timeout;
this.blockWhenFull = blockWhenFull;
this.discardWhenFull = discardWhenFull;
this.offerTimeout = offerTimeout;
}
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
WaitForTaskToComplete wait = waitForTaskToComplete;
if (exchange.getProperty(Exchange.ASYNC_WAIT) != null) {
wait = exchange.getProperty(Exchange.ASYNC_WAIT, WaitForTaskToComplete.class);
}
if (wait == WaitForTaskToComplete.Always
|| (wait == WaitForTaskToComplete.IfReplyExpected && ExchangeHelper.isOutCapable(exchange))) {
// do not handover the completion as we wait for the copy to complete, and copy its result back when it done
Exchange copy = prepareCopy(exchange, false);
// latch that waits until we are complete
final CountDownLatch latch = new CountDownLatch(1);
// we should wait for the reply so install a on completion so we know when its complete
copy.adapt(ExtendedExchange.class).addOnCompletion(new SynchronizationAdapter() {
@Override
public void onDone(Exchange response) {
// check for timeout, which then already would have invoked the latch
if (latch.getCount() == 0) {
if (LOG.isTraceEnabled()) {
LOG.trace("{}. Timeout occurred so response will be ignored: {}", this, response.getMessage());
}
return;
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("{} with response: {}", this, response.getMessage());
}
try {
ExchangeHelper.copyResults(exchange, response);
} finally {
// always ensure latch is triggered
latch.countDown();
}
}
}
@Override
public boolean allowHandover() {
// do not allow handover as we want to seda producer to have its completion triggered
// at this point in the routing (at this leg), instead of at the very last (this ensure timeout is honored)
return false;
}
@Override
public String toString() {
return "onDone at endpoint: " + endpoint;
}
});
try {
// do not copy as we already did the copy
addToQueue(copy, false);
} catch (SedaConsumerNotAvailableException e) {
exchange.setException(e);
callback.done(true);
return true;
}
if (timeout > 0) {
if (LOG.isTraceEnabled()) {
LOG.trace("Waiting for task to complete using timeout (ms): {} at [{}]", timeout,
endpoint.getEndpointUri());
}
// lets see if we can get the task done before the timeout
boolean done = false;
try {
done = latch.await(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// ignore
}
if (!done) {
exchange.setException(new ExchangeTimedOutException(exchange, timeout));
// remove timed out Exchange from queue
endpoint.getQueue().remove(copy);
// count down to indicate timeout
latch.countDown();
}
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Waiting for task to complete (blocking) at [{}]", endpoint.getEndpointUri());
}
// no timeout then wait until its done
try {
latch.await();
} catch (InterruptedException e) {
// ignore
}
}
} else {
// no wait, eg its a InOnly then just add to queue and return
try {
addToQueue(exchange, true);
} catch (SedaConsumerNotAvailableException e) {
exchange.setException(e);
callback.done(true);
return true;
}
}
// we use OnCompletion on the Exchange to callback and wait for the Exchange to be done
// so we should just signal the callback we are done synchronously
callback.done(true);
return true;
}
protected Exchange prepareCopy(Exchange exchange, boolean handover) {
// use a new copy of the exchange to route async (and use same message id)
// if handover we need to do special handover to avoid handing over
// RestBindingMarshalOnCompletion as it should not be handed over with SEDA
Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, handover, true,
synchronization -> !synchronization.getClass().getName().contains("RestBindingMarshalOnCompletion"));
return copy;
}
@Override
protected void doStart() throws Exception {
super.doStart();
endpoint.onStarted(this);
}
@Override
protected void doStop() throws Exception {
endpoint.onStopped(this);
super.doStop();
}
/**
* Strategy method for adding the exchange to the queue.
* <p>
* Will perform a blocking "put" if blockWhenFull is true, otherwise it will simply add which will throw exception
* if the queue is full
*
* @param exchange the exchange to add to the queue
* @param copy whether to create a copy of the exchange to use for adding to the queue
*/
protected void addToQueue(Exchange exchange, boolean copy) throws SedaConsumerNotAvailableException {
BlockingQueue<Exchange> queue = null;
QueueReference queueReference = endpoint.getQueueReference();
if (queueReference != null) {
queue = queueReference.getQueue();
}
if (queue == null) {
throw new SedaConsumerNotAvailableException("No queue available on endpoint: " + endpoint, exchange);
}
boolean empty = !queueReference.hasConsumers();
if (empty) {
if (endpoint.isFailIfNoConsumers()) {
throw new SedaConsumerNotAvailableException("No consumers available on endpoint: " + endpoint, exchange);
} else if (endpoint.isDiscardIfNoConsumers()) {
LOG.debug("Discard message as no active consumers on endpoint: {}", endpoint);
return;
}
}
Exchange target = exchange;
// handover the completion so its the copy which performs that, as we do not wait
if (copy) {
target = prepareCopy(exchange, true);
}
LOG.trace("Adding Exchange to queue: {}", target);
if (discardWhenFull) {
try {
boolean added = queue.offer(target, 0, TimeUnit.MILLISECONDS);
if (!added) {
LOG.trace("Discarding Exchange as queue is full: {}", target);
}
} catch (InterruptedException e) {
// ignore
LOG.debug("Offer interrupted, are we stopping? {}", isStopping() || isStopped());
}
} else if (blockWhenFull && offerTimeout == 0) {
try {
queue.put(target);
} catch (InterruptedException e) {
// ignore
LOG.debug("Put interrupted, are we stopping? {}", isStopping() || isStopped());
}
} else if (blockWhenFull && offerTimeout > 0) {
try {
boolean added = queue.offer(target, offerTimeout, TimeUnit.MILLISECONDS);
if (!added) {
throw new IllegalStateException(
"Fails to insert element into queue, "
+ "after timeout of " + offerTimeout + " milliseconds");
}
} catch (InterruptedException e) {
// ignore
LOG.debug("Offer interrupted, are we stopping? {}", isStopping() || isStopped());
}
} else {
queue.add(target);
}
}
}
|
nikhilvibhav/camel
|
components/camel-seda/src/main/java/org/apache/camel/component/seda/SedaProducer.java
|
Java
|
apache-2.0
| 10,784
|
package org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
/**
* This represents a destination to a page at an x,y coordinate with a zoom setting.
* The default x,y,z will be whatever is the current value in the viewer application and
* are not required.
*
* @author Ben Litchfield
*/
public class PDPageXYZDestination extends PDPageDestination
{
/**
* The type of this destination.
*/
protected static final String TYPE = "XYZ";
/**
* Default constructor.
*
*/
public PDPageXYZDestination()
{
super();
array.growToSize(5);
array.setName( 1, TYPE );
}
/**
* Constructor from an existing destination array.
*
* @param arr The destination array.
*/
public PDPageXYZDestination( COSArray arr )
{
super( arr );
}
/**
* Get the left x coordinate. A return value of -1 implies that the current x-coordinate
* will be used.
*
* @return The left x coordinate.
*/
public int getLeft()
{
return array.getInt( 2 );
}
/**
* Set the left x-coordinate, a value of -1 implies that the current x-coordinate
* will be used.
* @param x The left x coordinate.
*/
public void setLeft( int x )
{
array.growToSize( 3 );
if( x == -1 )
{
array.set( 2, (COSBase)null );
}
else
{
array.setInt( 2, x );
}
}
/**
* Get the top y coordinate. A return value of -1 implies that the current y-coordinate
* will be used.
*
* @return The top y coordinate.
*/
public int getTop()
{
return array.getInt( 3 );
}
/**
* Set the top y-coordinate, a value of -1 implies that the current y-coordinate
* will be used.
* @param y The top ycoordinate.
*/
public void setTop( int y )
{
array.growToSize( 4 );
if( y == -1 )
{
array.set( 3, (COSBase)null );
}
else
{
array.setInt( 3, y );
}
}
/**
* Get the zoom value. A return value of -1 implies that the current zoom
* will be used.
*
* @return The zoom value for the page.
*/
public int getZoom()
{
return array.getInt( 4 );
}
/**
* Set the zoom value for the page, a value of -1 implies that the current zoom
* will be used.
* @param zoom The zoom value.
*/
public void setZoom( int zoom )
{
array.growToSize( 5 );
if( zoom == -1 )
{
array.set( 4, (COSBase)null );
}
else
{
array.setInt( 4, zoom );
}
}
}
|
mdamt/PdfBox-Android
|
library/src/main/java/org/apache/pdfbox/pdmodel/interactive/documentnavigation/destination/PDPageXYZDestination.java
|
Java
|
apache-2.0
| 2,967
|
<!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_45) on Thu Oct 13 19:29:17 UTC 2016 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class liquibase.diff.output.changelog.core.UnexpectedSequenceChangeGenerator (Liquibase Core 3.5.3 API)
</TITLE>
<META NAME="date" CONTENT="2016-10-13">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class liquibase.diff.output.changelog.core.UnexpectedSequenceChangeGenerator (Liquibase Core 3.5.3 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../liquibase/diff/output/changelog/core/UnexpectedSequenceChangeGenerator.html" title="class in liquibase.diff.output.changelog.core"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?liquibase/diff/output/changelog/core//class-useUnexpectedSequenceChangeGenerator.html" target="_top"><B>FRAMES</B></A>
<A HREF="UnexpectedSequenceChangeGenerator.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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>liquibase.diff.output.changelog.core.UnexpectedSequenceChangeGenerator</B></H2>
</CENTER>
No usage of liquibase.diff.output.changelog.core.UnexpectedSequenceChangeGenerator
<P>
<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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../liquibase/diff/output/changelog/core/UnexpectedSequenceChangeGenerator.html" title="class in liquibase.diff.output.changelog.core"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?liquibase/diff/output/changelog/core//class-useUnexpectedSequenceChangeGenerator.html" target="_top"><B>FRAMES</B></A>
<A HREF="UnexpectedSequenceChangeGenerator.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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2016 <a href="http://www.liquibase.org">Liquibase.org</a>. All rights reserved.
</BODY>
</HTML>
|
ErpMicroServices/party-database
|
liquibase-3.5.3-bin/sdk/javadoc/liquibase/diff/output/changelog/core/class-use/UnexpectedSequenceChangeGenerator.html
|
HTML
|
apache-2.0
| 6,525
|
package checkpoints_test
import (
"context"
"path/filepath"
"sort"
"testing"
. "github.com/pingcap/check"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/br/pkg/lightning/checkpoints"
"github.com/pingcap/tidb/br/pkg/lightning/config"
"github.com/pingcap/tidb/br/pkg/lightning/mydump"
"github.com/pingcap/tidb/br/pkg/lightning/verification"
)
func Test(t *testing.T) {
TestingT(t)
}
var _ = Suite(&cpFileSuite{})
type cpFileSuite struct {
cpdb *checkpoints.FileCheckpointsDB
}
func newTestConfig() *config.Config {
cfg := config.NewConfig()
cfg.Mydumper.SourceDir = "/data"
cfg.TaskID = 123
cfg.TiDB.Port = 4000
cfg.TiDB.PdAddr = "127.0.0.1:2379"
cfg.TikvImporter.Backend = config.BackendLocal
cfg.TikvImporter.Addr = "127.0.0.1:8287"
cfg.TikvImporter.SortedKVDir = "/tmp/sorted-kv"
return cfg
}
func (s *cpFileSuite) SetUpTest(c *C) {
dir := c.MkDir()
s.cpdb = checkpoints.NewFileCheckpointsDB(filepath.Join(dir, "cp.pb"))
ctx := context.Background()
cpdb := s.cpdb
// 2. initialize with checkpoint data.
cfg := newTestConfig()
err := cpdb.Initialize(ctx, cfg, map[string]*checkpoints.TidbDBInfo{
"db1": {
Name: "db1",
Tables: map[string]*checkpoints.TidbTableInfo{
"t1": {Name: "t1"},
"t2": {Name: "t2"},
},
},
"db2": {
Name: "db2",
Tables: map[string]*checkpoints.TidbTableInfo{
"t3": {Name: "t3"},
},
},
})
c.Assert(err, IsNil)
// 3. set some checkpoints
err = cpdb.InsertEngineCheckpoints(ctx, "`db1`.`t2`", map[int32]*checkpoints.EngineCheckpoint{
0: {
Status: checkpoints.CheckpointStatusLoaded,
Chunks: []*checkpoints.ChunkCheckpoint{{
Key: checkpoints.ChunkCheckpointKey{
Path: "/tmp/path/1.sql",
Offset: 0,
},
FileMeta: mydump.SourceFileMeta{
Path: "/tmp/path/1.sql",
Type: mydump.SourceTypeSQL,
FileSize: 12345,
},
Chunk: mydump.Chunk{
Offset: 12,
EndOffset: 102400,
PrevRowIDMax: 1,
RowIDMax: 5000,
},
}},
},
-1: {
Status: checkpoints.CheckpointStatusLoaded,
Chunks: nil,
},
})
c.Assert(err, IsNil)
err = cpdb.InsertEngineCheckpoints(ctx, "`db2`.`t3`", map[int32]*checkpoints.EngineCheckpoint{
-1: {
Status: checkpoints.CheckpointStatusLoaded,
Chunks: nil,
},
})
c.Assert(err, IsNil)
// 4. update some checkpoints
cpd := checkpoints.NewTableCheckpointDiff()
scm := checkpoints.StatusCheckpointMerger{
EngineID: 0,
Status: checkpoints.CheckpointStatusImported,
}
scm.MergeInto(cpd)
scm = checkpoints.StatusCheckpointMerger{
EngineID: checkpoints.WholeTableEngineID,
Status: checkpoints.CheckpointStatusAllWritten,
}
scm.MergeInto(cpd)
rcm := checkpoints.RebaseCheckpointMerger{
AllocBase: 132861,
}
rcm.MergeInto(cpd)
cksum := checkpoints.TableChecksumMerger{
Checksum: verification.MakeKVChecksum(4492, 686, 486070148910),
}
cksum.MergeInto(cpd)
ccm := checkpoints.ChunkCheckpointMerger{
EngineID: 0,
Key: checkpoints.ChunkCheckpointKey{Path: "/tmp/path/1.sql", Offset: 0},
Checksum: verification.MakeKVChecksum(4491, 586, 486070148917),
Pos: 55904,
RowID: 681,
}
ccm.MergeInto(cpd)
cpdb.Update(map[string]*checkpoints.TableCheckpointDiff{"`db1`.`t2`": cpd})
}
func (s *cpFileSuite) TearDownTest(c *C) {
c.Assert(s.cpdb.Close(), IsNil)
}
func (s *cpFileSuite) setInvalidStatus() {
cpd := checkpoints.NewTableCheckpointDiff()
scm := checkpoints.StatusCheckpointMerger{
EngineID: -1,
Status: checkpoints.CheckpointStatusAllWritten,
}
scm.SetInvalid()
scm.MergeInto(cpd)
s.cpdb.Update(map[string]*checkpoints.TableCheckpointDiff{
"`db1`.`t2`": cpd,
"`db2`.`t3`": cpd,
})
}
func (s *cpFileSuite) TestGet(c *C) {
ctx := context.Background()
// 5. get back the checkpoints
cp, err := s.cpdb.Get(ctx, "`db1`.`t2`")
c.Assert(err, IsNil)
c.Assert(cp, DeepEquals, &checkpoints.TableCheckpoint{
Status: checkpoints.CheckpointStatusAllWritten,
AllocBase: 132861,
Checksum: verification.MakeKVChecksum(4492, 686, 486070148910),
Engines: map[int32]*checkpoints.EngineCheckpoint{
-1: {
Status: checkpoints.CheckpointStatusLoaded,
Chunks: []*checkpoints.ChunkCheckpoint{},
},
0: {
Status: checkpoints.CheckpointStatusImported,
Chunks: []*checkpoints.ChunkCheckpoint{{
Key: checkpoints.ChunkCheckpointKey{
Path: "/tmp/path/1.sql",
Offset: 0,
},
FileMeta: mydump.SourceFileMeta{
Path: "/tmp/path/1.sql",
Type: mydump.SourceTypeSQL,
FileSize: 12345,
},
ColumnPermutation: []int{},
Chunk: mydump.Chunk{
Offset: 55904,
EndOffset: 102400,
PrevRowIDMax: 681,
RowIDMax: 5000,
},
Checksum: verification.MakeKVChecksum(4491, 586, 486070148917),
}},
},
},
})
cp, err = s.cpdb.Get(ctx, "`db2`.`t3`")
c.Assert(err, IsNil)
c.Assert(cp, DeepEquals, &checkpoints.TableCheckpoint{
Status: checkpoints.CheckpointStatusLoaded,
Engines: map[int32]*checkpoints.EngineCheckpoint{
-1: {
Status: checkpoints.CheckpointStatusLoaded,
Chunks: []*checkpoints.ChunkCheckpoint{},
},
},
})
cp, err = s.cpdb.Get(ctx, "`db3`.`not-exists`")
c.Assert(cp, IsNil)
c.Assert(errors.IsNotFound(err), IsTrue)
}
func (s *cpFileSuite) TestRemoveAllCheckpoints(c *C) {
ctx := context.Background()
err := s.cpdb.RemoveCheckpoint(ctx, "all")
c.Assert(err, IsNil)
cp, err := s.cpdb.Get(ctx, "`db1`.`t2`")
c.Assert(cp, IsNil)
c.Assert(errors.IsNotFound(err), IsTrue)
cp, err = s.cpdb.Get(ctx, "`db2`.`t3`")
c.Assert(cp, IsNil)
c.Assert(errors.IsNotFound(err), IsTrue)
}
func (s *cpFileSuite) TestRemoveOneCheckpoint(c *C) {
ctx := context.Background()
err := s.cpdb.RemoveCheckpoint(ctx, "`db1`.`t2`")
c.Assert(err, IsNil)
cp, err := s.cpdb.Get(ctx, "`db1`.`t2`")
c.Assert(cp, IsNil)
c.Assert(errors.IsNotFound(err), IsTrue)
cp, err = s.cpdb.Get(ctx, "`db2`.`t3`")
c.Assert(err, IsNil)
c.Assert(cp.Status, Equals, checkpoints.CheckpointStatusLoaded)
}
func (s *cpFileSuite) TestIgnoreAllErrorCheckpoints(c *C) {
ctx := context.Background()
s.setInvalidStatus()
err := s.cpdb.IgnoreErrorCheckpoint(ctx, "all")
c.Assert(err, IsNil)
cp, err := s.cpdb.Get(ctx, "`db1`.`t2`")
c.Assert(err, IsNil)
c.Assert(cp.Status, Equals, checkpoints.CheckpointStatusLoaded)
cp, err = s.cpdb.Get(ctx, "`db2`.`t3`")
c.Assert(err, IsNil)
c.Assert(cp.Status, Equals, checkpoints.CheckpointStatusLoaded)
}
func (s *cpFileSuite) TestIgnoreOneErrorCheckpoints(c *C) {
ctx := context.Background()
s.setInvalidStatus()
err := s.cpdb.IgnoreErrorCheckpoint(ctx, "`db1`.`t2`")
c.Assert(err, IsNil)
cp, err := s.cpdb.Get(ctx, "`db1`.`t2`")
c.Assert(err, IsNil)
c.Assert(cp.Status, Equals, checkpoints.CheckpointStatusLoaded)
cp, err = s.cpdb.Get(ctx, "`db2`.`t3`")
c.Assert(err, IsNil)
c.Assert(cp.Status, Equals, checkpoints.CheckpointStatusAllWritten/10)
}
func (s *cpFileSuite) TestDestroyAllErrorCheckpoints(c *C) {
ctx := context.Background()
s.setInvalidStatus()
dtc, err := s.cpdb.DestroyErrorCheckpoint(ctx, "all")
c.Assert(err, IsNil)
sort.Slice(dtc, func(i, j int) bool { return dtc[i].TableName < dtc[j].TableName })
c.Assert(dtc, DeepEquals, []checkpoints.DestroyedTableCheckpoint{
{
TableName: "`db1`.`t2`",
MinEngineID: -1,
MaxEngineID: 0,
},
{
TableName: "`db2`.`t3`",
MinEngineID: -1,
MaxEngineID: -1,
},
})
cp, err := s.cpdb.Get(ctx, "`db1`.`t2`")
c.Assert(cp, IsNil)
c.Assert(errors.IsNotFound(err), IsTrue)
cp, err = s.cpdb.Get(ctx, "`db2`.`t3`")
c.Assert(cp, IsNil)
c.Assert(errors.IsNotFound(err), IsTrue)
}
func (s *cpFileSuite) TestDestroyOneErrorCheckpoint(c *C) {
ctx := context.Background()
s.setInvalidStatus()
dtc, err := s.cpdb.DestroyErrorCheckpoint(ctx, "`db1`.`t2`")
c.Assert(err, IsNil)
c.Assert(dtc, DeepEquals, []checkpoints.DestroyedTableCheckpoint{
{
TableName: "`db1`.`t2`",
MinEngineID: -1,
MaxEngineID: 0,
},
})
cp, err := s.cpdb.Get(ctx, "`db1`.`t2`")
c.Assert(cp, IsNil)
c.Assert(errors.IsNotFound(err), IsTrue)
cp, err = s.cpdb.Get(ctx, "`db2`.`t3`")
c.Assert(err, IsNil)
c.Assert(cp.Status, Equals, checkpoints.CheckpointStatusAllWritten/10)
}
|
coocood/tidb
|
br/pkg/lightning/checkpoints/checkpoints_file_test.go
|
GO
|
apache-2.0
| 8,239
|
// Copyright 2010 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.
// This code was generated by google-apis-code-generator 1.5.1
// C++ generator version: 0.1.3
// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
// YouTube Data API (youtube/v3)
// Generated from:
// Version: v3
// Generated by:
// Tool: google-apis-code-generator 1.5.1
// C++: 0.1.3
#ifndef GOOGLE_YOUTUBE_API_VIDEO_CONVERSION_PINGS_H_
#define GOOGLE_YOUTUBE_API_VIDEO_CONVERSION_PINGS_H_
#include "googleapis/base/macros.h"
#include "googleapis/client/data/jsoncpp_data.h"
#include "googleapis/strings/stringpiece.h"
#include "google/youtube_api/video_conversion_ping.h"
namespace Json {
class Value;
} // namespace Json
namespace google_youtube_api {
using namespace googleapis;
/**
* No description provided.
*
* @ingroup DataObject
*/
class VideoConversionPings : public client::JsonCppData {
public:
/**
* Creates a new default instance.
*
* @return Ownership is passed back to the caller.
*/
static VideoConversionPings* New();
/**
* Standard constructor for an immutable data object instance.
*
* @param[in] storage The underlying data storage for this instance.
*/
explicit VideoConversionPings(const Json::Value& storage);
/**
* Standard constructor for a mutable data object instance.
*
* @param[in] storage The underlying data storage for this instance.
*/
explicit VideoConversionPings(Json::Value* storage);
/**
* Standard destructor.
*/
virtual ~VideoConversionPings();
/**
* Returns a string denoting the type of this data object.
*
* @return <code>google_youtube_api::VideoConversionPings</code>
*/
const StringPiece GetTypeName() const {
return StringPiece("google_youtube_api::VideoConversionPings");
}
/**
* Determine if the '<code>pings</code>' attribute was set.
*
* @return true if the '<code>pings</code>' attribute was set.
*/
bool has_pings() const {
return Storage().isMember("pings");
}
/**
* Clears the '<code>pings</code>' attribute.
*/
void clear_pings() {
MutableStorage()->removeMember("pings");
}
/**
* Get a reference to the value of the '<code>pings</code>' attribute.
*/
const client::JsonCppArray<VideoConversionPing > get_pings() const;
/**
* Gets a reference to a mutable value of the '<code>pings</code>' property.
*
* Pings that the app shall fire for a video (authenticated by biscotti
* cookie). Each ping has a context, in which the app must fire the ping, and
* a url identifying the ping.
*
* @return The result can be modified to change the attribute value.
*/
client::JsonCppArray<VideoConversionPing > mutable_pings();
private:
void operator=(const VideoConversionPings&);
}; // VideoConversionPings
} // namespace google_youtube_api
#endif // GOOGLE_YOUTUBE_API_VIDEO_CONVERSION_PINGS_H_
|
rcari/google-api-cpp-client
|
service_apis/youtube/google/youtube_api/video_conversion_pings.h
|
C
|
apache-2.0
| 3,536
|
/*
* Copyright [2005] [University Corporation for Advanced Internet Development, 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 org.opensaml.saml2.metadata.validator;
import org.opensaml.saml2.metadata.AdditionalMetadataLocation;
import org.opensaml.xml.util.DatatypeHelper;
import org.opensaml.xml.validation.ValidationException;
import org.opensaml.xml.validation.Validator;
/**
* Checks {@link org.opensaml.saml2.metadata.AdditionalMetadataLocation} for Schema compliance.
*/
public class AdditionalMetadataLocationSchemaValidator implements Validator<AdditionalMetadataLocation> {
/** Constructor */
public AdditionalMetadataLocationSchemaValidator() {
}
/** {@inheritDoc} */
public void validate(AdditionalMetadataLocation aml) throws ValidationException {
validateLocation(aml);
validateNamespace(aml);
}
/**
* Checks that Location is present.
*
* @param aml
* @throws ValidationException
*/
protected void validateLocation(AdditionalMetadataLocation aml) throws ValidationException {
if (DatatypeHelper.isEmpty(aml.getLocationURI())) {
throw new ValidationException("Location required");
}
}
/**
* Checks that Namespace is present.
*
* @param aml
* @throws ValidationException
*/
protected void validateNamespace(AdditionalMetadataLocation aml) throws ValidationException {
if (DatatypeHelper.isEmpty(aml.getNamespaceURI())) {
throw new ValidationException("Namespace required");
}
}
}
|
danpal/OpenSAML
|
src/main/java/org/opensaml/saml2/metadata/validator/AdditionalMetadataLocationSchemaValidator.java
|
Java
|
apache-2.0
| 2,113
|
<?php
final class ReleephIntentFieldSpecification
extends ReleephFieldSpecification {
public function getName() {
return 'Intent';
}
public function renderValueForHeaderView() {
return id(new ReleephRequestIntentsView())
->setReleephRequest($this->getReleephRequest())
->setReleephProject($this->getReleephProject())
->render();
}
public function shouldAppearOnCommitMessage() {
return true;
}
public function shouldAppearOnRevertMessage() {
return true;
}
public function renderLabelForCommitMessage() {
return "Approved By";
}
public function renderLabelForRevertMessage() {
return "Rejected By";
}
public function renderValueForCommitMessage() {
return $this->renderIntentsForCommitMessage(ReleephRequest::INTENT_WANT);
}
public function renderValueForRevertMessage() {
return $this->renderIntentsForCommitMessage(ReleephRequest::INTENT_PASS);
}
private function renderIntentsForCommitMessage($print_intent) {
$intents = $this->getReleephRequest()->getUserIntents();
$requestor = $this->getReleephRequest()->getRequestUserPHID();
$pusher_phids = $this->getReleephProject()->getPushers();
$phids = array_unique($pusher_phids + array_keys($intents));
$handles = id(new PhabricatorObjectHandleData($phids))
->setViewer($this->getUser())
->loadHandles();
$tokens = array();
foreach ($phids as $phid) {
$intent = idx($intents, $phid);
if ($intent == $print_intent) {
$name = $handles[$phid]->getName();
$is_pusher = in_array($phid, $pusher_phids);
$is_requestor = $phid == $requestor;
if ($is_pusher) {
if ($is_requestor) {
$token = "{$name} (pusher and requestor)";
} else {
$token = "{$name} (pusher)";
}
} else {
if ($is_requestor) {
$token = "{$name} (requestor)";
} else {
$token = $name;
}
}
$tokens[] = $token;
}
}
return implode(', ', $tokens);
}
}
|
apexstudios/phabricator
|
src/applications/releeph/field/specification/ReleephIntentFieldSpecification.php
|
PHP
|
apache-2.0
| 2,090
|
package com.ai.st.at;
public class DemoProviderbClientApplication {
public static void main(String[] args) {
}
}
|
01Studios/traffic
|
demo-providerb/demo-providerb-client/src/main/java/com/ai/st/at/DemoProviderbClientApplication.java
|
Java
|
apache-2.0
| 117
|
from __future__ import absolute_import
from collections import namedtuple
# Other useful structs
TopicPartition = namedtuple("TopicPartition",
["topic", "partition"])
BrokerMetadata = namedtuple("BrokerMetadata",
["nodeId", "host", "port", "rack"])
PartitionMetadata = namedtuple("PartitionMetadata",
["topic", "partition", "leader", "replicas", "isr", "error"])
OffsetAndMetadata = namedtuple("OffsetAndMetadata",
# TODO add leaderEpoch: OffsetAndMetadata(offset, leaderEpoch, metadata)
["offset", "metadata"])
OffsetAndTimestamp = namedtuple("OffsetAndTimestamp",
["offset", "timestamp"])
# Define retry policy for async producer
# Limit value: int >= 0, 0 means no retries
RetryOptions = namedtuple("RetryOptions",
["limit", "backoff_ms", "retry_on_timeouts"])
|
mumrah/kafka-python
|
kafka/structs.py
|
Python
|
apache-2.0
| 801
|
package Paws::OpsWorks::ListTagsResult;
use Moose;
has NextToken => (is => 'ro', isa => 'Str');
has Tags => (is => 'ro', isa => 'Paws::OpsWorks::Tags');
has _request_id => (is => 'ro', isa => 'Str');
### main pod documentation begin ###
=head1 NAME
Paws::OpsWorks::ListTagsResult
=head1 ATTRIBUTES
=head2 NextToken => Str
If a paginated request does not return all of the remaining results,
this parameter is set to a token that you can assign to the request
object's C<NextToken> parameter to get the next set of results. If the
previous paginated request returned all of the remaining results, this
parameter is set to C<null>.
=head2 Tags => L<Paws::OpsWorks::Tags>
A set of key-value pairs that contain tag keys and tag values that are
attached to a stack or layer.
=head2 _request_id => Str
=cut
1;
|
ioanrogers/aws-sdk-perl
|
auto-lib/Paws/OpsWorks/ListTagsResult.pm
|
Perl
|
apache-2.0
| 828
|
require 'rails_helper'
RSpec.describe GooddataProject, :type => :model do
before { @gooddata_project = FactoryGirl.create(:gooddata_project) }
subject { @gooddata_project }
it { should respond_to(:name) }
it { should validate_uniqueness_of(:name) }
it { should validate_presence_of(:name) }
it { should respond_to(:project_uid) }
it { should respond_to(:client) }
it { should be_valid }
it { should belong_to(:client) }
it { should allow_value('fe2grfsh5vh25kwm69zd3nhzki1cecyc').for(:project_uid) }
it { should_not allow_value('fe2grfsh5vh25k-m69zd3nhzki1cecyc').for(:project_uid) }
it { should_not allow_value('fe2grfsh5vh25kzki1cecyc').for(:project_uid) }
it { should_not allow_value('').for(:project_uid) }
it { should_not allow_value(nil).for(:project_uid) }
end
|
greatvines/amylase
|
spec/models/gooddata_project_spec.rb
|
Ruby
|
apache-2.0
| 800
|
/**
* @ngdoc directive
* @memberof ngMap
* @name ng-map
* @param Attr2Options {service}
* convert html attribute to Gogole map api options
* @description
* Implementation of {@link __MapController}
* Initialize a Google map within a `<div>` tag
* with given options and register events
*
* @attr {Expression} map-initialized
* callback function when map is initialized
* e.g., map-initialized="mycallback(map)"
* @attr {Expression} geo-callback if center is an address or current location,
* the expression is will be executed when geo-lookup is successful.
* e.g., geo-callback="showMyStoreInfo()"
* @attr {Array} geo-fallback-center
* The center of map incase geolocation failed. i.e. [0,0]
* @attr {Object} geo-location-options
* The navigator geolocation options.
* e.g., { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }.
* If none specified, { timeout: 5000 }.
* If timeout not specified, timeout: 5000 added
* @attr {Boolean} zoom-to-include-markers
* When true, map boundary will be changed automatially
* to include all markers when initialized
* @attr {Boolean} default-style
* When false, the default styling,
* `display:block;height:300px`, will be ignored.
* @attr {String} <MapOption> Any Google map options,
* https://developers.google.com/maps/documentation/javascript/reference?csw=1#MapOptions
* @attr {String} <MapEvent> Any Google map events,
* https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/map_events.html
* @attr {Boolean} single-info-window
* When true the map will only display one info window at the time,
* if not set or false,
* everytime an info window is open it will be displayed with the othe one.
* @example
* Usage:
* <map MAP_OPTIONS_OR_MAP_EVENTS ..>
* ... Any children directives
* </map>
*
* Example:
* <map center="[40.74, -74.18]" on-click="doThat()">
* </map>
*
* <map geo-fallback-center="[40.74, -74.18]" zoom-to-inlude-markers="true">
* </map>
*/
(function () {
'use strict';
var mapDirective = function () {
return {
restrict: 'AE',
controller: '__MapController',
conrollerAs: 'ngmap'
};
};
angular.module('ngMap').directive('map', [mapDirective]);
angular.module('ngMap').directive('ngMap', [mapDirective]);
})();
|
alejandromartincruz/codingtogether
|
vendor/assets/bower_components/ngmap/directives/map.js
|
JavaScript
|
apache-2.0
| 2,327
|
<!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_26) on Wed Oct 03 05:15:38 UTC 2012 -->
<TITLE>
Uses of Class org.apache.hadoop.record.compiler.JFile (Hadoop 1.0.4 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-03">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.record.compiler.JFile (Hadoop 1.0.4 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/record/compiler//class-useJFile.html" target="_top"><B>FRAMES</B></A>
<A HREF="JFile.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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.record.compiler.JFile</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.record.compiler"><B>org.apache.hadoop.record.compiler</B></A></TD>
<TD>This package contains classes needed for code generation
from the hadoop record compiler. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.record.compiler.generated"><B>org.apache.hadoop.record.compiler.generated</B></A></TD>
<TD>This package contains code generated by JavaCC from the
Hadoop record syntax file rcc.jj. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.record.compiler"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A> in <A HREF="../../../../../../org/apache/hadoop/record/compiler/package-summary.html">org.apache.hadoop.record.compiler</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructor parameters in <A HREF="../../../../../../org/apache/hadoop/record/compiler/package-summary.html">org.apache.hadoop.record.compiler</A> with type arguments of type <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html#JFile(java.lang.String, java.util.ArrayList, java.util.ArrayList)">JFile</A></B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> name,
<A HREF="http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html?is-external=true" title="class or interface in java.util">ArrayList</A><<A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A>> inclFiles,
<A HREF="http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html?is-external=true" title="class or interface in java.util">ArrayList</A><<A HREF="../../../../../../org/apache/hadoop/record/compiler/JRecord.html" title="class in org.apache.hadoop.record.compiler">JRecord</A>> recList)</CODE>
<BR>
Creates a new instance of JFile</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.record.compiler.generated"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A> in <A HREF="../../../../../../org/apache/hadoop/record/compiler/generated/package-summary.html">org.apache.hadoop.record.compiler.generated</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/hadoop/record/compiler/generated/package-summary.html">org.apache.hadoop.record.compiler.generated</A> that return <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></CODE></FONT></TD>
<TD><CODE><B>Rcc.</B><B><A HREF="../../../../../../org/apache/hadoop/record/compiler/generated/Rcc.html#Include()">Include</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler">JFile</A></CODE></FONT></TD>
<TD><CODE><B>Rcc.</B><B><A HREF="../../../../../../org/apache/hadoop/record/compiler/generated/Rcc.html#Input()">Input</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/record/compiler/JFile.html" title="class in org.apache.hadoop.record.compiler"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/record/compiler//class-useJFile.html" target="_top"><B>FRAMES</B></A>
<A HREF="JFile.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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
|
jrnz/hadoop
|
docs/api/org/apache/hadoop/record/compiler/class-use/JFile.html
|
HTML
|
apache-2.0
| 11,047
|
---
layout: vakit_dashboard
title: NEW_BRUNSWICK, KANADA için iftar, namaz vakitleri ve hava durumu - ilçe/eyalet seç
permalink: /KANADA/NEW_BRUNSWICK/MONCTON
---
<script type="text/javascript">
var GLOBAL_COUNTRY = 'KANADA';
var GLOBAL_CITY = 'NEW_BRUNSWICK';
var GLOBAL_STATE = 'MONCTON';
var lat = 72;
var lon = 21;
</script>
|
hakanu/iftar
|
_posts_/vakit/KANADA/NEW_BRUNSWICK/MONCTON/2017-02-01-MONCTON.markdown
|
Markdown
|
apache-2.0
| 343
|
// Copyright 2013-2016 Stanford University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef STOKE_SRC_TRANSFORM_WEIGHTED_H
#define STOKE_SRC_TRANSFORM_WEIGHTED_H
#include <algorithm>
#include <cassert>
#include <random>
#include <set>
#include <vector>
#include "src/transform/transform.h"
namespace stoke {
class WeightedTransform : public Transform {
public:
/** Creates a new transformation helper; guaranteed to pass invariants. */
WeightedTransform(TransformPools& pools) : Transform(pools) {
}
std::string get_name() const {
return "Weighted";
}
TransformInfo operator()(Cfg& cfg) {
size_t pool_index = gen_() % transform_pool_.size();
size_t tform_index = transform_pool_[pool_index];
Transform* tr = transforms_[tform_index];
auto ti = (*tr)(cfg);
ti.move_type = tform_index;
return ti;
}
void undo(Cfg& cfg, const TransformInfo& info) const {
transforms_[info.move_type]->undo(cfg, info);
}
/** Add a transform to the set. */
void insert_transform(Transform* tr, size_t weight = 1) {
size_t label = transforms_.size();
transforms_.push_back(tr);
for (size_t i = 0; i < weight; ++i)
transform_pool_.push_back(label);
}
/** Get a pointer to a transform at a given index. This is
useful to identify what transform was used by looking at the
move_type field of TransformInfo(). */
Transform* get_transform(size_t index) const {
assert(index < transforms_.size());
return transforms_[index];
}
/** Returns the number of transforms available to choose from. */
size_t size() const {
return transforms_.size();
}
/** Set a seed for the random number generator. */
virtual void set_seed(std::default_random_engine::result_type seed) {
for (auto tform : transforms_)
tform->set_seed(seed);
gen_.seed(seed);
}
protected:
/** Transforms that we have available to use. */
std::vector<Transform*> transforms_;
/** Members are indexes into transforms_ vector. The indexes are
repeated based on the given weight of the transform. */
std::vector<size_t> transform_pool_;
};
} // namespace stoke
#endif
|
jyi/abc
|
src/transform/weighted.h
|
C
|
apache-2.0
| 2,669
|
define(
({
loadingInfo: "جاري التحميل...",
emptyInfo: "لا توجد بنود ليتم عرضها",
loadFailInfo: "لم تنجح عملية تحميل البيانات!",
loadMore: "المزيد من التحميل",
loadMoreLoading: "جاري التحميل...",
loadPrevious: "تحميل السابق",
loadPreviousLoading: "جاري التحميل..."
})
);
|
abssi/poc-tijari
|
dojoLib/toolkit/dojo/gridx/nls/ar/Body.js
|
JavaScript
|
apache-2.0
| 379
|
# Orlando-Labao
|
Labao/Orlando-Labao
|
README.md
|
Markdown
|
apache-2.0
| 16
|
// Copyright 2011 Splunk, 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.
// This example will login to Splunk, perform a regular search, wait until
// it is done, and then print out the raw results and some key-value pairs
var splunkjs = require('../../../index');
var Async = splunkjs.Async;
exports.main = function(opts, callback) {
// This is just for testing - ignore it
opts = opts || {};
var username = opts.username || "admin";
var password = opts.password || "changeme";
var scheme = opts.scheme || "https";
var host = opts.host || "localhost";
var port = opts.port || "8089";
var version = opts.version || "default";
var service = new splunkjs.Service({
username: username,
password: password,
scheme: scheme,
host: host,
port: port,
version: version
});
Async.chain([
// First, we log in
function(done) {
service.login(done);
},
// Perform the search
function(success, done) {
if (!success) {
done("Error logging in");
}
service.search("search index=_internal | head 3", {}, done);
},
// Wait until the job is done
function(job, done) {
job.track({}, function(job) {
// Ask the server for the results
job.results({}, done);
});
},
// Print out the statistics and get the results
function(results, job, done) {
// Print out the statics
console.log("Job Statistics: ");
console.log(" Event Count: " + job.properties().eventCount);
console.log(" Disk Usage: " + job.properties().diskUsage + " bytes");
console.log(" Priority: " + job.properties().priority);
// Find the index of the fields we want
var rawIndex = results.fields.indexOf("_raw");
var sourcetypeIndex = results.fields.indexOf("sourcetype");
var userIndex = results.fields.indexOf("user");
// Print out each result and the key-value pairs we want
console.log("Results: ");
for(var i = 0; i < results.rows.length; i++) {
console.log(" Result " + i + ": ");
console.log(" sourcetype: " + results.rows[i][sourcetypeIndex]);
console.log(" user: " + results.rows[i][userIndex]);
console.log(" _raw: " + results.rows[i][rawIndex]);
}
// Once we're done, cancel the job.
job.cancel(done);
}
],
function(err) {
callback(err);
}
);
};
if (module === require.main) {
exports.main({}, function() {});
}
|
adamryman/splunk-sdk-javascript
|
examples/node/helloworld/search_normal.js
|
JavaScript
|
apache-2.0
| 3,563
|
// Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package codec
import (
"errors"
"net"
"net/rpc"
"testing"
// can not import xxx.pb with rpc stub here,
// because it will cause import cycle.
msg "github.com/cockroachdb/cockroach/rpc/codec/message.pb"
"github.com/cockroachdb/cockroach/util/log"
)
type Arith int
func (t *Arith) Add(args *msg.ArithRequest, reply *msg.ArithResponse) error {
reply.C = args.GetA() + args.GetB()
log.Infof("Arith.Add(%v, %v): %v", args.GetA(), args.GetB(), reply.GetC())
return nil
}
func (t *Arith) Mul(args *msg.ArithRequest, reply *msg.ArithResponse) error {
reply.C = args.GetA() * args.GetB()
return nil
}
func (t *Arith) Div(args *msg.ArithRequest, reply *msg.ArithResponse) error {
if args.GetB() == 0 {
return errors.New("divide by zero")
}
reply.C = args.GetA() / args.GetB()
return nil
}
func (t *Arith) Error(args *msg.ArithRequest, reply *msg.ArithResponse) error {
return errors.New("ArithError")
}
type Echo int
func (t *Echo) Echo(args *msg.EchoRequest, reply *msg.EchoResponse) error {
reply.Msg = args.Msg
return nil
}
func TestAll(t *testing.T) {
srvAddr, err := listenAndServeArithAndEchoService("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal("could not start server")
}
conn, err := net.Dial(srvAddr.Network(), srvAddr.String())
if err != nil {
t.Fatalf("could not dial client to %s: %s", srvAddr, err)
}
client := rpc.NewClientWithCodec(NewClientCodec(conn))
defer client.Close()
testArithClient(t, client)
testEchoClient(t, client)
testArithClientAsync(t, client)
testEchoClientAsync(t, client)
}
func listenAndServeArithAndEchoService(network, addr string) (net.Addr, error) {
clients, err := net.Listen(network, addr)
if err != nil {
return nil, err
}
srv := rpc.NewServer()
if err := srv.RegisterName("ArithService", new(Arith)); err != nil {
return nil, err
}
if err := srv.RegisterName("EchoService", new(Echo)); err != nil {
return nil, err
}
go func() {
for {
conn, err := clients.Accept()
if err != nil {
log.Infof("clients.Accept(): %v\n", err)
continue
}
go srv.ServeCodec(NewServerCodec(conn))
}
}()
return clients.Addr(), nil
}
func testArithClient(t *testing.T, client *rpc.Client) {
var args msg.ArithRequest
var reply msg.ArithResponse
var err error
// Add
args.A = 1
args.B = 2
if err = client.Call("ArithService.Add", &args, &reply); err != nil {
t.Fatalf(`arith.Add: %v`, err)
}
if reply.GetC() != 3 {
t.Fatalf(`arith.Add: expected = %d, got = %d`, 3, reply.GetC())
}
// Mul
args.A = 2
args.B = 3
if err = client.Call("ArithService.Mul", &args, &reply); err != nil {
t.Fatalf(`arith.Mul: %v`, err)
}
if reply.GetC() != 6 {
t.Fatalf(`arith.Mul: expected = %d, got = %d`, 6, reply.GetC())
}
// Div
args.A = 13
args.B = 5
if err = client.Call("ArithService.Div", &args, &reply); err != nil {
t.Fatalf(`arith.Div: %v`, err)
}
if reply.GetC() != 2 {
t.Fatalf(`arith.Div: expected = %d, got = %d`, 2, reply.GetC())
}
// Div zero
args.A = 1
args.B = 0
if err = client.Call("ArithService.Div", &args, &reply); err.Error() != "divide by zero" {
t.Fatalf(`arith.Error: expected = "%s", got = "%s"`, "divide by zero", err.Error())
}
// Error
args.A = 1
args.B = 2
if err = client.Call("ArithService.Error", &args, &reply); err.Error() != "ArithError" {
t.Fatalf(`arith.Error: expected = "%s", got = "%s"`, "ArithError", err.Error())
}
}
func testArithClientAsync(t *testing.T, client *rpc.Client) {
done := make(chan *rpc.Call, 16)
callInfoList := []struct {
method string
args *msg.ArithRequest
reply *msg.ArithResponse
err error
}{
{
"ArithService.Add",
&msg.ArithRequest{A: 1, B: 2},
&msg.ArithResponse{C: 3},
nil,
},
{
"ArithService.Mul",
&msg.ArithRequest{A: 2, B: 3},
&msg.ArithResponse{C: 6},
nil,
},
{
"ArithService.Div",
&msg.ArithRequest{A: 13, B: 5},
&msg.ArithResponse{C: 2},
nil,
},
{
"ArithService.Div",
&msg.ArithRequest{A: 1, B: 0},
&msg.ArithResponse{},
errors.New("divide by zero"),
},
{
"ArithService.Error",
&msg.ArithRequest{A: 1, B: 2},
&msg.ArithResponse{},
errors.New("ArithError"),
},
}
// GoCall list
calls := make([]*rpc.Call, len(callInfoList))
for i := 0; i < len(calls); i++ {
calls[i] = client.Go(callInfoList[i].method,
callInfoList[i].args, callInfoList[i].reply,
done,
)
}
for i := 0; i < len(calls); i++ {
<-calls[i].Done
}
// check result
for i := 0; i < len(calls); i++ {
if callInfoList[i].err != nil {
if calls[i].Error.Error() != callInfoList[i].err.Error() {
t.Fatalf(`%s: expected %v, Got = %v`,
callInfoList[i].method,
callInfoList[i].err,
calls[i].Error,
)
}
continue
}
got := calls[i].Reply.(*msg.ArithResponse).GetC()
expected := callInfoList[i].reply.GetC()
if got != expected {
t.Fatalf(`%s: expected %v, Got = %v`,
callInfoList[i].method, got, expected,
)
}
}
}
func testEchoClient(t *testing.T, client *rpc.Client) {
var args msg.EchoRequest
var reply msg.EchoResponse
var err error
// EchoService.Echo
args.Msg = "Hello, Protobuf-RPC"
if err = client.Call("EchoService.Echo", &args, &reply); err != nil {
t.Fatalf(`EchoService.Echo: %v`, err)
}
if reply.GetMsg() != args.GetMsg() {
t.Fatalf(`EchoService.Echo: expected = "%s", got = "%s"`, args.GetMsg(), reply.GetMsg())
}
}
func testEchoClientAsync(t *testing.T, client *rpc.Client) {
// EchoService.Echo
args := &msg.EchoRequest{Msg: "Hello, Protobuf-RPC"}
reply := &msg.EchoResponse{}
echoCall := client.Go("EchoService.Echo", args, reply, nil)
// EchoService.Echo reply
echoCall = <-echoCall.Done
if echoCall.Error != nil {
t.Fatalf(`EchoService.Echo: %v`, echoCall.Error)
}
if echoCall.Reply.(*msg.EchoResponse).GetMsg() != args.GetMsg() {
t.Fatalf(`EchoService.Echo: expected = "%s", got = "%s"`,
args.GetMsg(),
echoCall.Reply.(*msg.EchoResponse).GetMsg(),
)
}
}
|
Kevin-GuanJian/cockroach
|
rpc/codec/rpc_test.go
|
GO
|
apache-2.0
| 6,115
|
/*
* 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.geode.distributed.internal.locks;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
/**
* Used to provide information on a grantor request made to the elder.
*
* @since GemFire 4.0
*/
public class GrantorInfo {
private final InternalDistributedMember id;
private final boolean needsRecovery;
private final long versionId;
private boolean initiatingTransfer;
private final int serialNumber;
public GrantorInfo(InternalDistributedMember id, long versionId, int serialNumber,
boolean needsRecovery) {
this.id = id;
this.needsRecovery = needsRecovery;
this.versionId = versionId;
this.serialNumber = serialNumber;
}
/** Caller is sync'ed on ElderState */
public void setInitiatingTransfer(boolean initiatingTransfer) {
this.initiatingTransfer = initiatingTransfer;
}
/** Caller is sync'ed on ElderState */
public boolean isInitiatingTransfer() {
return initiatingTransfer;
}
/**
* Gets the member id of this grantor.
*/
public InternalDistributedMember getId() {
return id;
}
/**
* Returns true if the current grantor needs to do lock recovery.
*/
public boolean needsRecovery() {
return needsRecovery;
}
/**
* Returns the elder version id of this grantor.
*/
public long getVersionId() {
return versionId;
}
/**
* Returns the DLockService serial number of this grantor.
*/
public int getSerialNumber() {
return serialNumber;
}
/** Returns human readable String version of this object. */
@Override
public String toString() {
return "<GrantorInfo id=" + id + " versionId=" + versionId + " serialNumber="
+ serialNumber + " needsRecovery=" + needsRecovery + " initiatingTransfer="
+ initiatingTransfer + ">";
}
}
|
jdeppe-pivotal/geode
|
geode-core/src/main/java/org/apache/geode/distributed/internal/locks/GrantorInfo.java
|
Java
|
apache-2.0
| 2,614
|
<!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_29) on Mon Nov 26 17:21:13 MSK 2012 -->
<TITLE>
RoundTripHFPlaceholder12 (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2012-11-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="RoundTripHFPlaceholder12 (POI API Documentation)";
}
}
</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="class-use/RoundTripHFPlaceholder12.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/poi/hslf/record/RecordTypes.Type.html" title="class in org.apache.poi.hslf.record"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/apache/poi/hslf/record/SheetContainer.html" title="class in org.apache.poi.hslf.record"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/hslf/record/RoundTripHFPlaceholder12.html" target="_top"><B>FRAMES</B></A>
<A HREF="RoundTripHFPlaceholder12.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 | <A HREF="#fields_inherited_from_class_org.apache.poi.hslf.record.Record">FIELD</A> | <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">
org.apache.poi.hslf.record</FONT>
<BR>
Class RoundTripHFPlaceholder12</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">org.apache.poi.hslf.record.Record</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html" title="class in org.apache.poi.hslf.record">org.apache.poi.hslf.record.RecordAtom</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.hslf.record.RoundTripHFPlaceholder12</B>
</PRE>
<HR>
<DL>
<DT><PRE>public final class <B>RoundTripHFPlaceholder12</B><DT>extends <A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html" title="class in org.apache.poi.hslf.record">RecordAtom</A></DL>
</PRE>
<P>
An atom record that specifies that a shape is a header or footer placeholder shape
<P>
<P>
<DL>
<DT><B>Since:</B></DT>
<DD>PowerPoint 2007</DD>
<DT><B>Author:</B></DT>
<DD>Yegor Kozlov</DD>
</DL>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_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>Field Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="fields_inherited_from_class_org.apache.poi.hslf.record.Record"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Fields inherited from class org.apache.poi.hslf.record.<A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">Record</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html#logger">logger</A></CODE></TD>
</TR>
</TABLE>
<!-- ======== 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 ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected </CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/RoundTripHFPlaceholder12.html#RoundTripHFPlaceholder12(byte[], int, int)">RoundTripHFPlaceholder12</A></B>(byte[] source,
int start,
int len)</CODE>
<BR>
Constructs the comment atom record from its source data.</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> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/RoundTripHFPlaceholder12.html#getPlaceholderId()">getPlaceholderId</A></B>()</CODE>
<BR>
Gets the comment number (note - each user normally has their own count).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> long</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/RoundTripHFPlaceholder12.html#getRecordType()">getRecordType</A></B>()</CODE>
<BR>
Gets the record type.</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="../../../../../org/apache/poi/hslf/record/RoundTripHFPlaceholder12.html#setPlaceholderId(int)">setPlaceholderId</A></B>(int number)</CODE>
<BR>
Sets the comment number (note - each user normally has their own count).</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="../../../../../org/apache/poi/hslf/record/RoundTripHFPlaceholder12.html#writeOut(java.io.OutputStream)">writeOut</A></B>(java.io.OutputStream out)</CODE>
<BR>
Write the contents of the record back, so it can be written
to disk</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_org.apache.poi.hslf.record.RecordAtom"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class org.apache.poi.hslf.record.<A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html" title="class in org.apache.poi.hslf.record">RecordAtom</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html#getChildRecords()">getChildRecords</A>, <A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html#isAnAtom()">isAnAtom</A></CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_org.apache.poi.hslf.record.Record"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class org.apache.poi.hslf.record.<A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">Record</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html#buildRecordAtOffset(byte[], int)">buildRecordAtOffset</A>, <A HREF="../../../../../org/apache/poi/hslf/record/Record.html#createRecordForType(long, byte[], int, int)">createRecordForType</A>, <A HREF="../../../../../org/apache/poi/hslf/record/Record.html#findChildRecords(byte[], int, int)">findChildRecords</A>, <A HREF="../../../../../org/apache/poi/hslf/record/Record.html#writeLittleEndian(int, java.io.OutputStream)">writeLittleEndian</A>, <A HREF="../../../../../org/apache/poi/hslf/record/Record.html#writeLittleEndian(short, java.io.OutputStream)">writeLittleEndian</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.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</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="RoundTripHFPlaceholder12(byte[], int, int)"><!-- --></A><H3>
RoundTripHFPlaceholder12</H3>
<PRE>
protected <B>RoundTripHFPlaceholder12</B>(byte[] source,
int start,
int len)</PRE>
<DL>
<DD>Constructs the comment atom record from its source data.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>source</CODE> - the source data as a byte array.<DD><CODE>start</CODE> - the start offset into the byte array.<DD><CODE>len</CODE> - the length of the slice in the byte array.</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="getPlaceholderId()"><!-- --></A><H3>
getPlaceholderId</H3>
<PRE>
public int <B>getPlaceholderId</B>()</PRE>
<DL>
<DD>Gets the comment number (note - each user normally has their own count).
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the comment number.</DL>
</DD>
</DL>
<HR>
<A NAME="setPlaceholderId(int)"><!-- --></A><H3>
setPlaceholderId</H3>
<PRE>
public void <B>setPlaceholderId</B>(int number)</PRE>
<DL>
<DD>Sets the comment number (note - each user normally has their own count).
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>number</CODE> - the comment number.</DL>
</DD>
</DL>
<HR>
<A NAME="getRecordType()"><!-- --></A><H3>
getRecordType</H3>
<PRE>
public long <B>getRecordType</B>()</PRE>
<DL>
<DD>Gets the record type.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html#getRecordType()">getRecordType</A></CODE> in class <CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">Record</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the record type.</DL>
</DD>
</DL>
<HR>
<A NAME="writeOut(java.io.OutputStream)"><!-- --></A><H3>
writeOut</H3>
<PRE>
public void <B>writeOut</B>(java.io.OutputStream out)
throws java.io.IOException</PRE>
<DL>
<DD>Write the contents of the record back, so it can be written
to disk
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html#writeOut(java.io.OutputStream)">writeOut</A></CODE> in class <CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">Record</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>out</CODE> - the output stream to write to.
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE> - if an error occurs.</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="class-use/RoundTripHFPlaceholder12.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/poi/hslf/record/RecordTypes.Type.html" title="class in org.apache.poi.hslf.record"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/apache/poi/hslf/record/SheetContainer.html" title="class in org.apache.poi.hslf.record"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/hslf/record/RoundTripHFPlaceholder12.html" target="_top"><B>FRAMES</B></A>
<A HREF="RoundTripHFPlaceholder12.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 | <A HREF="#fields_inherited_from_class_org.apache.poi.hslf.record.Record">FIELD</A> | <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>
<i>Copyright 2012 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
|
brenthand/Panda
|
poi-3.9/docs/apidocs/org/apache/poi/hslf/record/RoundTripHFPlaceholder12.html
|
HTML
|
apache-2.0
| 18,097
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index of new symbols in 2.2</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="index.html" title="GLib Reference Manual">
<link rel="up" href="index.html" title="GLib Reference Manual">
<link rel="prev" href="api-index-deprecated.html" title="Index of deprecated symbols">
<link rel="next" href="api-index-2-4.html" title="Index of new symbols in 2.4">
<meta name="generator" content="GTK-Doc V1.19 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="2">
<tr valign="middle">
<td><a accesskey="p" href="api-index-deprecated.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td>
<td> </td>
<td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td>
<th width="100%" align="center">GLib Reference Manual</th>
<td><a accesskey="n" href="api-index-2-4.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td>
</tr>
<tr><td colspan="5" class="shortcuts">
<a class="shortcut" href="#idxA">A</a>
|
<a class="shortcut" href="#idxF">F</a>
|
<a class="shortcut" href="#idxG">G</a>
|
<a class="shortcut" href="#idxL">L</a>
|
<a class="shortcut" href="#idxM">M</a>
|
<a class="shortcut" href="#idxP">P</a>
|
<a class="shortcut" href="#idxS">S</a>
|
<a class="shortcut" href="#idxU">U</a>
|
<a class="shortcut" href="#idxV">V</a>
</td></tr>
</table>
<div class="index">
<div class="titlepage"><div><div><h1 class="title">
<a name="api-index-2-2"></a>Index of new symbols in 2.2</h1></div></div></div>
<a name="idx"></a><a name="idxA"></a><h3 class="title">A</h3>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-ascii-strtoull" title="g_ascii_strtoull ()">g_ascii_strtoull</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
<a name="idxF"></a><h3 class="title">F</h3>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-fprintf" title="g_fprintf ()">g_fprintf</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
<a name="idxG"></a><h3 class="title">G</h3>
<dt>
<a class="link" href="glib-Miscellaneous-Utility-Functions.html#g-get-application-name" title="g_get_application_name ()">g_get_application_name</a>, function in <a class="link" href="glib-Miscellaneous-Utility-Functions.html" title="Miscellaneous Utility Functions">Miscellaneous Utility Functions</a>
</dt>
<dd></dd>
<dt>
<a class="link" href="glib-Miscellaneous-Macros.html#G-GNUC-DEPRECATED:CAPS" title="G_GNUC_DEPRECATED">G_GNUC_DEPRECATED</a>, macro in <a class="link" href="glib-Miscellaneous-Macros.html" title="Miscellaneous Macros">Miscellaneous Macros</a>
</dt>
<dd></dd>
<a name="idxL"></a><h3 class="title">L</h3>
<dt>
<a class="link" href="glib-Miscellaneous-Macros.html#G-LIKELY:CAPS" title="G_LIKELY()">G_LIKELY</a>, macro in <a class="link" href="glib-Miscellaneous-Macros.html" title="Miscellaneous Macros">Miscellaneous Macros</a>
</dt>
<dd></dd>
<a name="idxM"></a><h3 class="title">M</h3>
<dt>
<a class="link" href="glib-Simple-XML-Subset-Parser.html#g-markup-parse-context-get-element" title="g_markup_parse_context_get_element ()">g_markup_parse_context_get_element</a>, function in <a class="link" href="glib-Simple-XML-Subset-Parser.html" title="Simple XML Subset Parser">Simple XML Subset Parser</a>
</dt>
<dd></dd>
<a name="idxP"></a><h3 class="title">P</h3>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-printf" title="g_printf ()">g_printf</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
<a name="idxS"></a><h3 class="title">S</h3>
<dt>
<a class="link" href="glib-Miscellaneous-Utility-Functions.html#g-set-application-name" title="g_set_application_name ()">g_set_application_name</a>, function in <a class="link" href="glib-Miscellaneous-Utility-Functions.html" title="Miscellaneous Utility Functions">Miscellaneous Utility Functions</a>
</dt>
<dd></dd>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-sprintf" title="g_sprintf ()">g_sprintf</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-str-has-prefix" title="g_str_has_prefix ()">g_str_has_prefix</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-str-has-suffix" title="g_str_has_suffix ()">g_str_has_suffix</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
<a name="idxU"></a><h3 class="title">U</h3>
<dt>
<a class="link" href="glib-Miscellaneous-Macros.html#G-UNLIKELY:CAPS" title="G_UNLIKELY()">G_UNLIKELY</a>, macro in <a class="link" href="glib-Miscellaneous-Macros.html" title="Miscellaneous Macros">Miscellaneous Macros</a>
</dt>
<dd></dd>
<dt>
<a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strreverse" title="g_utf8_strreverse ()">g_utf8_strreverse</a>, function in <a class="link" href="glib-Unicode-Manipulation.html" title="Unicode Manipulation">Unicode Manipulation</a>
</dt>
<dd></dd>
<a name="idxV"></a><h3 class="title">V</h3>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-vfprintf" title="g_vfprintf ()">g_vfprintf</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-vprintf" title="g_vprintf ()">g_vprintf</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
<dt>
<a class="link" href="glib-String-Utility-Functions.html#g-vsprintf" title="g_vsprintf ()">g_vsprintf</a>, function in <a class="link" href="glib-String-Utility-Functions.html" title="String Utility Functions">String Utility Functions</a>
</dt>
<dd></dd>
</div>
<div class="footer">
<hr>
Generated by GTK-Doc V1.19</div>
</body>
</html>
|
minixalpha/SourceLearning
|
glib/src/glib-2.37.93/docs/reference/glib/html/api-index-2-2.html
|
HTML
|
apache-2.0
| 7,138
|
.htmlarea { background: #fff; border: 1px solid #7f9db9; }
.htmlarea iframe { border: none; padding: 0; margin: 0; }
.htmlarea textarea { border: none; padding: 0; margin: 0; }
.htmlarea .toolbar {
cursor: default;
background: ButtonFace;
padding: 4px;
border: 1px solid;
border-color: ButtonHighlight ButtonHighlight ButtonShadow ButtonHighlight;
}
.htmlarea .toolbar table { font-family: tahoma,verdana,sans-serif; font-size: 8pt; }
.htmlarea .toolbar img { border: none; }
.htmlarea .toolbar .label { padding: 0px 3px; }
.htmlarea .toolbar .button {
background: ButtonFace;
color: ButtonText;
border: 1px solid ButtonFace;
padding: 1px;
margin: 0px;
width: 18px;
height: 18px;
}
.htmlarea .toolbar .buttonHover {
border: 1px solid;
border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
}
.htmlarea .toolbar .buttonActive, .htmlarea .toolbar .buttonPressed {
padding: 2px 0px 0px 2px;
border: 1px solid;
border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
}
.htmlarea .toolbar .buttonPressed {
background: ButtonHighlight;
}
.htmlarea .toolbar .indicator {
padding: 0px 3px;
overflow: hidden;
width: 20px;
text-align: center;
cursor: default;
border: 1px solid ButtonShadow;
}
.htmlarea .toolbar .buttonDisabled {
filter: gray() alpha(opacity = 25);
opacity: 0.25;
}
.htmlarea .toolbar .separator {
position: relative;
margin: 3px;
border-left: 1px solid ButtonShadow;
border-right: 1px solid ButtonHighlight;
width: 0px;
height: 16px;
padding: 0px;
}
.htmlarea .toolbar .space { width: 5px; }
.htmlarea .toolbar select { font: 8pt Tahoma,Verdana,sans-serif; }
.htmlarea .toolbar select,
.htmlarea .toolbar select:hover,
.htmlarea .toolbar select:active { background: FieldFace; color: ButtonText; }
.htmlarea .statusBar {
border: 1px solid;
border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonHighlight;
padding: 2px 4px;
background-color: ButtonFace;
color: ButtonText;
font: 8pt Tahoma,Verdana,sans-serif;
}
.htmlarea .statusBar .statusBarTree a {
padding: 2px 5px;
color: #00f;
}
.htmlarea .statusBar .statusBarTree a:visited { color: #00f; }
.htmlarea .statusBar .statusBarTree a:hover {
background-color: Highlight;
color: HighlightText;
padding: 1px 4px;
border: 1px solid HighlightText;
}
/* Hidden DIV popup dialogs (PopupDiv) */
.dialog {
color: ButtonText;
background: ButtonFace;
}
.dialog .content { padding: 2px; }
.dialog, .dialog button, .dialog input, .dialog select, .dialog textarea, .dialog table {
font: 8pt Tahoma,Verdana,sans-serif;
}
.dialog table { border-collapse: collapse; }
.dialog .title {
background: #008;
color: #ff8;
border-bottom: 1px solid #000;
padding: 1px 0px 2px 5px;
font-size: 12px;
font-weight: bold;
cursor: default;
}
.dialog .title .button {
float: right;
border: 1px solid #66a;
padding: 0px 1px 0px 2px;
margin-right: 1px;
color: #fff;
text-align: center;
}
.dialog .title .button-hilite { border-color: #88f; background: #44c; }
.dialog button {
width: 5em;
padding: 0px;
}
.dialog .buttonColor {
padding: 1px;
cursor: default;
border: 1px solid;
border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
}
.dialog .buttonColor-hilite {
border-color: #000;
}
.dialog .buttonColor .chooser, .dialog .buttonColor .nocolor {
height: 0.6em;
border: 1px solid;
padding: 0px 1em;
border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
}
.dialog .buttonColor .nocolor { padding: 0px; }
.dialog .buttonColor .nocolor-hilite { background-color: #fff; color: #f00; }
.dialog .label { text-align: right; width: 6em; }
.dialog .value input { width: 100%; }
.dialog .buttons { text-align: right; padding: 2px 4px 0px 4px; }
.dialog legend { font-weight: bold; }
.dialog fieldset table { margin: 2px 0px; }
.popupdiv {
border: 2px solid;
border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
}
.popupwin {
padding: 0px;
margin: 0px;
}
.popupwin .title {
background: #fff;
color: #000;
font-weight: bold;
font-size: 120%;
padding: 3px 10px;
margin-bottom: 10px;
border-bottom: 1px solid black;
letter-spacing: 2px;
}
form { margin: 0px; border: none; }
.htmlarea .toolbar table {
font-family: tahoma,verdana,sans-serif;
font-size: 8pt;
margin-top: 0px;
margin-bottom: 0px;
border: none;
}
.htmlarea .toolbar td {
border: none;
padding: 0px;
}
.htmlarea .toolbar th {
border: none;
padding: 0px;
}
|
Pavel-Teplitsky/htmlarea-groupdocs-comparison-source
|
htmlarea/htmlarea/public/htmlarea.css
|
CSS
|
apache-2.0
| 4,555
|
# Akkaships
Battleship game implemented in Akka. Training project for Codemotion 2015
Slides from the workshop are available at [Slideshare](http://www.slideshare.net/miguel0afd/akkaships-primeros-pasos-con-akka-olvdate-de-los-threads)
## Requirements ##
[Apache Cassandra](http://www.apache.org/dyn/closer.lua/cassandra/2.1.11/apache-cassandra-2.1.11-bin.tar.gz)
To start cassandra:
> $CASSANDRA_HOME/bin/cassandra -f
To start CQL Shell:
> $CASSANDRA_HOME/bin/cqlsh
Requirement metadata:
CREATE KEYSPACE IF NOT EXISTS akkaships WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}
CREATE TABLE IF NOT EXISTS akkaships.users (user text, PRIMARY KEY((user)))
CREATE TABLE IF NOT EXISTS akkaships.statistics (user text, ts timeuuid, hit boolean, sunk boolean, PRIMARY KEY((ts),user,hit,sunk))
## Execute Game mode localhost ##
First it is necessary to compile:
mvn clean install
Now it's time to execute the server
mvn exec:java -pl Server -Dexec.mainClass="es.codemotion.akkaships.server.ServerApp"
Once server is started it is possible to start the Player
mvn exec:java -pl Client -Dexec.mainClass="es.codemotion.akkaships.client.PlayerApp"
## Configuration for a distributed environment ##
Player Configuration is in the file $AKKASHIPS_HOME/Client/src/main/resources/player-reference.conf and there it's
necessary to change ...
player.akka.remote.netty.tcp.hostname = "[Your IP]"
player.akka.cluster.seed-nodes = ["akka.tcp://ShipsServerCluster@[ServerIP]:61000"]
Server Configuration is in the file $AKKASHIPS_HOME/Server/src/main/resources/server-reference.conf and there it's
necessary to change ...
akkaships-server.akka.remote.netty.tcp.hostname = "[ServerIP]"
akkaships-server.akka.cluster.seed-nodes = ["akka.tcp://ShipsServerCluster@[ServerIP]:61000"]
Now it's time to recompile and follow the steps of the previous steps
|
jjlopezm/Akkaships-Exercise
|
README.md
|
Markdown
|
apache-2.0
| 1,950
|
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.schema;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static com.evolveum.midpoint.schema.TestConstants.*;
import java.io.IOException;
import java.util.List;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.xnode.MapXNode;
import com.evolveum.midpoint.prism.xnode.PrimitiveXNode;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import com.evolveum.midpoint.prism.parser.QueryConvertor;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.EqualFilter;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.util.JAXBUtilTest;
import com.evolveum.midpoint.schema.util.SchemaTestConstants;
import com.evolveum.midpoint.schema.util.SchemaTestUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.JAXBUtil;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CachingMetadataType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ExtensionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.GenericObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.XmlSchemaType;
import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import com.evolveum.prism.xml.ns._public.types_3.SchemaDefinitionType;
/**
* @author semancik
*
*/
public class TestJaxbConstruction {
private static final String FAUX_RESOURCE_OID = "fuuuuuuuuuuu";
private static final String ACCOUNT_NAME = "jack";
@BeforeSuite
public void setup() throws SchemaException, SAXException, IOException {
PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY);
}
@Test
public void testUserConstruction() throws JAXBException, SchemaException {
System.out.println("\n\n ===[ testUserConstruction ]===\n");
// GIVEN
PrismContext prismContext = PrismTestUtil.getPrismContext();
UserType userType = new UserType();
prismContext.adopt(userType);
PrismObject<UserType> user = userType.asPrismObject();
assertNotNull("No object definition after adopt", user.getDefinition());
SchemaTestUtil.assertUserDefinition(user.getDefinition());
// fullName: PolyString
userType.setFullName(new PolyStringType("Čučoriedka"));
PrismProperty<PolyString> fullNameProperty = user.findProperty(UserType.F_FULL_NAME);
PolyString fullName = fullNameProperty.getRealValue();
assertEquals("Wrong fullName orig", "Čučoriedka", fullName.getOrig());
assertEquals("Wrong fullName norm", "cucoriedka", fullName.getNorm());
// description: setting null value
userType.setDescription(null);
PrismProperty<String> descriptionProperty = user.findProperty(UserType.F_DESCRIPTION);
assertNull("Unexpected description property "+descriptionProperty, descriptionProperty);
// description: setting null value
userType.setDescription("blah blah");
descriptionProperty = user.findProperty(UserType.F_DESCRIPTION);
assertEquals("Wrong description value", "blah blah", descriptionProperty.getRealValue());
// description: resetting null value
userType.setDescription(null);
descriptionProperty = user.findProperty(UserType.F_DESCRIPTION);
assertNull("Unexpected description property (after reset) "+descriptionProperty, descriptionProperty);
// Extension
ExtensionType extension = new ExtensionType();
userType.setExtension(extension);
user.checkConsistence();
PrismContainer<Containerable> extensionContainer = user.findContainer(GenericObjectType.F_EXTENSION);
checkExtension(extensionContainer,"user extension after setExtension");
checkExtension(extension,"user extension after setExtension");
AssignmentType assignmentType = new AssignmentType();
userType.getAssignment().add(assignmentType);
user.checkConsistence();
user.assertDefinitions();
// Assignment
ExtensionType assignmentExtension = new ExtensionType();
assignmentType.setExtension(assignmentExtension);
user.assertDefinitions();
user.checkConsistence();
checkExtension(assignmentExtension,"assignment extension after setExtension");
user.checkConsistence();
user.assertDefinitions();
// accountRef/account
ObjectReferenceType accountRefType = new ObjectReferenceType();
accountRefType.setOid(USER_ACCOUNT_REF_1_OID);
MapXNode filterElement = createFilter();
SearchFilterType filter = new SearchFilterType();
filter.setFilterClauseXNode(filterElement);
accountRefType.setFilter(filter);
userType.getLinkRef().add(accountRefType);
assertAccountRefs(userType, USER_ACCOUNT_REF_1_OID);
user.checkConsistence();
user.assertDefinitions();
PrismReference accountRef = user.findReference(UserType.F_LINK_REF);
assertEquals("1/ Wrong accountRef values", 1, accountRef.getValues().size());
PrismReferenceValue accountRefVal0 = accountRef.getValue(0);
SearchFilterType prismFilter = accountRefVal0.getFilter();
assertNotNull("Filter have not passed", prismFilter);
//assertTrue("Bad filter in reference", prismFilter instanceof EqualsFilter);
// assertEquals("Difference filter", filterElement, prismFilter);
ShadowType accountShadowType = new ShadowType();
prismContext.adopt(accountShadowType);
accountShadowType.setOid(USER_ACCOUNT_REF_1_OID);
userType.getLink().add(accountShadowType);
//value still should be only one... (reference was only resolved)
assertEquals("2/ Wrong accountRef values", 1, user.findReference(UserType.F_LINK_REF).getValues().size());
accountShadowType = new ShadowType();
prismContext.adopt(accountShadowType);
accountShadowType.setOid(USER_ACCOUNT_REF_2_OID);
userType.getLink().add(accountShadowType);
assertEquals("3/ Wrong accountRef values", 2, user.findReference(UserType.F_LINK_REF).getValues().size());
assertAccountRefs(userType, USER_ACCOUNT_REF_1_OID, USER_ACCOUNT_REF_2_OID);
user.checkConsistence();
user.assertDefinitions();
assertEquals("4/ Wrong accountRef values", 2, accountRef.getValues().size());
PrismAsserts.assertReferenceValues(accountRef, USER_ACCOUNT_REF_1_OID, USER_ACCOUNT_REF_2_OID);
}
@Test
public void testUserConstructionBeforeAdopt() throws Exception {
System.out.println("\n\n ===[ testUserConstructionBeforeAdopt ]===\n");
// GIVEN
PrismContext prismContext = PrismTestUtil.getPrismContext();
UserType userType = new UserType();
userType.setFullName(new PolyStringType("Čučoriedka"));
userType.setDescription("blah blah");
ExtensionType extension = new ExtensionType();
userType.setExtension(extension);
AssignmentType assignmentType = new AssignmentType();
userType.getAssignment().add(assignmentType);
// Assignment
ExtensionType assignmentExtension = new ExtensionType();
assignmentType.setExtension(assignmentExtension);
// accountRef/account
ObjectReferenceType accountRefType = new ObjectReferenceType();
accountRefType.setOid(USER_ACCOUNT_REF_1_OID);
MapXNode filterElement = createFilter();
SearchFilterType filter = new SearchFilterType();
filter.setFilterClauseXNode(filterElement);
accountRefType.setFilter(filter);
userType.getLinkRef().add(accountRefType);
ShadowType accountShadowType = new ShadowType();
accountShadowType.setOid(USER_ACCOUNT_REF_1_OID);
userType.getLink().add(accountShadowType);
accountShadowType = new ShadowType();
accountShadowType.setOid(USER_ACCOUNT_REF_2_OID);
userType.getLink().add(accountShadowType);
// WHEN
prismContext.adopt(userType);
// THEN
PrismObject<UserType> user = userType.asPrismObject();
assertNotNull("No object definition after adopt", user.getDefinition());
SchemaTestUtil.assertUserDefinition(user.getDefinition());
// fullName: PolyString
PrismProperty<PolyString> fullNameProperty = user.findProperty(UserType.F_FULL_NAME);
user.checkConsistence();
user.assertDefinitions();
PolyString fullName = fullNameProperty.getRealValue();
assertEquals("Wrong fullName orig", "Čučoriedka", fullName.getOrig());
assertEquals("Wrong fullName norm", "cucoriedka", fullName.getNorm());
PrismProperty<String> descriptionProperty = user.findProperty(UserType.F_DESCRIPTION);
assertEquals("Wrong description value", "blah blah", descriptionProperty.getRealValue());
PrismContainer<Containerable> extensionContainer = user.findContainer(GenericObjectType.F_EXTENSION);
checkExtension(extensionContainer,"user extension");
checkExtension(extension,"user extension");
PrismReference accountRef = user.findReference(UserType.F_LINK_REF);
assertEquals("Wrong accountRef values", 2, accountRef.getValues().size());
PrismAsserts.assertReferenceValues(accountRef, USER_ACCOUNT_REF_1_OID, USER_ACCOUNT_REF_2_OID);
PrismReferenceValue accountRefVal0 = accountRef.getValue(0);
SearchFilterType prismFilter = accountRefVal0.getFilter();
assertNotNull("Filter have not passed", prismFilter);
// assertTrue("Wrong filter in reference " , prismFilter instanceof EqualsFilter);
// assertEquals("Difference filter", filterElement, prismFilter);
assertAccountRefs(userType, USER_ACCOUNT_REF_1_OID, USER_ACCOUNT_REF_2_OID);
user.assertDefinitions();
user.checkConsistence();
}
private void assertAccountRefs(UserType userType, String... accountOids) {
List<ObjectReferenceType> accountRefs = userType.getLinkRef();
assertEquals("Wrong number of accountRefs", accountOids.length, accountRefs.size());
for (String expectedAccountOid: accountOids) {
assertAccountRef(accountRefs, expectedAccountOid);
}
}
private void assertAccountRef(List<ObjectReferenceType> accountRefs, String expectedAccountOid) {
for (ObjectReferenceType accountRef: accountRefs) {
if (accountRef.getOid().equals(expectedAccountOid)) {
return;
}
}
AssertJUnit.fail("acountRef for oid "+expectedAccountOid+" was not found");
}
/**
* Similar to testUserConstruction, but some operations are done in a different order
* e.g. assignment is filled in first then set to the user.
*/
@Test
public void testUserConstructionReverse() throws JAXBException, SchemaException {
System.out.println("\n\n ===[ testUserConstructionReverse ]===\n");
// GIVEN
PrismContext prismContext = PrismTestUtil.getPrismContext();
UserType userType = new UserType();
prismContext.adopt(userType);
PrismObject<UserType> user = userType.asPrismObject();
assertNotNull("No object definition after adopt", user.getDefinition());
// Extension
ExtensionType extension = new ExtensionType();
userType.setExtension(extension);
user.checkConsistence();
PrismContainer<Containerable> extensionContainer = user.findContainer(GenericObjectType.F_EXTENSION);
checkExtension(extensionContainer,"user extension after setExtension");
checkExtension(extension,"user extension after setExtension");
AssignmentType assignmentType = new AssignmentType();
ExtensionType assignmentExtension = new ExtensionType();
assignmentType.setExtension(assignmentExtension);
PrismContainerValue<ExtensionType> assignmentExtensionValueFromJaxb = assignmentExtension.asPrismContainerValue();
PrismProperty<Integer> intProperty = assignmentExtensionValueFromJaxb.findOrCreateProperty(EXTENSION_INT_TYPE_ELEMENT);
intProperty.setRealValue(15);
PrismProperty<String> stringProperty = assignmentExtensionValueFromJaxb.findOrCreateItem(EXTENSION_STRING_TYPE_ELEMENT, PrismProperty.class);
stringProperty.setRealValue("fifteen men on a dead man chest");
// Adding assignemnt to the user should cause application of definitions
userType.getAssignment().add(assignmentType);
PrismAsserts.assertDefinition(assignmentType.asPrismContainerValue().getParent().getDefinition(),
UserType.F_ASSIGNMENT, AssignmentType.COMPLEX_TYPE, 0, -1);
PrismAsserts.assertDefinition(assignmentExtensionValueFromJaxb.getParent().getDefinition(),
AssignmentType.F_EXTENSION, ExtensionType.COMPLEX_TYPE, 0, 1);
assertTrue("assignment extension definition is not runtime", assignmentExtensionValueFromJaxb.getParent().getDefinition().isRuntimeSchema());
assertTrue("assignment extension definition is not dynamic", assignmentExtensionValueFromJaxb.getParent().getDefinition().isDynamic());
PrismAsserts.assertDefinition(intProperty.getDefinition(), EXTENSION_INT_TYPE_ELEMENT, DOMUtil.XSD_INT, 0, -1);
PrismAsserts.assertDefinition(stringProperty.getDefinition(), EXTENSION_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1);
user.assertDefinitions();
user.checkConsistence();
}
@Test
public void testGenericConstruction() throws JAXBException, SchemaException {
System.out.println("\n\n ===[ testGenericConstruction ]===\n");
// GIVEN
PrismContext prismContext = PrismTestUtil.getPrismContext();
GenericObjectType genericType = new GenericObjectType();
prismContext.adopt(genericType);
PrismObject<GenericObjectType> generic = genericType.asPrismObject();
assertNotNull("No object definition after adopt", generic.getDefinition());
// WHEN
ExtensionType extension = new ExtensionType();
genericType.setExtension(extension);
// THEN
generic.checkConsistence();
PrismContainer<Containerable> extensionContainer = generic.findContainer(GenericObjectType.F_EXTENSION);
checkExtension(extensionContainer,"user extension after setExtension");
checkExtension(extension,"user extension after setExtension");
generic.checkConsistence();
}
@Test
public void testAccountConstruction() throws JAXBException, SchemaException {
System.out.println("\n\n ===[ testAccountConstruction ]===\n");
// GIVEN
PrismContext prismContext = PrismTestUtil.getPrismContext();
ShadowType accountType = new ShadowType();
prismContext.adopt(accountType);
PrismObject<ShadowType> account = accountType.asPrismObject();
assertNotNull("No object definition after adopt", account.getDefinition());
// WHEN
accountType.setName(PrismTestUtil.createPolyStringType(ACCOUNT_NAME));
ObjectReferenceType resourceRefType = new ObjectReferenceType();
resourceRefType.setOid(FAUX_RESOURCE_OID);
resourceRefType.setType(ResourceType.COMPLEX_TYPE);
accountType.setResourceRef(resourceRefType);
// THEN (prism)
account.checkConsistence();
PrismAsserts.assertPropertyValue(account, ShadowType.F_NAME, PrismTestUtil.createPolyString(ACCOUNT_NAME));
PrismReference resourceRef = account.findReference(ShadowType.F_RESOURCE_REF);
assertNotNull("No resourceRef", resourceRef);
PrismReferenceValue resourceRefVal = resourceRef.getValue();
assertNotNull("No resourceRef value", resourceRefVal);
assertEquals("Wrong OID in resourceRef value", FAUX_RESOURCE_OID, resourceRefVal.getOid());
assertEquals("Wrong type in resourceRef value", ResourceType.COMPLEX_TYPE, resourceRefVal.getTargetType());
// Element filter = resourceRefVal.getFilter();
// assertNotNull("No filter in resourceRef value", filter);
// THEN (JAXB)
assertEquals("Wrong name (JAXB)", PrismTestUtil.createPolyStringType(ACCOUNT_NAME), accountType.getName());
resourceRefType = accountType.getResourceRef();
assertNotNull("No resourceRef (JAXB)", resourceRefType);
assertEquals("Wrong OID in resourceRef (JAXB)", FAUX_RESOURCE_OID, resourceRefType.getOid());
assertEquals("Wrong type in resourceRef (JAXB)", ResourceType.COMPLEX_TYPE, resourceRefType.getType());
// Filter filter = connectorRef.getFilter();
// assertNotNull("No filter in connectorRef value (JAXB)", filter);
// Element filterElement = filter.getFilter();
// assertNotNull("No filter element in connectorRef value (JAXB)", filterElement);
}
@Test
public void testExtensionTypeConstruction() throws Exception {
System.out.println("\n\n ===[ testExtensionTypeConstruction ]===\n");
// GIVEN
PrismContext prismContext = PrismTestUtil.getPrismContext();
GenericObjectType object = new GenericObjectType();
prismContext.adopt(object.asPrismObject(), GenericObjectType.class);
ExtensionType extension = new ExtensionType();
object.setExtension(extension);
PrismContainerValue extValue = extension.asPrismContainerValue();
assertNotNull("No extension definition", extValue.getParent().getDefinition());
// WHEN
Item item = extValue.findOrCreateItem(SchemaTestConstants.EXTENSION_STRING_TYPE_ELEMENT);
// THEN
assertNotNull(item);
object.asPrismObject().checkConsistence();
}
@Test
public void testResourceConstruction() throws Exception {
System.out.println("\n\n ===[ testResourceConstruction ]===\n");
// GIVEN
PrismContext prismContext = PrismTestUtil.getPrismContext();
ResourceType resourceType = new ResourceType();
prismContext.adopt(resourceType);
PrismObject<ResourceType> resource = resourceType.asPrismObject();
assertNotNull("No object definition after adopt", resource.getDefinition());
// name: PolyString
resourceType.setName(new PolyStringType("Môj risórs"));
PrismProperty<PolyString> fullNameProperty = resource.findProperty(ResourceType.F_NAME);
PolyString fullName = fullNameProperty.getRealValue();
assertEquals("Wrong name orig", "Môj risórs", fullName.getOrig());
assertEquals("Wrong name norm", "moj risors", fullName.getNorm());
// description: setting null value
resourceType.setDescription(null);
PrismProperty<String> descriptionProperty = resource.findProperty(UserType.F_DESCRIPTION);
assertNull("Unexpected description property "+descriptionProperty, descriptionProperty);
// description: setting null value
resourceType.setDescription("blah blah");
descriptionProperty = resource.findProperty(UserType.F_DESCRIPTION);
assertEquals("Wrong description value", "blah blah", descriptionProperty.getRealValue());
// description: resetting null value
resourceType.setDescription(null);
descriptionProperty = resource.findProperty(UserType.F_DESCRIPTION);
assertNull("Unexpected description property (after reset) "+descriptionProperty, descriptionProperty);
// Extension
ExtensionType extension = new ExtensionType();
resourceType.setExtension(extension);
resource.checkConsistence();
PrismContainer<Containerable> extensionContainer = resource.findContainer(GenericObjectType.F_EXTENSION);
checkExtension(extensionContainer,"resource extension after setExtension");
checkExtension(extension,"resource extension after setExtension");
// Schema
XmlSchemaType xmlSchemaType = new XmlSchemaType();
CachingMetadataType cachingMetadata = new CachingMetadataType();
cachingMetadata.setSerialNumber("serial123");
xmlSchemaType.setCachingMetadata(cachingMetadata);
resourceType.setSchema(xmlSchemaType);
SchemaDefinitionType schemaDefinition = new SchemaDefinitionType();
Element xsdSchemaElement = DOMUtil.createElement(DOMUtil.XSD_SCHEMA_ELEMENT);
schemaDefinition.getAny().add(xsdSchemaElement);
xmlSchemaType.setDefinition(schemaDefinition);
PrismContainer<Containerable> schemaContainer = resource.findContainer(ResourceType.F_SCHEMA);
assertNotNull("No schema container", schemaContainer);
// TODO
// Schema: null
resourceType.setSchema(null);
schemaContainer = resource.findContainer(ResourceType.F_SCHEMA);
assertNull("Unexpected schema container", schemaContainer);
}
private void checkExtension(PrismContainer<Containerable> extensionContainer, String sourceDescription) {
assertNotNull("No extension container in "+sourceDescription+" (prism)", extensionContainer);
assertNotNull("No extension definition in "+sourceDescription+" (prism)", extensionContainer.getDefinition());
assertTrue("Not runtime in definition in "+sourceDescription+" (prism)", extensionContainer.getDefinition().isRuntimeSchema());
}
private void checkExtension(ExtensionType extension, String sourceDescription) throws SchemaException {
PrismContainerValue<ExtensionType> extensionValueFromJaxb = extension.asPrismContainerValue();
assertNotNull("No extension container in "+sourceDescription+" (jaxb)", extensionValueFromJaxb);
assertNotNull("No extension definition in "+sourceDescription+" (jaxb)", extensionValueFromJaxb.getParent().getDefinition());
assertTrue("Not runtime in definition in "+sourceDescription+" (jaxb)", extensionValueFromJaxb.getParent().getDefinition().isRuntimeSchema());
PrismProperty<Integer> intProperty = extensionValueFromJaxb.findOrCreateProperty(EXTENSION_INT_TYPE_ELEMENT);
PrismAsserts.assertDefinition(intProperty.getDefinition(), EXTENSION_INT_TYPE_ELEMENT, DOMUtil.XSD_INT, 0, -1);
intProperty.setRealValue(15);
PrismProperty<String> stringProperty = extensionValueFromJaxb.findOrCreateItem(EXTENSION_STRING_TYPE_ELEMENT, PrismProperty.class);
PrismAsserts.assertDefinition(stringProperty.getDefinition(), EXTENSION_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1);
stringProperty.setRealValue("fifteen men on a dead man chest");
}
private MapXNode createFilter(){
MapXNode filter = new MapXNode();
MapXNode equalsElement = (MapXNode) filter.put(new QName(SchemaConstantsGenerated.NS_QUERY, "equal"), new MapXNode());
PrimitiveXNode<ItemPathType> pathElement = new PrimitiveXNode<>(new ItemPathType(new ItemPath(new QName("name"))));
equalsElement.put(new QName(SchemaConstantsGenerated.NS_QUERY, "path"), pathElement);
PrimitiveXNode<String> valueElement = new PrimitiveXNode<>("čučoriedka");
equalsElement.put(new QName(SchemaConstantsGenerated.NS_QUERY, "value"), valueElement);
return filter;
}
}
|
rpudil/midpoint
|
infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbConstruction.java
|
Java
|
apache-2.0
| 23,746
|
<!--/*
This is a helper fragment that renders components and pages.
*/-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<!--/* render components */-->
<div th:fragment="component(this)">
<div th:if="${this}">
<div th:replace="${'components/' + this.typeCode}" th:with="this = ${this}">
<!-- component script -->
</div>
</div>
</div>
<!--/* render page */-->
<div th:fragment="page(this)">
<div th:if="${this}">
<div th:replace="${this.get('renderTemplateFile')}" th:with="this = ${this}">
<!-- component script -->
</div>
</div>
</div>
</body>
</html>
|
mojo2012/spot-framework
|
spot-cms-base/src/main/resources/templates/cms.html
|
HTML
|
apache-2.0
| 612
|
/*
* Copyright 2016 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.storm.kafka.spout;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.hasKey;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.storm.kafka.spout.config.builder.SingleTopicKafkaSpoutConfiguration;
import org.apache.storm.kafka.spout.internal.KafkaConsumerFactory;
import org.apache.storm.kafka.spout.subscription.Subscription;
import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.utils.Time;
import org.apache.storm.utils.Time.SimulatedTime;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import static org.apache.storm.kafka.spout.config.builder.SingleTopicKafkaSpoutConfiguration.createKafkaSpoutConfigBuilder;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import java.util.HashSet;
import java.util.Set;
import org.apache.kafka.clients.consumer.ConsumerRecord;
public class KafkaSpoutRebalanceTest {
@Captor
private ArgumentCaptor<Map<TopicPartition, OffsetAndMetadata>> commitCapture;
private final long offsetCommitPeriodMs = 2_000;
private final Map<String, Object> conf = new HashMap<>();
private TopologyContext contextMock;
private SpoutOutputCollector collectorMock;
private KafkaConsumer<String, String> consumerMock;
private KafkaConsumerFactory<String, String> consumerFactory;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
contextMock = mock(TopologyContext.class);
collectorMock = mock(SpoutOutputCollector.class);
consumerMock = mock(KafkaConsumer.class);
consumerFactory = (kafkaSpoutConfig) -> consumerMock;
}
//Returns messageIds in order of emission
private List<KafkaSpoutMessageId> emitOneMessagePerPartitionThenRevokeOnePartition(KafkaSpout<String, String> spout, TopicPartition partitionThatWillBeRevoked, TopicPartition assignedPartition, ArgumentCaptor<ConsumerRebalanceListener> rebalanceListenerCapture) {
//Setup spout with mock consumer so we can get at the rebalance listener
spout.open(conf, contextMock, collectorMock);
spout.activate();
//Assign partitions to the spout
ConsumerRebalanceListener consumerRebalanceListener = rebalanceListenerCapture.getValue();
List<TopicPartition> assignedPartitions = new ArrayList<>();
assignedPartitions.add(partitionThatWillBeRevoked);
assignedPartitions.add(assignedPartition);
consumerRebalanceListener.onPartitionsAssigned(assignedPartitions);
//Make the consumer return a single message for each partition
Map<TopicPartition, List<ConsumerRecord<String, String>>> firstPartitionRecords = new HashMap<>();
firstPartitionRecords.put(partitionThatWillBeRevoked, Collections.singletonList(new ConsumerRecord(partitionThatWillBeRevoked.topic(), partitionThatWillBeRevoked.partition(), 0L, "key", "value")));
Map<TopicPartition, List<ConsumerRecord<String, String>>> secondPartitionRecords = new HashMap<>();
secondPartitionRecords.put(assignedPartition, Collections.singletonList(new ConsumerRecord(assignedPartition.topic(), assignedPartition.partition(), 0L, "key", "value")));
when(consumerMock.poll(anyLong()))
.thenReturn(new ConsumerRecords<>(firstPartitionRecords))
.thenReturn(new ConsumerRecords<>(secondPartitionRecords))
.thenReturn(new ConsumerRecords<>(Collections.emptyMap()));
//Emit the messages
spout.nextTuple();
ArgumentCaptor<KafkaSpoutMessageId> messageIdForRevokedPartition = ArgumentCaptor.forClass(KafkaSpoutMessageId.class);
verify(collectorMock).emit(anyString(), anyList(), messageIdForRevokedPartition.capture());
reset(collectorMock);
spout.nextTuple();
ArgumentCaptor<KafkaSpoutMessageId> messageIdForAssignedPartition = ArgumentCaptor.forClass(KafkaSpoutMessageId.class);
verify(collectorMock).emit(anyString(), anyList(), messageIdForAssignedPartition.capture());
//Now rebalance
consumerRebalanceListener.onPartitionsRevoked(assignedPartitions);
consumerRebalanceListener.onPartitionsAssigned(Collections.singleton(assignedPartition));
List<KafkaSpoutMessageId> emittedMessageIds = new ArrayList<>();
emittedMessageIds.add(messageIdForRevokedPartition.getValue());
emittedMessageIds.add(messageIdForAssignedPartition.getValue());
return emittedMessageIds;
}
@Test
public void spoutMustIgnoreAcksForTuplesItIsNotAssignedAfterRebalance() throws Exception {
//Acking tuples for partitions that are no longer assigned is useless since the spout will not be allowed to commit them
try (SimulatedTime simulatedTime = new SimulatedTime()) {
ArgumentCaptor<ConsumerRebalanceListener> rebalanceListenerCapture = ArgumentCaptor.forClass(ConsumerRebalanceListener.class);
Subscription subscriptionMock = mock(Subscription.class);
doNothing()
.when(subscriptionMock)
.subscribe(any(), rebalanceListenerCapture.capture(), any());
KafkaSpout<String, String> spout = new KafkaSpout<>(createKafkaSpoutConfigBuilder(subscriptionMock, -1)
.setOffsetCommitPeriodMs(offsetCommitPeriodMs)
.build(), consumerFactory);
String topic = SingleTopicKafkaSpoutConfiguration.TOPIC;
TopicPartition partitionThatWillBeRevoked = new TopicPartition(topic, 1);
TopicPartition assignedPartition = new TopicPartition(topic, 2);
//Emit a message on each partition and revoke the first partition
List<KafkaSpoutMessageId> emittedMessageIds = emitOneMessagePerPartitionThenRevokeOnePartition(
spout, partitionThatWillBeRevoked, assignedPartition, rebalanceListenerCapture);
//Ack both emitted tuples
spout.ack(emittedMessageIds.get(0));
spout.ack(emittedMessageIds.get(1));
//Ensure the commit timer has expired
Time.advanceTime(offsetCommitPeriodMs + KafkaSpout.TIMER_DELAY_MS);
//Make the spout commit any acked tuples
spout.nextTuple();
//Verify that it only committed the message on the assigned partition
verify(consumerMock, times(1)).commitSync(commitCapture.capture());
Map<TopicPartition, OffsetAndMetadata> commitCaptureMap = commitCapture.getValue();
assertThat(commitCaptureMap, hasKey(assignedPartition));
assertThat(commitCaptureMap, not(hasKey(partitionThatWillBeRevoked)));
}
}
@Test
public void spoutMustIgnoreFailsForTuplesItIsNotAssignedAfterRebalance() throws Exception {
//Failing tuples for partitions that are no longer assigned is useless since the spout will not be allowed to commit them if they later pass
ArgumentCaptor<ConsumerRebalanceListener> rebalanceListenerCapture = ArgumentCaptor.forClass(ConsumerRebalanceListener.class);
Subscription subscriptionMock = mock(Subscription.class);
doNothing()
.when(subscriptionMock)
.subscribe(any(), rebalanceListenerCapture.capture(), any());
KafkaSpoutRetryService retryServiceMock = mock(KafkaSpoutRetryService.class);
KafkaSpout<String, String> spout = new KafkaSpout<>(createKafkaSpoutConfigBuilder(subscriptionMock, -1)
.setOffsetCommitPeriodMs(10)
.setRetry(retryServiceMock)
.build(), consumerFactory);
String topic = SingleTopicKafkaSpoutConfiguration.TOPIC;
TopicPartition partitionThatWillBeRevoked = new TopicPartition(topic, 1);
TopicPartition assignedPartition = new TopicPartition(topic, 2);
when(retryServiceMock.getMessageId(any(TopicPartition.class), anyLong()))
.thenReturn(new KafkaSpoutMessageId(partitionThatWillBeRevoked, 0))
.thenReturn(new KafkaSpoutMessageId(assignedPartition, 0));
//Emit a message on each partition and revoke the first partition
List<KafkaSpoutMessageId> emittedMessageIds = emitOneMessagePerPartitionThenRevokeOnePartition(
spout, partitionThatWillBeRevoked, assignedPartition, rebalanceListenerCapture);
//Check that only two message ids were generated
verify(retryServiceMock, times(2)).getMessageId(any(TopicPartition.class), anyLong());
//Fail both emitted tuples
spout.fail(emittedMessageIds.get(0));
spout.fail(emittedMessageIds.get(1));
//Check that only the tuple on the currently assigned partition is retried
verify(retryServiceMock, never()).schedule(emittedMessageIds.get(0));
verify(retryServiceMock).schedule(emittedMessageIds.get(1));
}
@Test
public void testReassignPartitionSeeksForOnlyNewPartitions() {
/*
* When partitions are reassigned, the spout should seek with the first poll offset strategy for new partitions.
* Previously assigned partitions should be left alone, since the spout keeps the emitted and acked state for those.
*/
ArgumentCaptor<ConsumerRebalanceListener> rebalanceListenerCapture = ArgumentCaptor.forClass(ConsumerRebalanceListener.class);
Subscription subscriptionMock = mock(Subscription.class);
doNothing()
.when(subscriptionMock)
.subscribe(any(), rebalanceListenerCapture.capture(), any());
KafkaSpout<String, String> spout = new KafkaSpout<>(createKafkaSpoutConfigBuilder(subscriptionMock, -1)
.setFirstPollOffsetStrategy(KafkaSpoutConfig.FirstPollOffsetStrategy.UNCOMMITTED_EARLIEST)
.build(), consumerFactory);
String topic = SingleTopicKafkaSpoutConfiguration.TOPIC;
TopicPartition assignedPartition = new TopicPartition(topic, 1);
TopicPartition newPartition = new TopicPartition(topic, 2);
//Setup spout with mock consumer so we can get at the rebalance listener
spout.open(conf, contextMock, collectorMock);
spout.activate();
//Assign partitions to the spout
ConsumerRebalanceListener consumerRebalanceListener = rebalanceListenerCapture.getValue();
Set<TopicPartition> assignedPartitions = new HashSet<>();
assignedPartitions.add(assignedPartition);
consumerRebalanceListener.onPartitionsAssigned(assignedPartitions);
reset(consumerMock);
//Set up committed so it looks like some messages have been committed on each partition
long committedOffset = 500;
when(consumerMock.committed(assignedPartition)).thenReturn(new OffsetAndMetadata(committedOffset));
when(consumerMock.committed(newPartition)).thenReturn(new OffsetAndMetadata(committedOffset));
//Now rebalance and add a new partition
consumerRebalanceListener.onPartitionsRevoked(assignedPartitions);
Set<TopicPartition> newAssignedPartitions = new HashSet<>();
newAssignedPartitions.add(assignedPartition);
newAssignedPartitions.add(newPartition);
consumerRebalanceListener.onPartitionsAssigned(newAssignedPartitions);
//This partition was previously assigned, so the consumer position shouldn't change
verify(consumerMock, never()).seek(eq(assignedPartition), anyLong());
//This partition is new, and should start at the committed offset
verify(consumerMock).seek(newPartition, committedOffset);
}
}
|
wangcy6/storm_app
|
frame/storm-master/external/storm-kafka-client/src/test/java/org/apache/storm/kafka/spout/KafkaSpoutRebalanceTest.java
|
Java
|
apache-2.0
| 13,176
|
<!--
Copyright JS Foundation and other contributors, http://js.foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- WebSocket Input Node -->
<script type="text/html" data-template-name="websocket in">
<div class="form-row">
<label for="node-input-mode"><i class="fa fa-dot-circle-o"></i> <span data-i18n="websocket.label.type"></span></label>
<select id="node-input-mode">
<option value="server" data-i18n="websocket.listenon"></option>
<option value="client" data-i18n="websocket.connectto"></option>
</select>
</div>
<div class="form-row" id="websocket-server-row">
<label for="node-input-server"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.path"></span></label>
<input type="text" id="node-input-server">
</div>
<div class="form-row" id="websocket-client-row">
<label for="node-input-client"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.url"></span></label>
<input type="text" id="node-input-client">
</div>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
</div>
</script>
<script type="text/javascript">
(function() {
function ws_oneditprepare() {
$("#websocket-client-row").hide();
$("#node-input-mode").on("change", function() {
if ( $("#node-input-mode").val() === 'client') {
$("#websocket-server-row").hide();
$("#websocket-client-row").show();
}
else {
$("#websocket-server-row").show();
$("#websocket-client-row").hide();
}
});
if (this.client) {
$("#node-input-mode").val('client').change();
}
else {
$("#node-input-mode").val('server').change();
}
}
function ws_oneditsave() {
if ($("#node-input-mode").val() === 'client') {
$("#node-input-server").append('<option value="">Dummy</option>');
$("#node-input-server").val('');
}
else {
$("#node-input-client").append('<option value="">Dummy</option>');
$("#node-input-client").val('');
}
}
function ws_label() {
var nodeid = (this.client)?this.client:this.server;
var wsNode = RED.nodes.node(nodeid);
return this.name||(wsNode?"[ws] "+wsNode.label():"websocket");
}
function ws_validateserver() {
if ($("#node-input-mode").val() === 'client' || (this.client && !this.server)) {
return true;
}
else {
return RED.nodes.node(this.server) != null;
}
}
function ws_validateclient() {
if ($("#node-input-mode").val() === 'client' || (this.client && !this.server)) {
return RED.nodes.node(this.client) != null;
}
else {
return true;
}
}
RED.nodes.registerType('websocket in',{
category: 'network',
defaults: {
name: {value:""},
server: {type:"websocket-listener", validate: ws_validateserver},
client: {type:"websocket-client", validate: ws_validateclient}
},
color:"rgb(215, 215, 160)",
inputs:0,
outputs:1,
icon: "white-globe.svg",
labelStyle: function() {
return this.name?"node_label_italic":"";
},
label: ws_label,
oneditsave: ws_oneditsave,
oneditprepare: ws_oneditprepare
});
RED.nodes.registerType('websocket out',{
category: 'network',
defaults: {
name: {value:""},
server: {type:"websocket-listener", validate: ws_validateserver},
client: {type:"websocket-client", validate: ws_validateclient}
},
color:"rgb(215, 215, 160)",
inputs:1,
outputs:0,
icon: "white-globe.svg",
align: "right",
labelStyle: function() {
return this.name?"node_label_italic":"";
},
label: ws_label,
oneditsave: ws_oneditsave,
oneditprepare: ws_oneditprepare
});
RED.nodes.registerType('websocket-listener',{
category: 'config',
defaults: {
path: {value:"",required:true,validate:RED.validators.regex(/^((?!\/debug\/ws).)*$/)},
wholemsg: {value:"false"}
},
inputs:0,
outputs:0,
label: function() {
var root = RED.settings.httpNodeRoot;
if (root.slice(-1) != "/") {
root = root+"/";
}
if (this.path) {
if (this.path.charAt(0) == "/") {
root += this.path.slice(1);
} else {
root += this.path;
}
}
return root;
},
oneditprepare: function() {
var root = RED.settings.httpNodeRoot;
if (root.slice(-1) == "/") {
root = root.slice(0,-1);
}
if (root === "") {
$("#node-config-ws-tip").hide();
} else {
$("#node-config-ws-path").html(RED._("node-red:websocket.tip.path2", { path: root }));
$("#node-config-ws-tip").show();
}
}
});
RED.nodes.registerType('websocket-client',{
category: 'config',
defaults: {
path: {value:"",required:true,validate:RED.validators.regex(/^((?!\/debug\/ws).)*$/)},
tls: {type:"tls-config",required: false},
wholemsg: {value:"false"},
hb: {value: "", validate: RED.validators.number(/*blank allowed*/true) }
},
inputs:0,
outputs:0,
label: function() {
return this.path;
},
oneditprepare: function() {
$("#node-config-input-path").on("change keyup paste",function() {
$(".node-config-row-tls").toggle(/^wss:/i.test($(this).val()))
});
$("#node-config-input-path").change();
var heartbeatActive = (this.hb && this.hb != "0");
$("#node-config-input-hb-cb").prop("checked",heartbeatActive);
$("#node-config-input-hb-cb").on("change", function(evt) {
$("#node-config-input-hb-row").toggle(this.checked);
})
$("#node-config-input-hb-cb").trigger("change");
if (!heartbeatActive) {
$("#node-config-input-hb").val("");
}
},
oneditsave: function() {
if (!/^wss:/i.test($("#node-config-input-path").val())) {
$("#node-config-input-tls").val("_ADD_");
}
if (!$("#node-config-input-hb-cb").prop("checked")) {
$("#node-config-input-hb").val("0");
}
}
});
})();
</script>
<!-- WebSocket out Node -->
<script type="text/html" data-template-name="websocket out">
<div class="form-row">
<label for="node-input-mode"><i class="fa fa-dot-circle-o"></i> <span data-i18n="websocket.label.type"></span></label>
<select id="node-input-mode">
<option value="server" data-i18n="websocket.listenon"></option>
<option value="client" data-i18n="websocket.connectto"></option>
</select>
</div>
<div class="form-row" id="websocket-server-row">
<label for="node-input-server"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.path"></span></label>
<input type="text" id="node-input-server">
</div>
<div class="form-row" id="websocket-client-row">
<label for="node-input-client"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.url"></span></label>
<input type="text" id="node-input-client">
</div>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
</div>
</script>
<!-- WebSocket Server configuration node -->
<script type="text/html" data-template-name="websocket-listener">
<div class="form-row">
<label for="node-config-input-path"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.path"></span></label>
<input id="node-config-input-path" type="text" placeholder="/ws/example">
</div>
<div class="form-row">
<label for="node-config-input-wholemsg" data-i18n="websocket.sendrec"></label>
<select type="text" id="node-config-input-wholemsg" style="width: 70%;">
<option value="false" data-i18n="websocket.payload"></option>
<option value="true" data-i18n="websocket.message"></option>
</select>
</div>
<div class="form-tips">
<span data-i18n="[html]websocket.tip.path1"></span>
<p id="node-config-ws-tip"><span id="node-config-ws-path"></span></p>
</div>
</script>
<!-- WebSocket Client configuration node -->
<script type="text/html" data-template-name="websocket-client">
<div class="form-row">
<label for="node-config-input-path"><i class="fa fa-bookmark"></i> <span data-i18n="websocket.label.url"></span></label>
<input id="node-config-input-path" type="text" placeholder="ws://example.com/ws">
</div>
<div class="form-row node-config-row-tls hide">
<label for="node-config-input-tls" data-i18n="httpin.tls-config"></label>
<input type="text" id="node-config-input-tls">
</div>
<div class="form-row">
<label for="node-config-input-wholemsg" data-i18n="websocket.sendrec"></label>
<select type="text" id="node-config-input-wholemsg" style="width: 70%;">
<option value="false" data-i18n="websocket.payload"></option>
<option value="true" data-i18n="websocket.message"></option>
</select>
</div>
<div class="form-row" style="display: flex; align-items: center; min-height: 34px">
<label for="node-config-input-hb-cb" data-i18n="websocket.sendheartbeat"></label>
<input type="checkbox" style="margin: 0 8px; width:auto" id="node-config-input-hb-cb">
<span id="node-config-input-hb-row" class="hide" >
<input type="text" style="width: 70px; margin-right: 3px" id="node-config-input-hb">
<span data-i18n="inject.seconds"></span>
</span>
</div>
<div class="form-tips">
<p><span data-i18n="[html]websocket.tip.url1"></span></p>
<span data-i18n="[html]websocket.tip.url2"></span>
</div>
</script>
|
btsimonh/node-red
|
packages/node_modules/@node-red/nodes/core/network/22-websocket.html
|
HTML
|
apache-2.0
| 11,290
|
//
// Licensed to Green Energy Corp (www.greenenergycorp.com) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Green Enery Corp licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#include <opendnp3/DNP3/APDUConstants.h>
namespace apl
{
namespace dnp
{
bool IsResponse(FunctionCodes aCode)
{
return aCode == FC_RESPONSE || aCode == FC_UNSOLICITED_RESPONSE;
}
bool IsRequest(FunctionCodes aCode)
{
switch(aCode) {
case(FC_CONFIRM):
case(FC_RESPONSE):
case(FC_UNSOLICITED_RESPONSE):
return false;
default:
return true;
}
}
std::string ToString(FunctionCodes aCode)
{
switch(aCode) {
case(FC_CONFIRM) : return "Confirm";
case(FC_READ): return "Read";
case(FC_WRITE): return "Write";
case(FC_SELECT): return "Select";
case(FC_OPERATE): return "Operate";
case(FC_DIRECT_OPERATE): return "Direct Operate";
case(FC_DIRECT_OPERATE_NO_ACK): return "Operate No ACK";
case(FC_FREEZE): return "Freeze";
case(FC_FREEZE_NO_ACK): return "Freeze No ACK";
case(FC_FREEZE_CLEAR): return "Freeze Clear";
case(FC_FREEZE_CLEAR_NO_ACK): return "Freeze Clear No ACK";
case(FC_FREEZE_AT_TIME): return "Freeze At Time";
case(FC_FREEZE_AT_TIME_NO_ACK): return "Freeze At Time No ACK";
case(FC_COLD_RESTART): return "Cold Restart";
case(FC_WARM_RESTART): return "Warm Restart";
case(FC_INITIALIZE_DATA): return "Init Data";
case(FC_INITIALIZE_APPLICATION): return "Init App";
case(FC_START_APPLICATION): return "Start App";
case(FC_STOP_APPLICATION): return "Stop Appl";
case(FC_SAVE_CONFIGURATION): return "Save Config";
case(FC_ENABLE_UNSOLICITED): return "Enable Unsol";
case(FC_DISABLE_UNSOLICITED): return "Disable Unsol";
case(FC_ASSIGN_CLASS): return "Assign Classs";
case(FC_DELAY_MEASURE): return "Delay Measure";
case(FC_RECORD_TIME): return "Record Time";
case(FC_FILE_OPEN): return "File Open";
case(FC_FILE_CLOSE): return "File Close";
case(FC_FILE_DELETE): return "File Delete";
case(FC_FILE_INFO): return "File Info";
case(FC_FILE_AUTHENTICATE): return "File Authenticate";
case(FC_FILE_ABORT): return "File Abort";
case(FC_RESPONSE): return "Rsp";
case(FC_UNSOLICITED_RESPONSE): return "Unsol Rsp";
default: return "Undefined";
}
}
}
}
|
cverges/dnp3
|
opendnp3/DNP3/APDUConstants.cpp
|
C++
|
apache-2.0
| 2,823
|
# Copyright (c) 2014 Mirantis 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.
from cloudferrylib.base.action import action
from cloudferrylib.os.actions import snap_transfer
from cloudferrylib.os.actions import task_transfer
from cloudferrylib.utils.drivers import ssh_ceph_to_ceph
from cloudferrylib.utils import rbd_util
from cloudferrylib.utils import utils as utl
import copy
OLD_ID = 'old_id'
class DeployVolSnapshots(action.Action):
def run(self, storage_info=None, identity_info=None, **kwargs):
storage_info = copy.deepcopy(storage_info)
deploy_info = copy.deepcopy(storage_info)
deploy_info.update(identity_info)
storage_info.update(identity_info)
volume_resource = self.cloud.resources[utl.STORAGE_RESOURCE]
for vol_id, vol in deploy_info[utl.VOLUMES_TYPE].iteritems():
if vol['snapshots']:
vol_info = vol[utl.VOLUME_BODY]
snapshots_list = \
[snap_info for snap_info in vol['snapshots'].values()]
snapshots_list.sort(key=lambda x: x['created_at'])
for snap in snapshots_list:
if snapshots_list.index(snap) == 0:
act_snap_transfer = \
snap_transfer.SnapTransfer(
self.init,
ssh_ceph_to_ceph.SSHCephToCeph,
1)
else:
snap_num = snapshots_list.index(snap)
snap['prev_snapname'] = \
snapshots_list[snap_num - 1]['name']
act_snap_transfer = \
snap_transfer.SnapTransfer(
self.init,
ssh_ceph_to_ceph.SSHCephToCeph,
2)
act_snap_transfer.run(volume=vol_info, snapshot_info=snap)
volume_resource.create_snapshot(
volume_id=vol_id,
display_name=snap['display_name'],
display_description=snap['display_description'])
act_snap_transfer = snap_transfer.SnapTransfer(
self.init,
ssh_ceph_to_ceph.SSHCephToCeph,
3)
act_snap_transfer.run(volume=vol_info,
snapshot_info=snapshots_list[-1])
for snap in snapshots_list:
if volume_resource.config.storage.host:
act_delete_redundant_snap = \
rbd_util.RbdUtil(cloud=self.cloud,
config_migrate=self.cfg.migrate,
host=vol_info[utl.HOST_DST])
act_delete_redundant_snap.snap_rm(
vol_info[utl.PATH_DST],
snap['name'])
else:
act_delete_redundant_snap = \
rbd_util.RbdUtil(cloud=self.cloud,
config_migrate=self.cfg.migrate)
act_delete_redundant_snap.snap_rm(
vol_info[utl.PATH_DST],
snap['name'], vol_info[utl.HOST_DST])
else:
one_volume_info = {
'one_volume_info': {
utl.VOLUMES_TYPE: {
vol_id: vol
}
}
}
act_transport_vol_data = \
task_transfer.TaskTransfer(self.init,
'SSHCephToCeph',
input_info='one_volume_info')
act_transport_vol_data.run(**one_volume_info)
return {}
|
japaniel/CloudFerry
|
cloudferrylib/os/actions/deploy_snapshots.py
|
Python
|
apache-2.0
| 4,490
|
// Copyright 2016 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"strings"
"testing"
. "github.com/pingcap/check"
)
var _ = Suite(&testMyDecimalSuite{})
var _ = SerialSuites(&testMyDecimalSerialSuite{})
type testMyDecimalSuite struct {
}
// testMyDecimalSerialSuite hold test cases that must run in serial
type testMyDecimalSerialSuite struct {
}
func (s *testMyDecimalSuite) TestFromInt(c *C) {
tests := []struct {
input int64
output string
}{
{-12345, "-12345"},
{-1, "-1"},
{1, "1"},
{-9223372036854775807, "-9223372036854775807"},
{-9223372036854775808, "-9223372036854775808"},
}
for _, tt := range tests {
dec := NewDecFromInt(tt.input)
str := dec.ToString()
c.Check(string(str), Equals, tt.output)
}
}
func (s *testMyDecimalSuite) TestFromUint(c *C) {
tests := []struct {
input uint64
output string
}{
{12345, "12345"},
{0, "0"},
{18446744073709551615, "18446744073709551615"},
}
for _, tt := range tests {
var dec MyDecimal
dec.FromUint(tt.input)
str := dec.ToString()
c.Check(string(str), Equals, tt.output)
}
}
func (s *testMyDecimalSuite) TestToInt(c *C) {
tests := []struct {
input string
output int64
err error
}{
{"18446744073709551615", 9223372036854775807, ErrOverflow},
{"-1", -1, nil},
{"1", 1, nil},
{"-1.23", -1, ErrTruncated},
{"-9223372036854775807", -9223372036854775807, nil},
{"-9223372036854775808", -9223372036854775808, nil},
{"9223372036854775808", 9223372036854775807, ErrOverflow},
{"-9223372036854775809", -9223372036854775808, ErrOverflow},
}
for _, tt := range tests {
var dec MyDecimal
dec.FromString([]byte(tt.input))
result, ec := dec.ToInt()
c.Check(ec, Equals, tt.err)
c.Check(result, Equals, tt.output)
}
}
func (s *testMyDecimalSuite) TestToUint(c *C) {
tests := []struct {
input string
output uint64
err error
}{
{"12345", 12345, nil},
{"0", 0, nil},
/* ULLONG_MAX = 18446744073709551615ULL */
{"18446744073709551615", 18446744073709551615, nil},
{"18446744073709551616", 18446744073709551615, ErrOverflow},
{"-1", 0, ErrOverflow},
{"1.23", 1, ErrTruncated},
{"9999999999999999999999999.000", 18446744073709551615, ErrOverflow},
}
for _, tt := range tests {
var dec MyDecimal
dec.FromString([]byte(tt.input))
result, ec := dec.ToUint()
c.Check(ec, Equals, tt.err)
c.Check(result, Equals, tt.output)
}
}
func (s *testMyDecimalSuite) TestFromFloat(c *C) {
tests := []struct {
s string
f float64
}{
{"12345", 12345},
{"123.45", 123.45},
{"-123.45", -123.45},
{"0.00012345000098765", 0.00012345000098765},
{"1234500009876.5", 1234500009876.5},
}
for _, tt := range tests {
dec := NewDecFromFloatForTest(tt.f)
str := dec.ToString()
c.Check(string(str), Equals, tt.s)
}
}
func (s *testMyDecimalSuite) TestToFloat(c *C) {
tests := []struct {
s string
f float64
}{
{"12345", 12345},
{"123.45", 123.45},
{"-123.45", -123.45},
{"0.00012345000098765", 0.00012345000098765},
{"1234500009876.5", 1234500009876.5},
}
for _, ca := range tests {
var dec MyDecimal
dec.FromString([]byte(ca.s))
f, err := dec.ToFloat64()
c.Check(err, IsNil)
c.Check(f, Equals, ca.f)
}
}
func (s *testMyDecimalSuite) TestToHashKey(c *C) {
tests := []struct {
numbers []string
}{
{[]string{"1.1", "1.1000", "1.1000000", "1.10000000000", "01.1", "0001.1", "001.1000000"}},
{[]string{"-1.1", "-1.1000", "-1.1000000", "-1.10000000000", "-01.1", "-0001.1", "-001.1000000"}},
{[]string{".1", "0.1", "0.10", "000000.1", ".10000", "0000.10000", "000000000000000000.1"}},
{[]string{"0", "0000", ".0", ".00000", "00000.00000", "-0", "-0000", "-.0", "-.00000", "-00000.00000"}},
{[]string{".123456789123456789", ".1234567891234567890", ".12345678912345678900", ".123456789123456789000", ".1234567891234567890000", "0.123456789123456789",
".1234567891234567890000000000", "0000000.123456789123456789000"}},
{[]string{"12345", "012345", "0012345", "0000012345", "0000000012345", "00000000000012345", "12345.", "12345.00", "12345.000000000", "000012345.0000"}},
{[]string{"123E5", "12300000", "00123E5", "000000123E5", "12300000.00000000"}},
{[]string{"123E-2", "1.23", "00000001.23", "1.2300000000000000", "000000001.23000000000000"}},
}
for _, ca := range tests {
keys := make([]string, 0, len(ca.numbers))
for _, num := range ca.numbers {
var dec MyDecimal
c.Check(dec.FromString([]byte(num)), IsNil)
key, err := dec.ToHashKey()
c.Check(err, IsNil)
keys = append(keys, string(key))
}
for i := 1; i < len(keys); i++ {
c.Check(keys[0], Equals, keys[i])
}
}
binTests := []struct {
hashNumbers []string
binNumbers []string
}{
{[]string{"1.1", "1.1000", "1.1000000", "1.10000000000", "01.1", "0001.1", "001.1000000"},
[]string{"1.1", "0001.1", "01.1"}},
{[]string{"-1.1", "-1.1000", "-1.1000000", "-1.10000000000", "-01.1", "-0001.1", "-001.1000000"},
[]string{"-1.1", "-0001.1", "-01.1"}},
{[]string{".1", "0.1", "000000.1", ".10000", "0000.10000", "000000000000000000.1"},
[]string{".1", "0.1", "000000.1", "00.1"}},
{[]string{"0", "0000", ".0", ".00000", "00000.00000", "-0", "-0000", "-.0", "-.00000", "-00000.00000"},
[]string{"0", "0000", "00", "-0", "-00", "-000000"}},
{[]string{".123456789123456789", ".1234567891234567890", ".12345678912345678900", ".123456789123456789000", ".1234567891234567890000", "0.123456789123456789",
".1234567891234567890000000000", "0000000.123456789123456789000"},
[]string{".123456789123456789", "0.123456789123456789", "0000.123456789123456789", "0000000.123456789123456789"}},
{[]string{"12345", "012345", "0012345", "0000012345", "0000000012345", "00000000000012345", "12345.", "12345.00", "12345.000000000", "000012345.0000"},
[]string{"12345", "012345", "000012345", "000000000000012345"}},
{[]string{"123E5", "12300000", "00123E5", "000000123E5", "12300000.00000000"},
[]string{"12300000", "123E5", "00123E5", "0000000000123E5"}},
{[]string{"123E-2", "1.23", "00000001.23", "1.2300000000000000", "000000001.23000000000000"},
[]string{"123E-2", "1.23", "000001.23", "0000000000001.23"}},
}
for _, ca := range binTests {
keys := make([]string, 0, len(ca.hashNumbers)+len(ca.binNumbers))
for _, num := range ca.hashNumbers {
var dec MyDecimal
c.Check(dec.FromString([]byte(num)), IsNil)
key, err := dec.ToHashKey()
// remove digit len
key = key[:len(key)-1]
c.Check(err, IsNil)
keys = append(keys, string(key))
}
for _, num := range ca.binNumbers {
var dec MyDecimal
c.Check(dec.FromString([]byte(num)), IsNil)
prec, frac := dec.PrecisionAndFrac() // remove leading zeros but trailing zeros remain
key, err := dec.ToBin(prec, frac)
c.Check(err, IsNil)
keys = append(keys, string(key))
}
for i := 1; i < len(keys); i++ {
c.Check(keys[0], Equals, keys[i])
}
}
}
func (s *testMyDecimalSuite) TestRemoveTrailingZeros(c *C) {
tests := []string{
"0", "0.0", ".0", ".00000000", "0.0000", "0000", "0000.0", "0000.000",
"-0", "-0.0", "-.0", "-.00000000", "-0.0000", "-0000", "-0000.0", "-0000.000",
"123123123", "213123.", "21312.000", "21321.123", "213.1230000", "213123.000123000",
"-123123123", "-213123.", "-21312.000", "-21321.123", "-213.1230000", "-213123.000123000",
"123E5", "12300E-5", "0.00100E1", "0.001230E-3",
"123987654321.123456789000", "000000000123", "123456789.987654321", "999.999000",
}
for _, ca := range tests {
var dec MyDecimal
c.Check(dec.FromString([]byte(ca)), IsNil)
// calculate the number of digits after point but trailing zero
digitsFracExp := 0
str := string(dec.ToString())
point := strings.Index(str, ".")
if point != -1 {
pos := len(str) - 1
for pos > point {
if str[pos] != '0' {
break
}
pos--
}
digitsFracExp = pos - point
}
_, digitsFrac := dec.removeTrailingZeros()
c.Check(digitsFrac, Equals, digitsFracExp)
}
}
// this test will change global variable `wordBufLen`, so it must run in serial
func (s *testMyDecimalSerialSuite) TestShift(c *C) {
type tcase struct {
input string
shift int
output string
err error
}
var dotest = func(c *C, tests []tcase) {
for _, ca := range tests {
var dec MyDecimal
err := dec.FromString([]byte(ca.input))
c.Check(err, IsNil)
origin := dec
err = dec.Shift(ca.shift)
c.Check(err, Equals, ca.err)
result := dec.ToString()
c.Check(string(result), Equals, ca.output, Commentf("origin:%s\ndec:%s", origin.String(), string(result)))
}
}
wordBufLen = maxWordBufLen
tests := []tcase{
{"123.123", 1, "1231.23", nil},
{"123457189.123123456789000", 1, "1234571891.23123456789", nil},
{"123457189.123123456789000", 8, "12345718912312345.6789", nil},
{"123457189.123123456789000", 9, "123457189123123456.789", nil},
{"123457189.123123456789000", 10, "1234571891231234567.89", nil},
{"123457189.123123456789000", 17, "12345718912312345678900000", nil},
{"123457189.123123456789000", 18, "123457189123123456789000000", nil},
{"123457189.123123456789000", 19, "1234571891231234567890000000", nil},
{"123457189.123123456789000", 26, "12345718912312345678900000000000000", nil},
{"123457189.123123456789000", 27, "123457189123123456789000000000000000", nil},
{"123457189.123123456789000", 28, "1234571891231234567890000000000000000", nil},
{"000000000000000000000000123457189.123123456789000", 26, "12345718912312345678900000000000000", nil},
{"00000000123457189.123123456789000", 27, "123457189123123456789000000000000000", nil},
{"00000000000000000123457189.123123456789000", 28, "1234571891231234567890000000000000000", nil},
{"123", 1, "1230", nil},
{"123", 10, "1230000000000", nil},
{".123", 1, "1.23", nil},
{".123", 10, "1230000000", nil},
{".123", 14, "12300000000000", nil},
{"000.000", 1000, "0", nil},
{"000.", 1000, "0", nil},
{".000", 1000, "0", nil},
{"1", 1000, "1", ErrOverflow},
{"123.123", -1, "12.3123", nil},
{"123987654321.123456789000", -1, "12398765432.1123456789", nil},
{"123987654321.123456789000", -2, "1239876543.21123456789", nil},
{"123987654321.123456789000", -3, "123987654.321123456789", nil},
{"123987654321.123456789000", -8, "1239.87654321123456789", nil},
{"123987654321.123456789000", -9, "123.987654321123456789", nil},
{"123987654321.123456789000", -10, "12.3987654321123456789", nil},
{"123987654321.123456789000", -11, "1.23987654321123456789", nil},
{"123987654321.123456789000", -12, "0.123987654321123456789", nil},
{"123987654321.123456789000", -13, "0.0123987654321123456789", nil},
{"123987654321.123456789000", -14, "0.00123987654321123456789", nil},
{"00000087654321.123456789000", -14, "0.00000087654321123456789", nil},
}
dotest(c, tests)
wordBufLen = 2
tests = []tcase{
{"123.123", -2, "1.23123", nil},
{"123.123", -3, "0.123123", nil},
{"123.123", -6, "0.000123123", nil},
{"123.123", -7, "0.0000123123", nil},
{"123.123", -15, "0.000000000000123123", nil},
{"123.123", -16, "0.000000000000012312", ErrTruncated},
{"123.123", -17, "0.000000000000001231", ErrTruncated},
{"123.123", -18, "0.000000000000000123", ErrTruncated},
{"123.123", -19, "0.000000000000000012", ErrTruncated},
{"123.123", -20, "0.000000000000000001", ErrTruncated},
{"123.123", -21, "0", ErrTruncated},
{".000000000123", -1, "0.0000000000123", nil},
{".000000000123", -6, "0.000000000000000123", nil},
{".000000000123", -7, "0.000000000000000012", ErrTruncated},
{".000000000123", -8, "0.000000000000000001", ErrTruncated},
{".000000000123", -9, "0", ErrTruncated},
{".000000000123", 1, "0.00000000123", nil},
{".000000000123", 8, "0.0123", nil},
{".000000000123", 9, "0.123", nil},
{".000000000123", 10, "1.23", nil},
{".000000000123", 17, "12300000", nil},
{".000000000123", 18, "123000000", nil},
{".000000000123", 19, "1230000000", nil},
{".000000000123", 20, "12300000000", nil},
{".000000000123", 21, "123000000000", nil},
{".000000000123", 22, "1230000000000", nil},
{".000000000123", 23, "12300000000000", nil},
{".000000000123", 24, "123000000000000", nil},
{".000000000123", 25, "1230000000000000", nil},
{".000000000123", 26, "12300000000000000", nil},
{".000000000123", 27, "123000000000000000", nil},
{".000000000123", 28, "0.000000000123", ErrOverflow},
{"123456789.987654321", -1, "12345678.998765432", ErrTruncated},
{"123456789.987654321", -2, "1234567.899876543", ErrTruncated},
{"123456789.987654321", -8, "1.234567900", ErrTruncated},
{"123456789.987654321", -9, "0.123456789987654321", nil},
{"123456789.987654321", -10, "0.012345678998765432", ErrTruncated},
{"123456789.987654321", -17, "0.000000001234567900", ErrTruncated},
{"123456789.987654321", -18, "0.000000000123456790", ErrTruncated},
{"123456789.987654321", -19, "0.000000000012345679", ErrTruncated},
{"123456789.987654321", -26, "0.000000000000000001", ErrTruncated},
{"123456789.987654321", -27, "0", ErrTruncated},
{"123456789.987654321", 1, "1234567900", ErrTruncated},
{"123456789.987654321", 2, "12345678999", ErrTruncated},
{"123456789.987654321", 4, "1234567899877", ErrTruncated},
{"123456789.987654321", 8, "12345678998765432", ErrTruncated},
{"123456789.987654321", 9, "123456789987654321", nil},
{"123456789.987654321", 10, "123456789.987654321", ErrOverflow},
{"123456789.987654321", 0, "123456789.987654321", nil},
}
dotest(c, tests)
wordBufLen = maxWordBufLen
}
func (s *testMyDecimalSuite) TestRoundWithHalfEven(c *C) {
tests := []struct {
input string
scale int
output string
err error
}{
{"123456789.987654321", 1, "123456790.0", nil},
{"15.1", 0, "15", nil},
{"15.5", 0, "16", nil},
{"15.9", 0, "16", nil},
{"-15.1", 0, "-15", nil},
{"-15.5", 0, "-16", nil},
{"-15.9", 0, "-16", nil},
{"15.1", 1, "15.1", nil},
{"-15.1", 1, "-15.1", nil},
{"15.17", 1, "15.2", nil},
{"15.4", -1, "20", nil},
{"-15.4", -1, "-20", nil},
{"5.4", -1, "10", nil},
{".999", 0, "1", nil},
{"999999999", -9, "1000000000", nil},
}
for _, ca := range tests {
var dec MyDecimal
dec.FromString([]byte(ca.input))
var rounded MyDecimal
err := dec.Round(&rounded, ca.scale, ModeHalfEven)
c.Check(err, Equals, ca.err)
result := rounded.ToString()
c.Check(string(result), Equals, ca.output)
}
}
func (s *testMyDecimalSuite) TestRoundWithTruncate(c *C) {
tests := []struct {
input string
scale int
output string
err error
}{
{"123456789.987654321", 1, "123456789.9", nil},
{"15.1", 0, "15", nil},
{"15.5", 0, "15", nil},
{"15.9", 0, "15", nil},
{"-15.1", 0, "-15", nil},
{"-15.5", 0, "-15", nil},
{"-15.9", 0, "-15", nil},
{"15.1", 1, "15.1", nil},
{"-15.1", 1, "-15.1", nil},
{"15.17", 1, "15.1", nil},
{"15.4", -1, "10", nil},
{"-15.4", -1, "-10", nil},
{"5.4", -1, "0", nil},
{".999", 0, "0", nil},
{"999999999", -9, "0", nil},
}
for _, ca := range tests {
var dec MyDecimal
dec.FromString([]byte(ca.input))
var rounded MyDecimal
err := dec.Round(&rounded, ca.scale, ModeTruncate)
c.Check(err, Equals, ca.err)
result := rounded.ToString()
c.Check(string(result), Equals, ca.output)
}
}
func (s *testMyDecimalSuite) TestRoundWithCeil(c *C) {
tests := []struct {
input string
scale int
output string
err error
}{
{"123456789.987654321", 1, "123456790.0", nil},
{"15.1", 0, "16", nil},
{"15.5", 0, "16", nil},
{"15.9", 0, "16", nil},
//TODO:fix me
{"-15.1", 0, "-16", nil},
{"-15.5", 0, "-16", nil},
{"-15.9", 0, "-16", nil},
{"15.1", 1, "15.1", nil},
{"-15.1", 1, "-15.1", nil},
{"15.17", 1, "15.2", nil},
{"15.4", -1, "20", nil},
{"-15.4", -1, "-20", nil},
{"5.4", -1, "10", nil},
{".999", 0, "1", nil},
{"999999999", -9, "1000000000", nil},
}
for _, ca := range tests {
var dec MyDecimal
dec.FromString([]byte(ca.input))
var rounded MyDecimal
err := dec.Round(&rounded, ca.scale, modeCeiling)
c.Check(err, Equals, ca.err)
result := rounded.ToString()
c.Check(string(result), Equals, ca.output)
}
}
// this test will change global variable `wordBufLen`, so it must run in serial
func (s *testMyDecimalSerialSuite) TestFromString(c *C) {
type tcase struct {
input string
output string
err error
}
tests := []tcase{
{"12345", "12345", nil},
{"12345.", "12345", nil},
{"123.45.", "123.45", nil},
{"-123.45.", "-123.45", nil},
{".00012345000098765", "0.00012345000098765", nil},
{".12345000098765", "0.12345000098765", nil},
{"-.000000012345000098765", "-0.000000012345000098765", nil},
{"1234500009876.5", "1234500009876.5", nil},
{"123E5", "12300000", nil},
{"123E-2", "1.23", nil},
{"1e1073741823", "999999999999999999999999999999999999999999999999999999999999999999999999999999999", ErrOverflow},
{"-1e1073741823", "-999999999999999999999999999999999999999999999999999999999999999999999999999999999", ErrOverflow},
{"1e18446744073709551620", "0", ErrBadNumber},
{"1e", "1", ErrTruncated},
{"1e001", "10", nil},
{"1e00", "1", nil},
{"1eabc", "1", ErrTruncated},
{"1e 1dddd ", "10", ErrTruncated},
{"1e - 1", "1", ErrTruncated},
{"1e -1", "0.1", nil},
}
for _, ca := range tests {
var dec MyDecimal
err := dec.FromString([]byte(ca.input))
c.Check(err, Equals, ca.err, Commentf("input: %s", ca.input))
result := dec.ToString()
c.Check(string(result), Equals, ca.output, Commentf("dec:%s", dec.String()))
}
wordBufLen = 1
tests = []tcase{
{"123450000098765", "98765", ErrOverflow},
{"123450.000098765", "123450", ErrTruncated},
}
for _, ca := range tests {
var dec MyDecimal
err := dec.FromString([]byte(ca.input))
c.Check(err, Equals, ca.err)
result := dec.ToString()
c.Check(string(result), Equals, ca.output, Commentf("dec:%s", dec.String()))
}
wordBufLen = maxWordBufLen
}
func (s *testMyDecimalSuite) TestToString(c *C) {
type tcase struct {
input string
output string
}
tests := []tcase{
{"123.123", "123.123"},
{"123.1230", "123.1230"},
{"00123.123", "123.123"},
}
for _, ca := range tests {
var dec MyDecimal
dec.FromString([]byte(ca.input))
result := dec.ToString()
c.Check(string(result), Equals, ca.output)
}
}
func (s *testMyDecimalSuite) TestToBinFromBin(c *C) {
type tcase struct {
input string
precision int
frac int
output string
err error
}
tests := []tcase{
{"-10.55", 4, 2, "-10.55", nil},
{"0.0123456789012345678912345", 30, 25, "0.0123456789012345678912345", nil},
{"12345", 5, 0, "12345", nil},
{"12345", 10, 3, "12345.000", nil},
{"123.45", 10, 3, "123.450", nil},
{"-123.45", 20, 10, "-123.4500000000", nil},
{".00012345000098765", 15, 14, "0.00012345000098", ErrTruncated},
{".00012345000098765", 22, 20, "0.00012345000098765000", nil},
{".12345000098765", 30, 20, "0.12345000098765000000", nil},
{"-.000000012345000098765", 30, 20, "-0.00000001234500009876", ErrTruncated},
{"1234500009876.5", 30, 5, "1234500009876.50000", nil},
{"111111111.11", 10, 2, "11111111.11", ErrOverflow},
{"000000000.01", 7, 3, "0.010", nil},
{"123.4", 10, 2, "123.40", nil},
{"1000", 3, 0, "0", ErrOverflow},
{"0.1", 1, 1, "0.1", nil},
{"0.100", 1, 1, "0.1", ErrTruncated},
{"0.1000", 1, 1, "0.1", ErrTruncated},
{"0.10000", 1, 1, "0.1", ErrTruncated},
{"0.100000", 1, 1, "0.1", ErrTruncated},
{"0.1000000", 1, 1, "0.1", ErrTruncated},
{"0.10", 1, 1, "0.1", ErrTruncated},
{"0000000000000000000000000000000000000000000.000000000000123000000000000000", 15, 15, "0.000000000000123", ErrTruncated},
{"00000000000000000000000000000.00000000000012300", 15, 15, "0.000000000000123", ErrTruncated},
{"0000000000000000000000000000000000000000000.0000000000001234000000000000000", 16, 16, "0.0000000000001234", ErrTruncated},
{"00000000000000000000000000000.000000000000123400", 16, 16, "0.0000000000001234", ErrTruncated},
{"0.1", 2, 2, "0.10", nil},
{"0.10", 3, 3, "0.100", nil},
{"0.1", 3, 1, "0.1", nil},
{"0.0000000000001234", 32, 17, "0.00000000000012340", nil},
{"0.0000000000001234", 20, 20, "0.00000000000012340000", nil},
}
for _, ca := range tests {
var dec MyDecimal
err := dec.FromString([]byte(ca.input))
c.Assert(err, IsNil)
buf, err := dec.ToBin(ca.precision, ca.frac)
c.Assert(err, Equals, ca.err, Commentf(ca.input))
var dec2 MyDecimal
_, err = dec2.FromBin(buf, ca.precision, ca.frac)
c.Assert(err, IsNil)
str := dec2.ToString()
c.Assert(string(str), Equals, ca.output)
}
var dec MyDecimal
dec.FromInt(1)
errTests := []struct {
prec int
frac int
}{
{82, 1},
{-1, 1},
{10, 31},
{10, -1},
}
for _, tt := range errTests {
_, err := dec.ToBin(tt.prec, tt.frac)
c.Assert(ErrBadNumber.Equal(err), IsTrue)
}
}
func (s *testMyDecimalSuite) TestCompare(c *C) {
type tcase struct {
a string
b string
cmp int
}
tests := []tcase{
{"12", "13", -1},
{"13", "12", 1},
{"-10", "10", -1},
{"10", "-10", 1},
{"-12", "-13", 1},
{"0", "12", -1},
{"-10", "0", -1},
{"4", "4", 0},
{"-1.1", "-1.2", 1},
{"1.2", "1.1", 1},
{"1.1", "1.2", -1},
}
for _, tt := range tests {
var a, b MyDecimal
a.FromString([]byte(tt.a))
b.FromString([]byte(tt.b))
c.Assert(a.Compare(&b), Equals, tt.cmp)
}
}
func (s *testMyDecimalSuite) TestMaxDecimal(c *C) {
type tcase struct {
prec int
frac int
result string
}
tests := []tcase{
{1, 1, "0.9"},
{1, 0, "9"},
{2, 1, "9.9"},
{4, 2, "99.99"},
{6, 3, "999.999"},
{8, 4, "9999.9999"},
{10, 5, "99999.99999"},
{12, 6, "999999.999999"},
{14, 7, "9999999.9999999"},
{16, 8, "99999999.99999999"},
{18, 9, "999999999.999999999"},
{20, 10, "9999999999.9999999999"},
{20, 20, "0.99999999999999999999"},
{20, 0, "99999999999999999999"},
{40, 20, "99999999999999999999.99999999999999999999"},
}
for _, tt := range tests {
var dec MyDecimal
maxDecimal(tt.prec, tt.frac, &dec)
str := dec.ToString()
c.Assert(string(str), Equals, tt.result)
}
}
func (s *testMyDecimalSuite) TestNeg(c *C) {
type testCase struct {
a string
result string
err error
}
tests := []testCase{
{"-0.0000000000000000000000000000000000000000000000000017382578996420603", "0.0000000000000000000000000000000000000000000000000017382578996420603", nil},
{"-13890436710184412000000000000000000000000000000000000000000000000000000000000", "13890436710184412000000000000000000000000000000000000000000000000000000000000", nil},
{"0", "0", nil},
}
for _, tt := range tests {
a := NewDecFromStringForTest(tt.a)
negResult := DecimalNeg(a)
result := negResult.ToString()
c.Assert(string(result), Equals, tt.result)
}
}
func (s *testMyDecimalSuite) TestAdd(c *C) {
type testCase struct {
a string
b string
result string
err error
}
tests := []testCase{
{".00012345000098765", "123.45", "123.45012345000098765", nil},
{".1", ".45", "0.55", nil},
{"1234500009876.5", ".00012345000098765", "1234500009876.50012345000098765", nil},
{"9999909999999.5", ".555", "9999910000000.055", nil},
{"99999999", "1", "100000000", nil},
{"989999999", "1", "990000000", nil},
{"999999999", "1", "1000000000", nil},
{"12345", "123.45", "12468.45", nil},
{"-12345", "-123.45", "-12468.45", nil},
{"-12345", "123.45", "-12221.55", nil},
{"12345", "-123.45", "12221.55", nil},
{"123.45", "-12345", "-12221.55", nil},
{"-123.45", "12345", "12221.55", nil},
{"5", "-6.0", "-1.0", nil},
{"2" + strings.Repeat("1", 71), strings.Repeat("8", 81), "8888888890" + strings.Repeat("9", 71), nil},
{"-1234.1234", "1234.1234", "0.0000", nil},
}
for _, tt := range tests {
a := NewDecFromStringForTest(tt.a)
b := NewDecFromStringForTest(tt.b)
var sum MyDecimal
err := DecimalAdd(a, b, &sum)
c.Assert(err, Equals, tt.err)
result := sum.ToString()
c.Assert(string(result), Equals, tt.result)
}
}
func (s *testMyDecimalSuite) TestSub(c *C) {
type tcase struct {
a string
b string
result string
err error
}
tests := []tcase{
{".00012345000098765", "123.45", "-123.44987654999901235", nil},
{"1234500009876.5", ".00012345000098765", "1234500009876.49987654999901235", nil},
{"9999900000000.5", ".555", "9999899999999.945", nil},
{"1111.5551", "1111.555", "0.0001", nil},
{".555", ".555", "0.000", nil},
{"10000000", "1", "9999999", nil},
{"1000001000", ".1", "1000000999.9", nil},
{"1000000000", ".1", "999999999.9", nil},
{"12345", "123.45", "12221.55", nil},
{"-12345", "-123.45", "-12221.55", nil},
{"123.45", "12345", "-12221.55", nil},
{"-123.45", "-12345", "12221.55", nil},
{"-12345", "123.45", "-12468.45", nil},
{"12345", "-123.45", "12468.45", nil},
{"12.12", "12.12", "0.00", nil},
}
for _, tt := range tests {
var a, b, sum MyDecimal
a.FromString([]byte(tt.a))
b.FromString([]byte(tt.b))
err := DecimalSub(&a, &b, &sum)
c.Assert(err, Equals, tt.err)
result := sum.ToString()
c.Assert(string(result), Equals, tt.result)
}
}
func (s *testMyDecimalSuite) TestMul(c *C) {
type tcase struct {
a string
b string
result string
err error
}
tests := []tcase{
{"12", "10", "120", nil},
{"-123.456", "98765.4321", "-12193185.1853376", nil},
{"-123456000000", "98765432100000", "-12193185185337600000000000", nil},
{"123456", "987654321", "121931851853376", nil},
{"123456", "9876543210", "1219318518533760", nil},
{"123", "0.01", "1.23", nil},
{"123", "0", "0", nil},
{"-0.0000000000000000000000000000000000000000000000000017382578996420603", "-13890436710184412000000000000000000000000000000000000000000000000000000000000", "0.000000000000000000000000000000", ErrTruncated},
{"1" + strings.Repeat("0", 60), "1" + strings.Repeat("0", 60), "0", ErrOverflow},
{"0.5999991229316", "0.918755041726043", "0.5512522192246113614062276588", nil},
{"0.5999991229317", "0.918755041726042", "0.5512522192247026369112773314", nil},
{"0.000", "-1", "0.000", nil},
}
for _, tt := range tests {
var a, b, product MyDecimal
a.FromString([]byte(tt.a))
b.FromString([]byte(tt.b))
err := DecimalMul(&a, &b, &product)
c.Check(err, Equals, tt.err)
result := product.String()
c.Assert(result, Equals, tt.result)
}
}
func (s *testMyDecimalSuite) TestDivMod(c *C) {
type tcase struct {
a string
b string
result string
err error
}
tests := []tcase{
{"120", "10", "12.000000000", nil},
{"123", "0.01", "12300.000000000", nil},
{"120", "100000000000.00000", "0.000000001200000000", nil},
{"123", "0", "", ErrDivByZero},
{"0", "0", "", ErrDivByZero},
{"-12193185.1853376", "98765.4321", "-123.456000000000000000", nil},
{"121931851853376", "987654321", "123456.000000000", nil},
{"0", "987", "0.00000", nil},
{"1", "3", "0.333333333", nil},
{"1.000000000000", "3", "0.333333333333333333", nil},
{"1", "1", "1.000000000", nil},
{"0.0123456789012345678912345", "9999999999", "0.000000000001234567890246913578148141", nil},
{"10.333000000", "12.34500", "0.837019036046982584042122316", nil},
{"10.000000000060", "2", "5.000000000030000000", nil},
{"51", "0.003430", "14868.804664723032069970", nil},
}
for _, tt := range tests {
var a, b, to MyDecimal
a.FromString([]byte(tt.a))
b.FromString([]byte(tt.b))
err := DecimalDiv(&a, &b, &to, 5)
c.Check(err, Equals, tt.err)
if tt.err == ErrDivByZero {
continue
}
result := to.ToString()
c.Assert(string(result), Equals, tt.result)
}
tests = []tcase{
{"234", "10", "4", nil},
{"234.567", "10.555", "2.357", nil},
{"-234.567", "10.555", "-2.357", nil},
{"234.567", "-10.555", "2.357", nil},
{"99999999999999999999999999999999999999", "3", "0", nil},
{"51", "0.003430", "0.002760", nil},
{"0.0000000001", "1.0", "0.0000000001", nil},
{"0.000", "0.1", "0.000", nil},
}
for _, tt := range tests {
var a, b, to MyDecimal
a.FromString([]byte(tt.a))
b.FromString([]byte(tt.b))
ec := DecimalMod(&a, &b, &to)
c.Check(ec, Equals, tt.err)
if tt.err == ErrDivByZero {
continue
}
result := to.ToString()
c.Assert(string(result), Equals, tt.result)
}
tests = []tcase{
{"1", "1", "1.0000", nil},
{"1.00", "1", "1.000000", nil},
{"1", "1.000", "1.0000", nil},
{"2", "3", "0.6667", nil},
{"51", "0.003430", "14868.8047", nil},
{"0.000", "0.1", "0.0000000", nil},
}
for _, tt := range tests {
var a, b, to MyDecimal
a.FromString([]byte(tt.a))
b.FromString([]byte(tt.b))
ec := DecimalDiv(&a, &b, &to, DivFracIncr)
c.Check(ec, Equals, tt.err)
if tt.err == ErrDivByZero {
continue
}
c.Assert(to.String(), Equals, tt.result)
}
tests = []tcase{
{"1", "2.0", "1.0", nil},
{"1.0", "2", "1.0", nil},
{"2.23", "3", "2.23", nil},
{"51", "0.003430", "0.002760", nil},
}
for _, tt := range tests {
var a, b, to MyDecimal
a.FromString([]byte(tt.a))
b.FromString([]byte(tt.b))
ec := DecimalMod(&a, &b, &to)
c.Check(ec, Equals, tt.err)
if tt.err == ErrDivByZero {
continue
}
c.Assert(to.String(), Equals, tt.result)
}
}
func (s *testMyDecimalSuite) TestMaxOrMin(c *C) {
type tcase struct {
neg bool
prec int
frac int
result string
}
tests := []tcase{
{true, 2, 1, "-9.9"},
{false, 1, 1, "0.9"},
{true, 1, 0, "-9"},
{false, 0, 0, "0"},
{false, 4, 2, "99.99"},
}
for _, tt := range tests {
dec := NewMaxOrMinDec(tt.neg, tt.prec, tt.frac)
c.Assert(dec.String(), Equals, tt.result)
}
}
func (s *testMyDecimalSuite) TestReset(c *C) {
var x1, y1, z1 MyDecimal
c.Assert(x1.FromString([]byte("38520.130741106671")), IsNil)
c.Assert(y1.FromString([]byte("9863.944799797851")), IsNil)
c.Assert(DecimalAdd(&x1, &y1, &z1), IsNil)
var x2, y2, z2 MyDecimal
c.Assert(x2.FromString([]byte("121519.080207244")), IsNil)
c.Assert(y2.FromString([]byte("54982.444519146")), IsNil)
c.Assert(DecimalAdd(&x2, &y2, &z2), IsNil)
c.Assert(DecimalAdd(&x2, &y2, &z1), IsNil)
c.Assert(z1, Equals, z2)
}
func benchmarkMyDecimalToBinOrHashCases() []string {
return []string{
"1.000000000000", "3", "12.000000000", "120",
"120000", "100000000000.00000", "0.000000001200000000",
"98765.4321", "-123.456000000000000000",
"0", "0000000000", "0.00000000000",
}
}
func BenchmarkMyDecimalToBin(b *testing.B) {
cases := benchmarkMyDecimalToBinOrHashCases()
decs := make([]*MyDecimal, 0, len(cases))
for _, ca := range cases {
var dec MyDecimal
if err := dec.FromString([]byte(ca)); err != nil {
b.Fatal(err)
}
decs = append(decs, &dec)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, dec := range decs {
prec, frac := dec.PrecisionAndFrac()
_, err := dec.ToBin(prec, frac)
if err != nil {
b.Fatal(err)
}
}
}
}
func BenchmarkMyDecimalToHashKey(b *testing.B) {
cases := benchmarkMyDecimalToBinOrHashCases()
decs := make([]*MyDecimal, 0, len(cases))
for _, ca := range cases {
var dec MyDecimal
if err := dec.FromString([]byte(ca)); err != nil {
b.Fatal(err)
}
decs = append(decs, &dec)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, dec := range decs {
_, err := dec.ToHashKey()
if err != nil {
b.Fatal(err)
}
}
}
}
|
XuHuaiyu/tidb
|
types/mydecimal_test.go
|
GO
|
apache-2.0
| 31,514
|
alter table SYS_CATEGORY_ATTR add column LOOKUP boolean;
|
dimone-kun/cuba
|
modules/core/db/update/postgres/01/01-440-addDropdownToCategoryAttribute.sql
|
SQL
|
apache-2.0
| 58
|
"""
mbed SDK
Copyright (c) 2011-2017 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Title: GNU ARM Eclipse (http://gnuarmeclipse.github.io) exporter.
Description: Creates a managed build project that can be imported by
the GNU ARM Eclipse plug-ins.
Author: Liviu Ionescu <ilg@livius.net>
"""
import os
import copy
import tempfile
import shutil
import copy
from subprocess import call, Popen, PIPE
from os.path import splitext, basename, relpath, dirname, exists, join, dirname
from random import randint
from json import load
from tools.export.exporters import Exporter
from tools.options import list_profiles
from tools.targets import TARGET_MAP
from tools.utils import NotSupportedException
from tools.build_api import prepare_toolchain
# =============================================================================
class UID:
"""
Helper class, used to generate unique ids required by .cproject symbols.
"""
@property
def id(self):
return "%0.9u" % randint(0, 999999999)
# Global UID generator instance.
# Passed to the template engine, and referred as {{u.id}}.
# Each invocation generates a new number.
u = UID()
# =============================================================================
class GNUARMEclipse(Exporter):
NAME = 'GNU ARM Eclipse'
TOOLCHAIN = 'GCC_ARM'
# Indirectly support all GCC_ARM targets.
TARGETS = [target for target, obj in TARGET_MAP.iteritems()
if 'GCC_ARM' in obj.supported_toolchains]
# override
@property
def flags(self):
"""Returns a dictionary of toolchain flags.
Keys of the dictionary are:
cxx_flags - c++ flags
c_flags - c flags
ld_flags - linker flags
asm_flags - assembler flags
common_flags - common options
The difference from the parent function is that it does not
add macro definitions, since they are passed separately.
"""
config_header = self.toolchain.get_config_header()
flags = {key + "_flags": copy.deepcopy(value) for key, value
in self.toolchain.flags.iteritems()}
if config_header:
config_header = relpath(config_header,
self.resources.file_basepath[config_header])
flags['c_flags'] += self.toolchain.get_config_option(config_header)
flags['cxx_flags'] += self.toolchain.get_config_option(
config_header)
return flags
def toolchain_flags(self, toolchain):
"""Returns a dictionary of toolchain flags.
Keys of the dictionary are:
cxx_flags - c++ flags
c_flags - c flags
ld_flags - linker flags
asm_flags - assembler flags
common_flags - common options
The difference from the above is that it takes a parameter.
"""
# Note: use the config options from the currently selected toolchain.
config_header = self.toolchain.get_config_header()
flags = {key + "_flags": copy.deepcopy(value) for key, value
in toolchain.flags.iteritems()}
if config_header:
config_header = relpath(config_header,
self.resources.file_basepath[config_header])
header_options = self.toolchain.get_config_option(config_header)
flags['c_flags'] += header_options
flags['cxx_flags'] += header_options
return flags
# override
def generate(self):
"""
Generate the .project and .cproject files.
"""
if not self.resources.linker_script:
raise NotSupportedException("No linker script found.")
print
print 'Create a GNU ARM Eclipse C++ managed project'
print 'Project name: {0}'.format(self.project_name)
print 'Target: {0}'.format(self.toolchain.target.name)
print 'Toolchain: {0}'.format(self.TOOLCHAIN)
self.resources.win_to_unix()
# TODO: use some logger to display additional info if verbose
libraries = []
# print 'libraries'
# print self.resources.libraries
for lib in self.resources.libraries:
l, _ = splitext(basename(lib))
libraries.append(l[3:])
self.system_libraries = [
'stdc++', 'supc++', 'm', 'c', 'gcc', 'nosys'
]
# Read in all profiles, we'll extract compiler options.
profiles = self.get_all_profiles()
profile_ids = [s.lower() for s in profiles]
profile_ids.sort()
# TODO: get the list from existing .cproject
build_folders = [s.capitalize() for s in profile_ids]
build_folders.append('BUILD')
# print build_folders
objects = [self.filter_dot(s) for s in self.resources.objects]
for bf in build_folders:
objects = [o for o in objects if not o.startswith(bf + '/')]
# print 'objects'
# print objects
self.compute_exclusions()
self.include_path = [
self.filter_dot(s) for s in self.resources.inc_dirs]
print 'Include folders: {0}'.format(len(self.include_path))
self.as_defines = self.toolchain.get_symbols(True)
self.c_defines = self.toolchain.get_symbols()
self.cpp_defines = self.c_defines
print 'Symbols: {0}'.format(len(self.c_defines))
self.ld_script = self.filter_dot(
self.resources.linker_script)
print 'Linker script: {0}'.format(self.ld_script)
self.options = {}
for id in profile_ids:
# There are 4 categories of options, a category common too
# all tools and a specific category for each of the tools.
opts = {}
opts['common'] = {}
opts['as'] = {}
opts['c'] = {}
opts['cpp'] = {}
opts['ld'] = {}
opts['id'] = id
opts['name'] = opts['id'].capitalize()
print
print 'Build configuration: {0}'.format(opts['name'])
profile = profiles[id]
profile_toolchain = profile[self.TOOLCHAIN]
# A small hack, do not bother with src_path again,
# pass an empty string to avoid crashing.
src_paths = ['']
target_name = self.toolchain.target.name
toolchain = prepare_toolchain(
src_paths, target_name, self.TOOLCHAIN, build_profile=profile_toolchain)
# Hack to fill in build_dir
toolchain.build_dir = self.toolchain.build_dir
flags = self.toolchain_flags(toolchain)
print 'Common flags:', ' '.join(flags['common_flags'])
print 'C++ flags:', ' '.join(flags['cxx_flags'])
print 'C flags:', ' '.join(flags['c_flags'])
print 'ASM flags:', ' '.join(flags['asm_flags'])
print 'Linker flags:', ' '.join(flags['ld_flags'])
# Most GNU ARM Eclipse options have a parent,
# either debug or release.
if '-O0' in flags['common_flags'] or '-Og' in flags['common_flags']:
opts['parent_id'] = 'debug'
else:
opts['parent_id'] = 'release'
self.process_options(opts, flags)
opts['as']['defines'] = self.as_defines
opts['c']['defines'] = self.c_defines
opts['cpp']['defines'] = self.cpp_defines
opts['common']['include_paths'] = self.include_path
opts['common']['excluded_folders'] = '|'.join(
self.excluded_folders)
opts['ld']['library_paths'] = [
self.filter_dot(s) for s in self.resources.lib_dirs]
opts['ld']['object_files'] = objects
opts['ld']['user_libraries'] = libraries
opts['ld']['system_libraries'] = self.system_libraries
opts['ld']['script'] = self.ld_script
# Unique IDs used in multiple places.
# Those used only once are implemented with {{u.id}}.
uid = {}
uid['config'] = u.id
uid['tool_c_compiler'] = u.id
uid['tool_c_compiler_input'] = u.id
uid['tool_cpp_compiler'] = u.id
uid['tool_cpp_compiler_input'] = u.id
opts['uid'] = uid
self.options[id] = opts
jinja_ctx = {
'name': self.project_name,
# Compiler & linker command line options
'options': self.options,
# Must be an object with an `id` property, which
# will be called repeatedly, to generate multiple UIDs.
'u': u,
}
# TODO: it would be good to have jinja stop if one of the
# expected context values is not defined.
self.gen_file('gnuarmeclipse/.project.tmpl', jinja_ctx,
'.project', trim_blocks=True, lstrip_blocks=True)
self.gen_file('gnuarmeclipse/.cproject.tmpl', jinja_ctx,
'.cproject', trim_blocks=True, lstrip_blocks=True)
self.gen_file('gnuarmeclipse/makefile.targets.tmpl', jinja_ctx,
'makefile.targets', trim_blocks=True, lstrip_blocks=True)
if not exists('.mbedignore'):
print
print 'Create .mbedignore'
with open('.mbedignore', 'w') as f:
for bf in build_folders:
print bf + '/'
f.write(bf + '/\n')
print
print 'Done. Import the \'{0}\' project in Eclipse.'.format(self.project_name)
# override
@staticmethod
def build(project_name, log_name="build_log.txt", cleanup=True):
"""
Headless build an Eclipse project.
The following steps are performed:
- a temporary workspace is created,
- the project is imported,
- a clean build of all configurations is performed and
- the temporary workspace is removed.
The build results are in the Debug & Release folders.
All executables (eclipse & toolchain) must be in the PATH.
The general method to start a headless Eclipse build is:
$ eclipse \
--launcher.suppressErrors \
-nosplash \
-application org.eclipse.cdt.managedbuilder.core.headlessbuild \
-data /path/to/workspace \
-import /path/to/project \
-cleanBuild "project[/configuration] | all"
"""
# TODO: possibly use the log file.
# Create a temporary folder for the workspace.
tmp_folder = tempfile.mkdtemp()
cmd = [
'eclipse',
'--launcher.suppressErrors',
'-nosplash',
'-application org.eclipse.cdt.managedbuilder.core.headlessbuild',
'-data', tmp_folder,
'-import', os.getcwd(),
'-cleanBuild', project_name
]
p = Popen(' '.join(cmd), shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
ret_code = p.returncode
stdout_string = "=" * 10 + "STDOUT" + "=" * 10 + "\n"
err_string = "=" * 10 + "STDERR" + "=" * 10 + "\n"
err_string += err
ret_string = "SUCCESS\n"
if ret_code != 0:
ret_string += "FAILURE\n"
print "%s\n%s\n%s\n%s" % (stdout_string, out, err_string, ret_string)
if log_name:
# Write the output to the log file
with open(log_name, 'w+') as f:
f.write(stdout_string)
f.write(out)
f.write(err_string)
f.write(ret_string)
# Cleanup the exported and built files
if cleanup:
if exists(log_name):
os.remove(log_name)
os.remove('.project')
os.remove('.cproject')
if exists('Debug'):
shutil.rmtree('Debug')
if exists('Release'):
shutil.rmtree('Release')
if exists('makefile.targets'):
os.remove('makefile.targets')
# Always remove the temporary folder.
if exists(tmp_folder):
shutil.rmtree(tmp_folder)
if ret_code == 0:
# Return Success
return 0
# Seems like something went wrong.
return -1
# -------------------------------------------------------------------------
@staticmethod
def get_all_profiles():
tools_path = dirname(dirname(dirname(__file__)))
file_names = [join(tools_path, "profiles", fn) for fn in os.listdir(
join(tools_path, "profiles")) if fn.endswith(".json")]
# print file_names
profile_names = [basename(fn).replace(".json", "")
for fn in file_names]
# print profile_names
profiles = {}
for fn in file_names:
content = load(open(fn))
profile_name = basename(fn).replace(".json", "")
profiles[profile_name] = content
return profiles
# -------------------------------------------------------------------------
# Process source files/folders exclusions.
def compute_exclusions(self):
"""
With the project root as the only source folder known to CDT,
based on the list of source files, compute the folders to not
be included in the build.
The steps are:
- get the list of source folders, as dirname(source_file)
- compute the top folders (subfolders of the project folder)
- iterate all subfolders and add them to a tree, with all
nodes markes as 'not used'
- iterate the source folders and mark them as 'used' in the
tree, including all intermediate nodes
- recurse the tree and collect all unused folders; descend
the hierarchy only for used nodes
"""
source_folders = [self.filter_dot(s) for s in set(dirname(
src) for src in self.resources.c_sources + self.resources.cpp_sources + self.resources.s_sources)]
if '.' in source_folders:
source_folders.remove('.')
# print 'source folders'
# print source_folders
# Source folders were converted before and are guaranteed to
# use the POSIX separator.
top_folders = [f for f in set(s.split('/')[0]
for s in source_folders)]
# print 'top folders'
# print top_folders
self.source_tree = {}
for top_folder in top_folders:
for root, dirs, files in os.walk(top_folder, topdown=True):
# print root, dirs, files
# Paths returned by os.walk() must be split with os.dep
# to accomodate Windows weirdness.
parts = root.split(os.sep)
# Ignore paths that include parts starting with dot.
skip = False
for part in parts:
if part.startswith('.'):
skip = True
break
if skip:
continue
# Further process only leaf paths, (that do not have
# sub-folders).
if len(dirs) == 0:
# The path is reconstructed using POSIX separators.
self.add_source_folder_to_tree('/'.join(parts))
for folder in source_folders:
self.add_source_folder_to_tree(folder, True)
# print
# print self.source_tree
# self.dump_paths(self.source_tree)
# self.dump_tree(self.source_tree)
# print 'excludings'
self.excluded_folders = ['BUILD']
self.recurse_excludings(self.source_tree)
print 'Source folders: {0}, with {1} exclusions'.format(len(source_folders), len(self.excluded_folders))
def add_source_folder_to_tree(self, path, is_used=False):
"""
Decompose a path in an array of folder names and create the tree.
On the second pass the nodes should be already there; mark them
as used.
"""
# print path, is_used
# All paths arriving here are guaranteed to use the POSIX
# separators, os.walk() paths were also explicitly converted.
parts = path.split('/')
# print parts
node = self.source_tree
prev = None
for part in parts:
if part not in node.keys():
new_node = {}
new_node['name'] = part
new_node['children'] = {}
if prev != None:
new_node['parent'] = prev
node[part] = new_node
node[part]['is_used'] = is_used
prev = node[part]
node = node[part]['children']
def recurse_excludings(self, nodes):
"""
Recurse the tree and collect all unused folders; descend
the hierarchy only for used nodes.
"""
for k in nodes.keys():
node = nodes[k]
if node['is_used'] == False:
parts = []
cnode = node
while True:
parts.insert(0, cnode['name'])
if 'parent' not in cnode:
break
cnode = cnode['parent']
# Compose a POSIX path.
path = '/'.join(parts)
# print path
self.excluded_folders.append(path)
else:
self.recurse_excludings(node['children'])
# -------------------------------------------------------------------------
@staticmethod
def filter_dot(str):
"""
Remove the './' prefix, if present.
This function assumes that resources.win_to_unix()
replaced all windows backslashes with slashes.
"""
if str == None:
return None
if str[:2] == './':
return str[2:]
return str
# -------------------------------------------------------------------------
def dump_tree(self, nodes, depth=0):
for k in nodes.keys():
node = nodes[k]
parent_name = node['parent'][
'name'] if 'parent' in node.keys() else ''
print ' ' * depth, node['name'], node['is_used'], parent_name
if len(node['children'].keys()) != 0:
self.dump_tree(node['children'], depth + 1)
def dump_paths(self, nodes, depth=0):
for k in nodes.keys():
node = nodes[k]
parts = []
while True:
parts.insert(0, node['name'])
if 'parent' not in node:
break
node = node['parent']
path = '/'.join(parts)
print path, nodes[k]['is_used']
self.dump_paths(nodes[k]['children'], depth + 1)
# -------------------------------------------------------------------------
def process_options(self, opts, flags_in):
"""
CDT managed projects store lots of build options in separate
variables, with separate IDs in the .cproject file.
When the CDT build is started, all these options are brought
together to compose the compiler and linker command lines.
Here the process is reversed, from the compiler and linker
command lines, the options are identified and various flags are
set to control the template generation process.
Once identified, the options are removed from the command lines.
The options that were not identified are options that do not
have CDT equivalents and will be passed in the 'Other options'
categories.
Although this process does not have a very complicated logic,
given the large number of explicit configuration options
used by the GNU ARM Eclipse managed build plug-in, it is tedious...
"""
# Make a copy of the flags, to be one by one removed after processing.
flags = copy.deepcopy(flags_in)
if False:
print
print 'common_flags', flags['common_flags']
print 'asm_flags', flags['asm_flags']
print 'c_flags', flags['c_flags']
print 'cxx_flags', flags['cxx_flags']
print 'ld_flags', flags['ld_flags']
# Initialise the 'last resort' options where all unrecognised
# options will be collected.
opts['as']['other'] = ''
opts['c']['other'] = ''
opts['cpp']['other'] = ''
opts['ld']['other'] = ''
MCPUS = {
'Cortex-M0': {'mcpu': 'cortex-m0', 'fpu_unit': None},
'Cortex-M0+': {'mcpu': 'cortex-m0plus', 'fpu_unit': None},
'Cortex-M1': {'mcpu': 'cortex-m1', 'fpu_unit': None},
'Cortex-M3': {'mcpu': 'cortex-m3', 'fpu_unit': None},
'Cortex-M4': {'mcpu': 'cortex-m4', 'fpu_unit': None},
'Cortex-M4F': {'mcpu': 'cortex-m4', 'fpu_unit': 'fpv4spd16'},
'Cortex-M7': {'mcpu': 'cortex-m7', 'fpu_unit': None},
'Cortex-M7F': {'mcpu': 'cortex-m7', 'fpu_unit': 'fpv4spd16'},
'Cortex-M7FD': {'mcpu': 'cortex-m7', 'fpu_unit': 'fpv5d16'},
'Cortex-A9': {'mcpu': 'cortex-a9', 'fpu_unit': 'vfpv3'}
}
# Remove options that are supplied by CDT
self.remove_option(flags['common_flags'], '-c')
self.remove_option(flags['common_flags'], '-MMD')
# As 'plan B', get the CPU from the target definition.
core = self.toolchain.target.core
opts['common']['arm.target.family'] = None
# cortex-m0, cortex-m0-small-multiply, cortex-m0plus,
# cortex-m0plus-small-multiply, cortex-m1, cortex-m1-small-multiply,
# cortex-m3, cortex-m4, cortex-m7.
str = self.find_options(flags['common_flags'], '-mcpu=')
if str != None:
opts['common']['arm.target.family'] = str[len('-mcpu='):]
self.remove_option(flags['common_flags'], str)
self.remove_option(flags['ld_flags'], str)
else:
if core not in MCPUS:
raise NotSupportedException(
'Target core {0} not supported.'.format(core))
opts['common']['arm.target.family'] = MCPUS[core]['mcpu']
opts['common']['arm.target.arch'] = 'none'
str = self.find_options(flags['common_flags'], '-march=')
arch = str[len('-march='):]
archs = {'armv6-m': 'armv6-m', 'armv7-m': 'armv7-m', 'armv7-a': 'armv7-a'}
if arch in archs:
opts['common']['arm.target.arch'] = archs[arch]
self.remove_option(flags['common_flags'], str)
opts['common']['arm.target.instructionset'] = 'thumb'
if '-mthumb' in flags['common_flags']:
self.remove_option(flags['common_flags'], '-mthumb')
self.remove_option(flags['ld_flags'], '-mthumb')
elif '-marm' in flags['common_flags']:
opts['common']['arm.target.instructionset'] = 'arm'
self.remove_option(flags['common_flags'], '-marm')
self.remove_option(flags['ld_flags'], '-marm')
opts['common']['arm.target.thumbinterwork'] = False
if '-mthumb-interwork' in flags['common_flags']:
opts['common']['arm.target.thumbinterwork'] = True
self.remove_option(flags['common_flags'], '-mthumb-interwork')
opts['common']['arm.target.endianness'] = None
if '-mlittle-endian' in flags['common_flags']:
opts['common']['arm.target.endianness'] = 'little'
self.remove_option(flags['common_flags'], '-mlittle-endian')
elif '-mbig-endian' in flags['common_flags']:
opts['common']['arm.target.endianness'] = 'big'
self.remove_option(flags['common_flags'], '-mbig-endian')
opts['common']['arm.target.fpu.unit'] = None
# default, fpv4spd16, fpv5d16, fpv5spd16
str = self.find_options(flags['common_flags'], '-mfpu=')
if str != None:
fpu = str[len('-mfpu='):]
fpus = {
'fpv4-sp-d16': 'fpv4spd16',
'fpv5-d16': 'fpv5d16',
'fpv5-sp-d16': 'fpv5spd16'
}
if fpu in fpus:
opts['common']['arm.target.fpu.unit'] = fpus[fpu]
self.remove_option(flags['common_flags'], str)
self.remove_option(flags['ld_flags'], str)
if opts['common']['arm.target.fpu.unit'] == None:
if core not in MCPUS:
raise NotSupportedException(
'Target core {0} not supported.'.format(core))
if MCPUS[core]['fpu_unit']:
opts['common'][
'arm.target.fpu.unit'] = MCPUS[core]['fpu_unit']
# soft, softfp, hard.
str = self.find_options(flags['common_flags'], '-mfloat-abi=')
if str != None:
opts['common']['arm.target.fpu.abi'] = str[
len('-mfloat-abi='):]
self.remove_option(flags['common_flags'], str)
self.remove_option(flags['ld_flags'], str)
opts['common']['arm.target.unalignedaccess'] = None
if '-munaligned-access' in flags['common_flags']:
opts['common']['arm.target.unalignedaccess'] = 'enabled'
self.remove_option(flags['common_flags'], '-munaligned-access')
elif '-mno-unaligned-access' in flags['common_flags']:
opts['common']['arm.target.unalignedaccess'] = 'disabled'
self.remove_option(flags['common_flags'], '-mno-unaligned-access')
# Default optimisation level for Release.
opts['common']['optimization.level'] = '-Os'
# If the project defines an optimisation level, it is used
# only for the Release configuration, the Debug one used '-Og'.
str = self.find_options(flags['common_flags'], '-O')
if str != None:
levels = {
'-O0': 'none', '-O1': 'optimize', '-O2': 'more',
'-O3': 'most', '-Os': 'size', '-Og': 'debug'
}
if str in levels:
opts['common']['optimization.level'] = levels[str]
self.remove_option(flags['common_flags'], str)
include_files = []
for all_flags in [flags['common_flags'], flags['c_flags'], flags['cxx_flags']]:
while '-include' in all_flags:
ix = all_flags.index('-include')
str = all_flags[ix + 1]
if str not in include_files:
include_files.append(str)
self.remove_option(all_flags, '-include')
self.remove_option(all_flags, str)
opts['common']['include_files'] = include_files
if '-ansi' in flags['c_flags']:
opts['c']['compiler.std'] = '-ansi'
self.remove_option(flags['c_flags'], str)
else:
str = self.find_options(flags['c_flags'], '-std')
std = str[len('-std='):]
c_std = {
'c90': 'c90', 'c89': 'c90', 'gnu90': 'gnu90', 'gnu89': 'gnu90',
'c99': 'c99', 'c9x': 'c99', 'gnu99': 'gnu99', 'gnu9x': 'gnu98',
'c11': 'c11', 'c1x': 'c11', 'gnu11': 'gnu11', 'gnu1x': 'gnu11'
}
if std in c_std:
opts['c']['compiler.std'] = c_std[std]
self.remove_option(flags['c_flags'], str)
if '-ansi' in flags['cxx_flags']:
opts['cpp']['compiler.std'] = '-ansi'
self.remove_option(flags['cxx_flags'], str)
else:
str = self.find_options(flags['cxx_flags'], '-std')
std = str[len('-std='):]
cpp_std = {
'c++98': 'cpp98', 'c++03': 'cpp98',
'gnu++98': 'gnucpp98', 'gnu++03': 'gnucpp98',
'c++0x': 'cpp0x', 'gnu++0x': 'gnucpp0x',
'c++11': 'cpp11', 'gnu++11': 'gnucpp11',
'c++1y': 'cpp1y', 'gnu++1y': 'gnucpp1y',
'c++14': 'cpp14', 'gnu++14': 'gnucpp14',
'c++1z': 'cpp1z', 'gnu++1z': 'gnucpp1z',
}
if std in cpp_std:
opts['cpp']['compiler.std'] = cpp_std[std]
self.remove_option(flags['cxx_flags'], str)
# Common optimisation options.
optimization_options = {
'-fmessage-length=0': 'optimization.messagelength',
'-fsigned-char': 'optimization.signedchar',
'-ffunction-sections': 'optimization.functionsections',
'-fdata-sections': 'optimization.datasections',
'-fno-common': 'optimization.nocommon',
'-fno-inline-functions': 'optimization.noinlinefunctions',
'-ffreestanding': 'optimization.freestanding',
'-fno-builtin': 'optimization.nobuiltin',
'-fsingle-precision-constant': 'optimization.spconstant',
'-fPIC': 'optimization.PIC',
'-fno-move-loop-invariants': 'optimization.nomoveloopinvariants',
}
for option in optimization_options:
opts['common'][optimization_options[option]] = False
if option in flags['common_flags']:
opts['common'][optimization_options[option]] = True
self.remove_option(flags['common_flags'], option)
# Common warning options.
warning_options = {
'-fsyntax-only': 'warnings.syntaxonly',
'-pedantic': 'warnings.pedantic',
'-pedantic-errors': 'warnings.pedanticerrors',
'-w': 'warnings.nowarn',
'-Wunused': 'warnings.unused',
'-Wuninitialized': 'warnings.uninitialized',
'-Wall': 'warnings.allwarn',
'-Wextra': 'warnings.extrawarn',
'-Wmissing-declarations': 'warnings.missingdeclaration',
'-Wconversion': 'warnings.conversion',
'-Wpointer-arith': 'warnings.pointerarith',
'-Wpadded': 'warnings.padded',
'-Wshadow': 'warnings.shadow',
'-Wlogical-op': 'warnings.logicalop',
'-Waggregate-return': 'warnings.agreggatereturn',
'-Wfloat-equal': 'warnings.floatequal',
'-Werror': 'warnings.toerrors',
}
for option in warning_options:
opts['common'][warning_options[option]] = False
if option in flags['common_flags']:
opts['common'][warning_options[option]] = True
self.remove_option(flags['common_flags'], option)
# Common debug options.
debug_levels = {
'-g': 'default',
'-g1': 'minimal',
'-g3': 'max',
}
opts['common']['debugging.level'] = 'none'
for option in debug_levels:
if option in flags['common_flags']:
opts['common'][
'debugging.level'] = debug_levels[option]
self.remove_option(flags['common_flags'], option)
debug_formats = {
'-ggdb': 'gdb',
'-gstabs': 'stabs',
'-gstabs+': 'stabsplus',
'-gdwarf-2': 'dwarf2',
'-gdwarf-3': 'dwarf3',
'-gdwarf-4': 'dwarf4',
'-gdwarf-5': 'dwarf5',
}
opts['common']['debugging.format'] = ''
for option in debug_levels:
if option in flags['common_flags']:
opts['common'][
'debugging.format'] = debug_formats[option]
self.remove_option(flags['common_flags'], option)
opts['common']['debugging.prof'] = False
if '-p' in flags['common_flags']:
opts['common']['debugging.prof'] = True
self.remove_option(flags['common_flags'], '-p')
opts['common']['debugging.gprof'] = False
if '-pg' in flags['common_flags']:
opts['common']['debugging.gprof'] = True
self.remove_option(flags['common_flags'], '-gp')
# Assembler options.
opts['as']['usepreprocessor'] = False
while '-x' in flags['asm_flags']:
ix = flags['asm_flags'].index('-x')
str = flags['asm_flags'][ix + 1]
if str == 'assembler-with-cpp':
opts['as']['usepreprocessor'] = True
else:
# Collect all other assembler options.
opts['as']['other'] += ' -x ' + str
self.remove_option(flags['asm_flags'], '-x')
self.remove_option(flags['asm_flags'], 'assembler-with-cpp')
opts['as']['nostdinc'] = False
if '-nostdinc' in flags['asm_flags']:
opts['as']['nostdinc'] = True
self.remove_option(flags['asm_flags'], '-nostdinc')
opts['as']['verbose'] = False
if '-v' in flags['asm_flags']:
opts['as']['verbose'] = True
self.remove_option(flags['asm_flags'], '-v')
# C options.
opts['c']['nostdinc'] = False
if '-nostdinc' in flags['c_flags']:
opts['c']['nostdinc'] = True
self.remove_option(flags['c_flags'], '-nostdinc')
opts['c']['verbose'] = False
if '-v' in flags['c_flags']:
opts['c']['verbose'] = True
self.remove_option(flags['c_flags'], '-v')
warning_options = {
'-Wmissing-prototypes': 'warnings.missingprototypes',
'-Wstrict-prototypes': 'warnings.strictprototypes',
'-Wbad-function-cast': 'warnings.badfunctioncast',
}
for option in warning_options:
opts['c'][warning_options[option]] = False
if option in flags['common_flags']:
opts['c'][warning_options[option]] = True
self.remove_option(flags['common_flags'], option)
# C++ options.
opts['cpp']['nostdinc'] = False
if '-nostdinc' in flags['cxx_flags']:
opts['cpp']['nostdinc'] = True
self.remove_option(flags['cxx_flags'], '-nostdinc')
opts['cpp']['nostdincpp'] = False
if '-nostdinc++' in flags['cxx_flags']:
opts['cpp']['nostdincpp'] = True
self.remove_option(flags['cxx_flags'], '-nostdinc++')
optimization_options = {
'-fno-exceptions': 'optimization.noexceptions',
'-fno-rtti': 'optimization.nortti',
'-fno-use-cxa-atexit': 'optimization.nousecxaatexit',
'-fno-threadsafe-statics': 'optimization.nothreadsafestatics',
}
for option in optimization_options:
opts['cpp'][optimization_options[option]] = False
if option in flags['cxx_flags']:
opts['cpp'][optimization_options[option]] = True
self.remove_option(flags['cxx_flags'], option)
if option in flags['common_flags']:
opts['cpp'][optimization_options[option]] = True
self.remove_option(flags['common_flags'], option)
warning_options = {
'-Wabi': 'warnabi',
'-Wctor-dtor-privacy': 'warnings.ctordtorprivacy',
'-Wnoexcept': 'warnings.noexcept',
'-Wnon-virtual-dtor': 'warnings.nonvirtualdtor',
'-Wstrict-null-sentinel': 'warnings.strictnullsentinel',
'-Wsign-promo': 'warnings.signpromo',
'-Weffc++': 'warneffc',
}
for option in warning_options:
opts['cpp'][warning_options[option]] = False
if option in flags['cxx_flags']:
opts['cpp'][warning_options[option]] = True
self.remove_option(flags['cxx_flags'], option)
if option in flags['common_flags']:
opts['cpp'][warning_options[option]] = True
self.remove_option(flags['common_flags'], option)
opts['cpp']['verbose'] = False
if '-v' in flags['cxx_flags']:
opts['cpp']['verbose'] = True
self.remove_option(flags['cxx_flags'], '-v')
# Linker options.
linker_options = {
'-nostartfiles': 'nostart',
'-nodefaultlibs': 'nodeflibs',
'-nostdlib': 'nostdlibs',
}
for option in linker_options:
opts['ld'][linker_options[option]] = False
if option in flags['ld_flags']:
opts['ld'][linker_options[option]] = True
self.remove_option(flags['ld_flags'], option)
opts['ld']['gcsections'] = False
if '-Wl,--gc-sections' in flags['ld_flags']:
opts['ld']['gcsections'] = True
self.remove_option(flags['ld_flags'], '-Wl,--gc-sections')
opts['ld']['flags'] = []
to_remove = []
for opt in flags['ld_flags']:
if opt.startswith('-Wl,--wrap,'):
opts['ld']['flags'].append(
'--wrap=' + opt[len('-Wl,--wrap,'):])
to_remove.append(opt)
for opt in to_remove:
self.remove_option(flags['ld_flags'], opt)
# Other tool remaining options are separated by category.
opts['as']['otherwarnings'] = self.find_options(
flags['asm_flags'], '-W')
opts['c']['otherwarnings'] = self.find_options(
flags['c_flags'], '-W')
opts['c']['otheroptimizations'] = self.find_options(flags[
'c_flags'], '-f')
opts['cpp']['otherwarnings'] = self.find_options(
flags['cxx_flags'], '-W')
opts['cpp']['otheroptimizations'] = self.find_options(
flags['cxx_flags'], '-f')
# Other common remaining options are separated by category.
opts['common']['optimization.other'] = self.find_options(
flags['common_flags'], '-f')
opts['common']['warnings.other'] = self.find_options(
flags['common_flags'], '-W')
# Remaining common flags are added to each tool.
opts['as']['other'] += ' ' + \
' '.join(flags['common_flags']) + ' ' + \
' '.join(flags['asm_flags'])
opts['c']['other'] += ' ' + \
' '.join(flags['common_flags']) + ' ' + ' '.join(flags['c_flags'])
opts['cpp']['other'] += ' ' + \
' '.join(flags['common_flags']) + ' ' + \
' '.join(flags['cxx_flags'])
opts['ld']['other'] += ' ' + \
' '.join(flags['common_flags']) + ' ' + ' '.join(flags['ld_flags'])
if len(self.system_libraries) > 0:
opts['ld']['other'] += ' -Wl,--start-group '
opts['ld'][
'other'] += ' '.join('-l' + s for s in self.system_libraries)
opts['ld']['other'] += ' -Wl,--end-group '
# Strip all 'other' flags, since they might have leading spaces.
opts['as']['other'] = opts['as']['other'].strip()
opts['c']['other'] = opts['c']['other'].strip()
opts['cpp']['other'] = opts['cpp']['other'].strip()
opts['ld']['other'] = opts['ld']['other'].strip()
if False:
print
print opts
print
print 'common_flags', flags['common_flags']
print 'asm_flags', flags['asm_flags']
print 'c_flags', flags['c_flags']
print 'cxx_flags', flags['cxx_flags']
print 'ld_flags', flags['ld_flags']
@staticmethod
def find_options(lst, option):
tmp = [str for str in lst if str.startswith(option)]
if len(tmp) > 0:
return tmp[0]
else:
return None
@staticmethod
def find_options(lst, prefix):
other = ''
opts = [str for str in lst if str.startswith(prefix)]
if len(opts) > 0:
for opt in opts:
other += ' ' + opt
GNUARMEclipse.remove_option(lst, opt)
return other.strip()
@staticmethod
def remove_option(lst, option):
if option in lst:
lst.remove(option)
# =============================================================================
|
adustm/mbed
|
tools/export/gnuarmeclipse/__init__.py
|
Python
|
apache-2.0
| 40,515
|
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {CONSTANTS, MessageType} from '../../../src/3p-frame-messaging';
import {CommonSignals} from '../../../src/common-signals';
import {Deferred} from '../../../src/utils/promise';
import {IntersectionObserverHostForAd} from './intersection-observer-host';
import {Services} from '../../../src/services';
import {
SubscriptionApi,
isPausable,
listenFor,
listenForOncePromise,
makePausable,
postMessageToWindows,
setPaused,
} from '../../../src/iframe-helper';
import {dev, devAssert} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {getData} from '../../../src/event-helper';
import {getHtml} from '../../../src/get-html';
import {isExperimentOn} from '../../../src/experiments';
import {isGoogleAdsA4AValidEnvironment} from '../../../ads/google/a4a/utils';
import {removeElement} from '../../../src/dom';
import {reportErrorToAnalytics} from '../../../src/error';
import {setStyle} from '../../../src/style';
import {throttle} from '../../../src/utils/rate-limit';
const VISIBILITY_TIMEOUT = 10000;
const MIN_INABOX_POSITION_EVENT_INTERVAL = 100;
export class AmpAdXOriginIframeHandler {
/**
* @param {!./amp-ad-3p-impl.AmpAd3PImpl|!../../amp-a4a/0.1/amp-a4a.AmpA4A} baseInstance
*/
constructor(baseInstance) {
/** @private {!Window} */
this.win_ = baseInstance.win;
/** @private */
this.baseInstance_ = baseInstance;
/** @private {!Element} */
this.element_ = baseInstance.element;
/** @private {?./amp-ad-ui.AmpAdUIHandler} */
this.uiHandler_ = baseInstance.uiHandler;
/** @type {?HTMLIFrameElement} iframe instance */
this.iframe = null;
/** @private {?IntersectionObserverHostForAd} */
this.intersectionObserverHost_ = null;
/** @private {SubscriptionApi} */
this.embedStateApi_ = null;
/** @private {?SubscriptionApi} */
this.inaboxPositionApi_ = null;
/** @private {boolean} */
this.isInaboxPositionApiInit_ = false;
/** @private {!Array<!Function>} functions to unregister listeners */
this.unlisteners_ = [];
/** @private @const {!../../../src/service/viewport/viewport-interface.ViewportInterface} */
this.viewport_ = Services.viewportForDoc(this.baseInstance_.getAmpDoc());
/** @private {boolean} */
this.sendPositionPending_ = false;
}
/**
* Sets up listeners and iframe state for iframe containing ad creative.
* @param {!HTMLIFrameElement} iframe
* @param {boolean=} opt_isA4A when true do not listen to ad response
* @param {boolean=} opt_letCreativeTriggerRenderStart Whether to wait for
* render start from the creative, or simply trigger it in here.
* @return {!Promise} awaiting render complete promise
*/
init(iframe, opt_isA4A, opt_letCreativeTriggerRenderStart) {
devAssert(!this.iframe, 'multiple invocations of init without destroy!');
this.iframe = iframe;
this.iframe.setAttribute('scrolling', 'no');
this.baseInstance_.applyFillContent(this.iframe);
const timer = Services.timerFor(this.baseInstance_.win);
// Init IntersectionObserver service.
this.intersectionObserverHost_ = new IntersectionObserverHostForAd(
this.baseInstance_,
this.iframe,
true
);
this.embedStateApi_ = new SubscriptionApi(
this.iframe,
'send-embed-state',
true,
() => this.sendEmbedInfo_(this.baseInstance_.isInViewport())
);
// Enable creative position observer if inabox experiment enabled OR
// adsense running on non-CDN cache where AMP creatives are xdomained and
// may require this information.
if (
isExperimentOn(this.win_, 'inabox-position-api') ||
(/^adsense$/i.test(this.element_.getAttribute('type')) &&
!isGoogleAdsA4AValidEnvironment(this.win_))
) {
// To provide position to inabox.
this.inaboxPositionApi_ = new SubscriptionApi(
this.iframe,
MessageType.SEND_POSITIONS,
true,
() => {
// TODO(@zhouyx): Make sendPosition_ only send to
// message origin iframe
this.sendPosition_();
this.registerPosition_();
}
);
}
// Triggered by context.reportRenderedEntityIdentifier(…) inside the ad
// iframe.
listenForOncePromise(this.iframe, 'entity-id', true).then((info) => {
this.element_.creativeId = info.data['id'];
});
this.handleOneTimeRequest_(MessageType.GET_HTML, (payload) => {
const selector = payload['selector'];
const attributes = payload['attributes'];
let content = '';
if (this.element_.hasAttribute('data-html-access-allowed')) {
content = getHtml(this.baseInstance_.win, selector, attributes);
}
return Promise.resolve(content);
});
this.handleOneTimeRequest_(MessageType.GET_CONSENT_STATE, () => {
return this.baseInstance_.getConsentState().then((consentState) => {
return {consentState};
});
});
// Install iframe resize API.
this.unlisteners_.push(
listenFor(
this.iframe,
'embed-size',
(data, source, origin, event) => {
if (!!data['hasOverflow']) {
this.element_.warnOnMissingOverflow = false;
}
this.handleResize_(
data['height'],
data['width'],
source,
origin,
event
);
},
true,
true
)
);
this.unlisteners_.push(
this.baseInstance_.getAmpDoc().onVisibilityChanged(() => {
this.sendEmbedInfo_(this.baseInstance_.isInViewport());
})
);
this.unlisteners_.push(
listenFor(
this.iframe,
MessageType.USER_ERROR_IN_IFRAME,
(data) => {
this.userErrorForAnalytics_(data['message']);
},
true,
true /* opt_includingNestedWindows */
)
);
// Iframe.onload normally called by the Ad after full load.
const iframeLoadPromise = this.baseInstance_
.loadPromise(this.iframe)
.then(() => {
// Wait just a little to allow `no-content` message to arrive.
if (this.iframe) {
// Chrome does not reflect the iframe readystate.
this.iframe.readyState = 'complete';
}
return timer.promise(10);
});
// Calculate render-start and no-content signals.
const {
promise: renderStartPromise,
resolve: renderStartResolve,
} = new Deferred();
const {
promise: noContentPromise,
resolve: noContentResolve,
} = new Deferred();
if (
this.baseInstance_.config &&
this.baseInstance_.config.renderStartImplemented
) {
// When `render-start` is supported, these signals are mutually
// exclusive. Whichever arrives first wins.
listenForOncePromise(
this.iframe,
['render-start', 'no-content'],
true
).then((info) => {
const {data} = info;
if (data['type'] == 'render-start') {
this.renderStartMsgHandler_(info);
renderStartResolve();
} else {
this.noContent_();
noContentResolve();
}
});
} else {
// If `render-start` is not supported, listen to `bootstrap-loaded`.
// This will avoid keeping the Ad empty until it's fully loaded, which
// could be a long time.
listenForOncePromise(this.iframe, 'bootstrap-loaded', true).then(() => {
renderStartResolve();
});
// Likewise, no-content is observed here. However, it's impossible to
// assure exclusivity between `no-content` and `bootstrap-loaded` b/c
// `bootstrap-loaded` always arrives first.
listenForOncePromise(this.iframe, 'no-content', true).then(() => {
this.noContent_();
noContentResolve();
});
}
// Wait for initial load signal. Notice that this signal is not
// used to resolve the final layout promise because iframe may still be
// consuming significant network and CPU resources.
listenForOncePromise(this.iframe, CommonSignals.INI_LOAD, true).then(() => {
// TODO(dvoytenko, #7788): ensure that in-a-box "ini-load" message is
// received here as well.
this.baseInstance_.signals().signal(CommonSignals.INI_LOAD);
});
// If "pausable-iframe" enabled, try to make the iframe pausable. It doesn't
// matter here whether this will succeed or not.
if (isExperimentOn(this.win_, 'pausable-iframe')) {
makePausable(this.iframe);
}
this.element_.appendChild(this.iframe);
if (opt_isA4A && !opt_letCreativeTriggerRenderStart) {
// A4A writes creative frame directly to page once creative is received
// and therefore does not require render start message so attach and
// impose no loader delay. Network is using renderStart or
// bootstrap-loaded to indicate ad request was sent, either way we know
// that occurred for Fast Fetch.
this.baseInstance_.renderStarted();
renderStartResolve();
} else {
// Set iframe initially hidden which will be removed on render-start or
// load, whichever is earlier.
setStyle(this.iframe, 'visibility', 'hidden');
}
// If A4A where creative is responsible for triggering render start (e.g
// no fill for sticky ad case), only trigger if renderStart listener promise
// explicitly fired (though we do not expect this to occur for A4A).
const triggerRenderStartPromise =
opt_isA4A && opt_letCreativeTriggerRenderStart
? renderStartPromise
: Promise.race([
renderStartPromise,
iframeLoadPromise,
timer.promise(VISIBILITY_TIMEOUT),
]);
triggerRenderStartPromise.then(() => {
// Common signal RENDER_START invoked at toggle visibility time
// Note: 'render-start' msg and common signal RENDER_START are different
// 'render-start' msg is a way for implemented Ad to display ad earlier
// RENDER_START signal is a signal to inform AMP runtime and other AMP
// elements that the component visibility has been toggled on.
this.baseInstance_.renderStarted();
if (this.iframe) {
setStyle(this.iframe, 'visibility', '');
}
});
// The actual ad load is eariliest of iframe.onload event and no-content.
return Promise.race([iframeLoadPromise, noContentPromise]);
}
/**
* @param {string} requestType
* @param {function(*)} getter
* @private
*/
handleOneTimeRequest_(requestType, getter) {
this.unlisteners_.push(
listenFor(
this.iframe,
requestType,
(info, source, origin) => {
if (!this.iframe) {
return;
}
const messageId = info[CONSTANTS.messageIdFieldName];
const payload = info[CONSTANTS.payloadFieldName];
getter(payload).then((content) => {
const result = dict();
result[CONSTANTS.messageIdFieldName] = messageId;
result[CONSTANTS.contentFieldName] = content;
postMessageToWindows(
dev().assertElement(this.iframe),
[{win: source, origin}],
requestType + CONSTANTS.responseTypeSuffix,
result,
true
);
});
},
true /* opt_is3P */,
false /* opt_includingNestedWindows */
)
);
}
/**
* callback functon on receiving render-start
* @param {{data: !JsonObject}} info
* @private
*/
renderStartMsgHandler_(info) {
const data = getData(info);
this.handleResize_(
data['height'],
data['width'],
info['source'],
info['origin'],
info['event']
);
}
/**
* Cleans up the listeners on the cross domain ad iframe and frees the
* iframe resource.
* @param {boolean=} opt_keep
*/
freeXOriginIframe(opt_keep) {
this.cleanup_();
// If ask to keep the iframe.
// Use in the case of no-content and iframe is a master iframe.
if (opt_keep) {
return;
}
if (this.iframe) {
removeElement(this.iframe);
this.iframe = null;
}
}
/**
* Cleans up listeners on the ad, and apply the default UI for ad.
* @private
*/
noContent_() {
if (!this.iframe) {
// unlayout already called
return;
}
this.freeXOriginIframe(this.iframe.name.indexOf('_master') >= 0);
this.uiHandler_.applyNoContentUI();
}
/**
* Cleans up listeners on the ad iframe.
* @private
*/
cleanup_() {
this.unlisteners_.forEach((unlistener) => unlistener());
this.unlisteners_.length = 0;
if (this.embedStateApi_) {
this.embedStateApi_.destroy();
this.embedStateApi_ = null;
}
if (this.inaboxPositionApi_) {
this.inaboxPositionApi_.destroy();
this.inaboxPositionApi_ = null;
}
if (this.intersectionObserverHost_) {
this.intersectionObserverHost_.destroy();
this.intersectionObserverHost_ = null;
}
}
/**
* Updates the element's dimensions to accommodate the iframe's
* requested dimensions. Notifies the window that request the resize
* of success or failure.
* @param {number|string|undefined} height
* @param {number|string|undefined} width
* @param {!Window} source
* @param {string} origin
* @param {!MessageEvent} event
* @private
*/
handleResize_(height, width, source, origin, event) {
this.baseInstance_.getVsync().mutate(() => {
if (!this.iframe) {
// iframe can be cleanup before vsync.
return;
}
const iframeHeight = this.iframe./*OK*/ offsetHeight;
const iframeWidth = this.iframe./*OK*/ offsetWidth;
this.uiHandler_
.updateSize(height, width, iframeHeight, iframeWidth, event)
.then(
(info) => {
this.sendEmbedSizeResponse_(
info.success,
info.newWidth,
info.newHeight,
source,
origin
);
},
() => {}
);
});
}
/**
* Sends a response to the window which requested a resize.
* @param {boolean} success
* @param {number} requestedWidth
* @param {number} requestedHeight
* @param {!Window} source
* @param {string} origin
* @private
*/
sendEmbedSizeResponse_(
success,
requestedWidth,
requestedHeight,
source,
origin
) {
// The iframe may have been removed by the time we resize.
if (!this.iframe) {
return;
}
postMessageToWindows(
this.iframe,
[{win: source, origin}],
success ? 'embed-size-changed' : 'embed-size-denied',
dict({
'requestedWidth': requestedWidth,
'requestedHeight': requestedHeight,
}),
true
);
}
/**
* @param {boolean} inViewport
* @private
*/
sendEmbedInfo_(inViewport) {
if (!this.embedStateApi_) {
return;
}
this.embedStateApi_.send(
'embed-state',
dict({
'inViewport': inViewport,
'pageHidden': !this.baseInstance_.getAmpDoc().isVisible(),
})
);
}
/**
* Retrieve iframe position entry in next animation frame.
* @return {*} TODO(#23582): Specify return type
* @private
*/
getIframePositionPromise_() {
return this.viewport_
.getClientRectAsync(dev().assertElement(this.iframe))
.then((position) => {
devAssert(
position,
'element clientRect should intersects with root clientRect'
);
const viewport = this.viewport_.getRect();
return dict({
'targetRect': position,
'viewportRect': viewport,
});
});
}
/** @private */
sendPosition_() {
if (this.sendPositionPending_) {
// Only send once in single animation frame.
return;
}
this.sendPositionPending_ = true;
this.getIframePositionPromise_().then((position) => {
this.sendPositionPending_ = false;
this.inaboxPositionApi_.send(MessageType.POSITION, position);
});
}
/** @private */
registerPosition_() {
if (this.isInaboxPositionApiInit_) {
// only register to viewport scroll/resize once
return;
}
this.isInaboxPositionApiInit_ = true;
// Send window scroll/resize event to viewport.
this.unlisteners_.push(
this.viewport_.onScroll(
throttle(
this.win_,
() => {
this.getIframePositionPromise_().then((position) => {
this.inaboxPositionApi_.send(MessageType.POSITION, position);
});
},
MIN_INABOX_POSITION_EVENT_INTERVAL
)
)
);
this.unlisteners_.push(
this.viewport_.onResize(() => {
this.getIframePositionPromise_().then((position) => {
this.inaboxPositionApi_.send(MessageType.POSITION, position);
});
})
);
}
/**
* See BaseElement method.
* @param {boolean} inViewport
*/
viewportCallback(inViewport) {
if (this.intersectionObserverHost_) {
this.intersectionObserverHost_.onViewportCallback(inViewport);
}
this.sendEmbedInfo_(inViewport);
}
/**
* See BaseElement method.
*/
onLayoutMeasure() {
// When the framework has the need to remeasure us, our position might
// have changed. Send an intersection record if needed.
if (this.intersectionObserverHost_) {
this.intersectionObserverHost_.fire();
}
}
/**
* @param {string} message
* @private
*/
userErrorForAnalytics_(message) {
if (typeof message == 'string') {
const e = new Error(message);
e.name = '3pError';
reportErrorToAnalytics(e, this.baseInstance_.win);
}
}
/**
* @return {boolean}
*/
isPausable() {
return (
isExperimentOn(this.win_, 'pausable-iframe') &&
!!this.iframe &&
isPausable(this.iframe)
);
}
/**
* See `BaseElement.pauseCallback()` and `BaseElement.resumeCallback()`.
* @param {boolean} paused
*/
setPaused(paused) {
if (isExperimentOn(this.win_, 'pausable-iframe') && this.iframe) {
setPaused(this.iframe, paused);
}
}
}
// Make the class available to other late loaded amp-ad implementations
// without them having to depend on it directly.
AMP.AmpAdXOriginIframeHandler = AmpAdXOriginIframeHandler;
|
adup-tech/amphtml
|
extensions/amp-ad/0.1/amp-ad-xorigin-iframe-handler.js
|
JavaScript
|
apache-2.0
| 19,018
|
Scalaz support for json4s
=========================
This project adds a type class to parse JSON:
trait JSON[A] {
def read(json: JValue): Result[A]
def write(value: A): JValue
}
type Result[A] = ValidationNEL[Error, A]
Function 'read' returns an Applicative Functor, enabling parsing in an applicative style.
Simple example
--------------
scala> import scalaz._
scala> import Scalaz._
scala> import org.json4s.scalaz.JsonScalaz._
scala> import org.json4s._
scala> case class Address(street: String, zipCode: String)
scala> case class Person(name: String, age: Int, address: Address)
scala> val json = parse(""" {"street": "Manhattan 2", "zip": "00223" } """)
scala> (field[String]("street")(json) |@| field[String]("zip")(json)) { Address }
res0: Success(Address(Manhattan 2,00223))
scala> (field[String]("streets")(json) |@| field[String]("zip")(json)) { Address }
res1: Failure("no such field 'streets'")
Notice the required explicit types when reading fields from JSON. The library comes with helpers which
can lift functions with pure values into "parsing context". This works well with Scala's type inferencer:
scala> Address.applyJSON(field("street"), field("zip"))(json)
res2: Success(Address(Manhattan 2,00223))
Function 'applyJSON' above lifts function
(String, String) => Address
to
(JValue => Result[String], JValue => Result[String]) => (JValue => Result[Address])
Example which adds a new type class instance
--------------------------------------------
scala> implicit def addrJSONR: JSONR[Address] = Address.applyJSON(field("street"), field("zip"))
scala> val p = JsonParser.parse(""" {"name":"joe","age":34,"address":{"street": "Manhattan 2", "zip": "00223" }} """)
scala> Person.applyJSON(field("name"), field("age"), field("address"))(p)
res0: Success(Person(joe,34,Address(Manhattan 2,00223)))
Validation
----------
Applicative style parsing works nicely with validation and data conversion. It is easy to compose
transformations with various combinators Scalaz provides. An often used combinator is called a Kleisli
composition >=>.
def min(x: Int): Int => Result[Int] = (y: Int) =>
if (y < x) Fail("min", y + " < " + x) else y.success
def max(x: Int): Int => Result[Int] = (y: Int) =>
if (y > x) Fail("max", y + " > " + x) else y.success
// Creates a function JValue => Result[Person]
Person.applyJSON(field("name"), validate[Int]("age") >=> min(18) >=> max(60))
Installation
------------
Add dependency to your SBT project description:
val json4s_scalaz = "org.json4s" %% "json4s-scalaz" % "XXX"
Links
-----
* [More examples](https://github.com/lift/framework/tree/master/core/json-scalaz/src/test/scala/net/lifweb/json/scalaz)
* [Scalaz](http://code.google.com/p/scalaz/)
* [Kleisli composition](http://www.haskell.org/hoogle/?hoogle=%28a+-%3E+m+b%29+-%3E+%28b+-%3E+m+c%29+-%3E+%28a+-%3E+m+c%29)
|
nornagon/json4s
|
scalaz/README.md
|
Markdown
|
apache-2.0
| 2,987
|
<?php
/**************************************************************************
Copyright 2017 Benato Denis
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.
*****************************************************************************/
namespace Gishiki\tests\Security\Encryption\Symmetric;
use PHPUnit\Framework\TestCase;
use Gishiki\Security\Encryption\Symmetric\SymmetricException;
use Gishiki\Security\Encryption\Symmetric\SecretKey;
use Gishiki\Security\Encryption\Symmetric\Cryptography;
/**
* Various tests for encryption algorithms.
*
* @author Benato Denis <benato.denis96@gmail.com>
*/
class CryptographyTest extends TestCase
{
public function testInvalidMessageEncryption()
{
//generate the key
$key = new SecretKey(SecretKey::generate('testing/key'));
$message = 80;
$this->expectException(\InvalidArgumentException::class);
// try to encrypt the message
Cryptography::encrypt($key, $message);
}
public function testInvalidMessageDecryption()
{
//generate the key
$key = new SecretKey(SecretKey::generate('testing/key'));
$message = 'you should hide this, lol!';
//encrypt the message
$enc_message = Cryptography::encrypt($key, $message);
$this->expectException(\InvalidArgumentException::class);
//decrypt the message
Cryptography::decrypt($key, 70, $enc_message['IV_base64']);
}
public function testAES128Encryption()
{
//generate the key
$key = new SecretKey(SecretKey::generate('testing/key'));
$message = 'you should hide this, lol!';
//encrypt the message
$enc_message = Cryptography::encrypt($key, $message);
//decrypt the message
$result = Cryptography::decrypt($key, $enc_message['Encryption'], $enc_message['IV_base64']);
//test the result
$this->assertEquals($message, $result);
}
public function testAES128LongEncryption()
{
//generate the key
$key = new SecretKey(SecretKey::generate('testing/key'));
$message = base64_encode(openssl_random_pseudo_bytes(515));
//encrypt the message
$enc_message = Cryptography::encrypt($key, $message);
//decrypt the message
$result = Cryptography::decrypt($key, $enc_message['Encryption'], $enc_message['IV_base64']);
//test the result
$this->assertEquals($message, $result);
}
public function testAES192Encryption()
{
//generate the key
$key = new SecretKey(SecretKey::generate('T3st1n9/k3y <3', 24));
$message = base64_encode(openssl_random_pseudo_bytes(512));
//encrypt the message
$enc_message = Cryptography::encrypt($key, $message, null, Cryptography::AES_CBC_192);
//decrypt the message
$result = Cryptography::decrypt($key, $enc_message['Encryption'], $enc_message['IV_base64'], Cryptography::AES_CBC_192);
//test the result
$this->assertEquals($message, $result);
}
public function testAES256Encryption()
{
//generate the key
$key = new SecretKey(SecretKey::generate('T3st1n9/k3y <3', 32));
$message = base64_encode(openssl_random_pseudo_bytes(512));
//encrypt the message
$enc_message = Cryptography::encrypt($key, $message, null, Cryptography::AES_CBC_256);
//decrypt the message
$result = Cryptography::decrypt($key, $enc_message['Encryption'], $enc_message['IV_base64'], Cryptography::AES_CBC_256);
//test the result
$this->assertEquals($message, $result);
}
public function testInvalidKey()
{
$this->expectException(\InvalidArgumentException::class);
//generate the key
$key = new SecretKey(SecretKey::generate('T3st1n9/k3y <3', 1));
$message = base64_encode(openssl_random_pseudo_bytes(512));
//encrypt the message (trigger the exception)
Cryptography::encrypt($key, $message, null, Cryptography::AES_CBC_128);
}
public function testAES128BadKeyEncrypt()
{
//generate the key
$key = new SecretKey(SecretKey::generate('T3st1n9/k3y <3', 2));
$message = base64_encode(openssl_random_pseudo_bytes(512));
$this->expectException(SymmetricException::class);
//encrypt the message (trigger the exception)
Cryptography::encrypt($key, $message, null, Cryptography::AES_CBC_128);
}
public function testAES192BadKeyEncrypt()
{
$this->expectException(SymmetricException::class);
//generate the key
$key = new SecretKey(SecretKey::generate('T3st1n9/k3y <3', 40));
$message = base64_encode(openssl_random_pseudo_bytes(512));
//encrypt the message (trigger the exception)
Cryptography::encrypt($key, $message, null, Cryptography::AES_CBC_192);
}
public function testAES256BadKeyEncrypt()
{
$this->expectException(SymmetricException::class);
//generate the key
$key = new SecretKey(SecretKey::generate('T3st1n9/k3y <3', 12));
$message = base64_encode(openssl_random_pseudo_bytes(512));
//encrypt the message (trigger the exception)
Cryptography::encrypt($key, $message, null, Cryptography::AES_CBC_256);
}
public function testAES256BadKeyDecrypt()
{
//generate the key
$key = new SecretKey(SecretKey::generate('T3st1n9/k3y <3', 12));
$this->expectException(SymmetricException::class);
//encrypt the message (trigger the exception)
Cryptography::decrypt($key, "This message is useless.", openssl_random_pseudo_bytes(20), Cryptography::AES_CBC_256);
}
}
|
NeroReflex/Gishiki
|
tests/Security/Encryption/Symmetric/CryptographyTest.php
|
PHP
|
apache-2.0
| 6,228
|
<html>
<!-- $Id: tools.html,v 1.49 2009/10/13 11:42:05 andy_seaborne Exp $ -->
<!-- (c) Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company LP -->
<head>
<title>Jena Semantic Web Framework - Command Line Utilities</title>
<meta name="author" content="The Jena Team" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" type="text/css" href="styles/site.css" />
</head>
<body>
<div id="header">
Jena Command Line Utilities
</div>
<div id="main">
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<!-- Left -->
<td width="25ex" style="border-right: 1px solid #DDD;">
<div id="leftnav">
<div align="center" >
<img src="images/jena-logo-small.png" alt="jena logo" style="border:0;" />
</div>
<div class="grouptitle" style="width: 20ex;">on this site</div>
<div class="item"><a href="index.html">home</a></div>
<div class="item"><a href="downloads.html">downloads</a></div>
<div class="item"><a href="license.html">license</a></div>
<div class="item"><a href="documentation.html">documentation</a></div>
<div class="item"><a href="support.html">support</a></div>
<div class="item"><a href="resources.html">resources</a></div>
<div class="item"><a href="contrib/contributions.html">contributions</a></div>
<div class="item"> </div>
<div id="localnav">
<div class="item"> </div>
<div class="item"> </div>
<div class="item"> </div>
<div class="item"> </div>
<div class="item"> </div>
<div class="item"> </div>
</div>
</div>
</td>
<!-- Right -->
<td width="100%"> <!-- Set width. Fixed width above takes precedence : fixes Mozilla oddity -->
<div id="trail">
<a href="index.html">home</a>
» <a href="documentation.html">documentation</a>
» <a href="tools.html">tools</a>
</div>
<div id="content">
<p>
Jena provides a number of utilities that wrap up access to
some commonly used functionality.</p>
<p>These command utilities print a usage message with
the <code>-h</code> flag.</p>
<h2>RDF processing utilities</h2>
<dl>
<dt>jena.rdfparse</dt>
<dd>Call ARP</dd>
<dt>jena.rdfcat</dt>
<dd>Copy and merge models</dd>
<dt>jena.rdfcopy</dt>
<dd>Copy a model, changing its syntax</dd>
<dt>jena.rdfcompare</dt>
<dd>Test whether two models are isomorphic</dd>
<dt>jena.n3</dt>
<dd>A tool to access the N3 parser directly.</dd>
</dl>
<h2>Ontology utilities</h2>
<dl>
<dt>jena.schemagen</dt>
<dd><a href="how-to/schemagen.html">schemagen - a tool to generate Java
from a vocabulary or ontology</a></dd>
</dl>
<h2>Database utilities</h2>
<dl>
<dt>jena.dbcreate</dt>
<dd>Create a Jena model in a database.</dd>
<dt>jena.dblist</dt>
<dd>List all models in a databse.</dd>
<dt>jena.dbload</dt>
<dd>Load a file of data into a database.</dd>
<dt>jena.dbdump<dt>
<dd>Dump a database</dd>
<dt>jena.dbremove</dt>
<dd>Remove a Jena model and all its data from a database. Use with care.</dd>
</dl>
<h2>Query Utilities</h2>
<p><a href="http://openjena.org/ARQ/cmds.html">ARQ commands documentation</a></p>
<p>Scripts to run these commands, in the bin/ and bat/ directories,
require the environment variable <code>ARQROOT</code> to be set to
the root directory of a Jena or ARQ installation.</p>
<dl>
<dt><a href="http://openjena.org/ARQ/cmds.html#arq.query">arq.query</a></dt>
<dd>Execute a SPARQL query.</dd>
<dt><a href="http://openjena.org/ARQ/cmds.html#arq.sparql">arq.sparql</a></dt>
<dd>Execute a SPARQL query.</dd>
<dt><a href="http://openjena.org/ARQ/cmds.html#arq.rset">arq.rset</a></dt>
<dd>Parse <a href="http://www.w3.org/TR/rdf-sparql-XMLres/">SPARQL Query Results
XML Format</a> or
<a href="http://www.w3.org/2001/sw/DataAccess/tests/README.html">SPARQL testing
results</a> files. Print in these formats or in plain text.</dd>
<dt><a href="http://openjena.org/ARQ/cmds.html#arq.qtest">arq.qtest</a></dt>
<dd>Run SPARQL tests.</dd>
</dl>
<h2>Remote Access</h2>
<p>These programs can be set use use a proxy to traverse a firewall by
setting
system properties. To use a socks proxy include the following in the
command
line:</p>
<pre> -DsocksProxyHost=<your-proxy-domain-name-or-ip-address></pre>
<p>To use an http proxy include the following on the command line:</p>
<pre> -DproxySet=true -DproxyHost=<your-proxy> -DproxyPort=<your-proxy-port-number></pre>
<p> </p>
</dl></div><!-- end #content -->
</td>
</tr>
</table>
</div> <!-- end #main -->
<div id="footer">
</div>
<div id="logos">
<div class="left">
<a href="http://www.w3.org/RDF/" title="RDF Resource Description Framework">
<img border="0" src="images/rdf_w3c_icon.gif" alt="Resource Description Framework">
</a>
</div>
<div class="right">
<a href="http://sourceforge.net/projects/jena"><img src="http://sflogo.sourceforge.net/sflogo.php?group_id=40417&type=13" width="120" height="30" border="0" alt="Get Jena at SourceForge.net. Fast, secure and Free Open Source software downloads" /></a>
<!--
Hosted by:
<a href="http://sourceforge.net/projects/jena" title="SourceForge">
< !- -
<img src="http://sourceforge.net/sflogo.php?group_id=40417&type=1"
border="0"
alt="sourceforge.net" />
-->
<img src="images/sflogo-type1.png" border="0" alt="sourceforge.net"/>
</a>
</div>
</div>
</body>
</html>
|
BiGCAT-UM/wp2lod
|
lib/Jena-2.6.4/doc/tools.html
|
HTML
|
apache-2.0
| 5,358
|
<?php
final class PhortuneSubscriptionEditController extends PhortuneController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$subscription = id(new PhortuneSubscriptionQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$subscription) {
return new Aphront404Response();
}
id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession(
$viewer,
$request,
$this->getApplicationURI($subscription->getEditURI()));
$merchant = $subscription->getMerchant();
$account = $subscription->getAccount();
$title = pht('Subscription: %s', $subscription->getSubscriptionName());
$header = id(new PHUIHeaderView())
->setHeader($subscription->getSubscriptionName());
$view_uri = $subscription->getURI();
$valid_methods = id(new PhortunePaymentMethodQuery())
->setViewer($viewer)
->withAccountPHIDs(array($account->getPHID()))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->execute();
$valid_methods = mpull($valid_methods, null, 'getPHID');
$current_phid = $subscription->getDefaultPaymentMethodPHID();
$errors = array();
if ($request->isFormPost()) {
$default_method_phid = $request->getStr('defaultPaymentMethodPHID');
if (!$default_method_phid) {
$default_method_phid = null;
$e_method = null;
} else if ($default_method_phid == $current_phid) {
// If you have an invalid setting already, it's OK to retain it.
$e_method = null;
} else {
if (empty($valid_methods[$default_method_phid])) {
$e_method = pht('Invalid');
$errors[] = pht('You must select a valid default payment method.');
}
}
// TODO: We should use transactions here, and move the validation logic
// inside the Editor.
if (!$errors) {
$subscription->setDefaultPaymentMethodPHID($default_method_phid);
$subscription->save();
return id(new AphrontRedirectResponse())
->setURI($view_uri);
}
}
// Add the option to disable autopay.
$disable_options = array(
'' => pht('(Disable Autopay)'),
);
// Don't require the user to make a valid selection if the current method
// has become invalid.
// TODO: This should probably have a note about why this is bogus.
if ($current_phid && empty($valid_methods[$current_phid])) {
$handles = $this->loadViewerHandles(array($current_phid));
$current_options = array(
$current_phid => $handles[$current_phid]->getName(),
);
} else {
$current_options = array();
}
// Add any available options.
$valid_options = mpull($valid_methods, 'getFullDisplayName', 'getPHID');
$options = $disable_options + $current_options + $valid_options;
$crumbs = $this->buildApplicationCrumbs();
$this->addAccountCrumb($crumbs, $account);
$crumbs->addTextCrumb(
pht('Subscription %d', $subscription->getID()),
$view_uri);
$crumbs->addTextCrumb(pht('Edit'));
$form = id(new AphrontFormView())
->setUser($viewer)
->appendChild(
id(new AphrontFormSelectControl())
->setName('defaultPaymentMethodPHID')
->setLabel(pht('Autopay With'))
->setValue($current_phid)
->setOptions($options))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Save Changes'))
->addCancelButton($view_uri));
$box = id(new PHUIObjectBoxView())
->setUser($viewer)
->setHeaderText(pht('Edit %s', $subscription->getSubscriptionName()))
->setFormErrors($errors)
->appendChild($form);
return $this->buildApplicationPage(
array(
$crumbs,
$box,
),
array(
'title' => $title,
));
}
}
|
hach-que/unearth-phabricator
|
src/applications/phortune/controller/PhortuneSubscriptionEditController.php
|
PHP
|
apache-2.0
| 4,179
|
/*
* Copyright (c) 2014-2018 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* 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 monix.reactive.internal.builders
import scala.util.control.NonFatal
import monix.execution.{Ack, Cancelable, ExecutionModel}
import monix.reactive.Observable
import monix.reactive.observers.Subscriber
import scala.concurrent.Future
private[reactive]
final class ExecuteWithModelObservable[A](source: Observable[A], em: ExecutionModel)
extends Observable[A] {
override def unsafeSubscribeFn(out: Subscriber[A]): Cancelable = {
var streamErrors = true
try {
val newS = out.scheduler.withExecutionModel(em)
streamErrors = false
source.unsafeSubscribeFn(new Subscriber[A] {
implicit val scheduler = newS
def onError(ex: Throwable): Unit = out.onError(ex)
def onComplete(): Unit = out.onComplete()
def onNext(elem: A): Future[Ack] = out.onNext(elem)
})
}
catch {
case ex if NonFatal(ex) =>
if (streamErrors) out.onError(ex)
else out.scheduler.reportFailure(ex)
Cancelable.empty
}
}
}
|
Wogan/monix
|
monix-reactive/shared/src/main/scala/monix/reactive/internal/builders/ExecuteWithModelObservable.scala
|
Scala
|
apache-2.0
| 1,679
|
<!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_45-internal) on Fri Sep 18 20:29:05 UTC 2015 -->
<title>fi.vincit.multiusertest.annotation (core 0.3.0-beta4 API)</title>
<meta name="date" content="2015-09-18">
<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="fi.vincit.multiusertest.annotation (core 0.3.0-beta4 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 class="navBarCell1Rev">Package</li>
<li>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>Prev Package</li>
<li><a href="../../../../fi/vincit/multiusertest/rule/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?fi/vincit/multiusertest/annotation/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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 title="Package" class="title">Package fi.vincit.multiusertest.annotation</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Annotation Types Summary table, listing annotation types, and an explanation">
<caption><span>Annotation Types Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Annotation Type</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../fi/vincit/multiusertest/annotation/MultiUserTestConfig.html" title="annotation in fi.vincit.multiusertest.annotation">MultiUserTestConfig</a></td>
<td class="colLast">
<div class="block">
Configure the test class to use the desired runner and change the default expected
exception.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../fi/vincit/multiusertest/annotation/TestUsers.html" title="annotation in fi.vincit.multiusertest.annotation">TestUsers</a></td>
<td class="colLast">
<div class="block">
This annotation works with MultiUserTestRunner JUnit runner.</div>
</td>
</tr>
</tbody>
</table>
</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 class="navBarCell1Rev">Package</li>
<li>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>Prev Package</li>
<li><a href="../../../../fi/vincit/multiusertest/rule/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?fi/vincit/multiusertest/annotation/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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 ======= -->
</body>
</html>
|
juhasipo/multi-user-test-runner
|
latest/javadocs/fi/vincit/multiusertest/annotation/package-summary.html
|
HTML
|
apache-2.0
| 5,251
|
package com.opzoon.xos.env;
public class UnxCommandResultAnalysor {
}
|
github-hai/DemoCode
|
xOS/src/main/java/com/opzoon/xos/env/UnxCommandResultAnalysor.java
|
Java
|
apache-2.0
| 72
|
/*
* 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.groovy.lang.psi.impl.statements.typedef;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.SimpleModificationTracker;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.*;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierFlags;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrTraitField;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrTraitMethod;
import org.jetbrains.plugins.groovy.lang.psi.util.GrClassImplUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil;
import org.jetbrains.plugins.groovy.lang.resolve.ast.AstTransformContributor;
import java.util.*;
/**
* Created by Max Medvedev on 03/03/14
*/
public class GrTypeDefinitionMembersCache {
private static final Logger LOG = Logger.getInstance(GrTypeDefinitionMembersCache.class);
private static final Condition<PsiMethod> CONSTRUCTOR_CONDITION = new Condition<PsiMethod>() {
@Override
public boolean value(PsiMethod method) {
return method.isConstructor();
}
};
private final SimpleModificationTracker myTreeChangeTracker = new SimpleModificationTracker();
private final GrTypeDefinition myDefinition;
public GrTypeDefinitionMembersCache(GrTypeDefinition definition) {
myDefinition = definition;
}
public GrMethod[] getCodeMethods() {
return CachedValuesManager.getCachedValue(myDefinition, new CachedValueProvider<GrMethod[]>() {
@Nullable
@Override
public Result<GrMethod[]> compute() {
GrTypeDefinitionBody body = myDefinition.getBody();
GrMethod[] methods = body != null ? body.getMethods() : GrMethod.EMPTY_ARRAY;
return Result.create(methods, myTreeChangeTracker);
}
});
}
public GrMethod[] getCodeConstructors() {
return CachedValuesManager.getCachedValue(myDefinition, new CachedValueProvider<GrMethod[]>() {
@Nullable
@Override
public Result<GrMethod[]> compute() {
GrTypeDefinitionBody body = myDefinition.getBody();
GrMethod[] methods;
if (body != null) {
List<GrMethod> result = ContainerUtil.findAll(body.getMethods(), CONSTRUCTOR_CONDITION);
methods = result.toArray(new GrMethod[result.size()]);
}
else {
methods = GrMethod.EMPTY_ARRAY;
}
return Result.create(methods, myTreeChangeTracker);
}
});
}
public PsiMethod[] getConstructors() {
return CachedValuesManager.getCachedValue(myDefinition, new CachedValueProvider<PsiMethod[]>() {
@Nullable
@Override
public Result<PsiMethod[]> compute() {
List<PsiMethod> result = ContainerUtil.findAll(myDefinition.getMethods(), CONSTRUCTOR_CONDITION);
return Result.create(result.toArray(new PsiMethod[result.size()]), myTreeChangeTracker,
PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
}
});
}
public PsiClass[] getInnerClasses() {
return CachedValuesManager.getCachedValue(myDefinition, new CachedValueProvider<PsiClass[]>() {
@Nullable
@Override
public Result<PsiClass[]> compute() {
final List<PsiClass> result = ContainerUtil.newArrayList();
final GrTypeDefinitionBody body = myDefinition.getBody();
if (body != null) ContainerUtil.addAll(result, body.getInnerClasses());
result.addAll(AstTransformContributor.runContributorsForClasses(myDefinition));
return Result.create(result.toArray(new PsiClass[result.size()]), myTreeChangeTracker);
}
});
}
public GrField[] getFields() {
return CachedValuesManager.getCachedValue(myDefinition, new CachedValueProvider<GrField[]>() {
@Nullable
@Override
public Result<GrField[]> compute() {
List<GrField> fields = getFieldsImpl();
return Result.create(fields.toArray(new GrField[fields.size()]), myTreeChangeTracker, PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
}
});
}
private List<GrField> getFieldsImpl() {
List<GrField> fields = ContainerUtil.newArrayList(myDefinition.getCodeFields());
fields.addAll(new TraitCollector().collectFields());
fields.addAll(getSyntheticFields());
return fields;
}
private List<GrField> getSyntheticFields() {
return CachedValuesManager.getCachedValue(myDefinition, new CachedValueProvider<List<GrField>>() {
@Nullable
@Override
public Result<List<GrField>> compute() {
return Result.create(AstTransformContributor.runContributorsForFields(myDefinition), myTreeChangeTracker,
PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
}
});
}
public PsiMethod[] getMethods() {
return CachedValuesManager.getCachedValue(myDefinition, new CachedValueProvider<PsiMethod[]>() {
@Override
public Result<PsiMethod[]> compute() {
List<PsiMethod> result = ContainerUtil.newArrayList();
GrClassImplUtil.collectMethodsFromBody(myDefinition, result);
result.addAll(new TraitCollector().collectMethods(result));
for (PsiMethod method : AstTransformContributor.runContributorsForMethods(myDefinition)) {
GrClassImplUtil.addExpandingReflectedMethods(result, method);
}
for (GrField field : getSyntheticFields()) {
if (!field.isProperty()) continue;
ContainerUtil.addIfNotNull(result, field.getSetter());
Collections.addAll(result, field.getGetters());
}
return Result.create(result.toArray(new PsiMethod[result.size()]), myTreeChangeTracker,
PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
}
});
}
public void dropCaches() {
myTreeChangeTracker.incModificationCount();
}
private class TraitCollector {
private abstract class TraitProcessor<T extends PsiElement> {
private final ArrayList<CandidateInfo> result = ContainerUtil.newArrayList();
private final Set<PsiClass> processed = ContainerUtil.newHashSet();
public TraitProcessor(@NotNull GrTypeDefinition superClass, @NotNull PsiSubstitutor substitutor) {
process(superClass, substitutor);
}
@NotNull
public List<CandidateInfo> getResult() {
return result;
}
private void process(@NotNull GrTypeDefinition trait, @NotNull PsiSubstitutor substitutor) {
assert trait.isTrait();
if (!processed.add(trait)) return;
processTrait(trait, substitutor);
List<PsiClassType.ClassResolveResult> traits = getSuperTraitsByCorrectOrder(trait.getSuperTypes());
for (PsiClassType.ClassResolveResult resolveResult :traits) {
PsiClass superClass = resolveResult.getElement();
if (GrTraitUtil.isTrait(superClass)) {
final PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, trait, substitutor);
process((GrTypeDefinition)superClass, superSubstitutor);
}
}
}
protected abstract void processTrait(@NotNull GrTypeDefinition trait, @NotNull PsiSubstitutor substitutor);
protected void addCandidate(T element, PsiSubstitutor substitutor) {
result.add(new CandidateInfo(element, substitutor));
}
}
@NotNull
public List<PsiMethod> collectMethods(@NotNull List<PsiMethod> codeMethods) {
if (myDefinition.isInterface() && !myDefinition.isTrait()) return Collections.emptyList();
GrImplementsClause clause = myDefinition.getImplementsClause();
if (clause == null) return Collections.emptyList();
PsiClassType[] types = clause.getReferencedTypes();
List<PsiClassType.ClassResolveResult> traits = getSuperTraitsByCorrectOrder(types);
if (traits.isEmpty()) return Collections.emptyList();
Set<MethodSignature> existingSignatures = ContainerUtil.newHashSet(ContainerUtil.map(codeMethods, new Function<PsiMethod, MethodSignature>() {
@Override
public MethodSignature fun(PsiMethod method) {
return method.getSignature(PsiSubstitutor.EMPTY);
}
}));
List<PsiMethod> result = ContainerUtil.newArrayList();
for (PsiClassType.ClassResolveResult resolveResult : traits) {
GrTypeDefinition trait = (GrTypeDefinition)resolveResult.getElement();
LOG.assertTrue(trait != null);
List<CandidateInfo> concreteTraitMethods = new TraitProcessor<PsiMethod>(trait, resolveResult.getSubstitutor()) {
protected void processTrait(@NotNull GrTypeDefinition trait, @NotNull PsiSubstitutor substitutor) {
for (GrMethod method : trait.getCodeMethods()) {
if (!method.getModifierList().hasExplicitModifier(PsiModifier.ABSTRACT)) {
addCandidate(method, substitutor);
}
}
for (GrField field : trait.getCodeFields()) {
if (!field.isProperty()) continue;
for (GrAccessorMethod method : field.getGetters()) {
addCandidate(method, substitutor);
}
GrAccessorMethod setter = field.getSetter();
if (setter != null) {
addCandidate(setter, substitutor);
}
}
}
}.getResult();
for (CandidateInfo candidateInfo : concreteTraitMethods) {
List<GrMethod> methodsToAdd = getExpandingMethods(candidateInfo);
for (GrMethod impl : methodsToAdd) {
if (existingSignatures.add(impl.getSignature(PsiSubstitutor.EMPTY))) {
result.add(impl);
}
}
}
}
return result;
}
@NotNull
public List<GrField> collectFields() {
if (myDefinition.isInterface() && !myDefinition.isTrait()) return Collections.emptyList();
List<GrField> result = ContainerUtil.newArrayList();
if (myDefinition.isTrait()) {
for (GrField field : myDefinition.getCodeFields()) {
result.add(new GrTraitField(field, myDefinition, PsiSubstitutor.EMPTY));
}
}
GrImplementsClause clause = myDefinition.getImplementsClause();
if (clause == null) return result;
PsiClassType[] types = clause.getReferencedTypes();
List<PsiClassType.ClassResolveResult> traits = getSuperTraitsByCorrectOrder(types);
for (PsiClassType.ClassResolveResult resolveResult : traits) {
GrTypeDefinition trait = (GrTypeDefinition)resolveResult.getElement();
LOG.assertTrue(trait != null);
List<CandidateInfo> traitFields = new TraitProcessor<PsiField>(trait, resolveResult.getSubstitutor()) {
protected void processTrait(@NotNull GrTypeDefinition trait, @NotNull PsiSubstitutor substitutor) {
for (GrField field : trait.getCodeFields()) {
addCandidate(field, substitutor);
}
}
}.getResult();
for (CandidateInfo candidateInfo : traitFields) {
result.add(new GrTraitField(((PsiField)candidateInfo.getElement()), myDefinition, candidateInfo.getSubstitutor()));
}
}
if (myDefinition.isTrait()) {
for (GrField field : myDefinition.getCodeFields()) {
result.add(new GrTraitField(field, myDefinition, PsiSubstitutor.EMPTY));
}
}
return result;
}
@NotNull
private List<GrMethod> getExpandingMethods(@NotNull CandidateInfo candidateInfo) {
PsiMethod method = (PsiMethod)candidateInfo.getElement();
GrLightMethodBuilder implementation = GrTraitMethod.create(method, candidateInfo.getSubstitutor()).setContainingClass(myDefinition);
implementation.getModifierList().removeModifier(GrModifierFlags.ABSTRACT_MASK);
GrReflectedMethod[] reflectedMethods = implementation.getReflectedMethods();
return reflectedMethods.length > 0 ? Arrays.<GrMethod>asList(reflectedMethods) : Collections.<GrMethod>singletonList(implementation);
}
@NotNull
private List<PsiClassType.ClassResolveResult> getSuperTraitsByCorrectOrder(@NotNull PsiClassType[] types) {
List<PsiClassType.ClassResolveResult> traits = ContainerUtil.newArrayList();
for (int i = types.length - 1; i >= 0; i--) {
PsiClassType.ClassResolveResult resolveResult = types[i].resolveGenerics();
PsiClass superClass = resolveResult.getElement();
if (GrTraitUtil.isTrait(superClass)) {
traits.add(resolveResult);
}
}
return traits;
}
}
}
|
robovm/robovm-studio
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/GrTypeDefinitionMembersCache.java
|
Java
|
apache-2.0
| 14,114
|
class Post(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __iter__(self):
return iter(self.__dict__)
|
emitrom/integra-openstack-ui
|
workflows/post/post.py
|
Python
|
apache-2.0
| 151
|
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.andes.server.information.management;
import org.apache.commons.lang.StringUtils;
import org.wso2.andes.kernel.AndesContext;
import org.wso2.andes.kernel.AndesException;
import org.wso2.andes.kernel.AndesSubscription;
import org.wso2.andes.kernel.MessagingEngine;
import org.wso2.andes.management.common.mbeans.SubscriptionManagementInformation;
import org.wso2.andes.server.management.AMQManagedObject;
import javax.management.NotCompliantMBeanException;
import java.util.ArrayList;
import java.util.List;
/**
* Class to Handle data for all subscription related UIs
*/
public class SubscriptionManagementInformationMBean extends AMQManagedObject implements SubscriptionManagementInformation {
public SubscriptionManagementInformationMBean() throws NotCompliantMBeanException {
super(SubscriptionManagementInformation.class, SubscriptionManagementInformation.TYPE);
}
@Override
public String getObjectInstanceName() {
return SubscriptionManagementInformation.TYPE;
}
@Override
public String[] getAllQueueSubscriptions( String isDurable, String isActive) {
try {
List<String> allSubscriptionsForQueues = new ArrayList<String>();
List<String> allQueues = AndesContext.getInstance().getAMQPConstructStore().getQueueNames();
for (String queue : allQueues) {
List<AndesSubscription> subscriptions = AndesContext.getInstance().getSubscriptionStore().getAllSubscribersForDestination(queue, false);
for (AndesSubscription s : subscriptions) {
Long pendingMessageCount = MessagingEngine.getInstance().getMessageCountOfQueue(queue);
if (!isDurable.equals("*") && (Boolean.parseBoolean(isDurable) != s.isDurable())) {
continue;
}
if (!isActive.equals("*") && (Boolean.parseBoolean(isActive) != s.hasExternalSubscriptions())) {
continue;
}
allSubscriptionsForQueues.add(renderSubscriptionForUI(s,pendingMessageCount.intValue()));
}
}
return allSubscriptionsForQueues.toArray(new String[allSubscriptionsForQueues.size()]);
} catch (Exception e) {
throw new RuntimeException("Error in accessing subscription information", e);
}
}
@Override
public String[] getAllTopicSubscriptions(String isDurable, String isActive) {
try {
List<String> allSubscriptionsForTopics = new ArrayList<String>();
List<String> allTopics = AndesContext.getInstance().getSubscriptionStore().getTopics();
for (String topic : allTopics) {
List<AndesSubscription> subscriptions = AndesContext.getInstance().getSubscriptionStore().getAllSubscribersForDestination(topic, true);
for (AndesSubscription s : subscriptions) {
Long pendingMessageCount = MessagingEngine.getInstance().getMessageCountOfQueue(s.getTargetQueue());
if (!isDurable.equals("*") && (Boolean.parseBoolean(isDurable) != s.isDurable())) {
continue;
}
if (!isActive.equals("*") && (Boolean.parseBoolean(isActive) != s.hasExternalSubscriptions())) {
continue;
}
allSubscriptionsForTopics.add(renderSubscriptionForUI(s,pendingMessageCount.intValue()));
}
}
return allSubscriptionsForTopics.toArray(new String[allSubscriptionsForTopics.size()]);
} catch (Exception e) {
throw new RuntimeException("Error in accessing subscription information", e);
}
}
@Override
public int getMessageCount(String subscribedNode, String msgPattern ,String destinationName) {
try {
Long messageCount = MessagingEngine.getInstance().getMessageCountOfQueue(destinationName);
return messageCount.intValue();
}catch (Exception e) {
throw new RuntimeException("Error in retrieving pending message count", e);
}
}
/**
* This method returns the formatted subscription string to be compatible with the UI processor.
* <p/>
* Format of the string : "subscriptionInfo = subscriptionIdentifier |
* subscribedQueueOrTopicName | subscriberQueueBoundExchange | subscriberQueueName |
* isDurable | isActive | numberOfMessagesRemainingForSubscriber | subscriberNodeAddress"
*
* @param subscription AndesSubscription object that is to be translated to UI view
* @param pendingMessageCount Number of pending messages of subscription
* @return String representation of the subscription meta information and pending message count
*/
private static String renderSubscriptionForUI(AndesSubscription subscription,
int pendingMessageCount) throws AndesException {
String nodeId = subscription.getSubscribedNode().split("/")[1];
if (!StringUtils.isBlank(nodeId)) {
String subscriptionIdentifier = "1_" + nodeId + "@" + subscription.getTargetQueue();
//in case of topic whats in v2 is : topicSubscriber.getDestination() + "@" +
// topicSubscriber.boundTopicName; --
return subscriptionIdentifier + "|" + subscription.getTargetQueue() + "|" + subscription
.getTargetQueueBoundExchangeName() +
"|" + subscription.getTargetQueue() + "|" + subscription.isDurable() + "|" +
subscription.hasExternalSubscriptions() +
"|" + pendingMessageCount + "|" + subscription.getSubscribedNode();
} else {
throw new AndesException("Invalid format in Subscriber Node ID : " + subscription
.getSubscribedNode() + ". Delimiter should be /.");
}
}
}
|
pamod/andes
|
modules/andes-core/broker/src/main/java/org/wso2/andes/server/information/management/SubscriptionManagementInformationMBean.java
|
Java
|
apache-2.0
| 6,688
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>zebkit.io - zebkit</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/sunburst.css">
<link rel="stylesheet" href="../assets/css/main.dark.css" id="site_styles">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc" style="padding-top:16px;">
<div class="yui3-g">
<table style="width:auto">
<tr style="background:none">
<td valign="top" align="left" >
<div id="sidebar" class="yui3-u">
<div id="classes" class="sidebox">
<div class="hd">
<h2 class="no-toc">All packages</h2>
</div>
<div class="bd">
<ul>
<li>
<a href="../classes/environment.html">environment</a>
</li>
<li>
<a href="../classes/zebkit.html">zebkit</a>
</li>
<li>
<a href="../classes/zebkit.data.html">zebkit.data</a>
</li>
<li>
<a href="../classes/zebkit.draw.html">zebkit.draw</a>
</li>
<li>
<a href="../classes/zebkit.io.html">zebkit.io</a>
</li>
<li>
<a href="../classes/zebkit.layout.html">zebkit.layout</a>
</li>
<li>
<a href="../classes/zebkit.ui.html">zebkit.ui</a>
</li>
<li>
<a href="../classes/zebkit.ui.date.html">zebkit.ui.date</a>
</li>
<li>
<a href="../classes/zebkit.ui.design.html">zebkit.ui.design</a>
</li>
<li>
<a href="../classes/zebkit.ui.event.html">zebkit.ui.event</a>
</li>
<li>
<a href="../classes/zebkit.ui.grid.html">zebkit.ui.grid</a>
</li>
<li>
<a href="../classes/zebkit.ui.tree.html">zebkit.ui.tree</a>
</li>
<li>
<a href="../classes/zebkit.ui.vk.html">zebkit.ui.vk</a>
</li>
<li>
<a href="../classes/zebkit.ui.web.html">zebkit.ui.web</a>
</li>
<li>
<a href="../classes/zebkit.util.html">zebkit.util</a>
</li>
<li>
<a href="../classes/zebkit.web.html">zebkit.web</a>
</li>
</ul>
</div>
</div>
<div id="classes" class="sidebox">
<div class="hd">
<table border="0" cellpadding="0" cellspecing="0">
<tr>
<td>
<h2 class="no-toc">All classes</h2>
</td>
<td>
<input id="search" style="width:95%;" type=text value=""/>
</td>
</tr>
</table>
</div>
<div class="bd">
<table id="allClasses" style="background:none;" border="0">
<tr class="classNameCell" className="zebkit.Class" name="allClassesItem">
<td>
<a href="../classes/zebkit.Class.html">zebkit.Class</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.Class.zObject" name="allClassesItem">
<td>
<a href="../classes/zebkit.Class.zObject.html">zebkit.Class.zObject</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.DataModel" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.DataModel.html">zebkit.data.DataModel</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.Item" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.Item.html">zebkit.data.Item</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.ListModel" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.ListModel.html">zebkit.data.ListModel</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.Matrix" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.Matrix.html">zebkit.data.Matrix</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.SingleLineTxt" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.SingleLineTxt.html">zebkit.data.SingleLineTxt</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.Text" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.Text.html">zebkit.data.Text</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.TextEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.TextEvent.html">zebkit.data.TextEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.TextModel" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.TextModel.html">zebkit.data.TextModel</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.data.TreeModel" name="allClassesItem">
<td>
<a href="../classes/zebkit.data.TreeModel.html">zebkit.data.TreeModel</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.DoIt" name="allClassesItem">
<td>
<a href="../classes/zebkit.DoIt.html">zebkit.DoIt</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.ArrowView" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.ArrowView.html">zebkit.draw.ArrowView</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.BaseTextRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.BaseTextRender.html">zebkit.draw.BaseTextRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.BaseViewProvider" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.BaseViewProvider.html">zebkit.draw.BaseViewProvider</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Border" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Border.html">zebkit.draw.Border</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.CheckboxView" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.CheckboxView.html">zebkit.draw.CheckboxView</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.CompositeView" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.CompositeView.html">zebkit.draw.CompositeView</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.CutStringRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.CutStringRender.html">zebkit.draw.CutStringRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.DecoratedTextRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.DecoratedTextRender.html">zebkit.draw.DecoratedTextRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Dotted" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Dotted.html">zebkit.draw.Dotted</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Etched" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Etched.html">zebkit.draw.Etched</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.FunctionRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.FunctionRender.html">zebkit.draw.FunctionRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Gradient" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Gradient.html">zebkit.draw.Gradient</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Line" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Line.html">zebkit.draw.Line</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.PasswordText" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.PasswordText.html">zebkit.draw.PasswordText</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Pattern" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Pattern.html">zebkit.draw.Pattern</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.PentahedronShape" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.PentahedronShape.html">zebkit.draw.PentahedronShape</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Picture" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Picture.html">zebkit.draw.Picture</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Radial" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Radial.html">zebkit.draw.Radial</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.RadioView" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.RadioView.html">zebkit.draw.RadioView</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Raised" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Raised.html">zebkit.draw.Raised</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Render" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Render.html">zebkit.draw.Render</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.rgb" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.rgb.html">zebkit.draw.rgb</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.RoundBorder" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.RoundBorder.html">zebkit.draw.RoundBorder</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Shape" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Shape.html">zebkit.draw.Shape</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.StringRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.StringRender.html">zebkit.draw.StringRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.Sunken" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.Sunken.html">zebkit.draw.Sunken</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.TextRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.TextRender.html">zebkit.draw.TextRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.ThumbView" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.ThumbView.html">zebkit.draw.ThumbView</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.TitledBorder" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.TitledBorder.html">zebkit.draw.TitledBorder</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.ToggleView" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.ToggleView.html">zebkit.draw.ToggleView</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.TriangleShape" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.TriangleShape.html">zebkit.draw.TriangleShape</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.View" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.View.html">zebkit.draw.View</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.ViewSet" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.ViewSet.html">zebkit.draw.ViewSet</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.draw.WrappedTextRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.draw.WrappedTextRender.html">zebkit.draw.WrappedTextRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.Dummy" name="allClassesItem">
<td>
<a href="../classes/zebkit.Dummy.html">zebkit.Dummy</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.Event" name="allClassesItem">
<td>
<a href="../classes/zebkit.Event.html">zebkit.Event</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.EventProducer" name="allClassesItem">
<td>
<a href="../classes/zebkit.EventProducer.html">zebkit.EventProducer</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.Font" name="allClassesItem">
<td>
<a href="../classes/zebkit.Font.html">zebkit.Font</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.Interface" name="allClassesItem">
<td>
<a href="../classes/zebkit.Interface.html">zebkit.Interface</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.io.HTTP" name="allClassesItem">
<td>
<a href="../classes/zebkit.io.HTTP.html">zebkit.io.HTTP</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.io.JRPC" name="allClassesItem">
<td>
<a href="../classes/zebkit.io.JRPC.html">zebkit.io.JRPC</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.io.Service" name="allClassesItem">
<td>
<a href="../classes/zebkit.io.Service.html">zebkit.io.Service</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.io.XRPC" name="allClassesItem">
<td>
<a href="../classes/zebkit.io.XRPC.html">zebkit.io.XRPC</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.BorderLayout" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.BorderLayout.html">zebkit.layout.BorderLayout</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.Constraints" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.Constraints.html">zebkit.layout.Constraints</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.FlowLayout" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.FlowLayout.html">zebkit.layout.FlowLayout</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.GridLayout" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.GridLayout.html">zebkit.layout.GridLayout</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.Layout" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.Layout.html">zebkit.layout.Layout</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.Layoutable" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.Layoutable.html">zebkit.layout.Layoutable</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.ListLayout" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.ListLayout.html">zebkit.layout.ListLayout</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.PercentLayout" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.PercentLayout.html">zebkit.layout.PercentLayout</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.RasterLayout" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.RasterLayout.html">zebkit.layout.RasterLayout</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.layout.StackLayout" name="allClassesItem">
<td>
<a href="../classes/zebkit.layout.StackLayout.html">zebkit.layout.StackLayout</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.Listeners" name="allClassesItem">
<td>
<a href="../classes/zebkit.Listeners.html">zebkit.Listeners</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.Package" name="allClassesItem">
<td>
<a href="../classes/zebkit.Package.html">zebkit.Package</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.PathSearch" name="allClassesItem">
<td>
<a href="../classes/zebkit.PathSearch.html">zebkit.PathSearch</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.ArrowButton" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.ArrowButton.html">zebkit.ui.ArrowButton</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.BaseList" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.BaseList.html">zebkit.ui.BaseList</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.BoldLabel" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.BoldLabel.html">zebkit.ui.BoldLabel</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.BorderPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.BorderPan.html">zebkit.ui.BorderPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Button" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Button.html">zebkit.ui.Button</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Checkbox" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Checkbox.html">zebkit.ui.Checkbox</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Checkbox.Box" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Checkbox.Box.html">zebkit.ui.Checkbox.Box</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.CollapsiblePan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.CollapsiblePan.html">zebkit.ui.CollapsiblePan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Combo" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Combo.html">zebkit.ui.Combo</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Combo.ComboPadPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Combo.ComboPadPan.html">zebkit.ui.Combo.ComboPadPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Combo.ContentPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Combo.ContentPan.html">zebkit.ui.Combo.ContentPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Combo.EditableContentPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Combo.EditableContentPan.html">zebkit.ui.Combo.EditableContentPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Combo.ReadonlyContentPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Combo.ReadonlyContentPan.html">zebkit.ui.Combo.ReadonlyContentPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.CompList" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.CompList.html">zebkit.ui.CompList</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.CompRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.CompRender.html">zebkit.ui.CompRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Cursor" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Cursor.html">zebkit.ui.Cursor</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.date.Calendar" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.date.Calendar.html">zebkit.ui.date.Calendar</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.date.Calendar.MonthsCombo" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.date.Calendar.MonthsCombo.html">zebkit.ui.date.Calendar.MonthsCombo</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.date.DateInputField" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.date.DateInputField.html">zebkit.ui.date.DateInputField</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.date.DateRangeInput" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.date.DateRangeInput.html">zebkit.ui.date.DateRangeInput</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.date.DateTextField" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.date.DateTextField.html">zebkit.ui.date.DateTextField</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.date.MonthDaysGrid" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.date.MonthDaysGrid.html">zebkit.ui.date.MonthDaysGrid</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.date.MonthDaysGrid.DayPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.date.MonthDaysGrid.DayPan.html">zebkit.ui.date.MonthDaysGrid.DayPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.date.PopupCalendarMix" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.date.PopupCalendarMix.html">zebkit.ui.date.PopupCalendarMix</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.design.FormTreeModel" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.design.FormTreeModel.html">zebkit.ui.design.FormTreeModel</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.design.ShaperBorder" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.design.ShaperBorder.html">zebkit.ui.design.ShaperBorder</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.design.ShaperPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.design.ShaperPan.html">zebkit.ui.design.ShaperPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.DrawFocusMarker" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.DrawFocusMarker.html">zebkit.ui.DrawFocusMarker</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.Clipboard" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.Clipboard.html">zebkit.ui.event.Clipboard</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.CompEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.CompEvent.html">zebkit.ui.event.CompEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.CursorManager" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.CursorManager.html">zebkit.ui.event.CursorManager</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.EventManager" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.EventManager.html">zebkit.ui.event.EventManager</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.FocusEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.FocusEvent.html">zebkit.ui.event.FocusEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.FocusManager" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.FocusManager.html">zebkit.ui.event.FocusManager</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.KeyEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.KeyEvent.html">zebkit.ui.event.KeyEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.Manager" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.Manager.html">zebkit.ui.event.Manager</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.MenuEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.MenuEvent.html">zebkit.ui.event.MenuEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.PointerEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.PointerEvent.html">zebkit.ui.event.PointerEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.ShortcutEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.ShortcutEvent.html">zebkit.ui.event.ShortcutEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.ShortcutManager" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.ShortcutManager.html">zebkit.ui.event.ShortcutManager</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.TrackInputEventState" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.TrackInputEventState.html">zebkit.ui.event.TrackInputEventState</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.event.WinEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.event.WinEvent.html">zebkit.ui.event.WinEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.EvStatePan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.EvStatePan.html">zebkit.ui.EvStatePan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.FireEventRepeatedly" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.FireEventRepeatedly.html">zebkit.ui.FireEventRepeatedly</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.BaseCaption" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.BaseCaption.html">zebkit.ui.grid.BaseCaption</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.CaptionViewProvider" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.CaptionViewProvider.html">zebkit.ui.grid.CaptionViewProvider</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.CellSelectMode" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.CellSelectMode.html">zebkit.ui.grid.CellSelectMode</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.CellsVisibility" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.CellsVisibility.html">zebkit.ui.grid.CellsVisibility</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.ColSelectMode" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.ColSelectMode.html">zebkit.ui.grid.ColSelectMode</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.CompGridCaption" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.CompGridCaption.html">zebkit.ui.grid.CompGridCaption</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.CompGridCaption.TitlePan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.CompGridCaption.TitlePan.html">zebkit.ui.grid.CompGridCaption.TitlePan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.DefEditors" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.DefEditors.html">zebkit.ui.grid.DefEditors</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.DefViews" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.DefViews.html">zebkit.ui.grid.DefViews</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.Grid" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.Grid.html">zebkit.ui.grid.Grid</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.GridCaption" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.GridCaption.html">zebkit.ui.grid.GridCaption</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.GridStretchPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.GridStretchPan.html">zebkit.ui.grid.GridStretchPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.LeftCompGridCaption" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.LeftCompGridCaption.html">zebkit.ui.grid.LeftCompGridCaption</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.LeftGridCaption" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.LeftGridCaption.html">zebkit.ui.grid.LeftGridCaption</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.Metrics" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.Metrics.html">zebkit.ui.grid.Metrics</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.RowSelectMode" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.RowSelectMode.html">zebkit.ui.grid.RowSelectMode</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.grid.StrippedRows" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.grid.StrippedRows.html">zebkit.ui.grid.StrippedRows</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Group" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Group.html">zebkit.ui.Group</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.HostDecorativeViews" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.HostDecorativeViews.html">zebkit.ui.HostDecorativeViews</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.ImageLabel" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.ImageLabel.html">zebkit.ui.ImageLabel</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.ImagePan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.ImagePan.html">zebkit.ui.ImagePan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Label" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Label.html">zebkit.ui.Label</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Line" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Line.html">zebkit.ui.Line</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.LinearRulerPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.LinearRulerPan.html">zebkit.ui.LinearRulerPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Link" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Link.html">zebkit.ui.Link</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.List" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.List.html">zebkit.ui.List</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.List.ViewProvider" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.List.ViewProvider.html">zebkit.ui.List.ViewProvider</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Menu" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Menu.html">zebkit.ui.Menu</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Menubar" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Menubar.html">zebkit.ui.Menubar</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.MenuItem" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.MenuItem.html">zebkit.ui.MenuItem</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.MobileScrollMan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.MobileScrollMan.html">zebkit.ui.MobileScrollMan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Panel" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Panel.html">zebkit.ui.Panel</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.PassTextField" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.PassTextField.html">zebkit.ui.PassTextField</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.PointRulerPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.PointRulerPan.html">zebkit.ui.PointRulerPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.PointRulerPan.DeltaPointsGenerator" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.PointRulerPan.DeltaPointsGenerator.html">zebkit.ui.PointRulerPan.DeltaPointsGenerator</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.PointRulerPan.PointsGenerator" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.PointRulerPan.PointsGenerator.html">zebkit.ui.PointRulerPan.PointsGenerator</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.PopupLayer" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.PopupLayer.html">zebkit.ui.PopupLayer</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.PopupLayerMix" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.PopupLayerMix.html">zebkit.ui.PopupLayerMix</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Progress" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Progress.html">zebkit.ui.Progress</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Radiobox" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Radiobox.html">zebkit.ui.Radiobox</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.RootLayer" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.RootLayer.html">zebkit.ui.RootLayer</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.RootLayerMix" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.RootLayerMix.html">zebkit.ui.RootLayerMix</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.RulerPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.RulerPan.html">zebkit.ui.RulerPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.RulerPan.NumLabels" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.RulerPan.NumLabels.html">zebkit.ui.RulerPan.NumLabels</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.RulerPan.PercentageLabels" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.RulerPan.PercentageLabels.html">zebkit.ui.RulerPan.PercentageLabels</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Scroll" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Scroll.html">zebkit.ui.Scroll</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.ScrollManager" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.ScrollManager.html">zebkit.ui.ScrollManager</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.ScrollPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.ScrollPan.html">zebkit.ui.ScrollPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Slider" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Slider.html">zebkit.ui.Slider</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.SplitPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.SplitPan.html">zebkit.ui.SplitPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.StackPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.StackPan.html">zebkit.ui.StackPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.StatePan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.StatePan.html">zebkit.ui.StatePan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.StatusBarPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.StatusBarPan.html">zebkit.ui.StatusBarPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Tabs" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Tabs.html">zebkit.ui.Tabs</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Tabs.TabView" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Tabs.TabView.html">zebkit.ui.Tabs.TabView</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.TextArea" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.TextArea.html">zebkit.ui.TextArea</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.TextField" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.TextField.html">zebkit.ui.TextField</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.TextField.HintRender" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.TextField.HintRender.html">zebkit.ui.TextField.HintRender</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Toolbar" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Toolbar.html">zebkit.ui.Toolbar</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Tooltip" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Tooltip.html">zebkit.ui.Tooltip</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.TooltipManager" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.TooltipManager.html">zebkit.ui.TooltipManager</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.tree.BaseTree" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.tree.BaseTree.html">zebkit.ui.tree.BaseTree</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.tree.CompTree" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.tree.CompTree.html">zebkit.ui.tree.CompTree</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.tree.DefEditors" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.tree.DefEditors.html">zebkit.ui.tree.DefEditors</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.tree.DefViews" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.tree.DefViews.html">zebkit.ui.tree.DefViews</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.tree.Tree" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.tree.Tree.html">zebkit.ui.tree.Tree</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.ViewPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.ViewPan.html">zebkit.ui.ViewPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.CursorManager" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.CursorManager.html">zebkit.ui.web.CursorManager</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlCanvas" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlCanvas.html">zebkit.ui.web.HtmlCanvas</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlElement" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlElement.html">zebkit.ui.web.HtmlElement</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlFocusableElement" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlFocusableElement.html">zebkit.ui.web.HtmlFocusableElement</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlLayer" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlLayer.html">zebkit.ui.web.HtmlLayer</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlLink" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlLink.html">zebkit.ui.web.HtmlLink</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlScrollContent" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlScrollContent.html">zebkit.ui.web.HtmlScrollContent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlTextArea" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlTextArea.html">zebkit.ui.web.HtmlTextArea</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlTextField" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlTextField.html">zebkit.ui.web.HtmlTextField</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlTextInput" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlTextInput.html">zebkit.ui.web.HtmlTextInput</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.HtmlWindow" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.HtmlWindow.html">zebkit.ui.web.HtmlWindow</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.PopupLayer" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.PopupLayer.html">zebkit.ui.web.PopupLayer</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.RootLayer" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.RootLayer.html">zebkit.ui.web.RootLayer</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.VideoPan" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.VideoPan.html">zebkit.ui.web.VideoPan</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.web.WinLayer" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.web.WinLayer.html">zebkit.ui.web.WinLayer</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.Window" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.Window.html">zebkit.ui.Window</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.WinLayer" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.WinLayer.html">zebkit.ui.WinLayer</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.ui.zCanvas" name="allClassesItem">
<td>
<a href="../classes/zebkit.ui.zCanvas.html">zebkit.ui.zCanvas</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.URI" name="allClassesItem">
<td>
<a href="../classes/zebkit.URI.html">zebkit.URI</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.util.Position" name="allClassesItem">
<td>
<a href="../classes/zebkit.util.Position.html">zebkit.util.Position</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.util.Position.Metric" name="allClassesItem">
<td>
<a href="../classes/zebkit.util.Position.Metric.html">zebkit.util.Position.Metric</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.util.SingleColPosition" name="allClassesItem">
<td>
<a href="../classes/zebkit.util.SingleColPosition.html">zebkit.util.SingleColPosition</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.util.TasksSet" name="allClassesItem">
<td>
<a href="../classes/zebkit.util.TasksSet.html">zebkit.util.TasksSet</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.util.TasksSet.Task" name="allClassesItem">
<td>
<a href="../classes/zebkit.util.TasksSet.Task.html">zebkit.util.TasksSet.Task</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.web.Clipboard" name="allClassesItem">
<td>
<a href="../classes/zebkit.web.Clipboard.html">zebkit.web.Clipboard</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.web.KeyEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.web.KeyEvent.html">zebkit.web.KeyEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.web.KeyEventUninfier" name="allClassesItem">
<td>
<a href="../classes/zebkit.web.KeyEventUninfier.html">zebkit.web.KeyEventUninfier</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.web.MouseWheelSupport" name="allClassesItem">
<td>
<a href="../classes/zebkit.web.MouseWheelSupport.html">zebkit.web.MouseWheelSupport</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.web.PointerEvent" name="allClassesItem">
<td>
<a href="../classes/zebkit.web.PointerEvent.html">zebkit.web.PointerEvent</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.web.PointerEventUnifier" name="allClassesItem">
<td>
<a href="../classes/zebkit.web.PointerEventUnifier.html">zebkit.web.PointerEventUnifier</a>
</td>
</tr>
<tr class="classNameCell" className="zebkit.Zson" name="allClassesItem">
<td>
<a href="../classes/zebkit.Zson.html">zebkit.Zson</a>
</td>
</tr>
</table>
</div>
</div>
<script>
var root = document.getElementById("allClasses");
document.getElementById("search").addEventListener('input', function(e) {
var items = document.getElementsByName("allClassesItem"),
value = this.value.trim().toLowerCase();
for(var i = 0; i < items.length; i++) {
var item = items[i];
if (value.length < 3 || item.getAttribute("className").toLowerCase().indexOf(value) >= 0) {
item.style.display = "block";
} else {
item.style.display = "none";
};
}
});
</script> </div>
</td>
<td valign="top" align="left">
<div id="main" class="yui3-u">
<div class="content">
<div class="hd">
<table width="100%">
<tr>
<td>
<strong>
Package
</strong>
<strong class="name"">
zebkit.io
</strong>
</td>
<tr>
</table>
</div>
<br/>
<div class="intro">
<p>The module provides number of classes to help to communicate with remote services and servers by HTTP,
JSON-RPC, XML-RPC protocols.</p>
<pre class="code prettyprint"><code> // shortcut method to perform HTTP GET request
zebkit.io.GET("http://test.com").then(function(req) {
// handle request
req.responseText
...
}).catch(function(exception) {
// handle error
});</code></pre>
</div>
<br/>
<br/>
<div id="classdocs">
<ul>
<li>
<a href="#package">Package classes and interfaces</a>
</li>
<li>
<a href="#methods">
Package methods
</a>
</li>
</ul>
<div>
<div id="package">
<br/><br/>
<strong>Classes: </strong>
<ul style="column-count:2;column-gap:20px; list-style:none;">
<li>
<a href="zebkit.io.HTTP.html">
zebkit.io.HTTP
</a>
</li>
<li>
<a href="zebkit.io.JRPC.html">
zebkit.io.JRPC
</a>
</li>
<li>
<a href="zebkit.io.Service.html">
zebkit.io.Service
</a>
</li>
<li>
<a href="zebkit.io.XRPC.html">
zebkit.io.XRPC
</a>
</li>
</ul>
</div>
<div id="methods">
<div class="bd">
<br/>
<table border="0" style="width:auto;" cellpadding="2">
<tr style="background:none;">
<td>
<strong> public </strong>
</td>
<td>
<span class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</span>
</td>
<td>
<b>
<a class="name" href="#methods_b64decode">b64decode (input)</a>
</b>
</td>
</tr>
<tr style="background:none;">
<td>
<strong> public </strong>
</td>
<td>
<span class="type">
void
</span>
</td>
<td>
<b>
<a class="name" href="#methods_b64encode">b64encode (input)</a>
</b>
</td>
</tr>
<tr style="background:none;">
<td>
<strong> public </strong>
</td>
<td>
<span class="type">
<<a href="../classes/zebkit.DoIt.html" class="crosslink">zebkit.DoIt</a>>
</span>
</td>
<td>
<b>
<a class="name" href="#methods_GET">GET (url, [parameters])</a>
</b>
</td>
</tr>
<tr style="background:none;">
<td>
<strong> public </strong>
</td>
<td>
<span class="type">
<<a href="../classes/zebkit.DoIt.html" class="crosslink">zebkit.DoIt</a>>
</span>
</td>
<td>
<b>
<a class="name" href="#methods_POST">POST (url, [data])</a>
</b>
</td>
</tr>
<tr style="background:none;">
<td>
<strong> public </strong>
</td>
<td>
<span class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</span>
</td>
<td>
<b>
<a class="name" href="#methods_UID">UID ([size])</a>
</b>
</td>
</tr>
</table>
<br/>
</div>
<table>
<tr>
<td><a name="methods_b64decode"></a>
<div class="method item">
<span class="foundat">
</span>
<strong> public </strong>
<span class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</span>
<strong class="name"><code>b64decode</code> (<code>input</code>)</strong>
<br/>
<p>Decode the base64 encoded string</p>
<br/>
<strong>Parameters:</strong>
<ul class="params">
<li>
<span class="name"><code>input</code></span>
<strong class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</strong>
<p>base64 encoded string</p>
</li>
</ul>
<br/>
<div class="returns">
<strong>
Returns:
</strong>
<span class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</span>
<p>a string</p>
</div>
</div>
</td>
</tr>
<tr>
<td><a name="methods_b64encode"></a>
<div class="method item">
<span class="foundat">
</span>
<strong> public </strong>
<span class="type">
void
</span>
<strong class="name"><code>b64encode</code> (<code>input</code>)</strong>
<br/>
<p>Encode the given string into base64</p>
<br/>
<strong>Parameters:</strong>
<ul class="params">
<li>
<span class="name"><code>input</code></span>
<strong class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</strong>
<p>a string to be encoded</p>
</li>
</ul>
</div>
</td>
</tr>
<tr>
<td><a name="methods_GET"></a>
<div class="method item">
<span class="foundat">
</span>
<strong> public </strong>
<span class="type">
<<a href="../classes/zebkit.DoIt.html" class="crosslink">zebkit.DoIt</a>>
</span>
<strong class="name"><code>GET</code> (<code>url, [parameters]</code>)</strong>
<br/>
<p>Shortcut method to perform HTTP GET requests.</p>
<pre class="code prettyprint"><code> zebkit.io.GET("http://test.com").then(function(request) {
// handle result ...
}).catch(function(e) {
// handle error ...
});
var res = zebkit.io.GET("http://test.com", {
param1 : "var1",
param1 : "var2",
param1 : "var3"
}).then(function(req) {
// handle result ...
});</code></pre>
<br/>
<strong>Parameters:</strong>
<ul class="params">
<li>
<span class="name"><code>url</code></span>
<strong class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="crosslink external" target="_blank">Object</a>>
</strong>
<p>an URL</p>
</li>
<li>
<span class="name"><code>[parameters]</code></span>
<strong class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="crosslink external" target="_blank">Object</a>>
</strong>
<p>a dictionary of query parameters</p>
</li>
</ul>
<br/>
<div class="returns">
<strong>
Returns:
</strong>
<span class="type">
<<a href="../classes/zebkit.DoIt.html" class="crosslink">zebkit.DoIt</a>>
</span>
<p>an object to handle result</p>
</div>
</div>
</td>
</tr>
<tr>
<td><a name="methods_POST"></a>
<div class="method item">
<span class="foundat">
</span>
<strong> public </strong>
<span class="type">
<<a href="../classes/zebkit.DoIt.html" class="crosslink">zebkit.DoIt</a>>
</span>
<strong class="name"><code>POST</code> (<code>url, [data]</code>)</strong>
<br/>
<p>Shortcut method to perform HTTP POST requests.</p>
<pre class="code prettyprint"><code> zebkit.io.POST("http://test.com", null).then(function(request) {
// handle result
...
}).catch(function(e) {
// handle error ...
});
var res = zebkit.io.POST("http://test.com", {
param1 : "var1",
param1 : "var2",
param1 : "var3"
}).then(function(request) {
// handle result
...
});
zebkit.io.POST("http://test.com", "request").then(function(request) {
// handle error
...
});</code></pre>
<br/>
<strong>Parameters:</strong>
<ul class="params">
<li>
<span class="name"><code>url</code></span>
<strong class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</strong>
<p>an URL</p>
</li>
<li>
<span class="name"><code>[data]</code></span>
<strong class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="crosslink external" target="_blank">Object</a>>
</strong>
<p>a data or form data parameters</p>
</li>
</ul>
<br/>
<div class="returns">
<strong>
Returns:
</strong>
<span class="type">
<<a href="../classes/zebkit.DoIt.html" class="crosslink">zebkit.DoIt</a>>
</span>
<p>an object to handle result</p>
</div>
</div>
</td>
</tr>
<tr>
<td><a name="methods_UID"></a>
<div class="method item">
<span class="foundat">
</span>
<strong> public </strong>
<span class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</span>
<strong class="name"><code>UID</code> (<code>[size]</code>)</strong>
<br/>
<p>Generate UUID of the given length</p>
<br/>
<strong>Parameters:</strong>
<ul class="params">
<li>
<span class="name"><code>[size]</code></span>
<strong class="type">
<Integer>
</strong>
<p>the generated UUID length. The default size is 16 characters.</p>
</li>
</ul>
<br/>
<div class="returns">
<strong>
Returns:
</strong>
<span class="type">
<<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a>>
</span>
<p>an UUID</p>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/js/tabs.js"></script>
</body>
</html>
|
barmalei/zebkit
|
apidoc/dark/classes/zebkit.io.html
|
HTML
|
apache-2.0
| 105,825
|
/**
* 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.camel.component.kafka.springboot;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.camel.CamelContext;
import org.apache.camel.component.kafka.KafkaComponent;
import org.apache.camel.util.IntrospectionSupport;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@Configuration
@ConditionalOnBean(type = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@Conditional(KafkaComponentAutoConfiguration.Condition.class)
@AutoConfigureAfter(name = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@EnableConfigurationProperties(KafkaComponentConfiguration.class)
public class KafkaComponentAutoConfiguration {
@Lazy
@Bean(name = "kafka-component")
@ConditionalOnClass(CamelContext.class)
@ConditionalOnMissingBean(KafkaComponent.class)
public KafkaComponent configureKafkaComponent(CamelContext camelContext,
KafkaComponentConfiguration configuration) throws Exception {
KafkaComponent component = new KafkaComponent();
component.setCamelContext(camelContext);
Map<String, Object> parameters = new HashMap<>();
IntrospectionSupport.getProperties(configuration, parameters, null,
false);
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
Object value = entry.getValue();
Class<?> paramClass = value.getClass();
if (paramClass.getName().endsWith("NestedConfiguration")) {
Class nestedClass = null;
try {
nestedClass = (Class) paramClass.getDeclaredField(
"CAMEL_NESTED_CLASS").get(null);
HashMap<String, Object> nestedParameters = new HashMap<>();
IntrospectionSupport.getProperties(value, nestedParameters,
null, false);
Object nestedProperty = nestedClass.newInstance();
IntrospectionSupport.setProperties(camelContext,
camelContext.getTypeConverter(), nestedProperty,
nestedParameters);
entry.setValue(nestedProperty);
} catch (NoSuchFieldException e) {
}
}
}
IntrospectionSupport.setProperties(camelContext,
camelContext.getTypeConverter(), component, parameters);
return component;
}
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
public static class Condition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(
ConditionContext conditionContext,
AnnotatedTypeMetadata annotatedTypeMetadata) {
boolean groupEnabled = isEnabled(conditionContext,
"camel.component.", true);
ConditionMessage.Builder message = ConditionMessage
.forCondition("camel.component.kafka");
if (isEnabled(conditionContext, "camel.component.kafka.",
groupEnabled)) {
return ConditionOutcome.match(message.because("enabled"));
}
return ConditionOutcome.noMatch(message.because("not enabled"));
}
private boolean isEnabled(
org.springframework.context.annotation.ConditionContext context,
java.lang.String prefix, boolean defaultValue) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), prefix);
return resolver.getProperty("enabled", Boolean.class, defaultValue);
}
}
}
|
acartapanis/camel
|
platforms/spring-boot/components-starter/camel-kafka-starter/src/main/java/org/apache/camel/component/kafka/springboot/KafkaComponentAutoConfiguration.java
|
Java
|
apache-2.0
| 5,636
|
import { Reflection, Type } from "../models";
import type { Serializer } from "./serializer";
import type { ModelToObject } from "./schema";
/**
* Represents Serializer plugin component.
*
* Like {@link Converter} plugins each {@link Serializer} plugin defines a predicate that instructs if an
* object can be serialized by it, this is done dynamically at runtime via a `supports` method.
*
* Additionally, each {@link Serializer} plugin must define a predicate that instructs the group
* it belongs to.
*
* Serializers are grouped to improve performance when finding serializers that apply to a node,
* this makes it possible to skip the `supports` calls for `Type`s when searching for a
* `Reflection` and vise versa.
*/
export abstract class SerializerComponent<T> {
/**
* The priority this serializer should be executed with.
* A higher priority means the {@link Serializer} will be applied earlier.
*/
static PRIORITY = 0;
constructor(owner: Serializer) {
this.owner = owner;
}
/**
* Set when the SerializerComponent is added to the serializer.
*/
protected owner: Serializer;
/**
* A high-level predicate filtering which group this serializer belongs to.
* This is a high-level filter before the {@link SerializerComponent.supports} predicate filter.
*
* For example, use the {@link Reflection} class class to group all reflection based serializers:
* ```typescript
* class ReflectionSerializer {
* serializeGroup(instance) { return instance instanceof Reflection }
* }
* ```
*
* Use the {@link Type} class to group all type based serializers:
* ```typescript
* class TypeSerializer {
* serializeGroup(instance) { return instance instanceof Type }
* }
* ```
*/
abstract serializeGroup(instance: unknown): boolean;
/**
* The priority this serializer should be executed with.
* A higher priority means the {@link Serializer} will be applied earlier.
*/
get priority(): number {
return (
(this.constructor as typeof SerializerComponent)["PRIORITY"] ||
SerializerComponent.PRIORITY
);
}
abstract supports(item: unknown): boolean;
abstract toObject(item: T, obj?: object): Partial<ModelToObject<T>>;
}
export abstract class ReflectionSerializerComponent<
T extends Reflection
> extends SerializerComponent<T> {
/**
* Filter for instances of {@link Reflection}
*/
serializeGroup(instance: unknown): boolean {
return instance instanceof Reflection;
}
}
export abstract class TypeSerializerComponent<
T extends Type
> extends SerializerComponent<T> {
/**
* Filter for instances of {@link Type}
*/
serializeGroup(instance: unknown): boolean {
return instance instanceof Type;
}
}
|
TypeStrong/typedoc
|
src/lib/serialization/components.ts
|
TypeScript
|
apache-2.0
| 2,894
|
/*
* Copyright (C) 2012-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package dotty.runtime.function;
@FunctionalInterface
public interface JFunction2$mcDDI$sp extends JFunction2<Object, Object, Object> {
abstract double apply$mcDDI$sp(double v1, int v2);
default Object apply(Object v1, Object v2) { return (Double) apply$mcDDI$sp(scala.runtime.BoxesRunTime.unboxToDouble(v1), scala.runtime.BoxesRunTime.unboxToInt(v2)); }
}
|
som-snytt/dotty
|
library/src/dotty/runtime/function/JFunction2$mcDDI$sp.java
|
Java
|
apache-2.0
| 442
|
package tv.floe.metronome.io.records;
/**
* 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.
*/
import java.util.List;
import java.util.Map;
import java.util.Set;
//import org.apache.mahout.classifier.sgd.RecordFactory;
import org.apache.mahout.math.Vector;
/**
* Base interface for Knitting Boar's vectorization system
*
* @author jpatterson
*
*/
public interface RecordFactory {
public static String TWENTYNEWSGROUPS_RECORDFACTORY = "com.cloudera.knittingboar.records.TwentyNewsgroupsRecordFactory";
public static String RCV1_RECORDFACTORY = "com.cloudera.knittingboar.records.RCV1RecordFactory";
public static String CSV_RECORDFACTORY = "com.cloudera.knittingboar.records.CSVRecordFactory";
// we're evolving this interface, we'll settle on something soon
public int processLine(String line, Vector featureVector) throws Exception;
public double processLineAlt(String line, Vector v) throws Exception;
public void vectorizeLine(String line, Vector v_in, Vector v_out) throws Exception;
public String GetClassnameByID(int id);
// Map<String, Set<Integer>> getTraceDictionary();
// RecordFactory includeBiasTerm(boolean useBias);
public List<String> getTargetCategories();
public int getFeatureVectorSize();
// void firstLine(String line);
public void parseSchema();
public int getInputVectorSize();
// in the case of neural networks, else: size == 1
public int getOutputVectorSize();
}
|
jpatanooga/Metronome
|
src/main/java/tv/floe/metronome/io/records/RecordFactory.java
|
Java
|
apache-2.0
| 2,223
|
'use strict';
const expect = require('chai').use(require('dirty-chai')).expect;
const Promise = require('bluebird');
const testHelpers = require('../test-helpers');
describe('PasswordResetController', () => {
let agent;
beforeEach(async () => {
agent = await testHelpers.getAgent();
});
describe('requesting password resets', () => {
let username, recipientEmailAddress;
before(async () => {
username = 'passwordForgetter';
recipientEmailAddress = 'passwordForgetter@example.com';
const tempAgent = await testHelpers.getAgent();
const res = await tempAgent.post('/api/v1/auth/local/register').send({
name: username,
password: 'Obliviate!',
email: recipientEmailAddress
});
expect(res.statusCode).to.equal(200);
});
describe('when the requested account exists', () => {
it('returns a 202 response and sends an password reset email to the user', async () => {
const res = await agent.post(`/api/v1/user/${username}/passwordReset`);
expect(res.statusCode).to.equal(202);
expect(res.body).to.eql({});
const email = await new Promise(resolve => testHelpers.emailEmitter.once('email', resolve));
expect(email.sender).to.equal('no-reply@example.org');
expect(email.receivers).to.eql({[recipientEmailAddress]: true});
expect(email.subject).to.equal('[Porybox] Your password reset request');
expect(email.body).to.include(username);
const userRequests = await sails.models.passwordreset.find({owner: username});
expect(userRequests).to.have.lengthOf(1);
expect(email.body).to.include(userRequests[0].id);
});
});
describe('when the requested account does not exist', () => {
it('returns a 404 error', async () => {
// (the existence of a given account is not secret on porybox, so this does not cause an information leak)
const res = await agent.post(`/api/v1/user/${username}aaaaaa/passwordReset`);
expect(res.statusCode).to.equal(404);
});
});
});
describe('verifying password resets', () => {
let username, token, recipientEmailAddress, originalExpirationTime;
before(async () => {
originalExpirationTime = sails.services.constants.PASSWORD_RESET_EXPIRATION_TIME;
sails.services.constants.PASSWORD_RESET_EXPIRATION_TIME = 2000;
username = 'passwordForgetter2';
recipientEmailAddress = 'passwordForgetter2@example.com';
const tempAgent = await testHelpers.getAgent();
const res = await tempAgent.post('/api/v1/auth/local/register').send({
name: username,
password: 'Obliviate!',
email: recipientEmailAddress
});
expect(res.statusCode).to.equal(200);
});
beforeEach(async () => {
const res = await agent.post(`/api/v1/user/${username}/passwordReset`);
expect(res.statusCode).to.equal(202);
await Promise.delay(200);
token = (await sails.models.passwordreset.findOne({owner: username})).id;
});
it('returns a 200 response if the token is valid', async () => {
const res = await agent.get(`/api/v1/passwordReset/${token}`);
expect(res.statusCode).to.equal(200);
expect(res.body).to.eql({});
});
it('returns a 404 error if the token is incorrect', async () => {
const res = await agent.get(`/api/v1/passwordReset/${token}aaaaa`);
expect(res.statusCode).to.equal(404);
});
it('returns a 404 error if the token is expired', async () => {
await Promise.delay(sails.services.constants.PASSWORD_RESET_EXPIRATION_TIME);
const res = await agent.get(`/api/v1/passwordReset/${token}`);
expect(res.statusCode).to.equal(404);
});
it('returns a 404 error if the token is already used', async () => {
const res = await agent.del(`/api/v1/passwordReset/${token}`)
.send({newPassword: 'foobarbaz'});
expect(res.statusCode).to.equal(200);
const res2 = await agent.get(`/api/v1/passworeReset/${token}`);
expect(res2.statusCode).to.equal(404);
});
it('returns a 404 error if the token has been superceded by another token', async () => {
const res = await agent.post(`/api/v1/user/${username}/passwordReset`);
expect(res.statusCode).to.equal(202);
const res2 = await agent.get(`/api/v1/passworeReset/${token}`);
expect(res2.statusCode).to.equal(404);
});
after(() => {
sails.services.constants.PASSWORD_RESET_EXPIRATION_TIME = originalExpirationTime;
});
});
describe('activating password resets', () => {
let username, oldPassword, newPassword, token, originalExpirationTime, originalAgent;
before(() => {
originalExpirationTime = sails.services.constants.PASSWORD_RESET_EXPIRATION_TIME;
sails.services.constants.PASSWORD_RESET_EXPIRATION_TIME = 2000;
});
beforeEach(async () => {
username = 'resetter' + require('crypto').randomBytes(4).toString('hex');
oldPassword = 'hunter22'; // this will appear as ******** to anyone who reads the tests, right?
originalAgent = await testHelpers.getAgent();
const res = await originalAgent.post('/api/v1/auth/local/register').send({
name: username,
password: oldPassword,
email: 'testuser1@example.com'
});
expect(res.statusCode).to.equal(200);
newPassword = 'Tr0ub4dor&3';
const res2 = await agent.post(`/api/v1/user/${username}/passwordReset`);
expect(res2.statusCode).to.equal(202);
await Promise.delay(200);
token = (await sails.models.passwordreset.findOne({owner: username})).id;
});
describe('if the token is correct and not expired', () => {
it('should return a 200 status code', async () => {
const res = await agent.del(`/api/v1/passwordReset/${token}`).send({newPassword});
expect(res.statusCode).to.equal(200);
});
afterEach(async () => {
// should authenticate the current session
const res = await agent.get('/api/v1/me');
expect(res.statusCode).to.equal(302);
expect(res.header.location.endsWith(`/user/${username}`)).to.be.true();
});
afterEach(async () => {
// should allow login with the new password
const tempAgent = await testHelpers.getAgent();
const res = await tempAgent.post('/api/v1/auth/local').send({
name: username,
password: newPassword
});
expect(res.statusCode).to.equal(200);
const res2 = await tempAgent.get('/api/v1/me');
expect(res2.statusCode).to.equal(302);
expect(res2.header.location.endsWith(`/user/${username}`)).to.be.true();
});
afterEach(async () => {
// should not allow login with the old password
const tempAgent = await testHelpers.getAgent();
const res = await tempAgent.post('/api/v1/auth/local').send({
name: username,
password: oldPassword
});
expect(res.statusCode).to.equal(401);
const res2 = await tempAgent.get('/api/v1/me');
expect(res2.statusCode).to.equal(403);
});
afterEach(async () => {
// should not allow the token to be used again
const res = await agent.del(`/api/v1/passwordReset/${token}`).send({newPassword});
expect(res.statusCode).to.equal(404);
});
afterEach(async () => {
// should clear existing sessions
const res = await originalAgent.get('/api/v1/me');
expect(res.statusCode).to.equal(403);
});
});
describe('if the request is invalid', () => {
describe('if the token is incorrect', () => {
it('should return a 404 error', async () => {
const res = await agent.del(`/api/v1/passwordReset/${token}aaaa`).send({
newPassword
});
expect(res.statusCode).to.equal(404);
});
});
describe('if the token is correct but expired', () => {
it('should return a 404 error', async () => {
await Promise.delay(sails.services.constants.PASSWORD_RESET_EXPIRATION_TIME);
const res = await agent.del(`/api/v1/passwordReset/${token}`).send({newPassword});
expect(res.statusCode).to.equal(404);
});
});
describe('if another request has been made since this token was sent', () => {
it('should return a 404 error', async () => {
const res = await agent.post(`/api/v1/user/${username}/passwordReset`);
expect(res.statusCode).to.equal(202);
const res2 = await agent.del(`/api/v1/passwordReset/${token}`).send({newPassword});
expect(res2.statusCode).to.equal(404);
});
});
describe('if the new password is invalid', () => {
it('should return a 400 error', async () => {
const res = await agent.del(`/api/v1/passwordReset/${token}`)
.send({newPassword: 'a'});
expect(res.statusCode).to.equal(400);
// don't invalidate the token if the password is invalid
expect(await sails.models.passwordreset.findOne({id: token})).to.exist();
});
});
afterEach(async () => {
// should not authenticate the current session
const res = await agent.get('/api/v1/me');
expect(res.statusCode).to.equal(403);
});
afterEach(async () => {
// should not allow login with the new password
const tempAgent = await testHelpers.getAgent();
const res = await tempAgent.post('/api/v1/auth/local').send({
name: username,
password: newPassword
});
expect(res.statusCode).to.equal(401);
const res2 = await tempAgent.get('/api/v1/me');
expect(res2.statusCode).to.equal(403);
});
afterEach(async () => {
// should allow login with the old password
const tempAgent = await testHelpers.getAgent();
const res = await tempAgent.post('/api/v1/auth/local').send({
name: username,
password: oldPassword
});
expect(res.statusCode).to.equal(200);
const res2 = await tempAgent.get('/api/v1/me');
expect(res2.statusCode).to.equal(302);
expect(res2.header.location.endsWith(`/user/${username}`)).to.be.true();
});
afterEach(async () => {
// should not clear existing sessions
const res = await originalAgent.get('/api/v1/me');
expect(res.statusCode).to.equal(302);
expect(res.header.location).to.equal(`/api/v1/user/${username}`);
});
});
after(() => {
sails.services.constants.PASSWORD_RESET_EXPIRATION_TIME = originalExpirationTime;
});
});
});
|
porybox/porybox
|
test/controller/passwordReset.js
|
JavaScript
|
apache-2.0
| 10,711
|
/*
*
* 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 flash.swf;
import flash.swf.debug.DebugTable;
import flash.swf.tags.*;
import flash.swf.types.ButtonCondAction;
import flash.swf.types.ButtonRecord;
import flash.swf.types.CXForm;
import flash.swf.types.CXFormWithAlpha;
import flash.swf.types.CurvedEdgeRecord;
import flash.swf.types.FillStyle;
import flash.swf.types.Filter;
import flash.swf.types.FlashUUID;
import flash.swf.types.GlyphEntry;
import flash.swf.types.GradRecord;
import flash.swf.types.ImportRecord;
import flash.swf.types.KerningRecord;
import flash.swf.types.LineStyle;
import flash.swf.types.Matrix;
import flash.swf.types.MorphFillStyle;
import flash.swf.types.MorphGradRecord;
import flash.swf.types.MorphLineStyle;
import flash.swf.types.Rect;
import flash.swf.types.Shape;
import flash.swf.types.ShapeRecord;
import flash.swf.types.ShapeWithStyle;
import flash.swf.types.SoundInfo;
import flash.swf.types.StraightEdgeRecord;
import flash.swf.types.StyleChangeRecord;
import flash.swf.types.TextRecord;
import flash.swf.types.DropShadowFilter;
import flash.swf.types.BlurFilter;
import flash.swf.types.GlowFilter;
import flash.swf.types.BevelFilter;
import flash.swf.types.GradientGlowFilter;
import flash.swf.types.ConvolutionFilter;
import flash.swf.types.ColorMatrixFilter;
import flash.swf.types.GradientBevelFilter;
import flash.swf.types.Gradient;
import flash.swf.types.FocalGradient;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.zip.InflaterInputStream;
/**
* A SWF tag decoder. It is typically used by passing an InputStream
* to the constructor and then calling parse() with a TagHandler.
*/
public final class TagDecoder
implements TagValues
{
public TagDecoder(InputStream swfIn)
{
this.swfIn = swfIn;
this.swdIn = null;
}
public TagDecoder(InputStream swfIn, InputStream swdIn)
{
this.swfIn = swfIn;
this.swdIn = swdIn;
}
public TagDecoder(InputStream in, URL swfUrl)
{
this.swfIn = in;
this.swfUrl = swfUrl;
}
private Header header;
private InputStream swfIn;
private InputStream swdIn;
private URL swfUrl;
private DebugTable swd;
private SwfDecoder r;
private GenericTag jpegTables;
private TagHandler handler;
private boolean keepOffsets;
private Dictionary dict = new Dictionary();
/**
* thrown by decoders when we have a fatal error. Many errors
* are not fatal. In those cases, the error is reported but
* parsing continues.
*/
public static class FatalParseException extends Exception {
private static final long serialVersionUID = 5819679367367802771L;}
public void setKeepOffsets(boolean b)
{
keepOffsets = b;
}
/**
* process the whole SWF stream, and close the input streams when finished.
* @param handler
* @throws IOException
*/
public void parse(TagHandler handler) throws IOException
{
this.handler = handler;
try
{
try
{
handler.setDecoderDictionary(dict);
header = decodeHeader();
handler.header(header);
decodeTags(handler);
handler.finish();
}
catch( FatalParseException e )
{
// errors already reported to TagHandler.
}
finally
{
if (swfIn != null)
swfIn.close();
}
}
finally
{
if (swdIn != null)
swdIn.close();
}
}
public int getSwfVersion()
{
return header.version;
}
private void decodeTags(TagHandler handler) throws IOException
{
int type, h, length, currentOffset;
do
{
currentOffset = r.getOffset();
type = (h = r.readUI16()) >> 6;
// is this a long tag header (>=63 bytes)?
if (((length = h & 0x3F) == 0x3F))
{
// [ed] the player treats this as a signed field and stops if it is negative.
length = r.readSI32();
if (length < 0)
{
handler.error("negative tag length: " + length + " at offset " + currentOffset);
break;
}
}
int o = r.getOffset();
int eat = 0;
if (type != 0)
{
Tag t = decodeTag(type, length);
if (r.getOffset() - o != length)
{
handler.error("offset mismatch after " + Tag.names[t.code] + ": read " + (r.getOffset() - o) + ", expected " + length);
if (r.getOffset() - o < length)
{
eat = length - (r.getOffset() - o);
}
}
handler.setOffsetAndSize(currentOffset, r.getOffset() - currentOffset);
handler.any( t );
t.visit(handler);
if (eat > 0) // try to recover. (flash 8 sometimes writes nonsense, usually in fonts)
{
r.read( new byte[eat] );
}
}
}
while (type != 0);
}
private Tag decodeTag(int type, int length) throws IOException
{
Tag t;
int pos = r.getOffset();
switch (type)
{
case stagProductInfo:
t = decodeSerialNumber();
break;
case stagShowFrame:
t = new ShowFrame();
break;
case stagMetadata:
t = decodeMetadata();
break;
case stagDefineShape:
case stagDefineShape2:
case stagDefineShape3:
case stagDefineShape4:
t = decodeDefineShape(type);
break;
case stagPlaceObject:
t = decodePlaceObject(length);
break;
case stagRemoveObject:
case stagRemoveObject2:
t = decodeRemoveObject(type);
break;
case stagDefineBinaryData:
t = decodeDefineBinaryData(length);
break;
case stagDefineBits:
t = decodeDefineBits(length);
break;
case stagDefineButton:
t = decodeDefineButton(length);
break;
case stagJPEGTables:
t = jpegTables = decodeJPEGTables(length);
break;
case stagSetBackgroundColor:
t = decodeSetBackgroundColor();
break;
case stagDefineFont:
t = decodeDefineFont();
break;
case stagDefineText:
case stagDefineText2:
t = decodeDefineText(type);
break;
case stagDoAction:
t = decodeDoAction(length);
break;
case stagDefineFontInfo:
case stagDefineFontInfo2:
t = decodeDefineFontInfo(type, length);
break;
case stagDefineSound:
t = decodeDefineSound(length);
break;
case stagStartSound:
t = decodeStartSound();
break;
case stagDefineButtonSound:
t = decodeDefineButtonSound();
break;
case stagSoundStreamHead2:
case stagSoundStreamHead:
t = decodeSoundStreamHead(type);
break;
case stagSoundStreamBlock:
t = decodeSoundStreamBlock(length);
break;
case stagDefineBitsLossless:
t = decodeDefineBitsLossless(length);
break;
case stagDefineBitsJPEG2:
t = decodeDefineJPEG2(length);
break;
case stagDefineButtonCxform:
t = decodeDefineButtonCxform();
break;
case stagProtect:
t = decodeProtect(length);
break;
case stagPlaceObject2:
t = decodePlaceObject23(stagPlaceObject2, length);
break;
case stagPlaceObject3:
t = decodePlaceObject23(stagPlaceObject3, length);
break;
case stagDefineButton2:
t = decodeDefineButton2(length);
break;
case stagDefineBitsJPEG3:
t = decodeDefineJPEG3(length);
break;
case stagDefineBitsLossless2:
t = decodeDefineBitsLossless2(length);
break;
case stagDefineEditText:
t = decodeDefineEditText();
break;
case stagDefineSprite:
t = decodeDefineSprite(pos+length);
break;
case stagDefineScalingGrid:
t = decodeDefineScalingGrid();
break;
case stagFrameLabel:
t = decodeFrameLabel(length);
break;
case stagDefineMorphShape:
t = decodeDefineMorphShape();
break;
case stagDefineMorphShape2:
t = decodeDefineMorphShape2();
break;
case stagDefineFont2:
t = decodeDefineFont2();
break;
case stagDefineFont3:
t = decodeDefineFont3();
break;
case stagDefineFont4:
t = decodeDefineFont4(length);
break;
case stagExportAssets:
t = decodeExportAssets();
break;
case stagImportAssets:
case stagImportAssets2:
t = decodeImportAssets(type);
break;
case stagEnableDebugger2:
case stagEnableDebugger:
t = decodeEnableDebugger(type);
break;
case stagDoInitAction:
t = decodeDoInitAction(length);
break;
case stagDefineVideoStream:
t = decodeDefineVideoStream();
break;
case stagVideoFrame:
t = decodeVideoFrame(length);
break;
case stagDebugID:
t = decodeDebugID(type, length);
break;
case stagScriptLimits:
t = decodeScriptLimits();
break;
case stagSetTabIndex:
t = decodeSetTabIndex();
break;
case stagDoABC:
case stagDoABC2:
t = decodeDoABC(type, length);
break;
case stagSymbolClass:
t = decodeSymbolClass();
break;
case stagFileAttributes:
t = decodeFileAttributes();
break;
case stagEnableTelemetry:
t = decodeEnableTelemetry();
break;
case stagDefineFontAlignZones:
t = decodeDefineFontAlignZones();
break;
case stagCSMTextSettings:
t = decodeCSMTextSettings();
break;
case stagDefineSceneAndFrameLabelData:
t = decodeDefineSceneAndFrameData(length);
break;
case stagDefineFontName:
t = decodeDefineFontName();
break;
default:
t = decodeUnknown(length, type);
break;
}
int consumed = r.getOffset() - pos;
// [preilly] It looks like past Authoring tools have generated some SWF's with
// stagSoundStreamHead tags of length 4 with compression set to mp3, but the tag
// really has 6 bytes in it and the player always reads the 6 bytes, so ignore the
// difference between the consumed and the length for this special case.
if ((consumed != length) && (type == stagSoundStreamHead) && (consumed != (length + 2)))
{
throw new SwfFormatException(TagValues.names[type] + " at pos "+pos+ ": " + consumed +
" bytes were read. " + length + " byte were required.");
}
return t;
}
private Tag decodeDefineSceneAndFrameData(int length) throws IOException
{
DefineSceneAndFrameLabelData t = new DefineSceneAndFrameLabelData();
t.data = new byte[length];
r.readFully(t.data);
return t;
}
private Tag decodeDoABC(int type, int length) throws IOException
{
DoABC t;
if (type == stagDoABC2)
{
int pos = r.getOffset();
int skip = r.readSI32();
String name = r.readString();
t = new DoABC( name , skip );
// cannot just use length of string, because might not match
// the number of bytes in the string for nonascii characters
//length -= (4 + name.length() + 1);
length -= (r.getOffset() - pos);
}
else
{
t = new DoABC();
}
t.abc = new byte[length];
r.readFully(t.abc);
return t;
}
private Tag decodeSymbolClass() throws IOException
{
SymbolClass t = new SymbolClass();
int count = r.readUI16();
t.class2tag = new HashMap<String, Tag>(count);
for (int i=0; i < count; i++)
{
int idref = r.readUI16();
String name = r.readString();
if (idref == 0)
{
t.topLevelClass = name;
continue;
}
DefineTag ref = dict.getTag(idref);
t.class2tag.put(name, ref);
if (ref.name != null)
{
if (!ref.name.equals(name))
{
handler.error("SymbolClass: symbol " + idref + " already exported as " + ref.name);
}
//else
//{
// FIXME: is this right? seem to be getting redundant message in swfdumps that work right in the player
// FIXME: We should eventually enforce that export names not be used in zaphod movies,
// FIXME: but in the short term, all this message means is that the symbol was both exported
// FIXME: via ExportAssets and also associated with a class via SymbolClass. They have
// FIXME: different semantic meanings, so this error is a bit off-base. --rg
// handler.error("Redundant SymbolClass of " + ref.name + ". Found " + ref.getClass().getName() + " of same name in dictionary.");
//}
}
else
{
DefineTag other = dict.getTag(name);
if (other != null)
{
int id = dict.getId(other);
handler.error("Symbol " + name + " already refers to ID " + id);
}
ref.name = name;
dict.addName(ref, name);
}
}
return t;
}
private Tag decodeSetTabIndex() throws IOException
{
int depth = r.readUI16();
int index = r.readUI16();
return new SetTabIndex(depth, index);
}
private Tag decodeUnknown(int length, int code) throws IOException
{
GenericTag t;
t = new GenericTag(code);
t.data = new byte[length];
r.readFully(t.data);
return t;
}
private ScriptLimits decodeScriptLimits() throws IOException
{
ScriptLimits scriptLimits = new ScriptLimits(r.readUI16(), r.readUI16());
return scriptLimits;
}
private Tag decodeDebugID(int type, int length) throws IOException
{
DebugID t;
t = new DebugID(type);
t.uuid = decodeFlashUUID(length);
if (swdIn != null)
{
InputStream in = swdIn;
DebugTable swd = new DebugTable();
new DebugDecoder(in).readSwd(swd);
if (!t.uuid.equals(swd.uuid))
{
handler.error("SWD uuid "+swd.uuid+" doesn't match "+t.uuid);
}
else if (swd.version != getSwfVersion())
{
handler.error("SWD version number "+swd.version+" doesn't match SWF version number "+getSwfVersion());
}
else
{
this.swd = swd;
}
}
else if (swfUrl != null)
{
// look for a SWD file in the same place the player would look
String path = swfUrl.toString();
int q = path.indexOf("?");
String query = null;
if (q != -1)
{
query = path.substring(q);
path = path.substring(0, q);
}
URL swdUrl;
if (path.endsWith(".swf"))
{
path = path.substring(0,path.length()-4)+".swd";
}
else
{
path = path + ".swd";
}
if (query != null)
{
path = path + query;
}
swdUrl = new URL(path);
try
{
InputStream in = swdUrl.openStream();
DebugTable swd = new DebugTable();
new DebugDecoder(in).readSwd(swd);
if (!t.uuid.equals(swd.uuid))
{
handler.error("SWD uuid "+swd.uuid+" doesn't match "+t.uuid);
}
else if (swd.version != getSwfVersion())
{
handler.error("SWD version number "+swd.version+" doesn't match SWF version number "+getSwfVersion());
}
else
{
this.swd = swd;
}
}
catch (FileNotFoundException ex)
{
handler.error("SWD not found at url " + swdUrl);
}
}
return t;
}
private FlashUUID decodeFlashUUID(int length) throws IOException
{
byte[] uuid = new byte[length];
r.readFully(uuid);
return new FlashUUID(uuid);
}
private Tag decodeVideoFrame(int length) throws IOException
{
VideoFrame t;
t = new VideoFrame();
int pos = r.getOffset();
int idref = r.readUI16();
t.stream = (DefineVideoStream) dict.getTag(idref);
t.frameNum = r.readUI16();
length -= r.getOffset() - pos;
t.videoData = new byte[length];
r.readFully(t.videoData);
return t;
}
private Tag decodeDefineVideoStream() throws IOException
{
DefineVideoStream t;
t = new DefineVideoStream();
int id = r.readUI16();
t.numFrames = r.readUI16();
t.width = r.readUI16();
t.height = r.readUI16();
r.syncBits();
r.readUBits(4); // reserved
t.deblocking = r.readUBits(3);
t.smoothing = r.readBit();
t.codecID = r.readUI8();
dict.add(id, t);
return t;
}
private Tag decodeDoInitAction(int length) throws IOException
{
DoInitAction t;
t = new DoInitAction();
int idref = r.readUI16();
try
{
t.sprite = (DefineSprite) dict.getTag(idref);
if (t.sprite.initAction != null)
{
handler.error("Sprite " + idref + " initaction redefined");
}
else
{
t.sprite.initAction = t;
}
}
catch (IllegalArgumentException e)
{
handler.error(e.getMessage());
}
ActionDecoder actionDecoder = new ActionDecoder(r,swd);
actionDecoder.setKeepOffsets(keepOffsets);
t.actionList = actionDecoder.decode(length-2);
return t;
}
private Tag decodeEnableDebugger(int code) throws IOException
{
EnableDebugger t;
t = new EnableDebugger(code);
if (code == stagEnableDebugger2)
{
if (getSwfVersion() < 6)
handler.error("EnableDebugger2 not valid before SWF 6");
t.reserved = r.readUI16(); // reserved
}
t.password = r.readString();
return t;
}
private Tag decodeImportAssets(int code) throws IOException
{
ImportAssets t;
t = new ImportAssets(code);
t.url = r.readString();
if (code == stagImportAssets2)
{
t.downloadNow = (r.readUI8() == 1);
if (r.readUI8() == 1) // hasDigest == 1
{
t.SHA1 = new byte[20];
r.readFully(t.SHA1);
}
}
int count = r.readUI16();
t.importRecords = new ArrayList<ImportRecord>();
for (int i=0; i < count; i++)
{
ImportRecord ir = new ImportRecord();
int id = r.readUI16();
ir.name = r.readString();
t.importRecords.add(ir);
dict.add(id, ir);
dict.addName(ir, ir.name);
}
return t;
}
private Tag decodeExportAssets() throws IOException
{
ExportAssets t;
t = new ExportAssets();
int count = r.readUI16();
t.exports = new ArrayList<Tag>(count);
for (int i=0; i < count; i++)
{
int idref = r.readUI16();
String name = r.readString();
DefineTag ref = dict.getTag(idref);
t.exports.add(ref);
if (ref.name != null)
{
if (!ref.name.equals(name))
handler.error("ExportAsset: symbol " + idref + " already exported as " + ref.name);
else
handler.error("redundant export of "+ref.name);
}
else
{
DefineTag other = dict.getTag(name);
if (other != null)
{
int id = dict.getId(other);
handler.error("Symbol "+name+" already refers to ID "+id);
}
ref.name = name;
dict.addName(ref, name);
}
}
return t;
}
private Tag decodeDefineFont2() throws IOException
{
DefineFont2 t = new DefineFont2();
return decodeDefineFont2And3(t);
}
private Tag decodeDefineFont3() throws IOException
{
DefineFont3 t = new DefineFont3();
return decodeDefineFont2And3(t);
}
private Tag decodeDefineFont2And3(DefineFont2 t) throws IOException
{
int id = r.readUI16();
r.syncBits();
t.hasLayout = r.readBit();
t.shiftJIS = r.readBit();
t.smallText = r.readBit();
t.ansi = r.readBit();
t.wideOffsets = r.readBit();
t.wideCodes = r.readBit();
// enable after we're sure that bug 147073 isn't a bug. If it is a bug, then this can be
// removed as well as the stageDefineFont3-specific code in TagEncoder.defineFont2()
//if (t.code == stagDefineFont3 && ! t.wideCodes)
//{
// handler.error("widecodes must be true in DefineFont3");
//}
t.italic = r.readBit();
t.bold = r.readBit();
t.langCode = r.readUI8();
t.fontName = r.readLengthString();
int numGlyphs = r.readUI16();
long[] offsets = new long[numGlyphs];
for (int i = 0; i < numGlyphs; i++)
{
if (t.wideOffsets)
offsets[i] = r.readUI32();
else
offsets[i] = r.readUI16();
}
long codeTableOffset = 0;
if (numGlyphs > 0)
{
if (t.wideOffsets)
codeTableOffset = r.readUI32();
else
codeTableOffset = r.readUI16();
}
t.glyphShapeTable = new Shape[numGlyphs];
for (int i = 0; i < numGlyphs; i++)
{
int glyphLength;
if (i < (numGlyphs - 1))
glyphLength = (int)(offsets[i+1] - offsets[i]);
else
glyphLength = (int)(codeTableOffset - offsets[i]);
t.glyphShapeTable[i] = decodeGlyph(stagDefineShape3, glyphLength);
}
t.codeTable = new char[numGlyphs];
if (t.wideCodes)
{
for (int i = 0; i < numGlyphs; i++)
t.codeTable[i] = (char) r.readUI16();
}
else
{
for (int i = 0; i < numGlyphs; i++)
t.codeTable[i] = (char) r.readUI8();
}
if (t.hasLayout)
{
t.ascent = r.readSI16();
t.descent = r.readSI16();
t.leading = r.readSI16();
t.advanceTable = new short[numGlyphs];
for (int i = 0; i < numGlyphs; i++)
{
t.advanceTable[i] = (short)r.readSI16();
}
t.boundsTable = new Rect[numGlyphs];
for (int i = 0; i < numGlyphs; i++)
{
t.boundsTable[i] = decodeRect();
}
t.kerningCount = r.readUI16();
t.kerningTable = new KerningRecord[t.kerningCount];
for (int i = 0; i < t.kerningCount; i++)
{
t.kerningTable[i] = decodeKerningRecord(t.wideCodes);
}
}
dict.add(id, t);
dict.addFontFace( t );
return t;
}
private Tag decodeDefineFont4(int length) throws IOException
{
DefineFont4 t = new DefineFont4();
int pos = r.getOffset();
int id = r.readUI16();
r.syncBits();
r.readUBits(5); // reserved
t.hasFontData = r.readBit();
//t.smallText = r.readBit();
t.italic = r.readBit();
t.bold = r.readBit();
//t.langCode = r.readUI8();
t.fontName = r.readString();
if (t.hasFontData)
{
length -= r.getOffset() - pos;
t.data = new byte[length];
r.readFully(t.data);
}
dict.add(id, t);
dict.addFontFace(t);
return t;
}
private KerningRecord decodeKerningRecord(boolean wideCodes) throws IOException
{
KerningRecord kr = new KerningRecord();
kr.code1 = (wideCodes) ? r.readUI16() : r.readUI8();
kr.code2 = (wideCodes) ? r.readUI16() : r.readUI8();
kr.adjustment = r.readUI16();
return kr;
}
private Tag decodeDefineMorphShape() throws IOException
{
return decodeDefineMorphShape(stagDefineMorphShape);
}
private Tag decodeDefineMorphShape2() throws IOException
{
return decodeDefineMorphShape(stagDefineMorphShape2);
}
private Tag decodeDefineMorphShape(int code) throws IOException
{
DefineMorphShape t = new DefineMorphShape(code);
int id = r.readUI16();
t.startBounds = decodeRect();
t.endBounds = decodeRect();
if (code == stagDefineMorphShape2)
{
t.startEdgeBounds = decodeRect();
t.endEdgeBounds = decodeRect();
r.readUBits(6);
t.usesNonScalingStrokes = r.readBit();
t.usesScalingStrokes = r.readBit();
}
int offset = (int)r.readUI32(); // offset to EndEdges
t.fillStyles = decodeMorphFillstyles(code);
t.lineStyles = decodeMorphLinestyles(code);
t.startEdges = decodeShape(stagDefineShape3);
if (offset != 0)
t.endEdges = decodeShape(stagDefineShape3);
dict.add(id, t);
return t;
}
private MorphLineStyle[] decodeMorphLinestyles(int code) throws IOException
{
int count = r.readUI8();
if (count == 0xFF)
{
count = r.readUI16();
}
MorphLineStyle[] styles = new MorphLineStyle[count];
for (int i = 0; i < count; i++)
{
MorphLineStyle s = new MorphLineStyle();
s.startWidth = r.readUI16();
s.endWidth = r.readUI16();
if (code == stagDefineMorphShape2)
{
s.startCapsStyle = r.readUBits(2);
s.jointStyle = r.readUBits(2);
s.hasFill = r.readBit();
s.noHScale = r.readBit();
s.noVScale = r.readBit();
s.pixelHinting = r.readBit();
r.readUBits(5); // reserved
s.noClose = r.readBit();
s.endCapsStyle = r.readUBits(2);
if (s.jointStyle == 2)
{
s.miterLimit = r.readUI16();
}
}
if (!s.hasFill)
{
s.startColor = decodeRGBA(r);
s.endColor = decodeRGBA(r);
}
if (s.hasFill)
{
s.fillType = decodeMorphFillStyle(code);
}
styles[i] = s;
}
return styles;
}
private MorphFillStyle[] decodeMorphFillstyles(int shape) throws IOException
{
int count = r.readUI8();
if (count == 0xFF)
{
count = r.readUI16();
}
MorphFillStyle[] styles = new MorphFillStyle[count];
for (int i = 0; i < count; i++)
{
styles[i] = decodeMorphFillStyle(shape);
}
return styles;
}
private MorphFillStyle decodeMorphFillStyle(int shape) throws IOException
{
MorphFillStyle s = new MorphFillStyle();
s.type = r.readUI8();
switch (s.type)
{
case FillStyle.FILL_SOLID: // 0x00
s.startColor = decodeRGBA(r);
s.endColor = decodeRGBA(r);
break;
case FillStyle.FILL_GRADIENT: // 0x10 linear gradient fill
case FillStyle.FILL_RADIAL_GRADIENT: // 0x12 radial gradient fill
case FillStyle.FILL_FOCAL_RADIAL_GRADIENT: // 0x13 focal radial gradient fill
s.startGradientMatrix = decodeMatrix();
s.endGradientMatrix = decodeMatrix();
s.gradRecords = decodeMorphGradient();
if (s.type == FillStyle.FILL_FOCAL_RADIAL_GRADIENT && shape == stagDefineMorphShape2)
{
s.ratio1 = r.readSI16();
s.ratio2 = r.readSI16();
}
break;
case FillStyle.FILL_BITS: // 0x40 tiled bitmap fill
case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP): // 0x41 clipped bitmap fill
case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_NOSMOOTH): // 0x42 tiled non-smoothed fill
case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP | FillStyle.FILL_BITS_NOSMOOTH): // 0x43 clipped non-smoothed fill
int idref = r.readUI16();
try
{
s.bitmap = dict.getTag(idref);
}
catch (IllegalArgumentException ex)
{
handler.error(ex.getMessage());
s.bitmap = null;
}
s.startBitmapMatrix = decodeMatrix();
s.endBitmapMatrix = decodeMatrix();
break;
default:
throw new SwfFormatException("unrecognized fill style type: " + s.type);
}
return s;
}
private MorphGradRecord[] decodeMorphGradient() throws IOException
{
int num = r.readUI8();
MorphGradRecord[] gradRecords = new MorphGradRecord[num];
for (int i = 0; i < num; i++)
{
MorphGradRecord g = new MorphGradRecord();
g.startRatio = r.readUI8();
g.startColor = decodeRGBA(r);
g.endRatio = r.readUI8();
g.endColor = decodeRGBA(r);
gradRecords[i] = g;
}
return gradRecords;
}
private Tag decodeFrameLabel(int length) throws IOException
{
FrameLabel t = new FrameLabel();
int pos = r.getOffset();
t.label = r.readString();
if (getSwfVersion() >= 6)
{
if (length - r.getOffset() + pos == 1)
{
int anchor = r.readUI8();
if (anchor != 0 && anchor != 1)
handler.error("illegal anchor value: "+anchor+". Must be 0 or 1");
// player treats any nonzero value as true
t.anchor = (anchor != 0);
}
}
return t;
}
private Tag decodeDefineEditText() throws IOException
{
DefineEditText t;
t = new DefineEditText();
int id = r.readUI16();
t.bounds = decodeRect();
r.syncBits();
t.hasText = r.readBit();
t.wordWrap = r.readBit();
t.multiline = r.readBit();
t.password = r.readBit();
t.readOnly = r.readBit();
t.hasTextColor = r.readBit();
t.hasMaxLength = r.readBit();
t.hasFont = r.readBit();
t.hasFontClass = r.readBit(); // FP 9.0.45 or later
t.autoSize = r.readBit();
t.hasLayout = r.readBit();
t.noSelect = r.readBit();
t.border = r.readBit();
t.wasStatic = r.readBit();
t.html = r.readBit();
t.useOutlines = r.readBit();
if (t.hasFont)
{
int idref = r.readUI16();
t.font = (DefineFont) dict.getTag(idref);
t.height = r.readUI16();
}
if (t.hasFontClass)
{
t.fontClass = r.readString();
t.height = r.readUI16();
}
if (t.hasTextColor)
{
t.color = decodeRGBA(r);
}
if (t.hasMaxLength)
{
t.maxLength = r.readUI16();
}
if (t.hasLayout)
{
t.align = r.readUI8();
t.leftMargin = r.readUI16();
t.rightMargin = r.readUI16();
t.ident = r.readUI16();
t.leading = r.readSI16(); // see errata, leading is signed
}
t.varName = r.readString();
if (t.hasText)
{
t.initialText = r.readString();
}
dict.add(id, t);
return t;
}
private Tag decodeDefineScalingGrid() throws IOException
{
DefineScalingGrid t = new DefineScalingGrid();
int idref = r.readUI16();
try
{
t.scalingTarget = dict.getTag(idref);
if (t.scalingTarget instanceof DefineSprite)
{
DefineSprite targetSprite = (DefineSprite) t.scalingTarget;
if (targetSprite.scalingGrid != null)
{
handler.error("Sprite " + idref + " scaling grid redefined" );
}
targetSprite.scalingGrid = t;
}
else if (t.scalingTarget instanceof DefineButton)
{
DefineButton targetButton = (DefineButton) t.scalingTarget;
if (targetButton.scalingGrid != null)
{
handler.error("Button " + idref + " scaling grid redefined");
}
targetButton.scalingGrid = t;
}
}
catch (Exception e)
{
return null;
}
t.rect = decodeRect();
return t;
}
private Tag decodeDefineBitsLossless2(int length) throws IOException
{
DefineBitsLossless t;
t = new DefineBitsLossless(stagDefineBitsLossless2);
SwfDecoder r1 = r;
int pos = r1.getOffset();
int id = r1.readUI16();
t.format = r1.readUI8();
t.width = r1.readUI16();
t.height = r1.readUI16();
byte[] data;
switch (t.format)
{
case 3:
int colorTableSize = r1.readUI8()+1;
length -= r1.getOffset() - pos;
data = new byte[length];
r1.readFully(data);
r1 = new SwfDecoder(new InflaterInputStream(new ByteArrayInputStream(data)), getSwfVersion());
decodeAlphaColorMapData(r1, t, colorTableSize);
break;
case 4:
case 5:
length -= r1.getOffset() - pos;
data = new byte[length];
r1.readFully(data);
r1 = new SwfDecoder(new InflaterInputStream(new ByteArrayInputStream(data)), getSwfVersion());
t.data = new byte[t.width * t.height * 4];
r1.readFully(t.data);
break;
default:
throw new SwfFormatException("Illegal bitmap format " + t.format);
}
dict.add(id, t);
return t;
}
private void decodeAlphaColorMapData(SwfDecoder r1, DefineBitsLossless tag, int tableSize) throws IOException
{
int width = tag.width;
int height = tag.height;
tag.colorData = new int[tableSize];
for (int i = 0; i < tableSize; i++)
{
tag.colorData[i] = decodeRGBA(r1);
}
if (width % 4 != 0)
{
width = (width / 4 + 1) * 4;
}
int data_size = width * height;
tag.data = new byte[data_size];
//r1.read(tag.data);
int i = 0;
int b;
while (i < data_size)
{
b = r1.readUI8();
if (b != -1)
{
tag.data[i] = (byte) b;
i++;
}
else
{
break;
}
}
int extra = 0;
while (r1.readUI8() != -1)
{
extra++;
}
if (extra > 0)
{
throw new SwfFormatException(extra + " bytes of bitmap data (" + width + "x" + height + ") not read!");
}
else if (i != data_size)
{
throw new SwfFormatException("(" + width + "x" + height + ") data buffer " + (data_size - i) + " bytes too big...");
}
}
private Tag decodeDefineJPEG3(int length) throws IOException
{
DefineBitsJPEG3 t;
t = new DefineBitsJPEG3();
int pos = r.getOffset();
int id = r.readUI16();
t.alphaDataOffset = r.readUI32();
t.data = new byte[(int) t.alphaDataOffset];
r.readFully(t.data);
length -= r.getOffset() - pos;
byte[] temp = new byte[length];
r.readFully(temp);
SwfDecoder r1 = new SwfDecoder(new InflaterInputStream(new ByteArrayInputStream(temp)), getSwfVersion());
int alpha, i = 0;
byte[] alphaData = new byte[length];
while ((alpha = r1.readUI8()) != -1)
{
if (i == alphaData.length)
{
byte[] b = new byte[i + length];
System.arraycopy(alphaData, 0, b, 0, alphaData.length);
alphaData = b;
}
alphaData[i] = (byte)alpha;
i++;
}
t.alphaData = new byte[i];
System.arraycopy(alphaData, 0, t.alphaData, 0, i);
dict.add(id, t);
return t;
}
private Tag decodeDefineButton2(int length) throws IOException
{
int endpos = r.getOffset()+length;
DefineButton t = new DefineButton(stagDefineButton2);
int id = r.readUI16();
r.syncBits();
r.readUBits(7); // reserved
t.trackAsMenu = r.readBit();
int actionOffset = r.readUI16();
// read button data
ArrayList<Object> list = new ArrayList<Object>(5);
ButtonRecord record;
while ((record = decodeButtonRecord(t.code)) != null)
{
list.add(record);
}
t.buttonRecords = new ButtonRecord[list.size()];
list.toArray(t.buttonRecords);
list.clear();
if (actionOffset > 0)
{
list = new ArrayList<Object>();
int pos = r.getOffset();
while ((actionOffset = r.readUI16()) > 0)
{
list.add(decodeButtonCondAction(actionOffset-2));
if (r.getOffset() != pos+actionOffset)
{
throw new SwfFormatException("incorrect offset read in ButtonCondAction. read "+actionOffset+"");
}
pos = r.getOffset();
}
// actionOffset == 0 means this will be the last record
list.add(decodeButtonCondAction(endpos-r.getOffset()));
t.condActions = new ButtonCondAction[list.size()];
list.toArray(t.condActions);
}
else
{
t.condActions = new ButtonCondAction[0];
}
while (r.getOffset() < endpos)
{
int b = r.readUI8();
if (b != 0)
{
throw new SwfFormatException("nonzero data past end of DefineButton2");
}
}
dict.add(id, t);
return t;
}
private ButtonCondAction decodeButtonCondAction(int length) throws IOException
{
ButtonCondAction a = new ButtonCondAction();
r.syncBits();
a.keyPress = r.readUBits(7);
a.overDownToIdle = r.readBit();
a.idleToOverDown = r.readBit();
a.outDownToIdle = r.readBit();
a.outDownToOverDown = r.readBit();
a.overDownToOutDown = r.readBit();
a.overDownToOverUp = r.readBit();
a.overUpToOverDown = r.readBit();
a.overUpToIdle = r.readBit();
a.idleToOverUp = r.readBit();
ActionDecoder actionDecoder = new ActionDecoder(r,swd);
actionDecoder.setKeepOffsets(keepOffsets);
a.actionList = actionDecoder.decode(length-2);
return a;
}
private Tag decodePlaceObject23(int type, int length) throws IOException
{
PlaceObject t = new PlaceObject(type);
int pos = r.getOffset();
t.flags = r.readUI8();
if (type == stagPlaceObject3)
{
t.flags2 = r.readUI8();
}
t.depth = r.readUI16();
if (t.hasClassName())
{
t.className = r.readString();
}
if (t.hasCharID())
{
int idref = r.readUI16();
t.setRef(dict.getTag(idref));
}
if (t.hasMatrix())
{
t.matrix = decodeMatrix();
}
if (t.hasCxform())
{
t.setCxform(decodeCxforma());
}
if (t.hasRatio())
{
t.ratio = r.readUI16();
}
if (t.hasName())
{
t.name = r.readString();
}
if (t.hasClipDepth())
{
t.clipDepth = r.readUI16();
}
if (type == stagPlaceObject3)
{
if (t.hasFilterList())
{
t.filters = decodeFilterList();
}
if (t.hasBlendMode())
{
t.blendMode = r.readUI8();
}
}
if (t.hasClipAction())
{
ActionDecoder actionDecoder = new ActionDecoder(r,swd);
actionDecoder.setKeepOffsets(keepOffsets);
t.clipActions = actionDecoder.decodeClipActions(length - (r.getOffset() - pos));
}
return t;
}
private List<Filter> decodeFilterList() throws IOException
{
LinkedList<Filter> filters = new LinkedList<Filter>();
int count = r.readUI8();
for (int i = 0; i < count; ++i)
{
int filterID = r.readUI8();
switch( filterID )
{
// NOTE: the filter decoding is pretty much just "save enough bits to regenerate", and ignores
// the real formatting of the filters (i.e. fixed 8.8 types, etc.) If you need the actual
// values rather than just acting as a passthrough, you will need to enhance the types.
case DropShadowFilter.ID: filters.add( decodeDropShadowFilter() ); break;
case BlurFilter.ID: filters.add( decodeBlurFilter() ); break;
case GlowFilter.ID: filters.add( decodeGlowFilter() ); break;
case BevelFilter.ID: filters.add( decodeBevelFilter() ); break;
case GradientGlowFilter.ID: filters.add( decodeGradientGlowFilter() ); break;
case ConvolutionFilter.ID: filters.add( decodeConvolutionFilter() ); break;
case ColorMatrixFilter.ID: filters.add( decodeColorMatrixFilter() ); break;
case GradientBevelFilter.ID: filters.add( decodeGradientBevelFilter() ); break;
}
}
return filters;
}
private DropShadowFilter decodeDropShadowFilter() throws IOException
{
DropShadowFilter f = new DropShadowFilter();
f.color = decodeRGBA( r );
f.blurX = r.readSI32();
f.blurY = r.readSI32();
f.angle = r.readSI32();
f.distance = r.readSI32();
f.strength = r.readUI16(); // really fixed8
f.flags = r.readUI8();
return f;
}
private BlurFilter decodeBlurFilter() throws IOException
{
BlurFilter f = new BlurFilter();
f.blurX = r.readSI32(); // FIXED
f.blurY = r.readSI32();
f.passes = r.readUI8();
return f;
}
private GlowFilter decodeGlowFilter() throws IOException
{
GlowFilter f = new GlowFilter();
f.color = decodeRGBA( r );
f.blurX = r.readSI32();
f.blurY = r.readSI32();
f.strength = r.readUI16(); // fixed 8.8
f.flags = r.readUI8(); // bunch of fields
return f;
}
private BevelFilter decodeBevelFilter() throws IOException
{
BevelFilter f = new BevelFilter();
f.highlightColor = decodeRGBA(r);
f.shadowColor = decodeRGBA(r);
f.blurX = r.readSI32();
f.blurY = r.readSI32();
f.angle = r.readSI32();
f.distance = r.readSI32();
f.strength = r.readUI16(); // fixed 8.8
f.flags = r.readUI8(); // bunch of fields
return f;
}
private GradientGlowFilter decodeGradientGlowFilter() throws IOException
{
GradientGlowFilter f = new GradientGlowFilter();
f.numcolors = r.readUI8();
f.gradientColors = new int[f.numcolors];
for (int i = 0; i < f.numcolors; ++i)
f.gradientColors[i] = decodeRGBA( r );
f.gradientRatio = new int[f.numcolors];
for (int i = 0; i < f.numcolors; ++i)
f.gradientRatio[i] = r.readUI8();
// f.color = decodeRGBA( r );
f.blurX = r.readSI32();
f.blurY = r.readSI32();
f.angle = r.readSI32();
f.distance = r.readSI32();
f.strength = r.readUI16(); // fixed 8.8
f.flags = r.readUI8(); // bunch of fields
return f;
}
private ConvolutionFilter decodeConvolutionFilter() throws IOException
{
ConvolutionFilter f = new ConvolutionFilter();
f.matrixX = r.readUI8();
f.matrixY = r.readUI8();
f.divisor = r.readFloat();
f.bias = r.readFloat();
f.matrix = new float[f.matrixX*f.matrixY];
for (int i = 0; i <f.matrixX*f.matrixY; ++i)
f.matrix[i] = r.readFloat();
f.color = decodeRGBA( r );
f.flags = r.readUI8();
return f;
}
private ColorMatrixFilter decodeColorMatrixFilter() throws IOException
{
ColorMatrixFilter f = new ColorMatrixFilter();
for (int i = 0; i < 20; ++i)
{
f.values[i] = r.readFloat();
}
return f;
}
private GradientBevelFilter decodeGradientBevelFilter() throws IOException
{
GradientBevelFilter f = new GradientBevelFilter();
f.numcolors = r.readUI8();
f.gradientColors = new int[f.numcolors];
for (int i = 0; i < f.numcolors; ++i)
f.gradientColors[i] = decodeRGBA( r );
f.gradientRatio = new int[f.numcolors];
for (int i = 0; i < f.numcolors; ++i)
f.gradientRatio[i] = r.readUI8();
// f.shadowColor = decodeRGBA( r );
// f.highlightColor = decodeRGBA( r );
f.blurX = r.readSI32();
f.blurY = r.readSI32();
f.angle = r.readSI32();
f.distance = r.readSI32();
f.strength = r.readUI16();
f.flags = r.readUI8();
return f;
}
private Tag decodePlaceObject(int length) throws IOException
{
PlaceObject t = new PlaceObject(stagPlaceObject);
int pos = r.getOffset();
int idref = r.readUI16();
t.depth = r.readUI16();
t.setMatrix(decodeMatrix());
if (length - r.getOffset() + pos != 0)
{
t.setCxform(decodeCxform());
}
t.setRef(dict.getTag(idref));
return t;
}
private Tag decodePlaceObject2(int length) throws IOException
{
PlaceObject t;
t = new PlaceObject(stagPlaceObject2);
r.syncBits();
int pos = r.getOffset();
t.flags = r.readUI8();
t.depth = r.readUI16();
if (t.hasCharID())
{
int idref = r.readUI16();
t.ref = dict.getTag(idref);
}
if (t.hasMatrix())
{
t.matrix = decodeMatrix();
}
if (t.hasCxform())
{
// ed 5/22/03 the SWF 6 file format spec says this will be a CXFORM, but
// the spec is wrong. the player expects a CXFORMA.
t.colorTransform = decodeCxforma();
}
if (t.hasRatio())
{
t.ratio = r.readUI16();
}
if (t.hasName())
{
t.name = r.readString();
}
if (t.hasClipDepth())
{
t.clipDepth = r.readUI16();
}
if (t.hasClipAction())
{
ActionDecoder actionDecoder = new ActionDecoder(r,swd);
actionDecoder.setKeepOffsets(keepOffsets);
t.clipActions = actionDecoder.decodeClipActions(length - (r.getOffset() - pos));
}
return t;
}
private CXFormWithAlpha decodeCxforma() throws IOException
{
CXFormWithAlpha c = new CXFormWithAlpha();
r.syncBits();
c.hasAdd = r.readBit();
c.hasMult = r.readBit();
int nbits = r.readUBits(4);
if (c.hasMult)
{
c.redMultTerm = r.readSBits(nbits);
c.greenMultTerm = r.readSBits(nbits);
c.blueMultTerm = r.readSBits(nbits);
c.alphaMultTerm = r.readSBits(nbits);
}
if (c.hasAdd)
{
c.redAddTerm = r.readSBits(nbits);
c.greenAddTerm = r.readSBits(nbits);
c.blueAddTerm = r.readSBits(nbits);
c.alphaAddTerm = r.readSBits(nbits);
}
return c;
}
private Tag decodeProtect(int length) throws IOException
{
GenericTag t;
t = new GenericTag(stagProtect);
t.data = new byte[length];
r.readFully(t.data);
return t;
}
private Tag decodeDefineButtonCxform() throws IOException
{
DefineButtonCxform t;
t = new DefineButtonCxform();
int idref = r.readUI16();
t.button = (DefineButton) dict.getTag(idref);
if (t.button.cxform != null)
{
handler.error("button " + dict.getId(t.button) + " cxform redefined");
}
t.button.cxform = t;
t.colorTransform = decodeCxform();
return t;
}
private Tag decodeDefineJPEG2(int length) throws IOException
{
DefineBits t = new DefineBits(stagDefineBitsJPEG2);
int pos = r.getOffset();
int id = r.readUI16();
length -= r.getOffset() - pos;
t.data = new byte[length];
r.readFully(t.data);
dict.add(id, t);
return t;
}
private Tag decodeDefineBitsLossless(int length) throws IOException
{
DefineBitsLossless t = new DefineBitsLossless(stagDefineBitsLossless);
SwfDecoder r1 = r;
int pos = r1.getOffset();
int id = r1.readUI16();
t.format = r1.readUI8();
t.width = r1.readUI16();
t.height = r1.readUI16();
byte[] data;
switch (t.format)
{
case 3:
int tableSize = r1.readUI8() + 1;
length -= r1.getOffset() - pos;
data = new byte[length];
r1.readFully(data);
r1 = new SwfDecoder(new InflaterInputStream(new ByteArrayInputStream(data)), getSwfVersion());
decodeColorMapData(r1, t, tableSize);
break;
case 4:
case 5:
length -= r1.getOffset() - pos;
data = new byte[length];
r1.readFully(data);
r1 = new SwfDecoder(new InflaterInputStream(new ByteArrayInputStream(data)), getSwfVersion());
t.data = new byte[t.width * t.height * 4];
r1.readFully(t.data);
break;
default:
throw new SwfFormatException("Illegal bitmap format " + t.format);
}
dict.add(id, t);
return t;
}
private void decodeColorMapData(SwfDecoder r1, DefineBitsLossless tag, int tableSize) throws IOException
{
tag.colorData = new int[tableSize];
for (int i = 0; i < tableSize; i++)
{
tag.colorData[i] = decodeRGB(r1);
}
int width = tag.width;
int height = tag.height;
if (width % 4 != 0)
{
width = (width / 4 + 1) * 4;
}
tag.data = new byte[width * height];
r1.readFully(tag.data);
}
private Tag decodeSoundStreamBlock(int length) throws IOException
{
GenericTag t = new GenericTag(stagSoundStreamBlock);
t.data = new byte[length];
r.readFully(t.data);
return t;
}
private Tag decodeSoundStreamHead(int code) throws IOException
{
SoundStreamHead t;
t = new SoundStreamHead(code);
r.syncBits();
// mixFormat
r.readUBits(4); // reserved
t.playbackRate = r.readUBits(2);
t.playbackSize = r.readUBits(1);
t.playbackType = r.readUBits(1);
// format
t.compression = r.readUBits(4);
t.streamRate = r.readUBits(2);
t.streamSize = r.readUBits(1);
t.streamType = r.readUBits(1);
t.streamSampleCount = r.readUI16();
if (t.compression == SoundStreamHead.sndCompressMP3)
{
t.latencySeek = r.readSI16();
}
return t;
}
private Tag decodeDefineButtonSound() throws IOException
{
DefineButtonSound t;
t = new DefineButtonSound();
int idref = r.readUI16();
t.button = (DefineButton) dict.getTag(idref);
if (t.button.sounds != null)
{
handler.error("button " + idref + " sound redefined");
}
t.button.sounds = t;
idref = r.readUI16();
if (idref != 0)
{
t.sound0 = dict.getTag(idref);
t.info0 = decodeSoundInfo();
}
idref = r.readUI16();
if (idref != 0)
{
t.sound1 = dict.getTag(idref);
t.info1 = decodeSoundInfo();
}
idref = r.readUI16();
if (idref != 0)
{
t.sound2 = dict.getTag(idref);
t.info2 = decodeSoundInfo();
}
idref = r.readUI16();
if (idref != 0)
{
t.sound3 = dict.getTag(idref);
t.info3 = decodeSoundInfo();
}
return t;
}
private Tag decodeStartSound() throws IOException
{
StartSound t;
t = new StartSound();
int idref = r.readUI16();
t.sound = (DefineSound) dict.getTag(idref);
t.soundInfo = decodeSoundInfo();
return t;
}
private SoundInfo decodeSoundInfo() throws IOException
{
SoundInfo i = new SoundInfo();
r.syncBits();
r.readUBits(2); // reserved
i.syncStop = r.readBit();
i.syncNoMultiple = r.readBit();
boolean hasEnvelope = r.readBit();
boolean hasLoops = r.readBit();
boolean hasOutPoint = r.readBit();
boolean hasInPoint = r.readBit();
if (hasInPoint)
{
i.inPoint = r.readUI32();
}
if (hasOutPoint)
{
i.outPoint = r.readUI32();
}
if (hasLoops)
{
i.loopCount = r.readUI16();
}
if (hasEnvelope)
{
int points = r.readUI8();
i.records = new long[points];
for (int k = 0; k < points; k++)
{
i.records[k] = r.read64();
}
}
return i;
}
private Tag decodeDefineSound(int length) throws IOException
{
DefineSound t;
t = new DefineSound();
int pos = r.getOffset();
int id = r.readUI16();
r.syncBits();
t.format = r.readUBits(4);
t.rate = r.readUBits(2);
t.size = r.readUBits(1);
t.type = r.readUBits(1);
t.sampleCount = r.readUI32();
length -= r.getOffset() - pos;
t.data = new byte[length];
r.readFully(t.data);
dict.add(id, t);
return t;
}
private Tag decodeDefineFontInfo(int code, int length) throws IOException
{
DefineFontInfo t;
t = new DefineFontInfo(code);
int pos = r.getOffset();
int idref = r.readUI16();
t.font = (DefineFont1) dict.getTag(idref);
if (t.font.fontInfo != null)
{
handler.error("font " + idref + " info redefined");
}
t.font.fontInfo = t;
t.name = r.readLengthString();
r.syncBits();
r.readUBits(3); // reserved
t.shiftJIS = r.readBit();
t.ansi = r.readBit();
t.italic = r.readBit();
t.bold = r.readBit();
t.wideCodes = r.readBit();
if (code == stagDefineFontInfo2)
{
if (!t.wideCodes)
handler.error("widecodes must be true in DefineFontInfo2");
if (getSwfVersion() < 6)
handler.error("DefineFont2 not valid before SWF6");
t.langCode = r.readUI8();
}
length -= r.getOffset() - pos;
if (t.wideCodes)
{
length = length / 2;
t.codeTable = new char[length];
for (int i = 0; i < length; i++)
{
t.codeTable[i] = (char)r.readUI16();
}
}
else
{
t.codeTable = new char[length];
for (int i = 0; i < length; i++)
{
t.codeTable[i] = (char)r.readUI8();
}
}
return t;
}
private Tag decodeDoAction(int length) throws IOException
{
DoAction t = new DoAction();
ActionDecoder actionDecoder = new ActionDecoder(r,swd);
actionDecoder.setKeepOffsets(keepOffsets);
t.actionList = actionDecoder.decode(length);
return t;
}
private Tag decodeDefineText(int type) throws IOException
{
DefineText t = new DefineText(type);
int id = r.readUI16();
t.bounds = decodeRect();
t.matrix = decodeMatrix();
int glyphBits = r.readUI8();
int advanceBits = r.readUI8();
// todo range check - glyphBits and advanceBits must be <= 32
ArrayList<TextRecord> list = new ArrayList<TextRecord>(2);
int code;
while ((code = r.readUI8()) != 0)
{
list.add(decodeTextRecord(type, code, glyphBits, advanceBits));
}
t.records = list;
dict.add(id, t);
return t;
}
private GlyphEntry[] decodeGlyphEntries(int glyphBits, int advanceBits, int count) throws IOException
{
GlyphEntry[] e = new GlyphEntry[count];
r.syncBits();
for (int i = 0; i < count; i++)
{
GlyphEntry ge = new GlyphEntry();
ge.setIndex( r.readUBits(glyphBits) );
ge.advance = r.readSBits(advanceBits);
e[i] = ge;
}
return e;
}
private TextRecord decodeTextRecord(int defineText, int flags, int glyphBits, int advanceBits) throws IOException
{
TextRecord t = new TextRecord();
t.flags = flags;
if (t.hasFont())
{
int idref = r.readUI16();
t.font = (DefineFont) dict.getTag(idref);
}
if (t.hasColor())
{
switch (defineText)
{
case stagDefineText:
t.color = decodeRGB(r);
break;
case stagDefineText2:
t.color = decodeRGBA(r);
break;
default:
assert false;
}
}
if (t.hasX())
{
t.xOffset = r.readSI16();
}
if (t.hasY())
{
t.yOffset = r.readSI16();
}
if (t.hasHeight())
{
t.height = r.readUI16();
}
int count = r.readUI8();
t.entries = decodeGlyphEntries(glyphBits, advanceBits, count);
return t;
}
private Tag decodeDefineFont() throws IOException
{
DefineFont1 t;
t = new DefineFont1();
int id = r.readUI16();
int offset = r.readUI16();
int numGlyphs = offset/2;
t.glyphShapeTable = new Shape[numGlyphs];
// skip the offset table
for (int i = 1; i < numGlyphs; i++)
{
r.readUI16();
}
for (int i = 0; i < numGlyphs; i++)
{
t.glyphShapeTable[i] = decodeShape(stagDefineShape3);
}
dict.add(id, t);
dict.addFontFace( t );
return t;
}
private Tag decodeSetBackgroundColor() throws IOException
{
SetBackgroundColor t;
t = new SetBackgroundColor( decodeRGB(r));
return t;
}
/**
* decode jpeg tables. only one per movie. second and subsequent
* occurences of this tag are ignored by the player.
* @param length
* @return
* @throws IOException
*/
private GenericTag decodeJPEGTables(int length) throws IOException
{
GenericTag t;
t = new GenericTag(stagJPEGTables);
t.data = new byte[length];
r.readFully(t.data);
return t;
}
private Tag decodeDefineButton(int length) throws IOException
{
int startPos = r.getOffset();
DefineButton t;
t = new DefineButton(stagDefineButton);
int id = r.readUI16();
ArrayList<ButtonRecord> list = new ArrayList<ButtonRecord>();
ButtonRecord record;
do
{
record = decodeButtonRecord(t.code);
if (record != null)
{
list.add(record);
}
}
while (record != null);
t.buttonRecords = new ButtonRecord[list.size()];
list.toArray(t.buttonRecords);
// old school button actions only handle one possible transition
int consumed = r.getOffset()-startPos;
t.condActions = new ButtonCondAction[1];
t.condActions[0].overDownToOverUp = true;
ActionDecoder actionDecoder = new ActionDecoder(r,swd);
actionDecoder.setKeepOffsets(keepOffsets);
t.condActions[0].actionList = actionDecoder.decode(length-consumed);
t.trackAsMenu = false;
dict.add(id, t);
return t;
}
private ButtonRecord decodeButtonRecord(int type) throws IOException
{
boolean hasFilterList = false, hasBlendMode = false;
ButtonRecord b = new ButtonRecord();
r.syncBits();
int reserved;
if (type == stagDefineButton2)
{
reserved = r.readUBits(2);
hasBlendMode = r.readBit();
hasFilterList = r.readBit();
}
else
{
reserved = r.readUBits(4);
}
b.hitTest = r.readBit();
b.down = r.readBit();
b.over = r.readBit();
b.up = r.readBit();
if (reserved == 0 && !b.hitTest && !b.down && !b.over && !b.up)
{
return null;
}
int idref = r.readUI16();
b.characterRef = dict.getTag(idref);
b.placeDepth = r.readUI16();
b.placeMatrix = decodeMatrix();
if (type == stagDefineButton2)
{
b.colorTransform = decodeCxforma();
if (hasFilterList)
{
b.filters = decodeFilterList();
}
if (hasBlendMode)
{
b.blendMode = r.readUI8();
}
}
return b;
}
private Tag decodeDefineBinaryData(int length) throws IOException
{
DefineBinaryData t = new DefineBinaryData();
int pos = r.getOffset();
int id = r.readUI16();
t.reserved = r.readSI32();
length -= r.getOffset() - pos;
t.data = new byte[length];
r.readFully(t.data);
dict.add(id, t);
return t;
}
private Tag decodeDefineBits(int length) throws IOException
{
DefineBits t;
t = new DefineBits(stagDefineBits);
int pos = r.getOffset();
int id = r.readUI16();
length -= r.getOffset() - pos;
t.data = new byte[length];
r.readFully(t.data);
t.jpegTables = jpegTables;
dict.add(id, t);
return t;
}
private Tag decodeRemoveObject(int code) throws IOException
{
RemoveObject t;
t = new RemoveObject(code);
if (code == stagRemoveObject)
{
int idref = r.readUI16();
t.ref = dict.getTag(idref);
}
t.depth = r.readUI16();
return t;
}
private CXForm decodeCxform() throws IOException
{
CXForm c = new CXForm();
r.syncBits();
c.hasAdd = r.readBit();
c.hasMult = r.readBit();
int nbits = r.readUBits(4);
if (c.hasMult)
{
c.redMultTerm = r.readSBits(nbits);
c.greenMultTerm = r.readSBits(nbits);
c.blueMultTerm = r.readSBits(nbits);
}
if (c.hasAdd)
{
c.redAddTerm = r.readSBits(nbits);
c.greenAddTerm = r.readSBits(nbits);
c.blueAddTerm = r.readSBits(nbits);
}
return c;
}
private Tag decodeMetadata() throws IOException
{
Metadata t = new Metadata();
t.xml = r.readString();
return t;
}
private Tag decodeDefineShape(int shape) throws IOException
{
DefineShape t = new DefineShape(shape);
int id = r.readUI16();
t.bounds = decodeRect();
if (shape == stagDefineShape4)
{
t.edgeBounds = decodeRect();
r.readUBits(5);
t.usesFillWindingRule = r.readBit();
t.usesNonScalingStrokes = r.readBit();
t.usesScalingStrokes = r.readBit();
}
t.shapeWithStyle = decodeShapeWithStyle(shape);
dict.add(id, t);
return t;
}
private ShapeWithStyle decodeShapeWithStyle(int shape) throws IOException
{
ShapeWithStyle sw = new ShapeWithStyle();
r.syncBits();
sw.fillstyles = decodeFillstyles(shape);
sw.linestyles = decodeLinestyles(shape);
Shape s = decodeShape(shape);
sw.shapeRecords = s.shapeRecords;
return sw;
}
private ArrayList<LineStyle> decodeLinestyles(int shape) throws IOException
{
ArrayList<LineStyle> a = new ArrayList<LineStyle>();
int count = r.readUI8();
if (count == 0xFF)
{
count = r.readUI16();
}
for (int i = 0; i < count; i++)
{
a.add(decodeLineStyle(shape));
}
return a;
}
private LineStyle decodeLineStyle(int shape) throws IOException
{
LineStyle s = new LineStyle();
s.width = r.readUI16();
if (shape == stagDefineShape4)
{
s.flags = r.readUI16();
if (s.hasMiterJoint())
s.miterLimit = r.readUI16(); // 8.8 fixedpoint
}
if ((shape == stagDefineShape4) && (s.hasFillStyle()))
{
s.fillStyle = decodeFillStyle(shape);
}
else if ((shape == stagDefineShape3) || (shape == stagDefineShape4))
{
s.color = decodeRGBA(r);
}
else
{
s.color = decodeRGB(r);
}
return s;
}
private ArrayList<FillStyle> decodeFillstyles(int shape) throws IOException
{
ArrayList<FillStyle> a = new ArrayList<FillStyle>();
int count = r.readUI8();
if (count == 0xFF)
{
count = r.readUI16();
}
for (int i = 0; i < count; i++)
{
a.add(decodeFillStyle(shape));
}
return a;
}
private FillStyle decodeFillStyle(int shape) throws IOException
{
FillStyle s = new FillStyle();
s.type = r.readUI8();
switch (s.type)
{
case FillStyle.FILL_SOLID: // 0x00
if (shape == stagDefineShape3 || shape == stagDefineShape4)
s.color = decodeRGBA(r);
else if (shape == stagDefineShape2 || shape == stagDefineShape)
s.color = decodeRGB(r);
else
throw new SwfFormatException("bad shape code");
break;
case FillStyle.FILL_GRADIENT: // 0x10 linear gradient fill
case FillStyle.FILL_RADIAL_GRADIENT: // 0x12 radial gradient fill
case FillStyle.FILL_FOCAL_RADIAL_GRADIENT: // 0x13 focal radial gradient fill
s.matrix = decodeMatrix();
s.gradient = decodeGradient(shape, s.type);
break;
case FillStyle.FILL_BITS: // 0x40 tiled bitmap fill
case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP): // 0x41 clipped bitmap fill
case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_NOSMOOTH): // 0x42 tiled non-smoothed fill
case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP | FillStyle.FILL_BITS_NOSMOOTH): // 0x43 clipped non-smoothed fill
int idref = r.readUI16();
try
{
s.bitmap = dict.getTag(idref);
}
catch (IllegalArgumentException e)
{
s.bitmap = null;
handler.error(e.getMessage());
}
s.matrix = decodeMatrix();
break;
default:
throw new SwfFormatException("unrecognized fill style type: " + s.type);
}
return s;
}
private Gradient decodeGradient(int shape, int filltype) throws IOException
{
Gradient gradient = (filltype == FillStyle.FILL_FOCAL_RADIAL_GRADIENT)? new FocalGradient() : new Gradient();
r.syncBits();
gradient.spreadMode = r.readUBits( 2 );
gradient.interpolationMode = r.readUBits( 2 );
int count = r.readUBits( 4 );
gradient.records = new GradRecord[count];
for (int i = 0; i < count; i++)
{
gradient.records[i] = decodeGradRecord(shape);
}
if (filltype == FillStyle.FILL_FOCAL_RADIAL_GRADIENT)
{
((FocalGradient)gradient).focalPoint = r.readFixed8();
}
return gradient;
}
private GradRecord decodeGradRecord(int shape) throws IOException
{
GradRecord g = new GradRecord();
g.ratio = r.readUI8();
switch (shape)
{
case stagDefineShape:
case stagDefineShape2:
g.color = decodeRGB(r);
break;
case stagDefineShape3:
case stagDefineShape4:
g.color = decodeRGBA(r);
break;
}
return g;
}
private Matrix decodeMatrix() throws IOException
{
Matrix m = new Matrix();
r.syncBits();
m.hasScale = r.readBit();
if (m.hasScale)
{
int nScaleBits = r.readUBits(5);
m.scaleX = r.readSBits(nScaleBits);
m.scaleY = r.readSBits(nScaleBits);
}
m.hasRotate = r.readBit();
if (m.hasRotate)
{
int nRotateBits = r.readUBits(5);
m.rotateSkew0 = r.readSBits(nRotateBits);
m.rotateSkew1 = r.readSBits(nRotateBits);
}
int nTranslateBits = r.readUBits(5);
m.translateX = r.readSBits(nTranslateBits);
m.translateY = r.readSBits(nTranslateBits);
return m;
}
private int decodeRGBA(SwfDecoder r) throws IOException
{
int color = r.readUI8() << 16; // red
color |= r.readUI8() << 8; // green
color |= r.readUI8(); // blue
color |= r.readUI8() << 24; // alpha
// resulting format is 0xAARRGGBB
return color;
}
private int decodeRGB(SwfDecoder r) throws IOException
{
int color = r.readUI8() << 16; // red
color |= r.readUI8()<<8; // green
color |= r.readUI8(); // blue
// resulting format is 0x00RRGGBB
return color;
}
private Shape decodeGlyph(int shape, int count) throws IOException
{
Shape s1 = new Shape();
r.syncBits();
// SDK-18153 - Hack to work around third-party generated SWFs that
// do not include at least one shape record in glyph SHAPE.
if (count > 0)
{
// we use int[1] so we can pass numBits by reference
int[] numFillBits = new int[] { r.readUBits(4) };
int[] numLineBits = new int[] { r.readUBits(4) };
if (count > 1)
{
s1.shapeRecords = decodeShapeRecords(shape, numFillBits, numLineBits);
}
}
return s1;
}
private Shape decodeShape(int shape) throws IOException
{
Shape s1 = new Shape();
r.syncBits();
// we use int[1] so we can pass numBits by reference
int[] numFillBits = new int[] { r.readUBits(4) };
int[] numLineBits = new int[] { r.readUBits(4) };
s1.shapeRecords = decodeShapeRecords(shape, numFillBits, numLineBits);
return s1;
}
private List<ShapeRecord> decodeShapeRecords(int shape, int[] numFillBits, int[] numLineBits) throws IOException
{
ArrayList<ShapeRecord> list = new ArrayList<ShapeRecord>();
boolean endShapeRecord = false;
do
{
if (r.readBit())
{
// edge
if (r.readBit())
{
// line
list.add(decodeStraightEdgeRecord());
}
else
{
// curve
list.add(decodeCurvedEdgeRecord());
}
}
else
{
// style change
boolean stateNewStyles = r.readBit();
boolean stateLineStyle = r.readBit();
boolean stateFillStyle1 = r.readBit();
boolean stateFillStyle0 = r.readBit();
boolean stateMoveTo = r.readBit();
if (stateNewStyles || stateLineStyle || stateFillStyle1 ||
stateFillStyle0 || stateMoveTo)
{
StyleChangeRecord s = decodeStyleChangeRecord(stateNewStyles, stateLineStyle,
stateFillStyle1, stateFillStyle0, stateMoveTo,
shape, numFillBits, numLineBits);
list.add(s);
}
else
{
endShapeRecord = true;
}
}
}
while (!endShapeRecord);
return list;
}
private CurvedEdgeRecord decodeCurvedEdgeRecord() throws IOException
{
CurvedEdgeRecord s = new CurvedEdgeRecord();
int nbits = 2+r.readUBits(4);
s.controlDeltaX = r.readSBits(nbits);
s.controlDeltaY = r.readSBits(nbits);
s.anchorDeltaX = r.readSBits(nbits);
s.anchorDeltaY = r.readSBits(nbits);
return s;
}
private StraightEdgeRecord decodeStraightEdgeRecord() throws IOException
{
int nbits = 2+r.readUBits(4);
if (r.readBit())
{
// general line
int dx = r.readSBits(nbits);
int dy = r.readSBits(nbits);
return new StraightEdgeRecord(dx, dy);
}
else
{
if (r.readBit())
{
// vertical
int dy = r.readSBits(nbits);
return new StraightEdgeRecord(0, dy);
}
else
{
// horizontal
int dx = r.readSBits(nbits);
return new StraightEdgeRecord(dx, 0);
}
}
}
private StyleChangeRecord decodeStyleChangeRecord(boolean stateNewStyles,
boolean stateLineStyle,
boolean stateFillStyle1,
boolean stateFillStyle0,
boolean stateMoveTo,
int shape,
int[] numFillBits,
int[] numLineBits) throws IOException
{
StyleChangeRecord s = new StyleChangeRecord();
s.stateNewStyles = stateNewStyles;
s.stateLineStyle = stateLineStyle;
s.stateFillStyle1 = stateFillStyle1;
s.stateFillStyle0 = stateFillStyle0;
s.stateMoveTo = stateMoveTo;
if (s.stateMoveTo)
{
int moveBits = r.readUBits(5);
s.moveDeltaX = r.readSBits(moveBits);
s.moveDeltaY = r.readSBits(moveBits);
}
if (s.stateFillStyle0)
{
s.fillstyle0 = r.readUBits(numFillBits[0]);
}
if (s.stateFillStyle1)
{
s.fillstyle1 = r.readUBits(numFillBits[0]);
}
if (s.stateLineStyle)
{
s.linestyle = r.readUBits(numLineBits[0]);
}
if (s.stateNewStyles)
{
s.fillstyles = decodeFillstyles(shape);
s.linestyles = decodeLinestyles(shape);
r.syncBits();
numFillBits[0] = r.readUBits(4);
numLineBits[0] = r.readUBits(4);
}
return s;
}
private Tag decodeDefineSprite(int endpos) throws IOException
{
DefineSprite t = new DefineSprite();
t.header = header;
int id = r.readUI16();
t.framecount = r.readUI16();
decodeTags(t.tagList);
while (r.getOffset() < endpos)
{
// extra data at end of sprite. must be zero
int b = r.readUI8();
if (b != 0)
{
throw new SwfFormatException("nonzero data past end of sprite");
}
}
dict.add(id, t);
return t;
}
public Tag decodeSerialNumber() throws IOException
{
int product = r.readSI32();
int edition = r.readSI32();
byte[] version = new byte[2];
r.read(version);
byte majorVersion = version[0];
byte minorVersion = version[1];
long build = r.read64();
long compileDate = r.read64();
return new ProductInfo(product, edition, majorVersion, minorVersion, build, compileDate);
}
public Header decodeHeader() throws IOException, FatalParseException
{
Header header = new Header();
byte[] sig = new byte[8];
new DataInputStream(swfIn).readFully(sig);
header.version = sig[3];
header.length = sig[4]&0xFF | (sig[5]&0xFF)<<8 | (sig[6]&0xFF)<<16 | sig[7]<<24;
if (sig[0] == 'C' && sig[1] == 'W' && sig[2] == 'S')
{
header.compressed = true;
r = new SwfDecoder(new InflaterInputStream(swfIn), header.version, 8);
}
else if (sig[0] == 'F' || sig[1] == 'W' || sig[2] == 'S')
{
r = new SwfDecoder(swfIn, header.version, 8);
}
else
{
handler.error("Invalid signature found. Not a SWF file");
throw new FatalParseException();
}
header.size = decodeRect();
header.rate = r.readUI8() << 8 | r.readUI8();
header.framecount = r.readUI16();
return header;
}
public Tag decodeFileAttributes() throws IOException
{
FileAttributes tag = new FileAttributes();
r.syncBits();
r.readUBits(1); //reserved
tag.useDirectBlit = r.readBit();
tag.useGPU = r.readBit();
tag.hasMetadata = r.readBit();
tag.actionScript3 = r.readBit();
tag.suppressCrossDomainCaching = r.readBit();
tag.swfRelativeUrls = r.readBit();
tag.useNetwork = r.readBit();
tag.brokerProductManager = r.readBit();
tag.brokerLocalConnection = r.readBit();
r.readUBits(22); //reserved
return tag;
}
public Tag decodeEnableTelemetry() throws IOException
{
EnableTelemetry tag = new EnableTelemetry();
r.syncBits();
r.readUBits(16); //reserved
tag.enabled = true;
return tag;
}
public Tag decodeDefineFontAlignZones() throws IOException
{
DefineFontAlignZones zones = new DefineFontAlignZones();
int fontID = r.readUI16();
zones.font = (DefineFont3)dict.getTag(fontID);
zones.font.zones = zones;
zones.csmTableHint = r.readUBits(2);
r.readUBits(6); // reserved
zones.zoneTable = new ZoneRecord[zones.font.glyphShapeTable.length];
for (int i = 0; i < zones.font.glyphShapeTable.length; i++)
{
ZoneRecord record = new ZoneRecord();
zones.zoneTable[i] = record;
record.numZoneData = r.readUI8();
record.zoneData = new long[record.numZoneData];
for (int j = 0; j < record.numZoneData; j++)
{
record.zoneData[j] = r.readUI32();
}
record.zoneMask = r.readUI8();
}
return zones;
}
public Tag decodeCSMTextSettings() throws IOException
{
CSMTextSettings tag = new CSMTextSettings();
int textID = r.readUI16();
if (textID != 0)
{
tag.textReference = dict.getTag(textID);
if (tag.textReference instanceof DefineText)
{
((DefineText)tag.textReference).csmTextSettings = tag;
}
else if (tag.textReference instanceof DefineEditText)
{
((DefineEditText)tag.textReference).csmTextSettings = tag;
}
else
{
handler.error("CSMTextSettings' textID must reference a valid DefineText or DefineEditText. References " + tag.textReference);
}
}
tag.styleFlagsUseSaffron = r.readUBits(2);
tag.gridFitType = r.readUBits(3);
r.readUBits(3); // reserved
// FIXME: thickness/sharpness should be read in as 32 bit IEEE Single Precision format in little Endian
tag.thickness = r.readUBits(32);
tag.sharpness = r.readUBits(32);
r.readUBits(8); // reserved
return tag;
}
public Tag decodeDefineFontName() throws IOException
{
DefineFontName tag = new DefineFontName();
int fontID = r.readUI16();
tag.font = (DefineFont)dict.getTag(fontID);
tag.font.license = tag;
tag.fontName = r.readString();
tag.copyright = r.readString();
return tag;
}
private Rect decodeRect() throws IOException
{
r.syncBits();
Rect rect = new Rect();
int nBits = r.readUBits(5);
rect.xMin = r.readSBits(nBits);
rect.xMax = r.readSBits(nBits);
rect.yMin = r.readSBits(nBits);
rect.yMax = r.readSBits(nBits);
return rect;
}
}
|
apache/flex-sdk
|
modules/swfutils/src/java/flash/swf/TagDecoder.java
|
Java
|
apache-2.0
| 84,326
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.uiDesigner.propertyInspector.properties;
import com.intellij.openapi.project.Project;
import com.intellij.uiDesigner.core.AbstractLayout;
import com.intellij.uiDesigner.radComponents.RadContainer;
import java.awt.*;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
* @author yole
*/
public final class HGapProperty extends AbstractIntProperty<RadContainer> {
public static HGapProperty getInstance(Project project) {
return project.getService(HGapProperty.class);
}
public HGapProperty(){
super(null, "Horizontal Gap", -1);
}
@Override
public Integer getValue(final RadContainer component){
if (component.getLayout() instanceof BorderLayout) {
BorderLayout layout = (BorderLayout) component.getLayout();
return layout.getHgap();
}
if (component.getLayout() instanceof FlowLayout) {
FlowLayout layout = (FlowLayout) component.getLayout();
return layout.getHgap();
}
if (component.getLayout() instanceof CardLayout) {
CardLayout layout = (CardLayout) component.getLayout();
return layout.getHgap();
}
if (component.getLayout() instanceof AbstractLayout) {
final AbstractLayout layoutManager=(AbstractLayout)component.getLayout();
return layoutManager.getHGap();
}
return null;
}
@Override
protected void setValueImpl(final RadContainer component, final Integer value) throws Exception{
if (component.getLayout() instanceof BorderLayout) {
BorderLayout layout = (BorderLayout) component.getLayout();
layout.setHgap(value.intValue());
}
else if (component.getLayout() instanceof FlowLayout) {
FlowLayout layout = (FlowLayout) component.getLayout();
layout.setHgap(value.intValue());
}
else if (component.getLayout() instanceof CardLayout) {
CardLayout layout = (CardLayout) component.getLayout();
layout.setHgap(value.intValue());
}
else {
final AbstractLayout layoutManager=(AbstractLayout)component.getLayout();
layoutManager.setHGap(value.intValue());
}
}
@Override protected int getDefaultValue(final RadContainer radContainer) {
return getDefaultGap(radContainer.getLayout());
}
static int getDefaultGap(final LayoutManager layout) {
if (layout instanceof FlowLayout) {
return 5;
}
if (layout instanceof BorderLayout || layout instanceof CardLayout) {
return 0;
}
return -1;
}
}
|
ingokegel/intellij-community
|
plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/HGapProperty.java
|
Java
|
apache-2.0
| 2,599
|
/**
*
* 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.airavata.gfac.core;/*
*
* 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.
*
*/
public enum Script {
SHELL_NAME("shellName"),
QUEUE_NAME("queueName"),
NODES("nodes"),
CPU_COUNT("cpuCount"),
MAIL_ADDRESS("mailAddress"),
ACCOUNT_STRING("accountString"),
MAX_WALL_TIME("maxWallTime"),
JOB_NAME("jobName"),
STANDARD_OUT_FILE("standardOutFile"),
STANDARD_ERROR_FILE("standardErrorFile"),
QUALITY_OF_SERVICE("qualityOfService"),
RESERVATION("reservation"),
EXPORTS("exports"),
MODULE_COMMANDS("moduleCommands"),
SCRATCH_LOCATION("scratchLocation"),
WORKING_DIR("workingDirectory"),
PRE_JOB_COMMANDS("preJobCommands"),
JOB_SUBMITTER_COMMAND("jobSubmitterCommand"),
EXECUTABLE_PATH("executablePath"),
INPUTS("inputs"),
POST_JOB_COMMANDS("postJobCommands"),
USED_MEM("usedMem"),
PROCESS_PER_NODE("processPerNode"),
CHASSIS_NAME("chassisName"),
INPUT_DIR("inputDir"),
OUTPUT_DIR("outputDir"),
USER_NAME("userName"),
GATEWAY_ID("gatewayId"),
GATEWAY_USER_NAME("gatewayUserName"),
APPLICATION_NAME("applicationName"),
;
String name;
Script(String name) {
this.name = name;
}
}
|
machristie/airavata
|
modules/gfac/gfac-core/src/main/java/org/apache/airavata/gfac/core/Script.java
|
Java
|
apache-2.0
| 2,796
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>BaseTen Reference Manual</title>
<link href="documentation.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="logo-container">
<a id="logo" href="index.html">
<img src="http://basetenframework.org/chrome/site/trac_banner.png" alt="">
</a>
</div>
<div class="container">
<!-- Generated by Doxygen 1.8.8 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="class_b_x_object_status_info-members.html">List of all members</a> |
<a href="#pub-methods">Instance Methods</a> </div>
<div class="headertitle">
<div class="title">BXObjectStatusInfo Class Reference<div class="ingroups"><a class="el" href="group__baseten.html">BaseTen</a></div></div> </div>
</div><!--header-->
<div class="contents">
<a name="details" id="details"></a><h2 class="groupheader">Overview</h2>
<div class="textblock"><p>A proxy for retrieving database object status. </p>
<dl class="section see"><dt>See also</dt><dd>ValueTransformers </dd></dl>
</div><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Instance Methods</h2></td></tr>
<tr class="memitem:abdddcca55c0a3e7dab4145481c8b594c"><td class="memItemLeft" align="right" valign="top">(id) </td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_b_x_object_status_info.html#abdddcca55c0a3e7dab4145481c8b594c">valueForKey:</a></td></tr>
<tr class="separator:abdddcca55c0a3e7dab4145481c8b594c"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Method Documentation</h2>
<a class="anchor" id="abdddcca55c0a3e7dab4145481c8b594c"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">- (id) valueForKey: </td>
<td></td>
<td class="paramtype">(NSString *) </td>
<td class="paramname"><em>aKey</em></td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Returns a status constant for the given key. </p>
<p>The constant may then be passed to value transformers in BaseTenAppKit. </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">aKey</td><td>An NSString that corresponds to a field name. </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An NSValue that contains the constant. </dd></dl>
</div>
</div>
<hr/>The documentation for this class was generated from the following files:<ul>
<li>BXObjectStatusInfo.h</li>
<li>BXObjectStatusInfo.m</li>
</ul>
</div><!-- contents -->
</div>
<div class="footer"></div>
</body>
</html>
|
gservera/baseten
|
Documentation/html/interface_b_x_object_status_info.html
|
HTML
|
apache-2.0
| 3,601
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
/// <summary>
/// This service provides a central place where the workspace/project system layer may create
/// Document objects that represent items from the project system. These IDocuments are useful
/// in that they watch the running document table, tracking open/close events, and also file
/// change events while the file is closed.
/// </summary>
internal sealed partial class DocumentProvider : ForegroundThreadAffinitizedObject
{
#region Immutable readonly fields/properties that can be accessed from foreground or background threads - do not need locking for access.
private readonly object _gate = new object();
private readonly uint _runningDocumentTableEventCookie;
private readonly VisualStudioProjectTracker _projectTracker;
private readonly IVsFileChangeEx _fileChangeService;
private readonly IVsTextManager _textManager;
private readonly IVsRunningDocumentTable4 _runningDocumentTable;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly VisualStudioDocumentTrackingService _documentTrackingServiceOpt;
#endregion
#region Mutable fields accessed from foreground or background threads - need locking for access.
/// <summary>
/// The core data structure of this entire class.
/// </summary>
private readonly Dictionary<DocumentKey, StandardTextDocument> _documentMap = new Dictionary<DocumentKey, StandardTextDocument>();
private readonly Dictionary<uint, List<DocumentKey>> _docCookiesToOpenDocumentKeys = new Dictionary<uint, List<DocumentKey>>();
private readonly Dictionary<uint, ITextBuffer> _docCookiesToNonRoslynDocumentBuffers = new Dictionary<uint, ITextBuffer>();
private readonly Dictionary<string, DocumentId> _documentIdHints = new Dictionary<string, DocumentId>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<DocumentId, TaskAndTokenSource> _pendingDocumentInitializationTasks = new Dictionary<DocumentId, TaskAndTokenSource>();
#endregion
/// <summary>
/// Creates a document provider.
/// </summary>
/// <param name="serviceProvider">Service provider</param>
/// <param name="documentTrackingService">An optional <see cref="VisualStudioDocumentTrackingService"/> to track active and visible documents.</param>
public DocumentProvider(
VisualStudioProjectTracker projectTracker,
IServiceProvider serviceProvider,
VisualStudioDocumentTrackingService documentTrackingService)
{
var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
_projectTracker = projectTracker;
this._documentTrackingServiceOpt = documentTrackingService;
this._runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
this._editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
this._contentTypeRegistryService = componentModel.GetService<IContentTypeRegistryService>();
_textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));
_fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx));
var shell = (IVsShell)serviceProvider.GetService(typeof(SVsShell));
if (shell == null)
{
// This can happen only in tests, bail out.
return;
}
var runningDocumentTableForEvents = (IVsRunningDocumentTable)_runningDocumentTable;
Marshal.ThrowExceptionForHR(runningDocumentTableForEvents.AdviseRunningDocTableEvents(new RunningDocTableEventsSink(this), out _runningDocumentTableEventCookie));
}
[Obsolete("This overload is a compatibility shim for TypeScript; please do not use it.")]
public IVisualStudioHostDocument TryGetDocumentForFile(
IVisualStudioHostProject hostProject,
string filePath,
SourceCodeKind sourceCodeKind,
Func<ITextBuffer, bool> canUseTextBuffer,
Func<uint, IReadOnlyList<string>> getFolderNames,
EventHandler updatedOnDiskHandler = null,
EventHandler<bool> openedHandler = null,
EventHandler<bool> closingHandler = null)
{
return TryGetDocumentForFile(
(AbstractProject)hostProject,
filePath,
sourceCodeKind,
canUseTextBuffer,
getFolderNames,
updatedOnDiskHandler,
openedHandler,
closingHandler);
}
/// <summary>
/// Gets the <see cref="IVisualStudioHostDocument"/> for the file at the given filePath.
/// If we are on the foreground thread and this document is already open in the editor,
/// then we also attempt to associate the text buffer with it.
/// Otherwise, if we are on a background thread, then this text buffer association will happen on a scheduled task
/// whenever <see cref="NotifyDocumentRegisteredToProjectAndStartToRaiseEvents"/> is invoked for the returned document.
/// </summary>
public IVisualStudioHostDocument TryGetDocumentForFile(
AbstractProject hostProject,
string filePath,
SourceCodeKind sourceCodeKind,
Func<ITextBuffer, bool> canUseTextBuffer,
Func<uint, IReadOnlyList<string>> getFolderNames,
EventHandler updatedOnDiskHandler = null,
EventHandler<bool> openedHandler = null,
EventHandler<bool> closingHandler = null)
{
var documentKey = new DocumentKey(hostProject, filePath);
StandardTextDocument document;
lock (_gate)
{
if (_documentMap.TryGetValue(documentKey, out document))
{
return document;
}
}
ITextBuffer openTextBuffer = null;
uint foundCookie = VSConstants.VSCOOKIE_NIL;
if (IsForeground())
{
// If we are on the foreground thread and this document is already open in the editor we want to associate the text buffer with it.
// Otherwise, we are on a background thread, and this text buffer association will happen on a scheduled task
// whenever NotifyDocumentRegisteredToProjectAndStartToRaiseEvents is invoked for the returned document.
// However, determining if a document is already open is a bit complicated. With the introduction
// of the lazy tabs feature in Dev12, a document may be open (i.e. it has a tab in the shell) but not
// actually initialized (no data has been loaded for it because its contents have not actually been
// viewed or used). We only care about documents that are open AND initialized.
// That means we can't call IVsRunningDocumentTable::FindAndLockDocument to find the document; if the
// document is open but not initialized, the call will force initialization. This is bad for two
// reasons:
// 1.) It circumvents lazy tabs for any document that is part of a VB or C# project.
// 2.) Initialization may cause a whole host of other code to run synchronously, such as taggers.
// Instead, we check if the document is already initialized, and avoid asking for the doc data and
// hierarchy if it is not.
if (_runningDocumentTable.TryGetCookieForInitializedDocument(documentKey.Moniker, out foundCookie))
{
object foundDocData = _runningDocumentTable.GetDocumentData(foundCookie);
openTextBuffer = TryGetTextBufferFromDocData(foundDocData);
if (openTextBuffer == null)
{
// We're open but not open as a normal text buffer. This can happen if the
// project system (say in ASP.NET cases) is telling us to add a file which
// actually isn't a normal text file at all.
return null;
}
if (!canUseTextBuffer(openTextBuffer))
{
return null;
}
}
}
lock (_gate)
{
// If this is being added through a public call to Workspace.AddDocument (say, ApplyChanges) then we might
// already have a document ID that we should be using here.
_documentIdHints.TryGetValue(filePath, out var id);
document = new StandardTextDocument(
this,
hostProject,
documentKey,
getFolderNames,
sourceCodeKind,
_fileChangeService,
openTextBuffer,
id,
updatedOnDiskHandler,
openedHandler,
closingHandler);
// Add this to our document map
_documentMap.Add(documentKey, document);
if (openTextBuffer != null)
{
AddCookieOpenDocumentPair_NoLock(foundCookie, documentKey);
}
}
return document;
}
/// <summary>
/// Tries to return an ITextBuffer representing the document from the document's DocData.
/// </summary>
/// <param name="docData">The DocData from the running document table.</param>
/// <returns>The ITextBuffer. If one could not be found, this returns null.</returns>
private ITextBuffer TryGetTextBufferFromDocData(object docData)
{
AssertIsForeground();
if (docData is IVsTextBuffer shimTextBuffer)
{
return _editorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);
}
else
{
return null;
}
}
private void NewBufferOpened(uint docCookie, ITextBuffer textBuffer, DocumentKey documentKey, bool isCurrentContext)
{
AssertIsForeground();
lock (_gate)
{
NewBufferOpened_NoLock(docCookie, textBuffer, documentKey, isCurrentContext);
}
}
private void NewBufferOpened_NoLock(uint docCookie, ITextBuffer textBuffer, DocumentKey documentKey, bool isCurrentContext)
{
if (_documentMap.TryGetValue(documentKey, out var document))
{
document.ProcessOpen(textBuffer, isCurrentContext);
AddCookieOpenDocumentPair_NoLock(docCookie, documentKey);
}
}
/// <summary>
/// Notifies the document provider that this document is now registered in a project.
/// If we are on a foregroud thread, then this is done right away.
/// Otherwise, we schedule a task on foreground task scheduler.
/// </summary>
public void NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(IVisualStudioHostDocument document)
{
if (IsForeground())
{
NotifyDocumentRegisteredToProjectAndStartToRaiseEvents_Core(document, cancellationToken: CancellationToken.None);
}
else
{
var cts = new CancellationTokenSource();
var task = InvokeBelowInputPriority(() => NotifyDocumentRegisteredToProjectAndStartToRaiseEvents_Core(document, cts.Token), cts.Token);
AddPendingDocumentInitializationTask(document, task, cts);
}
}
private void AddPendingDocumentInitializationTask(IVisualStudioHostDocument document, Task task, CancellationTokenSource cts)
{
var taskAndTokenSource = new TaskAndTokenSource() { Task = task, CancellationTokenSource = cts };
lock (_gate)
{
// Add taskAndTokenSource to the pending document initialization tasks.
// Check for cancellation before adding as the task might already have been completed/cancelled/faulted before we reached here.
if (!cts.IsCancellationRequested && !task.IsCompleted)
{
_pendingDocumentInitializationTasks.Add(document.Id, taskAndTokenSource);
}
}
}
private void CancelPendingDocumentInitializationTasks_NoLock(IEnumerable<DocumentKey> documentKeys)
{
foreach (var documentKey in documentKeys)
{
if (_documentMap.TryGetValue(documentKey, out var document))
{
CancelPendingDocumentInitializationTask_NoLock(document);
}
}
}
private void CancelPendingDocumentInitializationTask(IVisualStudioHostDocument document)
{
lock (_gate)
{
CancelPendingDocumentInitializationTask_NoLock(document);
}
}
private void CancelPendingDocumentInitializationTask_NoLock(IVisualStudioHostDocument document)
{
// Remove pending initialization task for the document, if any, and dispose the cancellation token source.
if (_pendingDocumentInitializationTasks.TryGetValue(document.Id, out var taskAndTokenSource))
{
taskAndTokenSource.CancellationTokenSource.Cancel();
taskAndTokenSource.CancellationTokenSource.Dispose();
_pendingDocumentInitializationTasks.Remove(document.Id);
}
}
private void NotifyDocumentRegisteredToProjectAndStartToRaiseEvents_Core(IVisualStudioHostDocument document, CancellationToken cancellationToken)
{
AssertIsForeground();
cancellationToken.ThrowIfCancellationRequested();
// Ignore any other unknown kinds of documents
var standardDocument = document as StandardTextDocument;
if (standardDocument == null)
{
return;
}
// If it's already open, then we have nothing more to do here.
if (standardDocument.IsOpen)
{
return;
}
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.Key.Moniker, out var docCookie))
{
TryProcessOpenForDocCookie(docCookie, cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
CancelPendingDocumentInitializationTask(document);
}
private void TryProcessOpenForDocCookie(uint docCookie, CancellationToken cancellationToken)
{
AssertIsForeground();
lock (_gate)
{
cancellationToken.ThrowIfCancellationRequested();
TryProcessOpenForDocCookie_NoLock(docCookie);
}
}
private void TryProcessOpenForDocCookie_NoLock(uint docCookie)
{
string moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
_runningDocumentTable.GetDocumentHierarchyItem(docCookie, out var hierarchy, out var itemid);
if (_runningDocumentTable.GetDocumentData(docCookie) is IVsTextBuffer shimTextBuffer)
{
var hasAssociatedRoslynDocument = false;
foreach (var project in _projectTracker.ImmutableProjects)
{
var documentKey = new DocumentKey(project, moniker);
if (_documentMap.ContainsKey(documentKey))
{
hasAssociatedRoslynDocument = true;
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);
// If we already have an ITextBuffer for this document, then we can open it now.
// Otherwise, setup an event handler that will do it when the buffer loads.
if (textBuffer != null)
{
// We might already have this docCookie marked as open an older document. This can happen
// if we're in the middle of a rename but this class hasn't gotten the notification yet but
// another listener for RDT events got it
if (_docCookiesToOpenDocumentKeys.ContainsKey(docCookie))
{
CloseDocuments_NoLock(docCookie, monikerToKeep: moniker);
}
if (hierarchy == project.Hierarchy)
{
// This is the current context
NewBufferOpened_NoLock(docCookie, textBuffer, documentKey, isCurrentContext: true);
}
else
{
// This is a non-current linked context
NewBufferOpened_NoLock(docCookie, textBuffer, documentKey, isCurrentContext: false);
}
}
else
{
TextBufferDataEventsSink.HookupHandler(shimTextBuffer, onDocumentLoadCompleted: () => OnDocumentLoadCompleted(shimTextBuffer, documentKey, moniker));
}
}
}
if (!hasAssociatedRoslynDocument && this._documentTrackingServiceOpt != null && !_docCookiesToNonRoslynDocumentBuffers.ContainsKey(docCookie))
{
// Non-Roslyn document opened.
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);
if (textBuffer != null)
{
OnNonRoslynBufferOpened_NoLock(textBuffer, docCookie);
}
else
{
TextBufferDataEventsSink.HookupHandler(shimTextBuffer, onDocumentLoadCompleted: () => OnDocumentLoadCompleted(shimTextBuffer, documentKeyOpt: null, moniker: moniker));
}
}
}
else
{
// This is opening some other designer or property page. If it's tied to our IVsHierarchy, we should
// let the workspace know
foreach (var project in _projectTracker.ImmutableProjects)
{
if (hierarchy == project.Hierarchy)
{
_projectTracker.NotifyNonDocumentOpenedForProject(project);
}
}
}
}
private void OnNonRoslynBufferOpened_NoLock(ITextBuffer textBuffer, uint docCookie)
{
AssertIsForeground();
Contract.ThrowIfNull(textBuffer);
Contract.ThrowIfNull(_documentTrackingServiceOpt);
this._documentTrackingServiceOpt.OnNonRoslynBufferOpened(textBuffer);
_docCookiesToNonRoslynDocumentBuffers.Add(docCookie, textBuffer);
}
private void OnBeforeDocumentWindowShow(IVsWindowFrame frame, uint docCookie, bool firstShow)
{
AssertIsForeground();
var ids = GetDocumentIdsFromDocCookie(docCookie);
foreach (var id in ids)
{
this._documentTrackingServiceOpt?.DocumentFrameShowing(frame, id, firstShow);
}
}
private IList<DocumentId> GetDocumentIdsFromDocCookie(uint docCookie)
{
lock (_gate)
{
return GetDocumentIdsFromDocCookie_NoLock(docCookie);
}
}
private IList<DocumentId> GetDocumentIdsFromDocCookie_NoLock(uint docCookie)
{
AssertIsForeground();
if (!_docCookiesToOpenDocumentKeys.TryGetValue(docCookie, out var documentKeys))
{
return SpecializedCollections.EmptyList<DocumentId>();
}
IList<DocumentId> documentIds = new List<DocumentId>();
foreach (var documentKey in documentKeys)
{
documentIds.Add(_documentMap[documentKey].Id);
}
return documentIds;
}
/// <summary>
/// Closes all documents that match the cookie and predicate.
/// </summary>
/// <param name="docCookie">The cookie that we should close documents for.</param>
/// <param name="monikerToKeep">The moniker that we should _not_ close documents for. When a rename is happening,
/// we might have documents with both the old and new moniker attached to the same docCookie. In those cases
/// we only want to close anything that doesn't match the new name. Can be null to close everything.</param>
private void CloseDocuments(uint docCookie, string monikerToKeep)
{
AssertIsForeground();
lock (_gate)
{
CloseDocuments_NoLock(docCookie, monikerToKeep);
}
}
private void CloseDocuments_NoLock(uint docCookie, string monikerToKeep)
{
if (!_docCookiesToOpenDocumentKeys.TryGetValue(docCookie, out var documentKeys))
{
// Handle non-Roslyn document close.
if (this._documentTrackingServiceOpt != null && _docCookiesToNonRoslynDocumentBuffers.TryGetValue(docCookie, out ITextBuffer textBuffer))
{
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (!StringComparer.OrdinalIgnoreCase.Equals(moniker, monikerToKeep))
{
this._documentTrackingServiceOpt.OnNonRoslynBufferClosed(textBuffer);
_docCookiesToNonRoslynDocumentBuffers.Remove(docCookie);
}
}
return;
}
// We will remove from documentKeys the things we successfully closed,
// so clone the list so we can mutate while enumerating
var documentsToClose = documentKeys.Where(key => !StringComparer.OrdinalIgnoreCase.Equals(key.Moniker, monikerToKeep)).ToList();
// Cancel any pending scheduled tasks to register document opened for the documents we are closing.
CancelPendingDocumentInitializationTasks_NoLock(documentsToClose);
// For a given set of open linked or shared files, we may be closing one of the
// documents (e.g. excluding a linked file from one of its owning projects or
// unloading one of the head projects for a shared project) or the entire set of
// documents (e.g. closing the tab of a shared document). If the entire set of
// documents is closing, then we should avoid the process of updating the active
// context document between the closing of individual documents in the set. In the
// case of closing the tab of a shared document, this avoids updating the shared
// item context hierarchy for the entire shared project to head project owning the
// last documentKey in this list.
var updateActiveContext = documentsToClose.Count == 1;
foreach (var documentKey in documentsToClose)
{
var document = _documentMap[documentKey];
document.ProcessClose(updateActiveContext);
Contract.ThrowIfFalse(documentKeys.Remove(documentKey));
}
// If we removed all the keys, then remove the list entirely
if (documentKeys.Count == 0)
{
_docCookiesToOpenDocumentKeys.Remove(docCookie);
}
}
private void OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
if ((grfAttribs & (uint)__VSRDTATTRIB3.RDTA_DocumentInitialized) != 0)
{
TryProcessOpenForDocCookie(docCookie, CancellationToken.None);
}
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_MkDocument) != 0)
{
OnDocumentMonikerChanged(docCookie, pszMkDocumentOld, pszMkDocumentNew);
}
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_Hierarchy) != 0)
{
bool itemidChanged = (grfAttribs & (uint)__VSRDTATTRIB.RDTA_ItemID) != 0;
OnHierarchyChanged(docCookie, pHierOld, itemidOld, pHierNew, itemidNew, itemidChanged);
}
}
private void OnHierarchyChanged(uint docCookie, IVsHierarchy pHierOld, uint itemidOld, IVsHierarchy pHierNew, uint itemidNew, bool itemidChanged)
{
AssertIsForeground();
lock (_gate)
{
if (_docCookiesToOpenDocumentKeys.TryGetValue(docCookie, out var documentKeys))
{
foreach (var documentKey in documentKeys)
{
var document = _documentMap[documentKey];
var currDocHier = document.Project.Hierarchy;
if (currDocHier == pHierNew)
{
documentKey.HostProject.Workspace.OnDocumentContextUpdated(document.Id, document.GetOpenTextContainer());
}
}
}
}
}
private void OnDocumentMonikerChanged(uint docCookie, string oldMoniker, string newMoniker)
{
AssertIsForeground();
// If the moniker change only involves casing differences then the project system will
// not remove & add the file again with the new name, so we should not clear any state.
// Leaving the old casing in the DocumentKey is safe because DocumentKey equality
// checks ignore the casing of the moniker.
if (oldMoniker.Equals(newMoniker, StringComparison.OrdinalIgnoreCase))
{
return;
}
// While we don't natively track source file renames in the Visual Studio workspace, we do
// need to track them for Code Model's FileCodeModel instances. The lifetime of a FileCodeModel
// needs to be resilient through the source file add/remove that happens during a file rename.
RenameFileCodeModelInstances(docCookie, oldMoniker, newMoniker);
// Since our moniker changed, any old DocumentKeys are invalid. DocumentKeys are immutable,
// and HostDocuments implicitly have an immutable filename. Therefore, we choose to close
// all files associated with this docCookie, so they are no longer associated with an RDT document that
// no longer matches their filenames. This removes all tracking information and associations
// between cookies and documents in this class.
// In the case of miscellaneous files, we're also watching the RDT. If that saw the RDT event
// before we did, it's possible we've already updated state to handle the rename. Therefore, we
// should only handle the close if the moniker we had was out of date.
CloseDocuments(docCookie, monikerToKeep: newMoniker);
// We might also have new documents that now need to be opened, so handle them too. If the document
// isn't initialized we will wait until it's actually initialized to trigger the open; we see
// from the OnAfterAttributeChangeEx notification.
if (_runningDocumentTable.IsDocumentInitialized(docCookie))
{
TryProcessOpenForDocCookie(docCookie, CancellationToken.None);
}
}
private void RenameFileCodeModelInstances(uint docCookie, string oldMoniker, string newMoniker)
{
AssertIsForeground();
List<StandardTextDocument> documents;
lock (_gate)
{
if (!_docCookiesToOpenDocumentKeys.TryGetValue(docCookie, out var documentKeys))
{
return;
}
// We will remove from documentKeys the things we successfully closed,
// so clone the list so we can mutate while enumerating
documents = documentKeys
.Where(key => StringComparer.OrdinalIgnoreCase.Equals(key.Moniker, oldMoniker))
.Select(key => _documentMap[key])
.ToList();
}
foreach (var document in documents)
{
if (document.Project.Workspace is VisualStudioWorkspace workspace)
{
workspace.RenameFileCodeModelInstance(document.Id, newMoniker);
}
}
}
/// <summary>
/// Called by a VisualStudioDocument when that document is disposed.
/// </summary>
/// <param name="document">The document to stop tracking.</param>
private void StopTrackingDocument(StandardTextDocument document)
{
CancelPendingDocumentInitializationTask(document);
if (IsForeground())
{
StopTrackingDocument_Core(document);
}
else
{
InvokeBelowInputPriority(() => StopTrackingDocument_Core(document), CancellationToken.None);
}
}
private void StopTrackingDocument_Core(StandardTextDocument document)
{
AssertIsForeground();
lock (_gate)
{
StopTrackingDocument_Core_NoLock(document);
}
}
private void StopTrackingDocument_Core_NoLock(StandardTextDocument document)
{
if (document.IsOpen)
{
// TODO: This was previously faster, need a bidirectional 1-to-many map
foreach (var cookie in _docCookiesToOpenDocumentKeys.Keys)
{
var documentKeys = _docCookiesToOpenDocumentKeys[cookie];
if (documentKeys.Contains(document.Key))
{
documentKeys.Remove(document.Key);
if (documentKeys.IsEmpty())
{
_docCookiesToOpenDocumentKeys.Remove(cookie);
}
break;
}
}
}
_documentMap.Remove(document.Key);
}
private void AddCookieOpenDocumentPair_NoLock(uint foundCookie, DocumentKey documentKey)
{
if (_docCookiesToOpenDocumentKeys.TryGetValue(foundCookie, out var documentKeys))
{
if (!documentKeys.Contains(documentKey))
{
documentKeys.Add(documentKey);
}
}
else
{
_docCookiesToOpenDocumentKeys.Add(foundCookie, new List<DocumentKey> { documentKey });
}
}
private void OnDocumentLoadCompleted(IVsTextBuffer shimTextBuffer, DocumentKey documentKeyOpt, string moniker)
{
AssertIsForeground();
// This is called when IVsTextBufferDataEvents.OnLoadComplete() has been triggered for a
// newly-created buffer.
if (!_runningDocumentTable.TryGetCookieForInitializedDocument(moniker, out var docCookie))
{
return;
}
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer);
if (textBuffer == null)
{
throw new InvalidOperationException("The IVsTextBuffer has been populated but the underlying ITextBuffer does not exist!");
}
if (documentKeyOpt == null)
{
// Non-Roslyn document.
OnNonRoslynBufferOpened_NoLock(textBuffer, docCookie);
}
else
{
NewBufferOpened(docCookie, textBuffer, documentKeyOpt, IsCurrentContext(documentKeyOpt));
}
}
private bool IsCurrentContext(DocumentKey documentKey)
{
AssertIsForeground();
var document = documentKey.HostProject.GetCurrentDocumentFromPath(documentKey.Moniker);
return document != null && LinkedFileUtilities.IsCurrentContextHierarchy(document, _runningDocumentTable);
}
public IDisposable ProvideDocumentIdHint(string filePath, DocumentId documentId)
{
lock (_gate)
{
_documentIdHints[filePath] = documentId;
return new DocumentIdHint(this, filePath);
}
}
/// <summary>
/// A small IDisposable object that's returned from ProvideDocumentIdHint.
/// </summary>
private class DocumentIdHint : IDisposable
{
private readonly DocumentProvider _documentProvider;
private readonly string _filePath;
public DocumentIdHint(DocumentProvider documentProvider, string filePath)
{
_documentProvider = documentProvider;
_filePath = filePath;
}
public void Dispose()
{
lock (_documentProvider._gate)
{
_documentProvider._documentIdHints.Remove(_filePath);
}
}
}
private struct TaskAndTokenSource
{
public Task Task { get; set; }
public CancellationTokenSource CancellationTokenSource { get; set; }
}
}
}
|
khyperia/roslyn
|
src/VisualStudio/Core/Def/Implementation/ProjectSystem/DocumentProvider.cs
|
C#
|
apache-2.0
| 35,471
|
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System.Windows;
using Microsoft.Win32;
namespace Microsoft.NodejsTools.Profiling {
/// <summary>
/// Interaction logic for LaunchProfiling.xaml
/// </summary>
public partial class LaunchProfiling : DialogWindowVersioningWorkaround {
readonly ProfilingTargetView _viewModel;
public LaunchProfiling(ProfilingTargetView viewModel) {
_viewModel = viewModel;
InitializeComponent();
DataContext = _viewModel;
}
private void FindInterpreterClick(object sender, RoutedEventArgs e) {
var standalone = _viewModel.Standalone;
if (standalone != null) {
var dlg = new OpenFileDialog();
// TODO: Specify an OpenFileDialog filter for finding an interpreter to profile
dlg.CheckFileExists = true;
bool res = dlg.ShowDialog() ?? false;
if (res) {
standalone.InterpreterPath = dlg.FileName;
}
}
}
private void FindScriptClick(object sender, RoutedEventArgs e) {
var standalone = _viewModel.Standalone;
if (standalone != null) {
var dlg = new OpenFileDialog();
// TODO: Specify an OpenFileDialog filter for finding a script to profile
dlg.CheckFileExists = true;
bool res = dlg.ShowDialog() ?? false;
if (res) {
standalone.ScriptPath = dlg.FileName;
}
}
}
private void FindWorkingDirectoryClick(object sender, RoutedEventArgs e) {
var standalone = _viewModel.Standalone;
if (standalone != null) {
var dlg = new System.Windows.Forms.FolderBrowserDialog();
dlg.SelectedPath = standalone.WorkingDirectory;
var res = dlg.ShowDialog();
if (res == System.Windows.Forms.DialogResult.OK) {
standalone.WorkingDirectory = dlg.SelectedPath;
}
}
}
private void OkClick(object sender, RoutedEventArgs e) {
this.DialogResult = true;
Close();
}
private void CancelClick(object sender, RoutedEventArgs e) {
this.DialogResult = false;
Close();
}
}
}
|
munyirik/nodejstools
|
Nodejs/Product/Profiling/Profiling/LaunchProfiling.xaml.cs
|
C#
|
apache-2.0
| 3,041
|
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-10 23:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_auto_20190430_1254'),
]
operations = [
migrations.AddField(
model_name='backupoperation_decl',
name='uuid',
field=models.CharField(blank=True, help_text=b'unique identifer of this request', max_length=80, null=True),
),
]
|
opencord/xos
|
xos/core/migrations/0012_backupoperation_decl_uuid.py
|
Python
|
apache-2.0
| 1,124
|
#!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import json
import os
import time
from utils import getUserId
from utils import validate_websafe_key
from utils import ndb_to_message
from utils import message_to_ndb
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from models import Profile
from models import ProfileMiniForm
from models import ProfileForm
from models import TeeShirtSize
from models import Conference
from models import ConferenceForm
from models import ConferenceForms
from models import ConferenceQueryForm
from models import ConferenceQueryForms
from models import BooleanMessage
from models import ConflictException
from models import StringMessage
from models import Session
from models import SessionForm
from models import SessionCreateForm
from models import SessionForms
from models import SessionType
from models import Speaker
from models import SpeakerForm
from models import SpeakerCreateForm
from models import SpeakerForms
from models import WishList
from models import WishListForm
from settings import WEB_CLIENT_ID
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
# - - - Conference Defaults - - - - - - - - - - - - - - - - -
DEFAULTS = {
"city": "Default City",
"maxAttendees": 0,
"seatsAvailable": 0,
"topics": [
"Default",
"Topic"
],
}
OPERATORS = {
'EQ': '=',
'GT': '>',
'GTEQ': '>=',
'LT': '<',
'LTEQ': '<=',
'NE': '!='
}
FIELDS = {
'CITY': 'city',
'TOPIC': 'topics',
'MONTH': 'month',
'MAX_ATTENDEES': 'maxAttendees',
}
MEMCACHE_ANNOUNCEMENTS_KEY = "RECENT ANNOUNCEMENTS"
CONF_POST_REQUEST = endpoints.ResourceContainer(message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
register=messages.BooleanField(2))
CONF_GET_REQUEST = endpoints.ResourceContainer(message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1))
SESSION_POST_REQUEST = endpoints.ResourceContainer(SessionCreateForm,
websafeConferenceKey=messages.StringField(1))
SESSIONS_GET_REQUEST = endpoints.ResourceContainer(message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
sessionType=messages.StringField(2))
SPEAKER_GET_REQUEST = endpoints.ResourceContainer(message_types.VoidMessage,
websafeSpeakerKey=messages.StringField(1))
WISHLIST_PUT_REQUEST = endpoints.ResourceContainer(message_types.VoidMessage,
add=messages.StringField(1), remove=messages.StringField(2))
SPEAKER_QUERY_BY_NAME = endpoints.ResourceContainer(message_types.VoidMessage,
firstName=messages.StringField(1), lastName=messages.StringField(2))
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.api(name='conference', version='v1',
allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID],
scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
"""Conference API v0.1"""
# - - - Profile objects - - - - - - - - - - - - - - - - - - -
def _copyProfileToForm(self, prof):
"""Copy relevant fields from Profile to ProfileForm."""
# copy relevant fields from Profile to ProfileForm
pf = ProfileForm()
for field in pf.all_fields():
if hasattr(prof, field.name):
# convert t-shirt string to Enum; just copy others
if field.name == 'teeShirtSize':
setattr(pf, field.name,
getattr(TeeShirtSize, getattr(prof, field.name)))
else:
setattr(pf, field.name, getattr(prof, field.name))
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if
non-existent."""
## TODO 2
## step 1: make sure user is authed
## uncomment the following lines:
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
profile = p_key.get()
## step 2: create a new Profile from logged in user data
## you can use user.nickname() to get displayName
## and user.email() to get mainEmail
if not profile:
profile = Profile(userId=None, key=p_key,
displayName=user.nickname(), mainEmail=user.email(),
teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), )
profile.put()
return profile # return Profile
def _doProfile(self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
val = getattr(save_request, field)
if val:
setattr(prof, field, str(val))
prof.put()
# return ProfileForm
return self._copyProfileToForm(prof)
@endpoints.method(message_types.VoidMessage, ProfileForm, path='profile',
http_method='GET', name='getProfile')
def getProfile(self, request):
"""Return user profile."""
return self._doProfile()
# TODO 1
# 1. change request class
# 2. pass request to _doProfile function
@endpoints.method(ProfileMiniForm, ProfileForm, path='profile',
http_method='POST', name='saveProfile')
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# - - - Conference objects - - - - - - - - - - - - - - - - -
def _copyConferenceToForm(self, conf, displayName):
"""Copy relevant fields from Conference to ConferenceForm."""
cf = ConferenceForm()
for field in cf.all_fields():
if hasattr(conf, field.name):
# convert Date to date string; just copy others
if field.name.endswith('Date'):
setattr(cf, field.name, str(getattr(conf, field.name)))
else:
setattr(cf, field.name, getattr(conf, field.name))
elif field.name == "websafeKey":
setattr(cf, field.name, conf.key.urlsafe())
if displayName:
setattr(cf, 'organizerDisplayName', displayName)
cf.check_initialized()
return cf
def _createConferenceObject(self, request):
"""Create or update Conference object, returning
ConferenceForm/request."""
# preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if not request.name:
raise endpoints.BadRequestException(
"Conference 'name' field required")
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in
request.all_fields()}
del data['websafeKey']
del data['organizerDisplayName']
# add default values for those missing (both data model & outbound
# Message)
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[df])
# convert dates from strings to Date objects; set month based on
# start_date
if data['startDate']:
data['startDate'] = datetime.strptime(data['startDate'][:10],
"%Y-%m-%d").date()
data['month'] = data['startDate'].month
else:
data['month'] = 0
if data['endDate']:
data['endDate'] = datetime.strptime(data['endDate'][:10],
"%Y-%m-%d").date()
# set seatsAvailable to be same as maxAttendees on creation
# both for data model & outbound Message
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
setattr(request, "seatsAvailable", data["maxAttendees"])
# make Profile Key from user ID
p_key = ndb.Key(Profile, user_id)
# allocate new Conference ID with Profile key as parent
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
# make Conference key from ID
c_key = ndb.Key(Conference, c_id, parent=p_key)
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
# Look for TODO 2
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
Conference(**data).put()
taskqueue.add(
params={'email': user.email(), 'conferenceInfo': repr(request)},
url='/tasks/send_confirmation_email')
return request
@endpoints.method(ConferenceForm, ConferenceForm, path='conference',
http_method='POST', name='createConference')
def createConference(self, request):
"""Create new conference."""
return self._createConferenceObject(request)
@endpoints.method(CONF_GET_REQUEST, ConferenceForm,
path='conference/{websafeConferenceKey}',
http_method='GET', name='getConference')
def getConference(self, request):
""" Gets details about the specified conference """
conf_key = ndb.Key(urlsafe=request.websafeConferenceKey)
conference = conf_key.get()
return self._copyConferenceToForm(conference, "")
def _getQuery(self, request):
"""Return formatted query from the submitted filters."""
q = Conference.query()
inequality_filter, filters = self._formatFilters(request.filters)
# If exists, sort on inequality filter first
if not inequality_filter:
q = q.order(Conference.name)
else:
q = q.order(ndb.GenericProperty(inequality_filter))
q = q.order(Conference.name)
for filtr in filters:
if filtr["field"] in ["month", "maxAttendees"]:
filtr["value"] = int(filtr["value"])
formatted_query = ndb.query.FilterNode(filtr["field"],
filtr["operator"],
filtr["value"])
q = q.filter(formatted_query)
return q
def _formatFilters(self, filters):
"""Parse, check validity and format user supplied filters."""
formatted_filters = []
inequality_field = None
for f in filters:
filtr = {field.name: getattr(f, field.name) for field in
f.all_fields()}
try:
filtr["field"] = FIELDS[filtr["field"]]
filtr["operator"] = OPERATORS[filtr["operator"]]
except KeyError:
raise endpoints.BadRequestException(
"Filter contains invalid field or operator.")
# Every operation except "=" is an inequality
if filtr["operator"] != "=":
# check if inequality operation has been used in previous
# filters
# disallow the filter if inequality was performed on a
# different field before
# track the field on which the inequality operation is
# performed
if inequality_field and inequality_field != filtr["field"]:
raise endpoints.BadRequestException(
"Inequality filter is allowed on only one field.")
else:
inequality_field = filtr["field"]
formatted_filters.append(filtr)
return (inequality_field, formatted_filters)
@endpoints.method(ConferenceQueryForms, ConferenceForms,
path='queryConferences', http_method='POST',
name='queryConferences')
def queryConferences(self, request):
"""Query for conferences."""
conferences = self._getQuery(request)
# return individual ConferenceForm object per Conference
return ConferenceForms(
items=[self._copyConferenceToForm(conf, "") for conf in
conferences])
@endpoints.method(message_types.VoidMessage, ConferenceForms,
path='getConferencesCreated', http_method='GET',
name='getConferencesCreated')
def getConferencesCreated(self, request):
""" Get a list of all the conferences created by the logged in user """
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
profile_key = ndb.Key(Profile, user_id)
conferences = Conference.query(ancestor=profile_key)
profile = profile_key.get()
display_name = getattr(profile, 'displayName')
return ConferenceForms(
items=[self._copyConferenceToForm(conf, display_name) for conf in
conferences])
# - - - Registration - - - - - - - - - - - - - - - - - - - -
@ndb.transactional(xg=True)
def _conferenceRegistration(self, request, reg=True):
"""Register or unregister user for selected conference."""
retval = None
prof = self._getProfileFromUser() # get user Profile
# check if conf exists given websafeConfKey
# get conference; check that it exists
wsck = request.websafeConferenceKey
conf = ndb.Key(urlsafe=wsck).get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % wsck)
# register
if reg:
# check if user already registered otherwise add
if wsck in prof.conferenceKeysToAttend:
raise ConflictException(
"You have already registered for this conference")
# check if seats avail
if conf.seatsAvailable <= 0:
raise ConflictException("There are no seats available.")
# register user, take away one seat
prof.conferenceKeysToAttend.append(wsck)
conf.seatsAvailable -= 1
retval = True
# unregister
else:
# check if user already registered
if wsck in prof.conferenceKeysToAttend:
# unregister user, add back one seat
prof.conferenceKeysToAttend.remove(wsck)
conf.seatsAvailable += 1
retval = True
else:
retval = False
# write things back to the datastore & return
prof.put()
conf.put()
return BooleanMessage(data=retval)
@endpoints.method(CONF_POST_REQUEST, BooleanMessage,
path='conference/{websafeConferenceKey}',
http_method='POST', name='registerForConference')
def registerForConference(self, request):
"""Register user for selected conference."""
if request.register == False:
return self._conferenceRegistration(request, False)
else:
return self._conferenceRegistration(request)
@endpoints.method(message_types.VoidMessage, ConferenceForms,
path='conferences/attending', http_method='GET',
name='getConferencesToAttend')
def getConferencesToAttend(self, request):
"""Get list of conferences that user has registered for."""
# TODO:
# step 1: get user profile
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorizaton required.')
profile_key = ndb.Key(Profile, getUserId(user))
profile = profile_key.get()
# step 2: get conferenceKeysToAttend from profile.
# to make a ndb key from websafe key you can use:
# ndb.Key(urlsafe=my_websafe_key_string)
conferenceWsKeysToAttend = profile.conferenceKeysToAttend
conferenceKeysToAttend = []
for wsKey in conferenceWsKeysToAttend:
key = ndb.Key(urlsafe=wsKey)
conferenceKeysToAttend.append(key)
# step 3: fetch conferences from datastore.
# Use get_multi(array_of_keys) to fetch all keys at once.
# Do not fetch them one by one!
conferences = ndb.get_multi(conferenceKeysToAttend)
# return set of ConferenceForm objects per Conference
return ConferenceForms(
items=[self._copyConferenceToForm(conf, "") for conf in
conferences])
# - - - Announcements - - - - - - - - - - - - - - - - - - - -
@staticmethod
def _cacheAnnouncement():
"""Create Announcement & assign to memcache; used by
memcache cron job & putAnnouncement().
"""
confs = Conference.query(ndb.AND(Conference.seatsAvailable <= 5,
Conference.seatsAvailable > 0)).fetch(
projection=[Conference.name])
if confs:
# If there are almost sold out conferences,
# format announcement and set it in memcache
announcement = '%s %s' % (
'Last chance to attend! The following conferences '
'are nearly sold out:', ', '.join(conf.name for conf in confs))
memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement)
else:
# If there are no sold out conferences,
# delete the memcache announcements entry
announcement = ""
memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY)
return announcement
@endpoints.method(message_types.VoidMessage, StringMessage,
path='conference/announcement/get', http_method='GET',
name='getAnnouncement')
def getAnnouncement(self, request):
"""Return Announcement from memcache."""
# TODO 1
# return an existing announcement from Memcache or an empty string.
announcement = memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY)
if announcement is None:
announcement = ""
return StringMessage(data=announcement)
# - - - Sessions - - - - - - - - - - - - - - - - - - - - - - - - -
def _getSessionFormsFromWsKeys(self, ws_session_keys):
"""
Returns a list of sessions as a session_forms message given an array of
websafe session keys
:param ws_session_keys: String, websafe session keys
:return: session_forms
"""
session_keys = []
for ws_session_key in ws_session_keys:
session_key = ndb.Key(urlsafe=ws_session_key)
session_keys.append(session_key)
sessions = ndb.get_multi(session_keys)
session_forms = SessionForms(
items=[self._copySessionToForm(session) for session in sessions])
return session_forms
def _copySessionToForm(self, session):
"""
Converts a session object into a session_form message
:param session: A session object
:return: session_form
"""
session_form = SessionForm()
exclusions = ['typeOfSession', 'speaker']
session_form = ndb_to_message(session, session_form, exclusions)
if session.typeOfSession:
session_form.typeOfSession = SessionType(session.typeOfSession)
if session.speaker:
session_form.speaker = self._getSpeakerFormFromWsKey(
session.speaker)
session_form.check_initialized()
return session_form
def _createSessionObject(self, request):
"""
:param request: the endpoint request
:return: session_form, message of the newly created session
"""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required.')
user_id = getUserId(user)
# make sure we're given a websafe conference key
conference_key = validate_websafe_key(request.websafeConferenceKey,
'Conference')
# if we're given a websafe speaker key, make sure it's valid
if request.speaker:
validate_websafe_key(request.speaker, 'Speaker')
# get the conference
conference = conference_key.get()
# make sure the user can edit this conference
if conference.organizerUserId != user_id:
raise endpoints.BadRequestException(
'You cannot edit this conference.')
# create a session object
session = Session()
# list the fields we want to exclude
exclusions = ['websafeConferenceKey', 'typeOfSession']
# use our handy copy function to copy the other fields
session = message_to_ndb(request, session, exclusions)
# deal with typeOfSession and get the enum value
if request.typeOfSession:
session.typeOfSession = str(SessionType(request.typeOfSession))
else:
session.typeOfSession = str(SessionType.NOT_SPECIFIED)
# allocate an id and create the key
session_id = Session.allocate_ids(size=1, parent=conference_key)[0]
session.key = ndb.Key(Session, session_id, parent=conference_key)
# save the session to ndb
session.put()
# kick off the featured speaker task
taskqueue.add(url='/tasks/set_featured_speaker',
params={'conference_key': conference_key.urlsafe()})
# return the newly created session
return self._copySessionToForm(session)
@endpoints.method(SESSION_POST_REQUEST, SessionForm,
path='conference/{websafeConferenceKey}/session',
http_method='POST', name='createConferenceSession')
def createConferenceSession(self, request):
""" Create a session for a conference. """
return self._createSessionObject(request)
@endpoints.method(SESSIONS_GET_REQUEST, SessionForms,
path='conference/{websafeConferenceKey}/session',
http_method='GET', name='getConferenceSessions')
def getConferenceSessions(self, request):
""" Get the list of sessions for a conference. """
conference_key = validate_websafe_key(request.websafeConferenceKey,
'Conference')
# Get all the sessions where the provided Conference is the ancestor
q = Session.query(ancestor=conference_key)
# If sessionType is provided as a query string, apply as a filter
if request.sessionType:
session_type = request.sessionType.upper()
if hasattr(SessionType, session_type):
q = q.filter(Session.typeOfSession == session_type)
# return the list of sessions
q = q.order(Session.startTime)
return SessionForms(
items=[self._copySessionToForm(session) for session in q])
# - - - - SPEAKERS - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def _copySpeakerToForm(self, speaker):
""" Copies the fields from a Speaker object to a Speaker message """
speaker_form = SpeakerForm()
speaker_form = ndb_to_message(speaker, speaker_form)
speaker_form.check_initialized()
return speaker_form
def _getSpeakerFormFromWsKey(self, ws_speaker_key):
"""
Returns a Speaker message given a websafe Speaker key.
:param ws_speaker_key: String, websafe Speaker key
:return: speaker_form
"""
# if ndb.Key(urlsafe=ws_speaker_key).kind() != 'Speaker':
# raise endpoints.BadRequestException('Invalid speaker provided.')
speaker_key = ndb.Key(urlsafe=ws_speaker_key)
speaker = speaker_key.get()
speaker_form = self._copySpeakerToForm(speaker)
return speaker_form
@endpoints.method(SpeakerCreateForm, SpeakerForm, path='speaker',
http_method='POST', name='createSpeaker')
def createSpeaker(self, request):
""" Create a speaker """
# Make sure the user is logged in.
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required.')
user_id = getUserId(user)
user_key = ndb.Key(Profile, user_id)
# Create the Speaker object
speaker = Speaker()
# Copy the fields from the request to the Speaker
speaker = message_to_ndb(request, speaker)
# Allocate the Speaker id and set the key with the User as parent
speaker_id = speaker.allocate_ids(size=1, parent=user_key)[0]
speaker.key = ndb.Key(Speaker, speaker_id, parent=user_key)
# Write the speaker to the db
speaker.put()
# Create a SpeakerForm and copy the fields from the request
speaker_form = SpeakerForm()
speaker_form = ndb_to_message(speaker, speaker_form)
# Send back the SpeakerForm including the websafe key
return speaker_form
@endpoints.method(SPEAKER_GET_REQUEST, SpeakerForm,
path='speaker/{websafeSpeakerKey}', http_method='GET',
name='getSpeaker')
def getSpeaker(self, request):
""" Get all the information about a speaker. """
# validate the websafe speaker key and retrieve the entity key
speaker_key = validate_websafe_key(request.websafeSpeakerKey,
'Speaker')
# get the speaker from the db
speaker = speaker_key.get()
# return a message object with the speaker info
return self._copySpeakerToForm(speaker)
@endpoints.method(message_types.VoidMessage, SpeakerForms, path='speaker',
http_method='GET', name='getSpeakerList')
def getSpeakerList(self, request):
""" List all of the speakers. """
q = Speaker.query()
# Order the speakers by last name then first name
q = q.order(Speaker.lastName)
q = q.order(Speaker.firstName)
speakers = q.fetch()
# return the list of speakers
return SpeakerForms(
items=[self._copySpeakerToForm(speaker) for speaker in speakers])
@endpoints.method(SPEAKER_GET_REQUEST, SessionForms,
path='speakers/{websafeSpeakerKey}/sessions',
http_method='GET', name='getSessionsBySpeaker')
def getSessionsBySpeaker(self, request):
""" Get the sessions at which a speaker is speaker across all
Conferences.
"""
# Validate the websafe speaker key and retrieve the entity key
speaker_key = validate_websafe_key(request.websafeSpeakerKey,
'Speaker')
# query sessions where the speaker is the requested speaker
q = Session.query()
q = q.filter(Session.speaker == speaker_key.urlsafe())
sessions = q.fetch()
# return the list of sessions
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions])
# - - - - Wish List - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def _createWishlist(self, user_key):
''' Creates a wishlist for a user '''
wishlist_id = WishList.allocate_ids(size=1, parent=user_key)[0]
wishlist_key = ndb.Key(WishList, wishlist_id, parent=user_key)
wishlist = WishList()
wishlist.key = wishlist_key
return wishlist
def _copyWishListToForm(self, wishlist):
''' Creates a message from a wishlist '''
wishlist_form = WishListForm()
wishlist_form.sessions = self._getSessionFormsFromWsKeys(
wishlist.sessions)
return wishlist_form
@endpoints.method(CONF_GET_REQUEST, WishListForm,
path='user/wishlist/{websafeConferenceKey}',
http_method='GET',
name='getSessionsInWishlistByConference')
def getSessionsInWishlistByConference(self, request):
""" List the wishlist items for the specified conference. """
# validate the websafe conference key
conference_key = validate_websafe_key(request.websafeConferenceKey,
'Conference')
# confirm the user
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required.')
user_id = getUserId(user)
user_key = ndb.Key(Profile, user_id)
# get the user's wishlist sessions as a projection
q_wishlist = WishList.query(ancestor=user_key)
# wl_sessions = q_wishlist.fetch(1, projection=[WishList.sessions])
wishlist = q_wishlist.fetch(1)[0]
wishlist_session_keys = []
# for session in wl_sessions:
for session in wishlist.sessions:
wishlist_session_keys.append(ndb.Key(urlsafe=session))
# query Sessions where the specified Conference is the ancestor
session_q = Session.query(ancestor=conference_key)
# filter the Sessions to include only the sessions in the wishlist
session_q = session_q.filter(Session.key.IN(wishlist_session_keys))
# get the keys of those sessions, which are the ones we're looking for
conf_session_keys = session_q.fetch(keys_only=True)
# create a wishlist
short_wishlist = WishList()
# copy the found Session keys into the wishlist as websafe keys
for key in conf_session_keys:
short_wishlist.sessions.append(key.urlsafe())
# return the reduced wishlist as a message
return self._copyWishListToForm(short_wishlist)
@endpoints.method(WISHLIST_PUT_REQUEST, WishListForm, path='user/wishlist',
http_method='PUT', name='updateWishlist')
def updateWishlist(self, request):
""" Add or remove sessions to the logged in user's wishlist """
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required.')
# Validate the websafe session key to add
ws_add_key = None
ws_remove_key = None
if request.add:
ws_add_key = validate_websafe_key(request.add, 'Session', False)
# Validate the websafe session key to remove
if request.remove:
ws_remove_key = validate_websafe_key(request.remove, 'Session',
False)
# Get the user wishlist
user_id = getUserId(user)
user_key = ndb.Key(Profile, user_id)
wishlist = WishList.query(ancestor=user_key).fetch(1)
# If there wasn't previously a wishlist, create it
if not wishlist:
wishlist = self._createWishlist(user_key)
else:
wishlist = wishlist[0]
# If there is a session to add, add it
if ws_add_key:
if ws_add_key not in wishlist.sessions:
wishlist.sessions.append(ws_add_key)
# If there is a session to remove, remove it
if ws_remove_key:
if ws_remove_key in wishlist.sessions:
wishlist.sessions.remove(ws_remove_key)
# Save the wishlist to db
wishlist.put()
# Create a message of the newly created wishlist
wishlist_form = self._copyWishListToForm(wishlist)
return wishlist_form
@endpoints.method(message_types.VoidMessage, WishListForm,
path='user/wishlist', http_method='GET',
name='getSessionsInWishlist')
def getSessionsInWishlist(self, request):
""" List all of the sessions in the logged in user's wishlist """
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required.')
user_id = getUserId(user)
user_key = ndb.Key(Profile, user_id)
# Get the user's wishlist
wishlist = WishList.query(ancestor=user_key).fetch(1)
if wishlist:
wishlist = wishlist[0]
# Return the wishlist
return self._copyWishListToForm(wishlist)
# - - - - FEATURED SPEAKER - - - - - - - - - - - - - - - - - - - - -
@staticmethod
def _get_conf_featured_speaker(conference_key):
# Get all the sessions for a Conference ordered by created datetime
q = Session.query(ancestor=conference_key)
q = q.order(-Session.created_at)
# Just need the speaker websafe key
sessions = q.fetch(projection=Session.speaker)
# Count the sessions for each speaker
speaker_counter = {}
for session in sessions:
if session.speaker:
if session.speaker not in speaker_counter:
speaker_counter[session.speaker] = 1
else:
speaker_counter[session.speaker] += 1
# Find the maximum number of times a speaker is speaking
if not speaker_counter:
return None
max_speaker_count = max(speaker_counter.values())
# Get all the speakers who are speaking the max number of times
max_speakers = [key for key in speaker_counter.keys() if
speaker_counter[key] == max_speaker_count]
# featured_speaker_ws_key = ''
featured_speaker_ws_key = None
# If there is only one speaker, that's our featured speaker
if len(max_speakers) == 1:
featured_speaker_ws_key = max_speakers[0]
# Else, cycle through the sessions and get the first speaker who
# is in the set of speakers speaking the max number of times
else:
for session in sessions:
if session.speaker in max_speakers:
featured_speaker_ws_key = session.speaker
break
if featured_speaker_ws_key:
return featured_speaker_ws_key
else:
return None
@staticmethod
def _featured_speaker_memcache_key(conference_key):
# Create and return a memcache key for the featured speaker
memcache_key = '-'.join(("feature-speaker", str(conference_key)))
return memcache_key
@classmethod
def _cache_featured_speaker(cls, ws_conference_key):
# Get the conference key from the websafe key
conference_key = ndb.Key(urlsafe=ws_conference_key)
# Get the featured speaker
featured_speaker = cls._get_conf_featured_speaker(conference_key)
# Get the memcache key
memcache_key = cls._featured_speaker_memcache_key(ws_conference_key)
# If there is a featured speaker, set the message and save it to cache
if featured_speaker:
speaker_key = ndb.Key(urlsafe=featured_speaker)
speaker = speaker_key.get()
speaker_name = ' '.join((speaker.firstName, speaker.lastName))
message = '%s %s' % (speaker_name, 'is the featured speaker.')
memcache.set(memcache_key, message)
else:
message = ""
memcache.delete(memcache_key)
return message
@classmethod
def _cache_featured_speakers(cls):
# Get the keys for all conferences
conferences = Conference.query().fetch(keys_only=True)
# For each Conference websafe key, cache the featured speaker
for conference in conferences:
if conference:
cls._cache_featured_speaker(conference.urlsafe())
return
@endpoints.method(CONF_GET_REQUEST, StringMessage,
path='conference/{websafeConferenceKey}/featuredSpeaker',
http_method='GET', name='getConferenceFeaturedSpeaker')
def getConferenceFeaturedSpeaker(self, request):
""" Gets the featured speaker for a conference """
ws_conference_key = validate_websafe_key(request.websafeConferenceKey,
'Conference', False)
# Get the memcache key we're looking for
memcache_key = self._featured_speaker_memcache_key(ws_conference_key)
# retrieve the message from memcache
message = memcache.get(memcache_key)
# If there is a message, return it
if message is None:
message = ""
return StringMessage(data=message)
# - - - - Query Problem - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.method(CONF_GET_REQUEST, SessionForms,
path='conference/{websafeConferenceKey}/queryProblem',
http_method='GET', name='conferenceQueryProblem')
def conferenceQueryProblem(self, request):
""" Returns sessions before 7pm that are not workshops """
# Validate the websafe conference key and retrieve the entity key
conference_key = validate_websafe_key(request.websafeConferenceKey,
'Conference')
# Query for all sessions which are children of the conference
q = Session.query(ancestor=conference_key)
# Filter for startTime less than 7pm (19:00)
startTimeFilter = datetime.strptime('19:00:00', '%H:%M:%S').time()
q = q.filter(Session.startTime < startTimeFilter)
q = q.filter(Session.startTime != None)
q = q.order(Session.startTime)
# Get the result with a projection of typeOfSession
earlySessions = q.fetch(projection=[Session.typeOfSession])
# Iterate through the results and keep only non-workshop results
keys = [s.key for s in earlySessions if s.typeOfSession != 'WORKSHOP']
# Get the db results for the reduced set of keys
sessions = ndb.get_multi(keys)
# Return the result as a list of sessions
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions])
# - - - - Additional Queries - - - - - - - - - - - - - - - - - - - - - -
@endpoints.method(message_types.VoidMessage, ConferenceForms,
path='conference/query/seatsAvailable',
http_method='GET',
name='getConferencesWithSpace')
def getConferencesWithSpace(self, request):
''' Get a list of conferences with seats available. '''
q = Conference.query()
q = q.filter(Conference.seatsAvailable > 0)
q = q.order(Conference.seatsAvailable)
return ConferenceForms(
items=[self._copyConferenceToForm(conf, "") for conf in q])
@endpoints.method(SPEAKER_QUERY_BY_NAME, SessionForms,
path='session/query/byName',
http_method='POST',
name='getSessionsBySpeakerName')
def getSessionsBySpeakerName(self, request):
""" Get a list of sessions by speaker first and/or last name. """
first_name = request.firstName
last_name = request.lastName
if not first_name and not last_name:
return SessionForms(items=[])
# query speakers for first name and last name, if provided
speaker_q = Speaker.query()
if first_name:
speaker_q = speaker_q.filter(Speaker.firstName == first_name)
if last_name:
speaker_q = speaker_q.filter(Speaker.lastName == last_name)
speaker_keys = speaker_q.fetch(keys_only=True)
# convert the speaker keys to websafe speaker keys
ws_speaker_keys = []
for key in speaker_keys:
ws_speaker_keys.append(key.urlsafe())
# query the sessions that have one of these websafe speaker keys
session_q = Session.query()
session_q = session_q.filter(Session.speaker.IN(ws_speaker_keys))
# return the sessions
return SessionForms(items=[self._copySessionToForm(session) for
session in session_q])
# registers API
api = endpoints.api_server([ConferenceApi])
|
kirklink/udacity-fullstack-p4
|
conference.py
|
Python
|
apache-2.0
| 40,994
|
package io.advantageous.qbit.metrics.support;
import io.advantageous.qbit.metrics.StatReplicator;
import io.advantageous.qbit.queue.QueueCallBackHandler;
import io.advantageous.qbit.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
* created by rhightower on 5/22/15.
*/
public class StatsDReplicator implements StatReplicator, QueueCallBackHandler {
private final int flushRateIntervalMS;
private final ByteBuffer sendBuffer;
private final boolean multiMetrics;
private final Random random = new Random();
private final Logger logger = LoggerFactory.getLogger(StatsDReplicator.class);
private final InetSocketAddress address;
private final int bufferSize;
private DatagramChannel channel;
private final ConcurrentHashMap<String, Metric> countMap = new ConcurrentHashMap<>();
private long lastFlush;
private long time;
private long lastOpenTime;
/*
Sets
StatsD supports counting unique occurences of events between flushes, using a Set to store all occurring events.
uniques:765|s
If the count at flush is 0 then you can opt to send no metric at all for this set, by setting config.deleteSets.
*/
public StatsDReplicator(String host, int port, boolean multiMetrics, int bufferSize, int flushRateIntervalMS) throws IOException {
this(InetAddress.getByName(host), port, multiMetrics, bufferSize, flushRateIntervalMS);
}
public StatsDReplicator(InetAddress host, int port, boolean multiMetrics, int bufferSize, int flushRateIntervalMS) throws IOException {
address = new InetSocketAddress(host, port);
this.bufferSize = bufferSize;
openChannel();
this.multiMetrics = multiMetrics;
this.flushRateIntervalMS = flushRateIntervalMS;
sendBuffer = ByteBuffer.allocate(bufferSize + 100);
}
private void openChannel() {
time = Timer.timer().now();
try {
if (channel!=null) {
try {
channel.close();
}catch (Exception ex) {
logger.debug("unable to clean up channel connection", ex);
}
}
channel = DatagramChannel.open();
lastOpenTime = time;
channel.configureBlocking(false);
channel.setOption(StandardSocketOptions.SO_SNDBUF, bufferSize * 2);
}catch (Exception ex) {
logger.error("Unable to open channel", ex);
}
}
protected void finalize() throws Throwable {
super.finalize();
flushStatSend();
}
@SuppressWarnings("UnusedReturnValue")
public boolean timing(String key, long value) {
return timing(key, value, 1.0);
}
public boolean timing(String key, long value, double sampleRate) {
return send(sampleRate, String.format(Locale.ENGLISH, "%s:%d|ms", key, value));
}
public boolean decrement(String key) {
return increment(key, -1, 1.0);
}
public boolean decrement(String key, int magnitude) {
return decrement(key, magnitude, 1.0);
}
public boolean decrement(String key, int magnitude, double sampleRate) {
magnitude = magnitude < 0 ? magnitude : -magnitude;
return increment(key, magnitude, sampleRate);
}
public boolean decrement(String... keys) {
return increment(-1, 1.0, keys);
}
public boolean decrement(int magnitude, String... keys) {
magnitude = magnitude < 0 ? magnitude : -magnitude;
return increment(magnitude, 1.0, keys);
}
public boolean decrement(int magnitude, double sampleRate, String... keys) {
magnitude = magnitude < 0 ? magnitude : -magnitude;
return increment(magnitude, sampleRate, keys);
}
public boolean increment(String key) {
return increment(key, 1, 1.0);
}
@SuppressWarnings("UnusedReturnValue")
public boolean increment(String key, long magnitude) {
return increment(key, magnitude, 1.0);
}
public boolean increment(String key, long magnitude, double sampleRate) {
String stat = String.format(Locale.ENGLISH, "%s:%s|c", key, magnitude);
return send(sampleRate, stat);
}
public boolean increment(long magnitude, double sampleRate, String... keys) {
String[] stats = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
stats[i] = String.format(Locale.ENGLISH, "%s:%s|c", keys[i], magnitude);
}
return send(sampleRate, stats);
}
@SuppressWarnings("UnusedReturnValue")
public boolean gauge(String key, double magnitude) {
return gauge(key, magnitude, 1.0);
}
public boolean gauge(String key, double magnitude, double sampleRate) {
final String stat = String.format(Locale.ENGLISH, "%s:%s|g", key, magnitude);
return send(sampleRate, stat);
}
private boolean send(double sampleRate, String... stats) {
boolean sentSomething = false; // didn't send anything
if (sampleRate < 1.0) {
for (String stat : stats) {
if (random.nextDouble() <= sampleRate) {
stat = String.format(Locale.ENGLISH, "%s|@%f", stat, sampleRate);
if (doSend(stat)) {
sentSomething = true;
}
}
}
} else {
for (String stat : stats) {
if (doSend(stat)) {
sentSomething = true;
}
}
}
return sentSomething;
}
private boolean doSend(String stat) {
try {
final byte[] data = stat.getBytes("utf-8");
// If we're going to go past the threshold of the buffer then flush.
// the +1 is for the potential '\n' in multi_metrics below
if (sendBuffer.remaining() < (data.length + 1)) {
if (!flushStatSend()) {
logger.error("Buffer overflow, connection might be down");
return false;
}
}
if (sendBuffer.position() > 0) { // multiple metrics are separated by '\n'
sendBuffer.put((byte) '\n');
}
sendBuffer.put(data); // append the data
if (!multiMetrics) {
flushStatSend();
}
return true;
} catch (IOException e) {
logger.error(
String.format("Could not send stat %s to host %s:%d",
sendBuffer.toString(), address.getHostName(),
address.getPort()), e);
return false;
}
}
@SuppressWarnings("UnusedReturnValue")
public boolean flushStatSend() {
try {
final int sizeOfBuffer = sendBuffer.position();
if (sizeOfBuffer <= 0) {
return false;
}
final int sentByteCount = sendBufferOverChannel();
if (sizeOfBuffer == sentByteCount) {
return true;
} else {
logger.error(String.format(
"Could not send all of stat %s to host %s:%d. Only sent %d bytes out of %d bytes", sendBuffer.toString(),
address.getHostName(), address.getPort(), sentByteCount, sizeOfBuffer));
return false;
}
} catch (IOException e) {
logger.error(
String.format("Could not send stat %s to host %s:%d", sendBuffer.toString(), address.getHostName(),
address.getPort()), e);
return false;
}
}
int resetDatagramEvery = 0;
private int sendBufferOverChannel() throws IOException {
if (resetDatagramEvery++ > 10) {
openChannel();
resetDatagramEvery=0;
}
try {
sendBuffer.flip();
/* Made this async. */
final int sentByteCount = channel.send(sendBuffer, address);
sendBuffer.limit(sendBuffer.capacity());
sendBuffer.rewind();
return sentByteCount;
}catch (IOException ex) {
DatagramChannel oldChannel = channel;
channel = null;
/* Added recovery logic. */
if (oldChannel!=null) {
oldChannel.close();
}
openChannel();
return 0;
}
}
@Override
public void replicateCount(final String name, final long count, final long time) {
if (count == 0) {
return;
}
Metric localCount = countMap.get(name);
if (localCount == null) {
localCount = Metric.count(name);
countMap.put(name, localCount);
}
localCount.value += count;
}
@Override
public void replicateLevel(final String name, final long level, final long time) {
Metric localCount = countMap.get(name);
if (localCount == null) {
localCount = Metric.level(name);
countMap.put(name, localCount);
/* Set the initial level. */
localCount.value = level;
/* Send the gauge. */
gauge(name, level);
}
localCount.value = level;
}
@Override
public void replicateTiming(String name, long timed, long time) {
/* A 0 timing is not useful. */
if (timed <= 0) {
return;
}
Metric localCount = countMap.get(name);
if (localCount == null) {
localCount = Metric.timing(name);
countMap.put(name, localCount);
/* Set the initial timing. */
localCount.value = timed;
/* Send the timing. */
timing(name, timed);
}
/** It would be nice to average the time. */
localCount.value = timed;
}
private void flushIfNeeded() {
long delta = time - lastFlush;
if (delta > flushRateIntervalMS) {
countMap.entrySet().forEach(entry -> {
if (entry.getValue().value != 0) {
switch (entry.getValue().type) {
case COUNT:
increment(entry.getKey(), entry.getValue().value);
break;
case TIMING:
timing(entry.getKey(), entry.getValue().value);
break;
case LEVEL:
gauge(entry.getKey(), entry.getValue().value);
break;
}
entry.getValue().value = 0;
}
});
flushStatSend();
lastFlush = time;
}
}
@Override
public void queueProcess() {
time = Timer.timer().now();
flushIfNeeded();
/* Reopen channel every hour so if there is a problem like last time
we are at least fixing it once an hour.
*/
if (time - lastOpenTime > (60 * 60 * 1000) || channel == null) {
openChannel();
}
}
enum MetricType {
COUNT, LEVEL, TIMING;
}
final static class Metric {
long value;
final String name;
final MetricType type;
public static Metric count(String name) {
return new Metric(name, MetricType.COUNT);
}
public static Metric level(String name) {
return new Metric(name, MetricType.LEVEL);
}
public static Metric timing(String name) {
return new Metric(name, MetricType.TIMING);
}
public Metric(String name, MetricType type) {
this.name = name;
this.type = type;
}
}
}
|
bsa01/qbit
|
qbit/admin/src/main/java/io/advantageous/qbit/metrics/support/StatsDReplicator.java
|
Java
|
apache-2.0
| 12,140
|
package uk.ac.ox.oucs.vle.resources;
/**
* These are marker classes that are used in JSON serialisation to limit the properties and nested objects
* that are returned.
*/
public class Views {
static public class Flat {}
}
|
ox-it/wl-course-signup
|
tool/src/main/java/uk/ac/ox/oucs/vle/resources/Views.java
|
Java
|
apache-2.0
| 230
|
require "logstash/agent"
require "logstash/pipeline"
require "logstash/event"
require "stud/try"
require "rspec/expectations"
require "thread"
module LogStashHelper
DEFAULT_NUMBER_OF_TRY = 5
DEFAULT_EXCEPTIONS_FOR_TRY = [RSpec::Expectations::ExpectationNotMetError]
def try(number_of_try = DEFAULT_NUMBER_OF_TRY, &block)
Stud.try(number_of_try.times, DEFAULT_EXCEPTIONS_FOR_TRY, &block)
end
def config(configstr)
let(:config) { configstr }
end # def config
def type(default_type)
let(:default_type) { default_type }
end
def tags(*tags)
let(:default_tags) { tags }
puts "Setting default tags: #{tags}"
end
def sample(sample_event, &block)
name = sample_event.is_a?(String) ? sample_event : LogStash::Json.dump(sample_event)
name = name[0..50] + "..." if name.length > 50
describe "\"#{name}\"" do
let(:pipeline) { LogStash::Pipeline.new(config) }
let(:event) do
sample_event = [sample_event] unless sample_event.is_a?(Array)
next sample_event.collect do |e|
e = { "message" => e } if e.is_a?(String)
next LogStash::Event.new(e)
end
end
let(:results) do
results = []
pipeline.instance_eval { @filters.each(&:register) }
event.each do |e|
# filter call the block on all filtered events, included new events added by the filter
pipeline.filter(e) { |filtered_event| results << filtered_event }
end
# flush makes sure to empty any buffered events in the filter
pipeline.flush_filters(:final => true) { |flushed_event| results << flushed_event }
results.select { |e| !e.cancelled? }
end
subject { results.length > 1 ? results : results.first }
it("when processed", &block)
end
end # def sample
def input(config, &block)
pipeline = LogStash::Pipeline.new(config)
queue = Queue.new
pipeline.instance_eval do
# create closure to capture queue
@output_func = lambda { |event| queue << event }
# output_func is now a method, call closure
def output_func(event)
@output_func.call(event)
end
end
pipeline_thread = Thread.new { pipeline.run }
sleep 0.1 while !pipeline.ready?
result = block.call(pipeline, queue)
pipeline.shutdown
pipeline_thread.join
result
end # def input
def plugin_input(plugin, &block)
queue = Queue.new
input_thread = Thread.new do
plugin.run(queue)
end
result = block.call(queue)
plugin.do_stop
input_thread.join
result
end
def agent(&block)
it("agent(#{caller[0].gsub(/ .*/, "")}) runs") do
pipeline = LogStash::Pipeline.new(config)
pipeline.run
block.call
end
end # def agent
end # module LogStash
|
svanschalkwyk/datafari
|
debian7/elk/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-beats-0.9.2/vendor/jruby/1.9/gems/logstash-devutils-0.0.18-java/lib/logstash/devutils/rspec/logstash_helpers.rb
|
Ruby
|
apache-2.0
| 2,809
|
/*
* Title: GridSim Toolkit
* Description: GridSim (Grid Simulation) Toolkit for Modeling and Simulation
* of Parallel and Distributed Systems such as Clusters and Grids
* License: GPL - http://www.gnu.org/copyleft/gpl.html
*/
package gridsim.parallel.scheduler;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import eduni.simjava.Sim_event;
import eduni.simjava.Sim_system;
import gridsim.AllocPolicy;
import gridsim.GridSim;
import gridsim.GridSimTags;
import gridsim.Gridlet;
import gridsim.parallel.ParallelResource;
import gridsim.parallel.ResourceDynamics;
import gridsim.parallel.SSGridlet;
import gridsim.parallel.SSGridletList;
import gridsim.parallel.gui.ActionType;
import gridsim.parallel.gui.Visualizer;
import gridsim.parallel.log.LoggerEnum;
import gridsim.parallel.log.Logging;
import gridsim.parallel.profile.PERange;
import gridsim.parallel.profile.PERangeList;
import gridsim.parallel.profile.ProfileEntry;
import gridsim.parallel.profile.SingleProfile;
import gridsim.parallel.util.WorkloadLublin99;
/**
* {@link ConservativeBackfill} class is an allocation policy for
* {@link ParallelResource} that implements conservative backfilling.
* The policy is based on the conservative backfilling algorithm
* described in the following papers:
* <p>
* <ul>
* <li> Dror G. Feitelson and Ahuva Mu'alem Weil, Utilization and
* Predictability in Scheduling the IBM SP2 with Backfilling, in
* Proceedings of the 12th International Parallel Processing Symposium on
* International Parallel Processing Symposium (IPPS 1998), pp. 542-546.
*
* <li>Ahuva W. Mu'alem and Dror G. Feitelson, Utilization, Predictability,
* Workloads, and User Runtime Estimates in Scheduling the IBM SP2
* with Backfilling. IEEE Transactions on Parallel and Distributed
* Systems, 12:(6), pp. 529-543, 2001.
* </ul>
*
* This policy maintains an availability profile. The availability
* profile contains information about the ranges of processing elements
* (PEs) available at future times. The size of the availability profile
* is proportional to the number of jobs in the running and waiting
* queues.
* <p>
* To illustrate how the availability profile works, imagine that
* the simulation has just started and the availability profile is empty.
* The grid resource has 500 PEs. Therefore, the range of PEs available
* is [0..499]. At simulation time 100, a job (<tt>Ja</tt>) arrives requiring
* 100 PEs. The job is expected to execute for 500 seconds. As the
* resource is not executing any jobs, <tt>Ja</tt> is accepted and given
* the range [0..99]. The ranges of current PEs available is updated
* to [100..499] and one entry is inserted at the profile to indicate
* that the range [0..499] will be available again at simulation time
* 600 seconds.
* <p>
* Now suppose that a job (<tt>Jb</tt>) arrives at simulation
* time 200 requiring 400 PEs and expected to run for 500 seconds.
* The policy checks the ranges currently available and find [100..499].
* It then scans the availability profile and analyses all the entries whose
* time is smaller than the expected termination time of <tt>Jb</tt>. The policy
* finds the intersections of PEs amongst the entries, process similar
* to finding intersections of sequences. While scanning the profile,
* the policy finds the entry at 600 seconds. The intersection of
* [100..499] and [0..499] is [100..499]. That means that there are
* enough resources to schedule <tt>Jb</tt> and then <tt>Jb</tt> starts
* the execution. The policy then updates the ranges of current PEs to [].
* After that, the policy updates the entry at 600 seconds to [0..99]
* and inserts an entry with time 700 seconds with the range [0..499].
* <p>
* Now consider that a third job (<tt>Jc</tt>) arrives at simulation time 250
* requiring 500 PEs and expected to run for 100 seconds. As the
* current ranges available is [], the policy scans the profile until
* it finds an entry with enough PEs available. In this case, the entry
* found is at 700 seconds. The policy would continue scanning the profile
* finding the intersection with other ranges if there were more. In this
* case, 700 seconds is the last entry in the profile. The job is
* then set to start execution at time 700 seconds. The policy then
* updates the entry at time 700 seconds to [] and creates an entry
* at 800 with [0..499]. <tt>Jc</tt> is then put in the waiting queue.
* <p>
* <b>NOTE THAT:</b><br>
* <ul>
* <li> The list of machines comprising this resource must be
* homogeneous.
* <li> Local load is not considered. If you would like to simulate this,
* you have to model the local load as jobs; it is more precise
* and faster. To do so, please check {@link WorkloadLublin99}.
* <li> Jobs cannot be paused or migrated.
* </ul>
*
* @author Marcos Dias de Assuncao
* @since 5.0
*
* @see gridsim.GridSim
* @see gridsim.ResourceCharacteristics
* @see gridsim.AllocPolicy
* @see PERange
* @see PERangeList
*/
public class ConservativeBackfill extends AllocPolicy {
private static Logger logger = Logging.getLogger(LoggerEnum.PARALLEL);
protected SSGridletList waitingJobs = new SSGridletList();
protected SSGridletList runningJobs = new SSGridletList();
protected SingleProfile profile; // availability of PEs
protected int ratingPE = 0; // The rating of one PE
protected Comparator<SSGridlet> jobOrder = null; // sorts the jobs for backfilling
protected ResourceDynamics dynamics = null;
// To update the schedule when required
protected static final int UPT_SCHEDULE = 10;
private double lastSchedUpt = 0.0D; // time of last schedule update
private Visualizer visualizer = null;
/**
* Allocates a new {@link ConservativeBackfill} object.
* @param resourceName the grid resource entity name that will contain
* this allocation policy
* @param entityName this object entity name
* @throws Exception This happens when one of the following scenarios occur:
* <ul>
* <li> Creating this entity before initialising GridSim package
* <li> The entity name is <code>null</code> or empty
* </ul>
*/
public ConservativeBackfill(String resourceName, String entityName)
throws Exception {
super(resourceName, entityName);
profile = new SingleProfile(super.totalPE_);
}
/**
* Handles internal events that come to this entity.
*/
public void body() {
// get the resource characteristics object to be used
dynamics = (ResourceDynamics)super.resource_;
// Gets the information on number of PEs and rating
// of one PE assuming that the machines are homogeneous
ratingPE = dynamics.getMIPSRatingOfOnePE();
// creates the profile responsible to keep resource availability info
profile = new SingleProfile(super.totalPE_);
visualizer = GridSim.getVisualizer();
// a loop that is looking for internal events only
// This loop does not stop when the policy receives an
// end of simulation event because it needs to handle
// all the internal events before it finishes its
// execution. This is particularly important for the
// GUI to show the completion of advance reservations
Sim_event ev = new Sim_event();
while ( Sim_system.running() ) {
super.sim_get_next(ev);
// if the simulation finishes then exit the loop
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION ||
super.isEndSimulation()) {
break;
}
processEvent(ev);
}
// CHECK for ANY INTERNAL EVENTS WAITING TO BE PROCESSED
while (super.sim_waiting() > 0) {
// wait for event and ignore
super.sim_get_next(ev);
logger.info("Ignore internal events");
}
waitingJobs.clear();
runningJobs.clear();
lastSchedUpt = 0.0D;
dynamics.resetFreePERanges();
}
/**
* Sets the heuristic used to order the jobs considered for backfilling
* or when a cancellation takes place
* @param comparator a comparator implementation.
* @return <code>true</code> if the heuristic was set correctly.
*/
public boolean setJobOrderingHeuristic(Comparator<SSGridlet> comparator) {
if(comparator == null) {
return false;
}
jobOrder = comparator;
return true;
}
/**
* Schedules a new job received by the Grid resource entity.
* @param gridlet a Gridlet object to be executed
* @param ack an acknowledgement, i.e. <code>true</code> if wanted to know
* whether this operation is successful or not;
* <code>false</code> otherwise (don't care)
*/
public synchronized void gridletSubmit(Gridlet gridlet, boolean ack) {
int reqPE = gridlet.getNumPE();
try {
// reject the Gridlet if it requires more PEs than the maximum
if(reqPE > super.totalPE_) {
String userName = GridSim.getEntityName( gridlet.getUserID() );
logger.warning("Gridlet #" + gridlet.getGridletID() + " from " +
userName + " user requires " + gridlet.getNumPE() + " PEs." +
"\n--> The resource has only " + super.totalPE_ + " PEs.");
gridlet.setGridletStatus(Gridlet.FAILED);
super.sendFinishGridlet(gridlet);
return;
}
} catch(Exception ex) {
logger.log(Level.WARNING, "Exception on submission of a Gridlet", ex);
}
// Creates a server side job
SSGridlet sgl = new SSGridlet(gridlet);
//-------------- FOR DEBUGGING PURPOSES ONLY --------------
visualizer.notifyListeners(super.get_id(), ActionType.ITEM_ARRIVED, true, sgl);
//----------------------------------------------------------
// if job cannot be scheduled immediately, then enqueue it
if(!startGridlet(sgl)) {
enqueueGridlet(sgl);
waitingJobs.add(sgl);
}
if (ack) {
// sends back an ack
super.sendAck(GridSimTags.GRIDLET_SUBMIT_ACK, true,
gridlet.getGridletID(), gridlet.getUserID());
}
//------------------ FOR DEBUGGING PURPOSES ONLY ----------------
visualizer.notifyListeners(super.get_id(), ActionType.ITEM_SCHEDULED, true, sgl);
//---------------------------------------------------------------
}
/**
* Finds the status of a specified job
* @param gridletId a job ID
* @param userId the user or owner's ID of this job
* @return the job status or <code>-1</code> if not found
*/
public synchronized int gridletStatus(int gridletId,int userId) {
SSGridlet sgl = null;
// Look for the Gridlet in the running queue
sgl = runningJobs.get(gridletId, userId);
if (sgl != null) {
return sgl.getStatus();
}
// Look for the gridlet in the waiting queue
sgl = waitingJobs.get(gridletId, userId);
if (sgl != null) {
return sgl.getStatus();
}
return -1; // -1 = unknown
}
/**
* Cancels a job running or in the waiting queue. This method will search the
* running and waiting queues. If a job is cancelled, the availability
* profile is shifted forwards. This process ensures that the job will not
* have an expected completion time worse than that initially stipulated.
* This process if known as the compression of the schedule.<br>
* <b>NOTE:</b>
* <ul>
* <li> This method firstly checks if the job has not finished. If the
* job has completed, it cannot be cancelled.
* <li> Once a job has been cancelled, it cannot be resumed to execute
* again since this method will pass the job back to sender.
* <li> If a job cannot be found in the queues, then a <code>null</code>
* job will be send back to sender.
* <li> After the job is cancelled, the jobs are moved forwards in the
* schedule. The entries in the profile incurred by each job are updated.
* This process consists in removing a job, returning its time slot to the
* profile and finding the schedule for the job again.
* </ul>
* @param gridletId a job ID
* @param userId the user or owner's ID of this job
*/
public synchronized void gridletCancel(int gridletId, int userId) {
SSGridlet sgl = null;
// The jobs whose execution time is larger than this time have to be
// shifted forwards. There's no point in changing jobs that are
// scheduled to start before this time.
double refTime = GridSim.clock();
sgl = runningJobs.get(gridletId, userId);
if (sgl != null) {
if(sgl.getStatus() == Gridlet.SUCCESS ||
sgl.getActualFinishTime() <= refTime) {
super.sendCancelGridlet(GridSimTags.GRIDLET_CANCEL,
null, gridletId, userId);
return; // cannot cancel the job
} else {
runningJobs.remove(sgl);
}
}
if(sgl == null) {
sgl = waitingJobs.get(gridletId, userId);
if (sgl != null) {
waitingJobs.remove(sgl);
refTime = sgl.getStartTime();
}
}
// Job has not been found
if(sgl == null) {
logger.info("Cannot find Gridlet #" + gridletId + " for User #" + userId);
super.sendCancelGridlet(GridSimTags.GRIDLET_CANCEL, null, gridletId, userId);
return;
}
sgl.setStatus(Gridlet.CANCELED);
//----------------- USED FOR DEBUGGING PURPOSES ONLY -------------------
visualizer.notifyListeners(super.get_id(), ActionType.ITEM_CANCELLED, true, sgl);
//----------------------------------------------------------------------
if(!sgl.hasReserved()) {
removeGridlet(sgl);
compressSchedule(refTime, sgl.getStatus() == Gridlet.INEXEC);
}
//------------------- USED FOR DEBUGGING PURPOSES ONLY -----------------
visualizer.notifyListeners(super.get_id(), ActionType.SCHEDULE_CHANGED, true);
//----------------------------------------------------------------------
// finalise and send the Gridlet back to user
sgl.finalizeGridlet();
super.sendCancelGridlet(GridSimTags.GRIDLET_CANCEL, sgl.getGridlet(), gridletId, userId);
}
@Override
public void gridletMove(int gridletId, int userId, int destId, boolean ack) {
logger.warning("Operation not supported");
}
@Override
public void gridletPause(int gridletId, int userId, boolean ack) {
logger.warning("Operation not supported");
}
@Override
public void gridletResume(int gridletId, int userId, boolean ack) {
logger.warning("Operation not supported");
}
/**
* This method performs the compression of the schedule. The method iterates
* the waiting jobs list. For each job, it removes its entry from the profile
* and then tries to reinsert the job in the profile. In the worst case, the
* job will be put back in the same place. This process ensures no job has
* a worse start time than that initially given.
* @param refTime jobs whose start time is larger than refTime may be shifted
* @param execute <code>true</code> means that the job cancelled was running,
* so this method will try to start waiting jobs. If not possible they are
* reinserted in the waiting queue with the new start time.
* @return <code>true</code> if the job has been updated.
*/
protected boolean compressSchedule(double refTime, boolean execute) {
if(jobOrder != null) {
Collections.sort(waitingJobs, jobOrder);
}
Iterator<SSGridlet> iterQueue = waitingJobs.iterator();
while(iterQueue.hasNext()) {
SSGridlet queuedSgl = iterQueue.next();
// Skip as it cannot get better than this.
if(queuedSgl.getStartTime() <= refTime) {
continue;
}
// jobs with reservation cannot be moved
if(!queuedSgl.hasReserved()) {
profile.addTimeSlot(queuedSgl.getStartTime(),
queuedSgl.getActualFinishTime(), queuedSgl.getPERangeList());
if(execute && startGridlet(queuedSgl)) {
iterQueue.remove();
}
else {
enqueueGridlet(queuedSgl);
}
}
}
return true;
}
/**
* This method finalises the jobs that have completed
* @return the number of jobs completed
*/
protected int finishRunningGridlets() {
double now = GridSim.clock();
int itemsFinished = 0;
Iterator<SSGridlet> iter = runningJobs.iterator();
while (iter.hasNext()) {
SSGridlet gridlet = iter.next();
if(gridlet.getActualFinishTime() <= now) {
gridletFinish(gridlet, Gridlet.SUCCESS);
iter.remove();
itemsFinished++;
}
}
return itemsFinished;
}
/**
* This method starts jobs that are in the queue and can be started
* @return the number of jobs started
*/
protected int startQueuedGridlets() {
int gridletStarted = 0;
double now = GridSim.clock();
Iterator<SSGridlet> iter = waitingJobs.iterator();
while (iter.hasNext()) {
SSGridlet gridlet = iter.next();
if(gridlet.getStartTime() <= now) {
gridlet.setStatus(Gridlet.INEXEC);
runningJobs.add(gridlet);
iter.remove();
gridletStarted++;
super.sendInternalEvent(gridlet.getActualFinishTime()-now,
UPT_SCHEDULE);
}
}
return gridletStarted;
}
/**
* This method is called to update the schedule. It removes completed
* jobs and returns them to the users and verifies whether there are
* jobs in the waiting list that should start execution.
*/
protected void updateSchedule() {
int itemsFinished = finishRunningGridlets();
profile.removePastEntries(GridSim.clock());
int itemsStarted = startQueuedGridlets();
// updates list of free resources available
// (hack to be compatible with GridSim's way of maintaining availability)
dynamics.resetFreePERanges(profile.checkImmediateAvailability().getAvailRanges());
//---------------- USED FOR DEBUGGING PURPOSES ONLY --------------------
if(itemsStarted > 0 || itemsFinished > 0){
visualizer.notifyListeners(super.get_id(), ActionType.SCHEDULE_CHANGED, true);
}
}
/*
* Process and event sent to this entity
* @param ev the event to be handled
*/
private synchronized void processEvent(Sim_event ev) {
double currentTime = GridSim.clock();
boolean success = false;
if(ev.get_src() == myId_) {
if (ev.get_tag() == UPT_SCHEDULE) {
if(currentTime > lastSchedUpt) {
// updates the schedule, finishes jobs, reservations, etc.
updateSchedule();
lastSchedUpt = currentTime;
}
success = true;
}
}
if(!success) {
processOtherEvent(ev);
}
}
/**
* Allocates a job into free PEs, sets the job status to INEXEC,
* @param sgl a SSGridlet object
* @return <code>true</code> if there is are free PE to process this job,
* <code>false</code> otherwise
*/
protected boolean startGridlet(SSGridlet sgl) {
int reqPE = sgl.getNumPE();
long runTime = forecastExecutionTime(ratingPE, sgl.getRemainingLength());
double currentTime = GridSim.clock() ;
double finishTime = currentTime + runTime;
ProfileEntry entry = profile.checkAvailability(reqPE, currentTime, runTime);
// if entry is null, there are not enough PEs to serve he job
if(entry == null) {
return false;
}
PERangeList selected = entry.getAvailRanges().selectPEs(reqPE);
profile.allocatePERanges(selected, currentTime, finishTime);
runningJobs.add(sgl);
sgl.setStartTime(currentTime);
sgl.setActualFinishTime(finishTime);
sgl.setStatus(Gridlet.INEXEC);
sgl.setPERangeList(selected);
// sends an internal event to handle the job completion
super.sendInternalEvent(runTime, UPT_SCHEDULE);
// updates list of free resources available
// (hack to be compatible with GridSim's way of maintaining availability)
dynamics.resetFreePERanges(profile.checkImmediateAvailability().getAvailRanges());
return true;
}
/**
* Enqueues a gridlet. That is, finds the anchor point, which is the point
* in the availability profile where there are enough processors to execute it.
* @param sgl the resource gridlet
*/
protected void enqueueGridlet(SSGridlet sgl){
int reqPE = sgl.getNumPE();
long runTime = forecastExecutionTime(ratingPE, sgl.getRemainingLength());
ProfileEntry entry = profile.findStartTime(reqPE, runTime);
PERangeList selected = entry.getAvailRanges().selectPEs(reqPE);
double startTime = entry.getTime();
double finishTime = startTime + runTime;
profile.allocatePERanges(selected, startTime, finishTime);
sgl.setPERangeList(selected);
sgl.setStatus(Gridlet.QUEUED);
sgl.setStartTime(startTime);
sgl.setActualFinishTime(finishTime);
}
/**
* Forecast finish time of a Gridlet.
* <tt>Finish time = length / available rating</tt>
* @param availableRating the shared MIPS rating for all Gridlets
* @param length remaining Gridlet length
* @return Gridlet's finish time.
* @pre availableRating >= 0.0
* @pre length >= 0.0
* @post $none
*/
protected long forecastExecutionTime(double availableRating, double length) {
long runTime = (long)((length / availableRating) + 1);
return Math.max(runTime, 1);
}
/**
* Updates the Gridlet's properties, such as status once a
* Gridlet is considered finished.
* @param sgl a SSGridlet object
* @param status the Gridlet status
*/
protected void gridletFinish(SSGridlet sgl, int status) {
// the order is important! Set the status first then finalise
// due to timing issues in SSGridlet class (Copied from GridSim)
sgl.setStatus(status);
sgl.finalizeGridlet();
sendFinishGridlet( sgl.getGridlet() );
}
/*
* Returns the time slot given to the job back to the profile
* @param grl the Gridlet to be removed
*/
private void removeGridlet(SSGridlet grl) {
if(!grl.hasReserved()) {
profile.addTimeSlot(grl.getStartTime(), grl.getActualFinishTime(), grl.getPERangeList());
}
}
}
|
mzuhri/salam
|
salam/salam-external-lib/src/main/java/gridsim/parallel/scheduler/ConservativeBackfill.java
|
Java
|
apache-2.0
| 23,347
|
/*
* Copyright © 2014 - 2018 Leipzig University (Database Research Group)
*
* 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.gradoop.flink.algorithms.fsm.dimspan.functions.mining;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.util.Collector;
import org.gradoop.flink.algorithms.fsm.dimspan.tuples.GraphWithPatternEmbeddingsMap;
import org.gradoop.flink.model.impl.tuples.WithCount;
/**
* (graph, pattern -> embedding) => pattern, ...
*/
public class ExpandFrequentPatterns
implements FlatMapFunction<GraphWithPatternEmbeddingsMap, WithCount<int[]>> {
@Override
public void flatMap(GraphWithPatternEmbeddingsMap graphWithPatternEmbeddingsMap,
Collector<WithCount<int[]>> collector) throws Exception {
for (int i = 0; i < graphWithPatternEmbeddingsMap.getMap().getPatternCount(); i++) {
int[] pattern = graphWithPatternEmbeddingsMap.getMap().getPattern(i);
int frequency = graphWithPatternEmbeddingsMap.getMap().getValues()[i][0];
collector.collect(new WithCount<>(pattern, frequency));
}
}
}
|
niklasteichmann/gradoop
|
gradoop-flink/src/main/java/org/gradoop/flink/algorithms/fsm/dimspan/functions/mining/ExpandFrequentPatterns.java
|
Java
|
apache-2.0
| 1,600
|
package router
import (
"sync/atomic"
"github.com/AsynkronIT/protoactor-go/actor"
)
type roundRobinGroupRouter struct {
GroupRouter
}
type roundRobinPoolRouter struct {
PoolRouter
}
type roundRobinState struct {
index int32
routees *actor.PIDSet
values []actor.PID
}
func (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {
state.routees = routees
state.values = routees.Values()
}
func (state *roundRobinState) GetRoutees() *actor.PIDSet {
return state.routees
}
func (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) {
pid := roundRobinRoutee(&state.index, state.values)
pid.Request(message, sender)
}
func NewRoundRobinPool(size int) *actor.Props {
return actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))
}
func NewRoundRobinGroup(routees ...*actor.PID) *actor.Props {
return actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))
}
func (config *roundRobinPoolRouter) CreateRouterState() Interface {
return &roundRobinState{}
}
func (config *roundRobinGroupRouter) CreateRouterState() Interface {
return &roundRobinState{}
}
func roundRobinRoutee(index *int32, routees []actor.PID) actor.PID {
i := int(atomic.AddInt32(index, 1))
if i < 0 {
*index = 0
i = 0
}
mod := len(routees)
routee := routees[i%mod]
return routee
}
|
martinyunify/qingcloud-cni
|
vendor/github.com/AsynkronIT/protoactor-go/router/roundrobin_router.go
|
GO
|
apache-2.0
| 1,384
|
html, body {
font-weight: 300;
height: 100%;
}
main.container {
min-height: 100vh;
padding: 15px 15px;
padding-bottom: 45px; /* prevents the content to be hidden by the gitter sidecar */
}
.container img {
width: 100%;
height: auto;
}
/* headers */
main header {
border-bottom: 1px solid rgba(0,0,0,.1);
margin-bottom: 16px;
padding-bottom: 16px;
}
main > h1 {
margin-bottom: 20px;
}
.byline {
font-size: 14px;
}
.byline, .byline a {
color: grey;
}
.byline .author {
display: block;
}
/* indexes */
ul.post-list {
list-style: none;
padding-left: 0;
}
.post-list h2 {
margin-bottom: 0;
}
/* headings anchors */
a.anchor {
color: transparent;
margin-left: -23px;
padding-right: 3px;
transition: color .4s ease-out;
}
a.anchor::before {
content: "\f0c1";
font-family: "Font Awesome 5 Free";
font-weight: 900;
font-size: 20px;
}
h1:hover a.anchor,
h2:hover a.anchor,
h3:hover a.anchor,
h4:hover a.anchor,
h5:hover a.anchor {
color: lightgrey;
text-decoration: none;
}
h1:hover a.anchor:hover,
h2:hover a.anchor:hover,
h3:hover a.anchor:hover,
h4:hover a.anchor:hover,
h5:hover a.anchor:hover {
color: var(--secondary);
}
/* blog footer */
.blog-author {
color: gray;
}
.blog-author img#author-img {
width: auto;
height: auto;
max-width:100px;
max-height:100px;
border-radius: 50%;
}
/* api docs */
.api span.letter-anchor {
float: left;
width: 50px;
height: 50px;
border-radius: 50px;
color: white;
margin-top: 6px;
margin-right: 8px;
line-height: 50px;
text-align: center;
text-decoration: none;
font-size: 43px;
font-family: var(--font-family-sans-serif);
}
.api span.letter-anchor.object {
line-height: 48px;
}
.api span.letter-anchor.class {
line-height: 48px;
padding-right: 3px;
}
.letter-anchor.object {
background: #2c6c8d;
}
.letter-anchor.class {
background: #44ad7d;
}
.letter-anchor.trait {
background: #19aacf;
}
.letter-anchor.enum {
background: #7803fc;
}
.letter-anchor.package {
background: #2c6c8d;
}
.api header {
font-family: var(--font-family-sans-serif);
}
.api header .name-prefix {
display: block;
}
.api header .name-suffix {
display: inline-block;
}
.api header h1 {
margin: -13px 8px 0 0;
display: inline-block;
}
.api h2 {
margin-top: 1rem;
}
.api h3 {
display: inline;
margin: 0;
font: inherit;
font-weight: bold;
}
/* improved display and wrapping of parameters */
.api .params, .api .type-params {
display: inline-flex;
flex-flow: wrap;
}
/* api layout */
.wide-table {
display: table;
width: 100%;
}
.api .member:hover {
background: var(--doc-bg);
cursor: pointer;
}
.api .left-column {
white-space: nowrap;
padding-left: 1em;
border-left: 3px solid transparent;/* table rows cannot have borders*/
font-family: var(--font-family-monospace);
text-align: right;
width: 1px;
}
.api .member:hover .left-column {
border-left: 3px solid var(--secondary);
}
.api .right-column {
display: inline;
text-align: right;
font-family: var(--font-family-monospace);
}
/* admonitions */
blockquote {
padding: 0 1em;
color: #777;
border-left: 0.25em solid #ddd;
}
aside {
padding: 15px;
margin: 10px 0;
}
aside.warning {
border-left: 3px solid var(--red500);
background-color: var(--aside-warning-bg);
}
aside.notice {
border-left: 3px solid #4c97e4;
background-color: #e4ebff;
}
aside.success {
border-left: 3px solid #36bf1d;
background-color: #ebfddd;
}
/* media queries for bigger screens (dottydoc is mobile-first) */
@media (min-width: 576px) {
.byline .author {
display: inline;
margin-left: 1em;
}
main.container {
padding: 15px 30px;
}
}
@media (min-width: 768px) {
.api .member {
display: table-row;
}
.api .left-column {
display: table-cell;
}
.api .right-column {
display: flex;
flex-flow: wrap;
}
main.container {
padding: 15px 45px;
}
}
header {
position: static !important;
width: 100% !important;
}
|
lampepfl/dotty
|
docs/_assets/css/dottydoc.css
|
CSS
|
apache-2.0
| 3,989
|
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.diagnostics;
import com.hazelcast.cluster.impl.MemberImpl;
import com.hazelcast.internal.cluster.ClusterService;
import com.hazelcast.internal.cluster.impl.ClusterHeartbeatManager;
import com.hazelcast.internal.cluster.impl.ClusterServiceImpl;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.properties.HazelcastProperties;
import com.hazelcast.spi.properties.HazelcastProperty;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* A diagnostics plugin that checks the quality of member/member heartbeats.
* <p>
* Normally, heartbeats are sent at a fixed frequency, but if there is a
* deviation in this frequency, it could indicate problems.
*/
public class MemberHeartbeatPlugin extends DiagnosticsPlugin {
/**
* The period in seconds the MemberHeartbeatPlugin runs.
* <p>
* This plugin is very cheap to use.
* <p>
* This plugin will only output if there is the max deviation is exceeded.
* <p>
* Setting the value high will lead to not seeing smaller deviations. E.g
* if this plugin runs every minute, then it will not see a lot of small
* deviations. The default of 10 seconds is ok since it will not generate
* too much overhead and noise and in most cases it is the big outliers
* we are interested in.
* <p>
* If set to 0, the plugin is disabled.
*/
public static final HazelcastProperty PERIOD_SECONDS = new HazelcastProperty(
"hazelcast.diagnostics.member-heartbeat.period.seconds", 10, SECONDS);
/**
* The maximum allowed deviation. E.g. if the interval of member/member
* heartbeats is 5 seconds, a 100% deviation will be fine with heartbeats
* arriving up to 5 seconds after they are expected. So a heartbeat arriving
* at 9 seconds will not be rendered, but a heartbeat received at 11 seconds,
* will be rendered.
*/
public static final HazelcastProperty MAX_DEVIATION_PERCENTAGE
= new HazelcastProperty("hazelcast.diagnostics.member-heartbeat.max-deviation-percentage", 100);
private static final float HUNDRED = 100f;
private final long periodMillis;
private final NodeEngineImpl nodeEngine;
private final int maxDeviationPercentage;
private boolean mainSectionStarted;
public MemberHeartbeatPlugin(NodeEngineImpl nodeEngine) {
super(nodeEngine.getLogger(MemberHazelcastInstanceInfoPlugin.class));
this.nodeEngine = nodeEngine;
HazelcastProperties properties = nodeEngine.getProperties();
this.periodMillis = properties.getMillis(PERIOD_SECONDS);
this.maxDeviationPercentage = properties.getInteger(MAX_DEVIATION_PERCENTAGE);
}
@Override
public long getPeriodMillis() {
return periodMillis;
}
@Override
public void onStart() {
logger.info("Plugin:active, period-millis:" + periodMillis);
}
@Override
public void run(DiagnosticsLogWriter writer) {
ClusterService cs = nodeEngine.getClusterService();
if (!(cs instanceof ClusterServiceImpl)) {
// lets be lenient for testing etc if some kind of mocked cluster service is encountered;
// we don't want to cause problems
return;
}
render(writer, (ClusterServiceImpl) cs);
}
private void render(DiagnosticsLogWriter writer, ClusterServiceImpl clusterService) {
ClusterHeartbeatManager clusterHeartbeatManager = clusterService.getClusterHeartbeatManager();
long expectedIntervalMillis = clusterHeartbeatManager.getHeartbeatIntervalMillis();
long nowMillis = System.currentTimeMillis();
for (MemberImpl member : clusterService.getMemberImpls()) {
long lastHeartbeatMillis = clusterHeartbeatManager.getLastHeartbeatTime(member);
if (lastHeartbeatMillis == 0L) {
// member without a heartbeat; lets skip it
continue;
}
long noHeartbeatMillis = nowMillis - lastHeartbeatMillis;
float deviation = HUNDRED * ((float) (noHeartbeatMillis - expectedIntervalMillis)) / expectedIntervalMillis;
if (deviation >= maxDeviationPercentage) {
startLazyMainSection(writer);
writer.startSection("member" + member.getAddress());
writer.writeKeyValueEntry("deviation(%)", deviation);
writer.writeKeyValueEntry("noHeartbeat(ms)", noHeartbeatMillis);
writer.writeKeyValueEntry("lastHeartbeat(ms)", lastHeartbeatMillis);
writer.writeKeyValueEntryAsDateTime("lastHeartbeat(date-time)", lastHeartbeatMillis);
writer.writeKeyValueEntry("now(ms)", nowMillis);
writer.writeKeyValueEntryAsDateTime("now(date-time)", nowMillis);
writer.endSection();
}
}
endLazyMainSection(writer);
}
private void startLazyMainSection(DiagnosticsLogWriter writer) {
if (!mainSectionStarted) {
mainSectionStarted = true;
writer.startSection("MemberHeartbeats");
}
}
private void endLazyMainSection(DiagnosticsLogWriter writer) {
if (mainSectionStarted) {
mainSectionStarted = false;
writer.endSection();
}
}
}
|
mesutcelik/hazelcast
|
hazelcast/src/main/java/com/hazelcast/internal/diagnostics/MemberHeartbeatPlugin.java
|
Java
|
apache-2.0
| 5,971
|
/*
* Copyright 2014 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onehippo.cms7.essentials.plugins.tagging;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.onehippo.cms7.essentials.dashboard.ctx.PluginContext;
import org.onehippo.cms7.essentials.dashboard.instructions.InstructionStatus;
import org.onehippo.cms7.essentials.dashboard.packaging.DefaultInstructionPackage;
import org.onehippo.cms7.essentials.dashboard.utils.GlobalUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Forget about instructions. All we need to do is create a facet navigation node.
*/
public class TaggingInstructionPackage extends DefaultInstructionPackage {
private static Logger log = LoggerFactory.getLogger(TaggingInstructionPackage.class);
@Override
public InstructionStatus execute(final PluginContext context) {
InstructionStatus status = InstructionStatus.SUCCESS;
final Session session = context.createSession();
try {
if (!session.nodeExists("/tags")) {
final Node rootNode = session.getRootNode();
final Node tags = rootNode.addNode("tags", "hippofacnav:facetnavigation");
final String rootIdentifier = session.getNode("/content").getIdentifier();
tags.setProperty("hippo:docbase", rootIdentifier);
tags.setProperty("hippofacnav:facets", new String[]{"hippostd:tags"});
tags.setProperty("hippofacnav:limit", 100);
session.save();
} else {
log.debug("/tags node already exists");
}
} catch (RepositoryException e) {
status = InstructionStatus.FAILED;
log.error("Error setting up /tags facet node", e);
} finally {
GlobalUtils.cleanupSession(session);
}
return status;
}
}
|
onehippo/essentials
|
plugins/tagging/src/main/java/org/onehippo/cms7/essentials/plugins/tagging/TaggingInstructionPackage.java
|
Java
|
apache-2.0
| 2,473
|
/**
* Copyright 2011-2015 Quickstep Technologies LLC.
* Copyright 2015 Pivotal Software, 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.
**/
#ifndef QUICKSTEP_UTILITY_BIT_MANIPULATION_HPP_
#define QUICKSTEP_UTILITY_BIT_MANIPULATION_HPP_
#include <cstdint>
#include "utility/UtilityConfig.h"
namespace quickstep {
/** \addtogroup Utility
* @{
*/
/**
* @brief Count the number of ones in a word, using a fast assembly instruction
* if possible.
*
* @param word A word to count ones in.
* @return The number of 1-bits in word.
**/
template <typename UIntType>
inline int population_count(UIntType word) {
int count = 0;
while (word) {
if (word & 0x1U) {
++count;
}
word >>= 1;
}
return count;
}
#ifdef QUICKSTEP_HAVE_BUILTIN_POPCOUNT
template <>
inline int population_count<std::uint8_t>(std::uint8_t word) {
return __builtin_popcount(word);
}
template <>
inline int population_count<std::uint16_t>(std::uint16_t word) {
return __builtin_popcount(word);
}
template <>
inline int population_count<unsigned>(unsigned word) {
return __builtin_popcount(word);
}
template <>
inline int population_count<unsigned long>(unsigned long word) { // NOLINT(runtime/int)
return __builtin_popcountl(word);
}
template <>
inline int population_count<unsigned long long>(unsigned long long word) { // NOLINT(runtime/int)
return __builtin_popcountll(word);
}
#endif
/**
* @brief Count the number of leading zeroes before the first one in a word,
* using a fast assembly instruction if possible.
* @note This can also be used to count leading ones before the first zero by
* bit-flipping word as ~word.
* @warning The result is undefined if word is zero.
*
* @param word A word to count leading zeroes in.
* @return The number leading 0-bits before the first 1-bit in word.
**/
template <typename UIntType>
inline int leading_zero_count(UIntType word) {
if (word) {
constexpr UIntType maxone = static_cast<UIntType>(0x1) << ((sizeof(UIntType) << 3) - 1);
int count = 0;
while (!(word & maxone)) {
++count;
word <<= 1;
}
return count;
} else {
return sizeof(UIntType) << 3;
}
}
#ifdef QUICKSTEP_HAVE_BUILTIN_CLZ
template <>
inline int leading_zero_count<std::uint8_t>(std::uint8_t word) {
return __builtin_clz(word) - 24;
}
template <>
inline int leading_zero_count<std::uint16_t>(std::uint16_t word) {
return __builtin_clz(word) - 16;
}
template <>
inline int leading_zero_count<unsigned>(unsigned word) {
return __builtin_clz(word);
}
template <>
inline int leading_zero_count<unsigned long>(unsigned long word) { // NOLINT(runtime/int)
return __builtin_clzl(word);
}
template <>
inline int leading_zero_count<unsigned long long>(unsigned long long word) { // NOLINT(runtime/int)
return __builtin_clzll(word);
}
#endif
/**
* @brief Count the number of trailing zeroes behind the last one in a word,
* using a fast assembly instruction if possible.
* @note This can also be used to count trailing ones behind the first zero by
* bit-flipping word as ~word.
* @warning The result is undefined if word is zero.
*
* @param word A word to count trailing zeroes in.
* @return The number trailing 0-bits behind the last 1-bit in word.
**/
template <typename UIntType>
inline int trailing_zero_count(UIntType word) {
if (word) {
int count = 0;
while (!(word & 0x1U)) {
++count;
word >>= 1;
}
return count;
} else {
return sizeof(UIntType) << 3;
}
}
#ifdef QUICKSTEP_HAVE_BUILTIN_CTZ
template <>
inline int trailing_zero_count<std::uint8_t>(std::uint8_t word) {
return __builtin_ctz(word);
}
template <>
inline int trailing_zero_count<std::uint16_t>(std::uint16_t word) {
return __builtin_ctz(word);
}
template <>
inline int trailing_zero_count<unsigned>(unsigned word) {
return __builtin_ctz(word);
}
template <>
inline int trailing_zero_count<unsigned long>(unsigned long word) { // NOLINT(runtime/int)
return __builtin_ctzl(word);
}
template <>
inline int trailing_zero_count<unsigned long long>(unsigned long long word) { // NOLINT(runtime/int)
return __builtin_ctzll(word);
}
#endif
/** @} */
} // namespace quickstep
#endif // QUICKSTEP_UTILITY_BIT_MANIPULATION_HPP_
|
pivotalsoftware/quickstep
|
utility/BitManipulation.hpp
|
C++
|
apache-2.0
| 4,813
|
/*
* 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.
*/
import Ember from 'ember';
import CommonUtils from "../utils/common-utils";
import {Workflow} from '../domain/workflow';
import {WorkflowXmlMapper} from '../domain/workflow_xml_mapper';
import SchemaVersions from '../domain/schema-versions';
import Constants from '../utils/constants';
var WorkflowImporter= Ember.Object.extend({
workflowMapper:null,
x2js : new X2JS(),
schemaVersions : SchemaVersions.create({}),
importWorkflow(workflowXml){
var workflow=Workflow.create({});
var errors=[];
workflow.initialize();
this.workflowMapper=WorkflowXmlMapper.create({schemaVersions:workflow.schemaVersions});
return this.processWorkflowXml(workflowXml,workflow, errors);
},
processWorkflowXml(workflowXml,workflow, errors){
var xmlDoc= Ember.$.parseXML( workflowXml );
if (xmlDoc && xmlDoc.getElementsByTagName('action').length>Constants.flowGraphMaxNodeCount){
errors.push({message: "Workflow is too large to be imported",dismissable:true});
return {workflow:null, errors: errors};
}
var workflowJson= this.get("x2js").xml_str2json(workflowXml);
if (!workflowJson || !workflowJson["workflow-app"]){
errors.push({message: "Could not import invalid workflow",dismissable:true});
return {workflow:null, errors: errors};
}
var workflowAppJson=workflowJson["workflow-app"];
var workflowVersion=CommonUtils.extractSchemaVersion(workflowAppJson._xmlns);
var maxWorkflowVersion = Math.max.apply(Math, this.get('schemaVersions').getSupportedVersions('workflow'));
if (workflowVersion > maxWorkflowVersion) {
errors.push({message: "Unsupported workflow version - " + workflowVersion});
} else {
workflow.schemaVersions.workflowVersion = workflowVersion;
}
this.processWorkflowActionVersions(workflowAppJson, workflow, errors);
if (workflowAppJson.info && workflowAppJson.info.__prefix==="sla") {
workflow.slaEnabled=true;
this.workflowMapper.handleSLAImport(workflow,workflowAppJson.info);
}
this.workflowMapper.handleCredentialImport(workflow,workflowAppJson.credentials);
this.workflowMapper.handleParametersImport(workflow,workflowAppJson.parameters);
var nodeMap=this.setupNodeMap(workflowAppJson,workflow,Ember.$(xmlDoc));
this.setupTransitions(workflowAppJson,nodeMap);
workflow.set("startNode",nodeMap.get("start").node);
this.populateKillNodes(workflow,nodeMap);
return {workflow: workflow, errors: errors};
},
processWorkflowActionVersions(workflowAppJson, workflow, errors) {
var importedWfActionVersions = Ember.Map.create();
var actions=workflowAppJson.action ? (workflowAppJson.action.length?workflowAppJson.action:[workflowAppJson.action]):[];
actions.forEach(function(wfAction) {
var wfActionType = Object.keys(wfAction)[0];
var wfActionXmlns = wfAction[wfActionType]._xmlns;
if (!wfActionXmlns) {
return;
}
var wfActionVersion = CommonUtils.extractSchemaVersion(wfActionXmlns);
if (importedWfActionVersions.get(wfActionType)) {
importedWfActionVersions.get(wfActionType).push(wfActionVersion);
} else {
importedWfActionVersions.set(wfActionType, [wfActionVersion]);
}
});
importedWfActionVersions._keys.forEach(function(wfActionType){
if(!CommonUtils.isSupportedAction(wfActionType)){
return;
}
var maxImportedActionVersion = Math.max.apply(null,importedWfActionVersions.get(wfActionType));
var supportedVersions = this.get('schemaVersions').getSupportedVersions(wfActionType);
importedWfActionVersions.get(wfActionType).forEach((version)=>{
if(supportedVersions.indexOf(version) === -1){
errors.push({message: "Unsupported " + wfActionType + " version - " + maxImportedActionVersion});
}else{
workflow.schemaVersions.actionVersions.set(wfActionType, maxImportedActionVersion);
}
}, this);
}, this);
},
processActionNode(nodeMap,action){
var actionMapper=this.get("workflowMapper").getNodeHandler("action");
var actionNode=actionMapper.handleImportNode(action);
nodeMap.set(actionNode.getName(),actionNode);
},
setupNodeMap(workflowAppJson,workflow,xmlDoc){
var self=this;
workflow.set("name",workflowAppJson["_name"]);
var nodeMap=new Map();
Object.keys(workflowAppJson).forEach(function (key) {
var nodeHandler=self.workflowMapper.getNodeHandler(key);
if (nodeHandler){
if (Ember.isArray(workflowAppJson[key])){
workflowAppJson[key].forEach(function(jsonObj){
var node=nodeHandler.handleImportNode(key,jsonObj,workflow,xmlDoc);
nodeMap.set(jsonObj._name,{json:jsonObj,node:node});
});
}else{
if ('action'===key){//action handler.
var actionDom=xmlDoc.find("action[name='"+workflowAppJson[key]._name+ "']");
}
var node=nodeHandler.handleImportNode(key,workflowAppJson[key],workflow,actionDom);
if (!workflowAppJson[key]._name){
nodeMap.set(key,{json:workflowAppJson[key],node:node});
}else{
nodeMap.set(workflowAppJson[key]._name,{json:workflowAppJson[key],node:node});
}
}
}
});
return nodeMap;
},
setupTransitions(workflowAppJson,nodeMap){
var self=this;
nodeMap.forEach(function(entry,key){
var node=entry.node;
if (!node){
console.error("could not process:",key);//TODO error handling...
return;
}
var json=entry.json;
var nodeHandler=self.workflowMapper.getNodeHandler(node.get("type"));
if (!nodeHandler){
console.error("could not process:",node.get("type"));//TODO error handling...
}
nodeHandler.handleImportTransitions(node,json,nodeMap);
});
},
getNodeIds(nodeMap){
var ids=[];
nodeMap.forEach(function(entry){
var node=entry.node;
ids.push(node.id);
});
return ids;
},
getNodeNames(nodeMap){
var names=[];
nodeMap.forEach(function(entry){
var node=entry.node;
names.push(node.id);
});
return names;
},
populateKillNodes(workflow,nodeMap){
if (this.containsKillNode(nodeMap)){
workflow.resetKillNodes();
}
nodeMap.forEach(function(entry){
var node=entry.node;
if (node.isKillNode()){
workflow.get("killNodes").pushObject(node);
}
});
},
containsKillNode(nodeMap){
var containsKillNode=false;
nodeMap.forEach(function(entry){
var node=entry.node;
if (node.isKillNode()){
containsKillNode=true;
}
});
return containsKillNode;
}
});
export {WorkflowImporter};
|
alexryndin/ambari
|
contrib/views/wfmanager/src/main/resources/ui/app/domain/workflow-importer.js
|
JavaScript
|
apache-2.0
| 7,530
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_111) on Thu Aug 18 01:51:18 UTC 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.hadoop.mapreduce.lib.db.DataDrivenDBRecordReader (Apache Hadoop Main 2.7.3 API)</title>
<meta name="date" content="2016-08-18">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.mapreduce.lib.db.DataDrivenDBRecordReader (Apache Hadoop Main 2.7.3 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DataDrivenDBRecordReader.html" title="class in org.apache.hadoop.mapreduce.lib.db">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?org/apache/hadoop/mapreduce/lib/db/class-use/DataDrivenDBRecordReader.html" target="_top">Frames</a></li>
<li><a href="DataDrivenDBRecordReader.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 Class org.apache.hadoop.mapreduce.lib.db.DataDrivenDBRecordReader" class="title">Uses of Class<br>org.apache.hadoop.mapreduce.lib.db.DataDrivenDBRecordReader</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DataDrivenDBRecordReader.html" title="class in org.apache.hadoop.mapreduce.lib.db">DataDrivenDBRecordReader</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="#org.apache.hadoop.mapreduce.lib.db">org.apache.hadoop.mapreduce.lib.db</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.hadoop.mapreduce.lib.db">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DataDrivenDBRecordReader.html" title="class in org.apache.hadoop.mapreduce.lib.db">DataDrivenDBRecordReader</a> in <a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/package-summary.html">org.apache.hadoop.mapreduce.lib.db</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DataDrivenDBRecordReader.html" title="class in org.apache.hadoop.mapreduce.lib.db">DataDrivenDBRecordReader</a> in <a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/package-summary.html">org.apache.hadoop.mapreduce.lib.db</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><strong><a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/MySQLDataDrivenDBRecordReader.html" title="class in org.apache.hadoop.mapreduce.lib.db">MySQLDataDrivenDBRecordReader</a><T extends <a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBWritable.html" title="interface in org.apache.hadoop.mapreduce.lib.db">DBWritable</a>></strong></code>
<div class="block">A RecordReader that reads records from a MySQL table via DataDrivenDBRecordReader</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/OracleDataDrivenDBRecordReader.html" title="class in org.apache.hadoop.mapreduce.lib.db">OracleDataDrivenDBRecordReader</a><T extends <a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBWritable.html" title="interface in org.apache.hadoop.mapreduce.lib.db">DBWritable</a>></strong></code>
<div class="block">A RecordReader that reads records from a Oracle table via DataDrivenDBRecordReader</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DataDrivenDBRecordReader.html" title="class in org.apache.hadoop.mapreduce.lib.db">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?org/apache/hadoop/mapreduce/lib/db/class-use/DataDrivenDBRecordReader.html" target="_top">Frames</a></li>
<li><a href="DataDrivenDBRecordReader.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 © 2016 <a href="http://www.apache.org">Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
|
TK-TarunW/ecosystem
|
hadoop-2.7.3/share/doc/hadoop/api/org/apache/hadoop/mapreduce/lib/db/class-use/DataDrivenDBRecordReader.html
|
HTML
|
apache-2.0
| 7,724
|
package at.jku.sea.cloud.rest.client.stream.provider.implementation;
import at.jku.sea.cloud.CollectionArtifact;
import at.jku.sea.cloud.rest.client.stream.provider.RestProvider;
import at.jku.sea.cloud.rest.pojo.factory.PojoFactory;
import at.jku.sea.cloud.rest.pojo.stream.provider.PojoCollectionArtifactProvider;
import at.jku.sea.cloud.rest.pojo.stream.provider.PojoProvider;
public class CollectionArtifactProvider extends RestProvider<Object> {
private CollectionArtifact collectionArtifact;
public CollectionArtifactProvider(CollectionArtifact collectionArtifact) {
this.collectionArtifact = collectionArtifact;
}
public CollectionArtifact getCollectionArtifact() {
return collectionArtifact;
}
public void setCollectionArtifact(CollectionArtifact collectionArtifact) {
this.collectionArtifact = collectionArtifact;
}
@Override
public PojoProvider map(PojoFactory pojoFactory) {
return new PojoCollectionArtifactProvider(pojoFactory.createPojo(collectionArtifact));
}
}
|
OnurKirkizoglu/master_thesis
|
at.jku.sea.cloud.rest.client/src/main/java/at/jku/sea/cloud/rest/client/stream/provider/implementation/CollectionArtifactProvider.java
|
Java
|
apache-2.0
| 1,020
|
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import mock
from oslo_config import cfg
from neutron.agent.common import config
from neutron.agent.common import ovs_lib
from neutron.common import constants
from networking_vsphere.drivers import ovs_firewall as ovs_fw
from networking_vsphere.tests import base
fake_port = {'security_group_source_groups': 'abc',
'mac_address': '00:11:22:33:44:55',
'network_id': "netid",
'id': "123",
'security_groups': "abc",
'lvid': "100",
'sg_provider_rules': [],
'security_group_rules': [
{"direction": "ingress",
"protocol": "tcp",
"port_range_min": 2001,
"port_range_max": 2009,
"source_port_range_min": 67,
"source_port_range_max": 68,
"ethertype": "IPv4",
"source_ip_prefix": "150.1.1.0/22",
"dest_ip_prefix": "170.1.1.0/22"}]}
fake_res_port = {'security_group_source_groups': 'abc',
'mac_address': '00:11:22:33:44:55',
'network_id': "netid",
'id': "123",
'security_groups': "abc",
'lvid': "100",
'device': "123"}
cookie = ("0x%x" % (hash("123") & 0xffffffffffffffff))
class TestOVSFirewallDriver(base.TestCase):
@mock.patch('networking_vsphere.drivers.ovs_firewall.OVSFirewallDriver.'
'check_ovs_firewall_restart')
@mock.patch('networking_vsphere.drivers.ovs_firewall.OVSFirewallDriver.'
'setup_base_flows')
@mock.patch('neutron.agent.common.ovs_lib.OVSBridge.create')
@mock.patch('neutron.agent.common.ovs_lib.OVSBridge.set_secure_mode')
@mock.patch('neutron.agent.common.ovs_lib.OVSBridge.get_port_ofport')
@mock.patch('neutron.agent.ovsdb.api.'
'API.get')
def setUp(self, mock_ovsdb_api, mock_get_port_ofport, mock_set_secure_mode,
mock_create_ovs_bridge, mock_setup_base_flows,
mock_check_ovs_firewall_restart,):
super(TestOVSFirewallDriver, self).setUp()
config.register_root_helper(cfg.CONF)
cfg.CONF.set_override('security_bridge_mapping',
"fake_sec_br:fake_if", 'SECURITYGROUP')
mock_get_port_ofport.return_value = 5
self.ovs_firewall = ovs_fw.OVSFirewallDriver()
self.ovs_firewall.sg_br = mock.Mock()
self.mock_br = ovs_lib.DeferredOVSBridge(self.ovs_firewall.sg_br)
self.LOG = ovs_fw.LOG
def test_get_compact_port(self):
compact_port = {'security_group_source_groups': 'abc',
'mac_address': '00:11:22:33:44:55',
'network_id': "netid",
'id': "123",
'device': "123",
'security_groups': "abc",
'lvid': "100"}
res = self.ovs_firewall._get_compact_port(fake_port)
self.assertEqual(compact_port, res)
def test_remove_ports_from_provider_cache(self):
self.ovs_firewall.provider_port_cache = set(['123', '124', '125'])
self.ovs_firewall.remove_ports_from_provider_cache(['123', '125'])
self.assertEqual(set(['124']), self.ovs_firewall.provider_port_cache)
self.ovs_firewall.provider_port_cache = set(['123', '124', '125'])
self.ovs_firewall.remove_ports_from_provider_cache(['121', '125'])
self.assertEqual(set(['123', '124']),
self.ovs_firewall.provider_port_cache)
def test_add_ovs_flow(self):
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
self.ovs_firewall._add_ovs_flow(self.mock_br, 0, 1, "normal")
mock_add_flow.assert_called_with(priority=0, actions='normal',
table=1)
def test_add_ovs_flow_with_protocol(self):
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
# rule with protocol
self.ovs_firewall._add_ovs_flow(self.mock_br, 0, 1, "normal",
protocol="arp")
mock_add_flow.assert_called_with(table=1, priority=0,
proto="arp", actions="normal")
def test_add_ovs_flow_with_dest_mac(self):
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
# rule with dl_dest
dest_mac = "01:00:00:00:00:00"
self.ovs_firewall._add_ovs_flow(self.mock_br, 0, 1, "normal",
dl_dest=dest_mac)
mock_add_flow.assert_called_with(table=1, priority=0,
dl_dst=dest_mac,
actions="normal")
def test_add_ovs_flow_with_tcpflag(self):
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
# rule with tcp_flags
t_flag = "+rst"
self.ovs_firewall._add_ovs_flow(self.mock_br, 0, 1, "normal",
tcp_flag=t_flag)
mock_add_flow.assert_called_with(table=1, priority=0,
proto=constants.PROTO_NAME_TCP,
tcp_flags=t_flag,
actions="normal")
def test_add_ovs_flow_with_icmptype(self):
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
# rule with icmp_req_type
self.ovs_firewall._add_ovs_flow(self.mock_br, 0, 1, "normal",
icmp_req_type=11)
mock_add_flow.assert_called_with(table=1, priority=0,
proto=constants.PROTO_NAME_ICMP,
icmp_type=11, actions="normal")
def test_add_ports_to_filter(self):
self.ovs_firewall.filtered_ports = {}
self.ovs_firewall.add_ports_to_filter([fake_port])
self.assertIsNotNone(self.ovs_firewall.filtered_ports)
ret_port = self.ovs_firewall.filtered_ports["123"]
self.assertEqual(fake_res_port, ret_port)
def test_setup_aap_flows(self):
port_with_app = copy.deepcopy(fake_port)
key = "allowed_address_pairs"
port_with_app[key] = [{'ip_address': '10.0.0.2',
'mac_address': 'aa:bb:cc:dd:ee:aa'},
{'ip_address': '10.0.0.3',
'mac_address': 'aa:bb:cc:dd:ee:ab'}]
with mock.patch.object(self.ovs_firewall, '_get_port_vlan',
return_value=100), \
mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
self.ovs_firewall._setup_aap_flows(self.mock_br, port_with_app)
self.assertEqual(2, mock_add_flow.call_count)
def test_setup_aap_flows_invalid_call(self):
port_with_app = copy.deepcopy(fake_port)
with mock.patch.object(self.ovs_firewall, '_get_port_vlan',
return_value=100), \
mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
self.ovs_firewall._setup_aap_flows(self.mock_br, port_with_app)
self.assertFalse(mock_add_flow.called)
def test_get_net_prefix_len(self):
ip_addr = "150.1.1.0/22"
length = self.ovs_firewall._get_net_prefix_len(ip_addr)
self.assertNotEqual(0, length)
ip_addr = None
length = self.ovs_firewall._get_net_prefix_len(ip_addr)
self.assertEqual(0, length)
def test_get_protocol(self):
proto = self.ovs_firewall._get_protocol("IPv4", None)
self.assertEqual(['ip'], proto)
proto = self.ovs_firewall._get_protocol("IPv6", None)
self.assertEqual(['ipv6'], proto)
proto = self.ovs_firewall._get_protocol("IPv6", 'icmp')
self.assertEqual(['icmp6'], proto)
proto = self.ovs_firewall._get_protocol("IPv4", 'icmp')
self.assertEqual(['icmp'], proto)
proto = self.ovs_firewall._get_protocol("IPv4", 'udp')
self.assertEqual(['udp'], proto)
proto = self.ovs_firewall._get_protocol("IPv6", 'tcp')
self.assertEqual(['tcp'], proto)
proto = self.ovs_firewall._get_protocol("IPv6", 'unknown')
self.assertEqual(['ipv6', 'unknown'], proto)
def test_add_flow_with_range(self):
flow = {"priority": 1}
res_flow = {"priority": 1,
"tp_dst": 1,
"tp_src": 1}
port = fake_port
direction = "fake_direction"
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_add_flows_to_sec_br'
) as mock_add_flows_sec_br:
self.ovs_firewall._add_flow_with_range(self.mock_br, port, flow,
direction, 1, 2, 1, 2)
mock_add_flows_sec_br.called_with(res_flow)
self.assertEqual(4, mock_add_flows_sec_br.call_count)
def test_add_flow_with_multiple_range(self):
flow = {"priority": 1}
port = fake_port
direction = "fake_direction"
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_add_flows_to_sec_br'
) as mock_add_flows_sec_br:
self.ovs_firewall._add_flow_with_range(self.mock_br, port, flow,
direction, 1, 3, 1, 2)
self.assertEqual(6, mock_add_flows_sec_br.call_count)
def test_add_flow_with_range_all_ports(self):
flow = {"priority": 1}
port = fake_port
direction = "fake_direction"
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_add_flows_to_sec_br'
) as mock_add_flows_sec_br:
self.ovs_firewall._add_flow_with_range(self.mock_br, port,
flow, direction, 1, 65535)
self.assertEqual(1, mock_add_flows_sec_br.call_count)
def test_add_flow_with_range_some_ports(self):
flow = {"priority": 1}
port = fake_port
direction = "fake_direction"
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_add_flows_to_sec_br'
) as mock_add_flows_sec_br:
self.ovs_firewall._add_flow_with_range(self.mock_br, port,
flow, direction, 1, 100)
self.assertEqual(100, mock_add_flows_sec_br.call_count)
def test_add_flows_to_sec_br_ingress_direction(self):
flows = {}
port = fake_port
direction = "ingress"
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
self.ovs_firewall._add_flows_to_sec_br(self.mock_br, port,
flows, direction)
self.assertTrue(mock_add_flow.called)
self.assertEqual(1, mock_add_flow.call_count)
def test_add_flows_to_sec_br_egress_direction(self):
flows = {}
port = fake_port
flows['dl_src'] = '01:02:03:04:05:06'
flows['proto'] = 'ip'
flows['dl_vlan'] = 25
port['fixed_ips'] = [u'70.0.0.5']
direction = "egress"
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
self.ovs_firewall._add_flows_to_sec_br(self.mock_br, port,
flows, direction)
self.assertTrue(mock_add_flow.called)
self.assertEqual(2, mock_add_flow.call_count)
def test_add_flows_to_sec_br_egress_direction_multiple_fixed_ips(self):
flows = {}
port = fake_port
flows['dl_src'] = '01:02:03:04:05:06'
flows['proto'] = 'ip'
flows['dl_vlan'] = 25
port['fixed_ips'] = [u'70.0.0.5', u'80.0.0.6']
direction = "egress"
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
self.ovs_firewall._add_flows_to_sec_br(self.mock_br, port,
flows, direction)
self.assertTrue(mock_add_flow.called)
self.assertEqual(4, mock_add_flow.call_count)
def test_add_flows_call_no_vlan(self):
port_with_app = copy.deepcopy(fake_port)
with mock.patch.object(self.ovs_firewall, '_get_port_vlan',
return_value=None), \
mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow,\
mock.patch.object(self.LOG, 'error') as mock_error_log:
self.ovs_firewall._add_flows(self.mock_br, port_with_app, cookie)
self.assertFalse(mock_add_flow.called)
self.assertTrue(mock_error_log.called)
def test_add_flows_call_tcp(self):
port = copy.deepcopy(fake_port)
with mock.patch.object(self.ovs_firewall, '_get_port_vlan',
return_value=100) as mock_get_vlan, \
mock.patch.object(self.ovs_firewall, '_get_protocol',
return_value=['tcp']) as mock_get_proto, \
mock.patch.object(self.ovs_firewall, '_add_flow_with_range'
) as mock_add_range_flows, \
mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow'):
self.ovs_firewall._add_flows(self.mock_br, port, cookie)
self.assertTrue(mock_get_vlan.called)
self.assertTrue(mock_get_proto.called)
self.assertTrue(mock_add_range_flows.called)
def test_add_flows_call_normal(self):
port = copy.deepcopy(fake_port)
with mock.patch.object(self.ovs_firewall, '_get_port_vlan',
return_value=100) as mock_get_vlan, \
mock.patch.object(self.ovs_firewall, '_get_protocol',
return_value=['ip']) as mock_get_proto, \
mock.patch.object(self.ovs_firewall, '_add_flow_with_range'
) as mock_add_range_flows, \
mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'add_flow') as mock_add_flow:
self.ovs_firewall._add_flows(self.mock_br, port, cookie)
self.assertTrue(mock_get_vlan.called)
self.assertTrue(mock_get_proto.called)
self.assertFalse(mock_add_range_flows.called)
self.assertTrue(mock_add_flow.called)
def test_prepare_port_filter(self):
self.ovs_firewall.provider_port_cache = set()
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_setup_aap_flows'
) as mock_aap_flow_fn, \
mock.patch.object(self.ovs_firewall, '_add_flows'
) as mock_add_flow_fn, \
mock.patch.object(self.mock_br, 'add_flow'):
self.ovs_firewall.prepare_port_filter(fake_port)
mock_aap_flow_fn.assert_called_with(self.mock_br, fake_port)
mock_add_flow_fn.assert_called_with(self.mock_br, fake_port,
cookie)
self.assertEqual(2, mock_add_flow_fn.call_count)
ret_port = self.ovs_firewall.filtered_ports['123']
self.assertEqual(fake_res_port, ret_port)
self.assertEqual(set(['123']),
self.ovs_firewall.provider_port_cache)
def test_prepare_port_filter_exception(self):
self.ovs_firewall.provider_port_cache = set()
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_setup_aap_flows',
side_effect=Exception()
) as mock_aap_flow_fn, \
mock.patch.object(self.ovs_firewall, '_add_flows'
) as mock_add_flow_fn, \
mock.patch.object(self.LOG, 'exception'
) as mock_exception_log:
self.ovs_firewall.prepare_port_filter(fake_port)
mock_aap_flow_fn.assert_called_with(self.mock_br, fake_port)
self.assertFalse(mock_add_flow_fn.called)
self.assertTrue(mock_exception_log.called)
self.assertEqual(set(), self.ovs_firewall.provider_port_cache)
def test_remove_only_tenant_flows(self):
self.ovs_firewall.filtered_ports["123"] = fake_res_port
with mock.patch.object(self.ovs_firewall, '_get_port_vlan',
return_value=100) as mock_get_vlan, \
mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'delete_flows'
) as mock_del_flows:
self.ovs_firewall._remove_flows(self.mock_br, "123")
self.assertTrue(mock_get_vlan.called)
self.assertEqual(4, mock_del_flows.call_count)
def test_remove_all_flows(self):
self.ovs_firewall.filtered_ports["123"] = fake_res_port
with mock.patch.object(self.ovs_firewall, '_get_port_vlan',
return_value=100) as mock_get_vlan, \
mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'delete_flows'
) as mock_del_flows:
self.ovs_firewall._remove_flows(self.mock_br, "123", True)
self.assertTrue(mock_get_vlan.called)
self.assertEqual(7, mock_del_flows.call_count)
def test_remove_flows_invalid_port(self):
res_port = copy.deepcopy(fake_res_port)
res_port.pop('mac_address')
self.ovs_firewall.filtered_ports["123"] = res_port
with mock.patch.object(self.ovs_firewall, '_get_port_vlan',
return_value=100) as mock_get_vlan, \
mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.mock_br, 'delete_flows'
) as mock_del_flows, \
mock.patch.object(self.LOG, 'debug') as mock_debug_log:
self.ovs_firewall._remove_flows(self.mock_br, "123")
self.assertTrue(mock_get_vlan.called)
self.assertEqual(1, mock_del_flows.call_count)
self.assertEqual(2, mock_debug_log.call_count)
def test_clean_port_filters(self):
self.ovs_firewall.filtered_ports["123"] = fake_res_port
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_remove_flows'
) as mock_rem_flow:
self.ovs_firewall.clean_port_filters(["123"])
mock_rem_flow.assert_called_with(self.mock_br, "123")
self.assertIn("123", self.ovs_firewall.filtered_ports)
def test_clean_port_filters_remove_port(self):
self.ovs_firewall.filtered_ports["123"] = fake_res_port
self.ovs_firewall.provider_port_cache = set(['123'])
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_remove_flows'
) as mock_rem_flow:
self.ovs_firewall.clean_port_filters(["123"], True)
mock_rem_flow.assert_called_with(self.mock_br, "123", True)
self.assertNotIn("123", self.ovs_firewall.filtered_ports)
self.assertNotIn("123", self.ovs_firewall.provider_port_cache)
def test_clean_port_filters_exception(self):
self.ovs_firewall.filtered_ports["123"] = fake_res_port
self.ovs_firewall.provider_port_cache = set(['123'])
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_remove_flows',
side_effect=Exception()
) as mock_rem_flow, \
mock.patch.object(self.LOG, 'exception'
) as mock_exception_log:
self.ovs_firewall.clean_port_filters(["123"], True)
mock_rem_flow.assert_called_with(self.mock_br, "123", True)
self.assertTrue(mock_exception_log.called)
self.assertIn("123", self.ovs_firewall.provider_port_cache)
self.assertIn("123", self.ovs_firewall.filtered_ports)
def test_normal_update_port_filters(self):
self.ovs_firewall.filtered_ports["123"] = fake_res_port
self.ovs_firewall.provider_port_cache = set(['123'])
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_remove_flows'
) as mock_rem_flow, \
mock.patch.object(self.ovs_firewall, '_setup_aap_flows'
) as mock_aap_flow_fn, \
mock.patch.object(self.ovs_firewall, '_add_flows'
) as mock_add_flow_fn:
self.ovs_firewall.update_port_filter(fake_port)
mock_rem_flow.assert_called_with(self.mock_br, "123")
mock_aap_flow_fn.assert_called_with(self.mock_br, fake_port)
mock_add_flow_fn.assert_called_with(self.mock_br, fake_port,
cookie)
self.assertEqual(1, mock_add_flow_fn.call_count)
self.assertIn("123", self.ovs_firewall.filtered_ports)
def test_update_port_filters_for_provider_update(self):
self.ovs_firewall.filtered_ports["123"] = fake_res_port
self.ovs_firewall.provider_port_cache = set()
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_remove_flows'
) as mock_rem_flow, \
mock.patch.object(self.ovs_firewall, '_setup_aap_flows'
) as mock_aap_flow_fn, \
mock.patch.object(self.ovs_firewall, '_add_flows'
) as mock_add_flow_fn:
self.ovs_firewall.update_port_filter(fake_port)
mock_rem_flow.assert_called_with(self.mock_br, "123", True)
mock_aap_flow_fn.assert_called_with(self.mock_br, fake_port)
mock_add_flow_fn.assert_called_with(self.mock_br, fake_port,
cookie)
self.assertEqual(2, mock_add_flow_fn.call_count)
self.assertIn("123", self.ovs_firewall.filtered_ports)
self.assertIn("123", self.ovs_firewall.provider_port_cache)
def test_update_port_filters_exception(self):
self.ovs_firewall.filtered_ports["123"] = fake_res_port
self.ovs_firewall.provider_port_cache = set(['123'])
with mock.patch.object(self.ovs_firewall.sg_br, 'deferred',
return_value=self.mock_br), \
mock.patch.object(self.ovs_firewall, '_remove_flows',
side_effect=Exception()) as mock_rem_flow, \
mock.patch.object(self.ovs_firewall, '_add_flows'
) as mock_add_flow_fn, \
mock.patch.object(self.LOG, 'exception'
) as mock_exception_log:
self.ovs_firewall.update_port_filter(fake_port)
mock_rem_flow.assert_called_with(self.mock_br, "123")
self.assertFalse(mock_add_flow_fn.called)
self.assertIn("123", self.ovs_firewall.filtered_ports)
self.assertTrue(mock_exception_log.called)
def test_ovs_firewall_restart_with_canary_flow(self):
flow = "cookie=0x0, duration=4633.482s, table=23, n_packets=0" + \
"n_bytes=0, idle_age=4633, priority=0 actions=drop"
with mock.patch.object(self.ovs_firewall.sg_br,
"dump_flows_for_table",
return_value=flow) as mock_dump_flow:
canary_flow = self.ovs_firewall.check_ovs_firewall_restart()
self.assertTrue(mock_dump_flow.called)
self.assertTrue(canary_flow)
def test_ovs_firewall_restart_without_canary_flow(self):
flow = ""
with mock.patch.object(self.ovs_firewall.sg_br,
"dump_flows_for_table",
return_value=flow) as mock_dump_flow:
canary_flow = self.ovs_firewall.check_ovs_firewall_restart()
self.assertTrue(mock_dump_flow.called)
self.assertFalse(canary_flow)
|
ekosareva/vmware-dvs
|
networking_vsphere/tests/unit/drivers/test_ovs_firewall.py
|
Python
|
apache-2.0
| 28,260
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.appcloud.provisioning.runtime.beans;
public class VolumeMountInfo {
private String mountPath;
private String name;
private boolean readOnly;
private String hostPath;
private String subPath;
private String nfsPath;
private String nfsServer;
public String getMountPath() {
return mountPath;
}
public void setMountPath(String mountPath) {
this.mountPath = mountPath;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public String getHostPath() {
return hostPath;
}
public void setHostPath(String hostPath) {
this.hostPath = hostPath;
}
public String getSubPath() {
return subPath;
}
public void setSubPath(String subPath) {
this.subPath = subPath;
}
public String getNfsPath() {
return nfsPath;
}
public void setNfsPath(String nfsPath) {
this.nfsPath = nfsPath;
}
public String getNfsServer() {
return nfsServer;
}
public void setNfsServer(String nfsServer) {
this.nfsServer = nfsServer;
}
}
|
gnudeep/app-cloud
|
modules/components/org.wso2.appcloud.provisioning.runtime/src/main/java/org/wso2/appcloud/provisioning/runtime/beans/VolumeMountInfo.java
|
Java
|
apache-2.0
| 1,968
|
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
validates :user_id, presence: true
validates :image, presence: true
validates :caption, length: { minimum: 3, maximum: 300 }
has_attached_file :image, styles: { :medium => "640x" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
|
dstroppa/ecs-cd-demo-app
|
web/app/models/post.rb
|
Ruby
|
apache-2.0
| 365
|
/* $Id: hash.h 840 2007-09-09 12:17:42Z michael $
* $URL: https://ssl.bulix.org/svn/lcd4linux/trunk/hash.h $
*
* hashes (associative arrays)
*
* Copyright (C) 2003 Michael Reinelt <michael@reinelt.co.at>
* Copyright (C) 2004 The LCD4Linux Team <lcd4linux-devel@users.sourceforge.net>
*
* This file is part of LCD4Linux.
*
* LCD4Linux is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* LCD4Linux is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#ifndef _HASH_H_
#define _HASH_H_
/* struct timeval */
#include <sys/time.h>
typedef struct {
int size;
char *value;
struct timeval timestamp;
} HASH_SLOT;
typedef struct {
char *key;
int val;
} HASH_COLUMN;
typedef struct {
char *key;
int index;
int nSlot;
HASH_SLOT *Slot;
} HASH_ITEM;
typedef struct {
int sorted;
struct timeval timestamp;
int nItems;
HASH_ITEM *Items;
int nColumns;
HASH_COLUMN *Columns;
char *delimiter;
} HASH;
void hash_create(HASH * Hash);
int hash_age(HASH * Hash, const char *key);
void hash_set_column(HASH * Hash, const int number, const char *column);
void hash_set_delimiter(HASH * Hash, const char *delimiter);
char *hash_get(HASH * Hash, const char *key, const char *column);
double hash_get_delta(HASH * Hash, const char *key, const char *column, const int delay);
double hash_get_regex(HASH * Hash, const char *key, const char *column, const int delay);
void hash_put(HASH * Hash, const char *key, const char *value);
void hash_put_delta(HASH * Hash, const char *key, const char *value);
void hash_destroy(HASH * Hash);
#endif
|
Johny-C/smartwatch-repo
|
lcd4linux/hash.h
|
C
|
apache-2.0
| 2,159
|
<?php
/*
* This file is part of the League\Fractal package.
*
* (c) Phil Sturgeon <me@philsturgeon.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
**/
namespace League\Fractal;
use InvalidArgumentException;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\Primitive;
use League\Fractal\Resource\NullResource;
use League\Fractal\Resource\ResourceInterface;
use League\Fractal\Serializer\SerializerAbstract;
/**
* Scope
*
* The scope class acts as a tracker, relating a specific resource in a specific
* context. For example, the same resource could be attached to multiple scopes.
* There are root scopes, parent scopes and child scopes.
*/
class Scope
{
/**
* @var array
*/
protected $availableIncludes = [];
/**
* @var string
*/
protected $scopeIdentifier;
/**
* @var \League\Fractal\Manager
*/
protected $manager;
/**
* @var ResourceInterface
*/
protected $resource;
/**
* @var array
*/
protected $parentScopes = [];
/**
* Create a new scope instance.
*
* @param Manager $manager
* @param ResourceInterface $resource
* @param string $scopeIdentifier
*
* @return void
*/
public function __construct(Manager $manager, ResourceInterface $resource, $scopeIdentifier = null)
{
$this->manager = $manager;
$this->resource = $resource;
$this->scopeIdentifier = $scopeIdentifier;
}
/**
* Embed a scope as a child of the current scope.
*
* @internal
*
* @param string $scopeIdentifier
* @param ResourceInterface $resource
*
* @return \League\Fractal\Scope
*/
public function embedChildScope($scopeIdentifier, $resource)
{
return $this->manager->createData($resource, $scopeIdentifier, $this);
}
/**
* Get the current identifier.
*
* @return string
*/
public function getScopeIdentifier()
{
return $this->scopeIdentifier;
}
/**
* Get the unique identifier for this scope.
*
* @param string $appendIdentifier
*
* @return string
*/
public function getIdentifier($appendIdentifier = null)
{
$identifierParts = array_merge($this->parentScopes, [$this->scopeIdentifier, $appendIdentifier]);
return implode('.', array_filter($identifierParts));
}
/**
* Getter for parentScopes.
*
* @return mixed
*/
public function getParentScopes()
{
return $this->parentScopes;
}
/**
* Getter for resource.
*
* @return ResourceInterface
*/
public function getResource()
{
return $this->resource;
}
/**
* Getter for manager.
*
* @return \League\Fractal\Manager
*/
public function getManager()
{
return $this->manager;
}
/**
* Is Requested.
*
* Check if - in relation to the current scope - this specific segment is allowed.
* That means, if a.b.c is requested and the current scope is a.b, then c is allowed. If the current
* scope is a then c is not allowed, even if it is there and potentially transformable.
*
* @internal
*
* @param string $checkScopeSegment
*
* @return bool Returns the new number of elements in the array.
*/
public function isRequested($checkScopeSegment)
{
if ($this->parentScopes) {
$scopeArray = array_slice($this->parentScopes, 1);
array_push($scopeArray, $this->scopeIdentifier, $checkScopeSegment);
} else {
$scopeArray = [$checkScopeSegment];
}
$scopeString = implode('.', (array) $scopeArray);
return in_array($scopeString, $this->manager->getRequestedIncludes());
}
/**
* Is Excluded.
*
* Check if - in relation to the current scope - this specific segment should
* be excluded. That means, if a.b.c is excluded and the current scope is a.b,
* then c will not be allowed in the transformation whether it appears in
* the list of default or available, requested includes.
*
* @internal
*
* @param string $checkScopeSegment
*
* @return bool
*/
public function isExcluded($checkScopeSegment)
{
if ($this->parentScopes) {
$scopeArray = array_slice($this->parentScopes, 1);
array_push($scopeArray, $this->scopeIdentifier, $checkScopeSegment);
} else {
$scopeArray = [$checkScopeSegment];
}
$scopeString = implode('.', (array) $scopeArray);
return in_array($scopeString, $this->manager->getRequestedExcludes());
}
/**
* Push Parent Scope.
*
* Push a scope identifier into parentScopes
*
* @internal
*
* @param string $identifierSegment
*
* @return int Returns the new number of elements in the array.
*/
public function pushParentScope($identifierSegment)
{
return array_push($this->parentScopes, $identifierSegment);
}
/**
* Set parent scopes.
*
* @internal
*
* @param string[] $parentScopes Value to set.
*
* @return $this
*/
public function setParentScopes($parentScopes)
{
$this->parentScopes = $parentScopes;
return $this;
}
/**
* Convert the current data for this scope to an array.
*
* @return array
*/
public function toArray()
{
list($rawData, $rawIncludedData) = $this->executeResourceTransformers();
$serializer = $this->manager->getSerializer();
$data = $this->serializeResource($serializer, $rawData);
// If the serializer wants the includes to be side-loaded then we'll
// serialize the included data and merge it with the data.
if ($serializer->sideloadIncludes()) {
//Filter out any relation that wasn't requested
$rawIncludedData = array_map(array($this, 'filterFieldsets'), $rawIncludedData);
$includedData = $serializer->includedData($this->resource, $rawIncludedData);
// If the serializer wants to inject additional information
// about the included resources, it can do so now.
$data = $serializer->injectData($data, $rawIncludedData);
if ($this->isRootScope()) {
// If the serializer wants to have a final word about all
// the objects that are sideloaded, it can do so now.
$includedData = $serializer->filterIncludes(
$includedData,
$data
);
}
$data = array_merge($data, $includedData);
}
if ($this->resource instanceof Collection) {
if ($this->resource->hasCursor()) {
$pagination = $serializer->cursor($this->resource->getCursor());
} elseif ($this->resource->hasPaginator()) {
$pagination = $serializer->paginator($this->resource->getPaginator());
}
if (! empty($pagination)) {
$this->resource->setMetaValue(key($pagination), current($pagination));
}
}
// Pull out all of OUR metadata and any custom meta data to merge with the main level data
$meta = $serializer->meta($this->resource->getMeta());
// in case of returning NullResource we should return null and not to go with array_merge
if (is_null($data)) {
if (!empty($meta)) {
return $meta;
}
return null;
}
return array_merge($data, $meta);
}
/**
* Convert the current data for this scope to JSON.
*
* @param int $options
*
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->toArray(), $options);
}
/**
* Transformer a primitive resource
*
* @return mixed
*/
public function transformPrimitiveResource()
{
if (! ($this->resource instanceof Primitive)) {
throw new InvalidArgumentException(
'Argument $resource should be an instance of League\Fractal\Resource\Primitive'
);
}
$transformer = $this->resource->getTransformer();
$data = $this->resource->getData();
if (null === $transformer) {
$transformedData = $data;
} elseif (is_callable($transformer)) {
$transformedData = call_user_func($transformer, $data);
} else {
$transformer->setCurrentScope($this);
$transformedData = $transformer->transform($data);
}
return $transformedData;
}
/**
* Execute the resources transformer and return the data and included data.
*
* @internal
*
* @return array
*/
protected function executeResourceTransformers()
{
$transformer = $this->resource->getTransformer();
$data = $this->resource->getData();
$transformedData = $includedData = [];
if ($this->resource instanceof Item) {
list($transformedData, $includedData[]) = $this->fireTransformer($transformer, $data);
} elseif ($this->resource instanceof Collection) {
foreach ($data as $value) {
list($transformedData[], $includedData[]) = $this->fireTransformer($transformer, $value);
}
} elseif ($this->resource instanceof NullResource) {
$transformedData = null;
$includedData = [];
} else {
throw new InvalidArgumentException(
'Argument $resource should be an instance of League\Fractal\Resource\Item'
.' or League\Fractal\Resource\Collection'
);
}
return [$transformedData, $includedData];
}
/**
* Serialize a resource
*
* @internal
*
* @param SerializerAbstract $serializer
* @param mixed $data
*
* @return array
*/
protected function serializeResource(SerializerAbstract $serializer, $data)
{
$resourceKey = $this->resource->getResourceKey();
if ($this->resource instanceof Collection) {
return $serializer->collection($resourceKey, $data);
}
if ($this->resource instanceof Item) {
return $serializer->item($resourceKey, $data);
}
return $serializer->null();
}
/**
* Fire the main transformer.
*
* @internal
*
* @param TransformerAbstract|callable $transformer
* @param mixed $data
*
* @return array
*/
protected function fireTransformer($transformer, $data)
{
$includedData = [];
if (is_callable($transformer)) {
$transformedData = call_user_func($transformer, $data);
} else {
$transformer->setCurrentScope($this);
$transformedData = $transformer->transform($data);
}
if ($this->transformerHasIncludes($transformer)) {
$includedData = $this->fireIncludedTransformers($transformer, $data);
$transformedData = $this->manager->getSerializer()->mergeIncludes($transformedData, $includedData);
}
//Stick only with requested fields
$transformedData = $this->filterFieldsets($transformedData);
return [$transformedData, $includedData];
}
/**
* Fire the included transformers.
*
* @internal
*
* @param \League\Fractal\TransformerAbstract $transformer
* @param mixed $data
*
* @return array
*/
protected function fireIncludedTransformers($transformer, $data)
{
$this->availableIncludes = $transformer->getAvailableIncludes();
return $transformer->processIncludedResources($this, $data) ?: [];
}
/**
* Determine if a transformer has any available includes.
*
* @internal
*
* @param TransformerAbstract|callable $transformer
*
* @return bool
*/
protected function transformerHasIncludes($transformer)
{
if (! $transformer instanceof TransformerAbstract) {
return false;
}
$defaultIncludes = $transformer->getDefaultIncludes();
$availableIncludes = $transformer->getAvailableIncludes();
return ! empty($defaultIncludes) || ! empty($availableIncludes);
}
/**
* Check, if this is the root scope.
*
* @return bool
*/
protected function isRootScope()
{
return empty($this->parentScopes);
}
/**
* Filter the provided data with the requested filter fieldset for
* the scope resource
*
* @internal
*
* @param array $data
*
* @return array
*/
protected function filterFieldsets(array $data)
{
if (!$this->hasFilterFieldset()) {
return $data;
}
$serializer = $this->manager->getSerializer();
$requestedFieldset = iterator_to_array($this->getFilterFieldset());
//Build the array of requested fieldsets with the mandatory serializer fields
$filterFieldset = array_flip(
array_merge(
$serializer->getMandatoryFields(),
$requestedFieldset
)
);
return array_intersect_key($data, $filterFieldset);
}
/**
* Return the requested filter fieldset for the scope resource
*
* @internal
*
* @return \League\Fractal\ParamBag|null
*/
protected function getFilterFieldset()
{
return $this->manager->getFieldset($this->getResourceType());
}
/**
* Check if there are requested filter fieldsets for the scope resource.
*
* @internal
*
* @return bool
*/
protected function hasFilterFieldset()
{
return $this->getFilterFieldset() !== null;
}
/**
* Return the scope resource type.
*
* @internal
*
* @return string
*/
protected function getResourceType()
{
return $this->resource->getResourceKey();
}
}
|
MasDeny/jwt-laravel-auth
|
vendor/league/fractal/src/Scope.php
|
PHP
|
apache-2.0
| 14,502
|
/*
* (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.timelock.paxos;
import com.palantir.timelock.corruption.detection.CorruptionHealthCheck;
import com.palantir.timelock.corruption.detection.RemoteCorruptionDetector;
import com.palantir.timelock.history.LocalHistoryLoader;
import org.immutables.value.Value;
@Value.Immutable
public interface TimeLockCorruptionComponents {
CorruptionHealthCheck timeLockCorruptionHealthCheck();
RemoteCorruptionDetector remoteCorruptionDetector();
LocalHistoryLoader localHistoryLoader();
static ImmutableTimeLockCorruptionComponents.Builder builder() {
return ImmutableTimeLockCorruptionComponents.builder();
}
}
|
palantir/atlasdb
|
timelock-agent/src/main/java/com/palantir/atlasdb/timelock/paxos/TimeLockCorruptionComponents.java
|
Java
|
apache-2.0
| 1,294
|
# Install script for directory: C:/Users/petit/Documents/Reflect_build123/llvm/tools/lto
# Set the install prefix
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
set(CMAKE_INSTALL_PREFIX "C:/Program Files (x86)/LLVM")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
if(BUILD_TYPE)
string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
else()
set(CMAKE_INSTALL_CONFIG_NAME "Release")
endif()
message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()
# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
if(COMPONENT)
message(STATUS "Install component: \"${COMPONENT}\"")
set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
else()
set(CMAKE_INSTALL_COMPONENT)
endif()
endif()
if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "LTO")
if("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Dd][Ee][Bb][Uu][Gg])$")
file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE SHARED_LIBRARY FILES "C:/Users/petit/Documents/Reflect_build123/build-clang/msvc/generated/Debug/bin/LTO.dll")
elseif("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Rr][Ee][Ll][Ee][Aa][Ss][Ee])$")
file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE SHARED_LIBRARY FILES "C:/Users/petit/Documents/Reflect_build123/build-clang/msvc/generated/Release/bin/LTO.dll")
elseif("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Mm][Ii][Nn][Ss][Ii][Zz][Ee][Rr][Ee][Ll])$")
file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE SHARED_LIBRARY FILES "C:/Users/petit/Documents/Reflect_build123/build-clang/msvc/generated/MinSizeRel/bin/LTO.dll")
elseif("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Rr][Ee][Ll][Ww][Ii][Tt][Hh][Dd][Ee][Bb][Ii][Nn][Ff][Oo])$")
file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE SHARED_LIBRARY FILES "C:/Users/petit/Documents/Reflect_build123/build-clang/msvc/generated/RelWithDebInfo/bin/LTO.dll")
endif()
endif()
if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include/llvm-c" TYPE FILE FILES "C:/Users/petit/Documents/Reflect_build123/llvm/include/llvm-c/lto.h")
endif()
|
Enseed/Reflect_build
|
build-clang/msvc/generated/tools/lto/cmake_install.cmake
|
CMake
|
apache-2.0
| 2,325
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>class_options (Thor::Base::ClassMethods)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre><span class="ruby-comment cmt"># File lib/bundler/vendor/thor/base.rb, line 202</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">class_options</span>(<span class="ruby-identifier">options</span>=<span class="ruby-keyword kw">nil</span>)
<span class="ruby-ivar">@class_options</span> <span class="ruby-operator">||=</span> <span class="ruby-identifier">from_superclass</span>(<span class="ruby-identifier">:class_options</span>, {})
<span class="ruby-identifier">build_options</span>(<span class="ruby-identifier">options</span>, <span class="ruby-ivar">@class_options</span>) <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>
<span class="ruby-ivar">@class_options</span>
<span class="ruby-keyword kw">end</span></pre>
</body>
</html>
|
ThoughtWorksStudios/excel-2010-mingle-addin
|
tools/ironruby/lib/ironruby/gems/1.8/doc/bundler-1.0.15/rdoc/classes/Thor/Base/ClassMethods.src/M000078.html
|
HTML
|
apache-2.0
| 1,302
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<meta name="description" content="Point cloud of the city of Montreal, Canada captured in 2015 with a resolution of 20 cm. Tiled and hosted by Cesium ion.">
<meta name="cesium-sandcastle-labels" content="ion Assets">
<title>Montreal Point Cloud</title>
<script type="text/javascript" src="../Sandcastle-header.js"></script>
<script type="text/javascript" src="../../../ThirdParty/requirejs-2.1.20/require.js"></script>
<script type="text/javascript">
require.config({
baseUrl : '../../../Source',
waitSeconds : 60
});
</script>
</head>
<body class="sandcastle-loading" data-sandcastle-bucket="bucket-requirejs.html">
<style>
@import url(../templates/bucket.css);
#toolbar {
background: rgba(42, 42, 42, 0.8);
padding: 4px;
border-radius: 4px;
}
#toolbar input {
vertical-align: middle;
padding-top: 2px;
padding-bottom: 2px;
}
#toolbar .header {
font-weight: bold;
}
</style>
<div id="cesiumContainer" class="fullSize"></div>
<div id="loadingOverlay"><h1>Loading...</h1></div>
<div id="toolbar">
<table><tbody>
<tr><td class="header">Classification Types</td></tr>
<tr>
<td>Ground</td>
<td><input type="checkbox" data-bind="checked: ground"></td>
</tr>
<tr>
<td>Low Vegetation</td>
<td><input type="checkbox" data-bind="checked: low_vegetation"></td>
</tr>
<tr>
<td>Medium Vegetation</td>
<td><input type="checkbox" data-bind="checked: medium_vegetation"></td>
</tr>
<tr>
<td>High Vegetation</td>
<td><input type="checkbox" data-bind="checked: high_vegetation"></td>
</tr>
<tr>
<td>Buildings</td>
<td><input type="checkbox" data-bind="checked: buildings"></td>
</tr>
<tr>
<td>Other/Unclassified</td>
<td><input type="checkbox" data-bind="checked: other"></td>
</tr>
</tbody></table>
</div>
<script id="cesium_sandcastle_script">
function startup(Cesium) {
'use strict';
//Sandcastle_Begin
var viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider: Cesium.createWorldTerrain()
});
// A ~10 billion point 3D Tileset of the city of Montreal, Canada captured in 2015 with a resolution of 20 cm. Tiled and hosted by Cesium ion.
var tileset = viewer.scene.primitives.add(
new Cesium.Cesium3DTileset({
url: Cesium.IonResource.fromAssetId(28945),
pointCloudShading: {
attenuation: true,
maximumAttenuation: 2
}
})
);
// Fly to a nice overview of the city.
viewer.camera.flyTo({
destination : new Cesium.Cartesian3(1223285.2286828577, -4319476.080312792, 4562579.020145769),
orientation : {
direction : new Cesium.Cartesian3(0.63053223097472, 0.47519958296727743, -0.6136892226931869),
up : new Cesium.Cartesian3(0.7699959023135587, -0.4824455703743441, 0.41755548379407276)
},
easingFunction: Cesium.EasingFunction.QUADRATIC_IN_OUT
});
// Add stored views around Montreal. You can add to this list by capturing camera.position, camera.direction and camera.up.
Sandcastle.addToolbarMenu([{
text : 'Overview',
onselect : function() {
viewer.camera.flyTo({
destination : new Cesium.Cartesian3(1268112.9336926902, -4347432.089579957, 4539129.813606778),
orientation : {
direction : new Cesium.Cartesian3(-0.23288147105081208, 0.9376599248561527, -0.25799241415197466),
up : new Cesium.Cartesian3(-0.015748156073159988, 0.2616156268422992, 0.9650436567182887)
},
easingFunction: Cesium.EasingFunction.QUADRATIC_IN_OUT
});
}
}, {
text : 'Highway',
onselect : function() {
viewer.camera.flyTo({
destination : new Cesium.Cartesian3(1266560.143870489, -4278126.842199712, 4542690.264566619),
orientation : {
direction : new Cesium.Cartesian3(-0.3402460635871598, -0.46669052711538217, -0.8163532128400116),
up : new Cesium.Cartesian3(0.08964012922691329, -0.8802940231336787, 0.46588311846138497)
},
easingFunction: Cesium.EasingFunction.QUADRATIC_IN_OUT
});
}
},
{
text : 'Olympic Stadium',
onselect : function() {
viewer.camera.flyTo({
destination : new Cesium.Cartesian3(1267081.619536883, -4290744.917138439, 4530941.041519919),
orientation : {
direction : new Cesium.Cartesian3(-0.735813047510908, 0.6294547560338262, 0.24973159435503312),
up : new Cesium.Cartesian3(-0.09796934684423217, -0.4638476756625683, 0.88048131204549)
},
easingFunction: Cesium.EasingFunction.QUADRATIC_IN_OUT
});
}
},
{
text : 'Biosphere Museum',
onselect : function() {
viewer.camera.flyTo({
destination : new Cesium.Cartesian3(1269319.8408991008, -4293301.826913256, 4527724.561372451),
orientation : {
direction : new Cesium.Cartesian3(-0.742505030107832, -0.3413204607149223, -0.5763563336703441),
up : new Cesium.Cartesian3(-0.04655102331027917, -0.8320643756800384, 0.5527222421370013)
},
easingFunction: Cesium.EasingFunction.QUADRATIC_IN_OUT
});
}
},
{
text : 'St. Joseph\'s Oratory of Mount Royal',
onselect : function() {
viewer.camera.flyTo({
destination : new Cesium.Cartesian3(1263148.6745904868, -4297262.506644816, 4525958.844284831),
orientation : {
direction : new Cesium.Cartesian3(0.6550952540993403, 0.7551122393690295, 0.025606913355780074),
up : new Cesium.Cartesian3(0.46670450470847263, -0.4310758971098583, 0.7722437932516845)
},
easingFunction: Cesium.EasingFunction.QUADRATIC_IN_OUT
});
}
}
]);
// Set up checkboxes for toggling the various classification settings.
var viewModel = {
ground: true,
other: true,
buildings: true,
low_vegetation: true,
medium_vegetation: true,
high_vegetation: true
};
// Assign colors to each classification type.
var pointStyles = {
'unclassified' : {
color: "color('#808080')",
show : true
},
'not_awarded' : {
color: "color('#FFDEAD')",
show : true
},
'ground' : {
color: "color('#FFDEAD')",
show : true
},
'low_vegetation' : {
color: "color('#63FF7E')",
show : true
},
'medium_vegetation' : {
color: "color('#63FF7E')",
show : true
},
'high_vegetation' : {
color: "color('#22B33A')",
show : true
},
'buildings' : {
color: "color('#efefef')",
show : true
},
'low_point' : {
color: "color('#808080')",
show : true
},
'reserved_city_diffusion' : {
color: "color('#808080')",
show : true
}
};
var classificationDictionary = {
'not_awarded' : 1,
'ground' : 2,
'low_vegetation' : 3,
'medium_vegetation' : 4,
'high_vegetation' : 5,
'buildings' : 6,
'low_point' : 7,
'reserved_city_diffusion' : 8,
'unclassified' : -1
};
// This is a helper function to re-apply the styles each time the UI/checkboxes are updated.
function applyStyle(tileset, styles) {
var styleObject = {};
var styleKeys = Object.keys(styles);
styleObject.color = {
conditions: []
};
styleObject.show = {
conditions: []
};
var finalCondition;
for (var i = 0; i < styleKeys.length; ++i) {
var key = styleKeys[i];
var id = classificationDictionary[key];
var colorCondition = ['${Classification} === ' + id, styles[key].color];
var showCondition = ['${Classification} === ' + id, styles[key].show];
if (id === -1) {
colorCondition[0] = true;
showCondition[0] = true;
finalCondition = {
colorCondition: colorCondition,
showCondition: showCondition
};
} else {
styleObject.color.conditions.push(colorCondition);
styleObject.show.conditions.push(showCondition);
}
}
if (Cesium.defined(finalCondition)) {
styleObject.color.conditions.push(finalCondition.colorCondition);
styleObject.show.conditions.push(finalCondition.showCondition);
}
tileset.style = new Cesium.Cesium3DTileStyle(styleObject);
}
// Apply an initial style.
applyStyle(tileset, pointStyles);
Cesium.knockout.track(viewModel);
var toolbar = document.getElementById('toolbar');
Cesium.knockout.applyBindings(viewModel, toolbar);
// Set up the checkboxes.
Cesium.knockout.getObservable(viewModel, 'ground').subscribe(function(show) {
pointStyles.ground.show = show;
pointStyles.not_awarded.show = show;
applyStyle(tileset, pointStyles);
});
Cesium.knockout.getObservable(viewModel, 'low_vegetation').subscribe(function(show) {
pointStyles.low_vegetation.show = show;
applyStyle(tileset, pointStyles);
});
Cesium.knockout.getObservable(viewModel, 'medium_vegetation').subscribe(function(show) {
pointStyles.medium_vegetation.show = show;
applyStyle(tileset, pointStyles);
});
Cesium.knockout.getObservable(viewModel, 'high_vegetation').subscribe(function(show) {
pointStyles.high_vegetation.show = show;
applyStyle(tileset, pointStyles);
});
Cesium.knockout.getObservable(viewModel, 'buildings').subscribe(function(show) {
pointStyles.buildings.show = show;
applyStyle(tileset, pointStyles);
});
Cesium.knockout.getObservable(viewModel, 'other').subscribe(function(show) {
pointStyles.low_point.show = show;
pointStyles.reserved_city_diffusion.show = show;
pointStyles.unclassified.show = show;
applyStyle(tileset, pointStyles);
});
//Sandcastle_End
Sandcastle.finishedLoading();
}
if (typeof Cesium !== 'undefined') {
startup(Cesium);
} else if (typeof require === 'function') {
require(['Cesium'], startup);
}
</script>
</body>
</html>
|
jasonbeverage/cesium
|
Apps/Sandcastle/gallery/Montreal Point Cloud.html
|
HTML
|
apache-2.0
| 10,388
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_60-ea) on Thu Jul 09 21:02:09 CEST 2015 -->
<title>Grapes (Groovy 2.4.4)</title>
<meta name="date" content="2015-07-09">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Grapes (Groovy 2.4.4)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="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="../../groovy/lang/GrabResolver.html" title="annotation in groovy.lang"><span class="strong">Prev Class</span></a></li>
<li><a href="../../groovy/lang/GroovyCallable.html" title="interface in groovy.lang"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?groovy/lang/Grapes.html" target="_top">Frames</a></li>
<li><a href="Grapes.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#annotation_type_required_element_summary">Required</a> | </li>
<li><a href="#annotation_type_optional_element_summary">Optional</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#annotation_type_element_detail">Element</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">groovy.lang</div>
<h2 title="Annotation Type Grapes" class="title">Annotation Type Grapes</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public @interface <span class="strong">Grapes</span></pre>
<div class="block">Sometimes we will need more than one grab per class, but we can only add
one annotation type per annotatable node. This class allows for multiple
grabs to be added.
<p>
For example:
<p>
<pre>
<code>@Grapes([@Grab(module='m1'), @Grab(module='m2')])</code>
class AnnotatedClass { ... }
</pre>
<p>
You can override an implicit transitive dependency by providing an explicit one.
E.g. htmlunit 2.6 normally uses xerces 2.9.1 but you can get 2.9.0 as follows:
<pre>
<code>@Grapes</code>([
<code>@Grab</code>('net.sourceforge.htmlunit:htmlunit:2.6'),
<code>@Grab</code>('xerces#xercesImpl;2.9.0')
])
</pre>
Obviously, only do this if you understand the consequences.
<p>
You can also remove transitive dependencies altogether (provided you
know you don't need them) using <code>@GrabExclude</code>.
For example, here is how we would not grab the <code>logkit</code> and
<code>avalon-framework</code> transitive dependencies for Apache POI:
<pre>
<code>@Grapes</code>([
<code>@Grab</code>("org.apache.poi#poi;3.5-beta6"),
<code>@GrabExclude</code>("logkit:logkit"),
<code>@GrabExclude</code>("avalon-framework#avalon-framework")
])
import org.apache.poi.hssf.util.CellReference
assert new CellReference(0, 0, false, false).formatAsString() == 'A1'
assert new CellReference(1, 3).formatAsString() == '$D$2'
</pre>
It is also sometimes also useful to use <code>@GrabConfig</code> to further adjust how dependencies
are grabbed. See <code>@GrabConfig</code> for further information.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ANNOTATION TYPE REQUIRED MEMBER SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="annotation_type_required_element_summary">
<!-- -->
</a>
<h3>Required Element Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Required Element Summary table, listing required elements, and an explanation">
<caption><span>Required Elements</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Required Element and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../groovy/lang/Grab.html" title="annotation in groovy.lang">Grab</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../groovy/lang/Grapes.html#value()">value</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- =========== ANNOTATION TYPE OPTIONAL MEMBER SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="annotation_type_optional_element_summary">
<!-- -->
</a>
<h3>Optional Element Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Optional Element Summary table, listing optional elements, and an explanation">
<caption><span>Optional Elements</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Optional Element and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../groovy/lang/Grapes.html#initClass()">initClass</a></strong></code>
<div class="block">This will be pushed into the child grab annotations if the value is not
set in the child annotation already.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ANNOTATION TYPE MEMBER DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="annotation_type_element_detail">
<!-- -->
</a>
<h3>Element Detail</h3>
<a name="value()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>value</h4>
<pre>public abstract <a href="../../groovy/lang/Grab.html" title="annotation in groovy.lang">Grab</a>[] value</pre>
</li>
</ul>
<a name="initClass()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>initClass</h4>
<pre>public abstract boolean initClass</pre>
<div class="block">This will be pushed into the child grab annotations if the value is not
set in the child annotation already.
<p>
This results in an effective change in the default value, which each @Grab
can still override</div>
<dl>
<dt>Default:</dt>
<dd>true</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em>Copyright © 2003-2015 The Apache Software Foundation. All rights reserved.</em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../groovy/lang/GrabResolver.html" title="annotation in groovy.lang"><span class="strong">Prev Class</span></a></li>
<li><a href="../../groovy/lang/GroovyCallable.html" title="interface in groovy.lang"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?groovy/lang/Grapes.html" target="_top">Frames</a></li>
<li><a href="Grapes.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#annotation_type_required_element_summary">Required</a> | </li>
<li><a href="#annotation_type_optional_element_summary">Optional</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#annotation_type_element_detail">Element</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
OpenBEL/kam-nav
|
tools/groovy/doc/html/api/groovy/lang/Grapes.html
|
HTML
|
apache-2.0
| 9,570
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* @class
* Initializes a new instance of the Provider class.
* @constructor
* Resource provider information.
*
* @member {string} [id] The provider ID.
*
* @member {string} [namespace] The namespace of the resource provider.
*
* @member {string} [registrationState] The registration state of the provider.
*
* @member {array} [resourceTypes] The collection of provider resource types.
*
*/
class Provider {
constructor() {
}
/**
* Defines the metadata of Provider
*
* @returns {object} metadata of Provider
*
*/
mapper() {
return {
required: false,
serializedName: 'Provider',
type: {
name: 'Composite',
className: 'Provider',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
namespace: {
required: false,
serializedName: 'namespace',
type: {
name: 'String'
}
},
registrationState: {
required: false,
readOnly: true,
serializedName: 'registrationState',
type: {
name: 'String'
}
},
resourceTypes: {
required: false,
readOnly: true,
serializedName: 'resourceTypes',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ProviderResourceTypeElementType',
type: {
name: 'Composite',
className: 'ProviderResourceType'
}
}
}
}
}
}
};
}
}
module.exports = Provider;
|
begoldsm/azure-sdk-for-node
|
lib/services/resourceManagement/lib/resource/models/provider.js
|
JavaScript
|
apache-2.0
| 2,219
|
# frozen_string_literal: true
class SessionsController < Devise::SessionsController
before_action :load_game, :load_message_count, except: %i[new destroy]
before_action :load_game_for_login, only: %i[new]
def load_game_for_login
@game = Game.instance
end
def new
super
end
end
|
mitre-cyber-academy/ctf-scoreboard
|
app/controllers/sessions_controller.rb
|
Ruby
|
apache-2.0
| 300
|
#!/usr/bin/env node
/**
* So we need two builds of sp-frontend with marginal changes for electron. The one for deployment at https://stream.place/ uses a root of "/" and the one for Electon uses a root of ".". This does
* that.
*/
/* eslint-disable no-console */
const child = require("child_process");
const fs = require("fs-extra");
const path = require("path");
const pkgRoot = path.resolve(__dirname, "..");
const oldPkgStr = fs.readFileSync(
path.resolve(pkgRoot, "package.json"),
"utf8"
);
fs.removeSync(path.resolve(pkgRoot, "build"));
fs.removeSync((pkgRoot, "build-electron"));
const newPkg = { ...JSON.parse(oldPkgStr), homepage: "." };
fs.writeFileSync(
path.resolve(pkgRoot, "package.json"),
JSON.stringify(newPkg, null, 2)
);
console.log("++++ building sp-frontend for electron ++++");
child.execSync("npm run prepare:build", { cwd: pkgRoot, stdio: "inherit" });
fs.renameSync(
path.resolve(pkgRoot, "build"),
path.resolve(pkgRoot, "build-electron")
);
fs.writeFileSync(path.resolve(pkgRoot, "package.json"), oldPkgStr);
console.log("++++ building sp-frontend for browsers ++++");
child.execSync("npm run prepare:build", { cwd: pkgRoot, stdio: "inherit" });
|
streamkitchen/streamkitchen
|
packages/sp-frontend/src/double-build.js
|
JavaScript
|
apache-2.0
| 1,191
|
/*
* 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 com.google.cloud.dataflow.sdk.util;
import static com.google.cloud.dataflow.sdk.util.TimeUtil.fromCloudTime;
import com.google.api.services.dataflow.Dataflow;
import com.google.api.services.dataflow.Dataflow.Projects.Jobs.Messages;
import com.google.api.services.dataflow.model.JobMessage;
import com.google.api.services.dataflow.model.ListJobMessagesResponse;
import com.google.cloud.dataflow.sdk.PipelineResult.State;
import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import org.joda.time.Instant;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A helper class for monitoring jobs submitted to the service.
*/
public final class MonitoringUtil {
private static final String GCLOUD_DATAFLOW_PREFIX = "gcloud alpha dataflow";
private static final String ENDPOINT_OVERRIDE_ENV_VAR =
"CLOUDSDK_API_ENDPOINT_OVERRIDES_DATAFLOW";
private static final Map<String, State> DATAFLOW_STATE_TO_JOB_STATE =
ImmutableMap
.<String, State>builder()
.put("JOB_STATE_UNKNOWN", State.UNKNOWN)
.put("JOB_STATE_STOPPED", State.STOPPED)
.put("JOB_STATE_RUNNING", State.RUNNING)
.put("JOB_STATE_DONE", State.DONE)
.put("JOB_STATE_FAILED", State.FAILED)
.put("JOB_STATE_CANCELLED", State.CANCELLED)
.put("JOB_STATE_UPDATED", State.UPDATED)
.build();
private String projectId;
private Messages messagesClient;
/**
* An interface that can be used for defining callbacks to receive a list
* of JobMessages containing monitoring information.
*/
public interface JobMessagesHandler {
/** Process the rows. */
void process(List<JobMessage> messages);
}
/** A handler that prints monitoring messages to a stream. */
public static class PrintHandler implements JobMessagesHandler {
private PrintStream out;
/**
* Construct the handler.
*
* @param stream The stream to write the messages to.
*/
public PrintHandler(PrintStream stream) {
out = stream;
}
@Override
public void process(List<JobMessage> messages) {
for (JobMessage message : messages) {
if (message.getMessageText() == null || message.getMessageText().isEmpty()) {
continue;
}
String importanceString = null;
if (message.getMessageImportance() == null) {
continue;
} else if (message.getMessageImportance().equals("JOB_MESSAGE_ERROR")) {
importanceString = "Error: ";
} else if (message.getMessageImportance().equals("JOB_MESSAGE_WARNING")) {
importanceString = "Warning: ";
} else if (message.getMessageImportance().equals("JOB_MESSAGE_BASIC")) {
importanceString = "Basic: ";
} else if (message.getMessageImportance().equals("JOB_MESSAGE_DETAILED")) {
importanceString = "Detail: ";
} else {
// TODO: Remove filtering here once getJobMessages supports minimum
// importance.
continue;
}
@Nullable Instant time = TimeUtil.fromCloudTime(message.getTime());
if (time == null) {
out.print("UNKNOWN TIMESTAMP: ");
} else {
out.print(time + ": ");
}
if (importanceString != null) {
out.print(importanceString);
}
out.println(message.getMessageText());
}
out.flush();
}
}
/** Construct a helper for monitoring. */
public MonitoringUtil(String projectId, Dataflow dataflow) {
this(projectId, dataflow.projects().jobs().messages());
}
// @VisibleForTesting
MonitoringUtil(String projectId, Messages messagesClient) {
this.projectId = projectId;
this.messagesClient = messagesClient;
}
/**
* Comparator for sorting rows in increasing order based on timestamp.
*/
public static class TimeStampComparator implements Comparator<JobMessage> {
@Override
public int compare(JobMessage o1, JobMessage o2) {
@Nullable Instant t1 = fromCloudTime(o1.getTime());
if (t1 == null) {
return -1;
}
@Nullable Instant t2 = fromCloudTime(o2.getTime());
if (t2 == null) {
return 1;
}
return t1.compareTo(t2);
}
}
/**
* Return job messages sorted in ascending order by timestamp.
* @param jobId The id of the job to get the messages for.
* @param startTimestampMs Return only those messages with a
* timestamp greater than this value.
* @return collection of messages
* @throws IOException
*/
public ArrayList<JobMessage> getJobMessages(
String jobId, long startTimestampMs) throws IOException {
// TODO: Allow filtering messages by importance
Instant startTimestamp = new Instant(startTimestampMs);
ArrayList<JobMessage> allMessages = new ArrayList<>();
String pageToken = null;
while (true) {
Messages.List listRequest = messagesClient.list(projectId, jobId);
if (pageToken != null) {
listRequest.setPageToken(pageToken);
}
ListJobMessagesResponse response = listRequest.execute();
if (response == null || response.getJobMessages() == null) {
return allMessages;
}
for (JobMessage m : response.getJobMessages()) {
@Nullable Instant timestamp = fromCloudTime(m.getTime());
if (timestamp == null) {
continue;
}
if (timestamp.isAfter(startTimestamp)) {
allMessages.add(m);
}
}
if (response.getNextPageToken() == null) {
break;
} else {
pageToken = response.getNextPageToken();
}
}
Collections.sort(allMessages, new TimeStampComparator());
return allMessages;
}
public static String getJobMonitoringPageURL(String projectName, String jobId) {
try {
// Project name is allowed in place of the project id: the user will be redirected to a URL
// that has the project name replaced with project id.
return String.format(
"https://console.developers.google.com/project/%s/dataflow/job/%s",
URLEncoder.encode(projectName, "UTF-8"),
URLEncoder.encode(jobId, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// Should never happen.
throw new AssertionError("UTF-8 encoding is not supported by the environment", e);
}
}
public static String getGcloudCancelCommand(DataflowPipelineOptions options, String jobId) {
// If using a different Dataflow API than default, prefix command with an API override.
String dataflowApiOverridePrefix = "";
String apiUrl = options.getDataflowClient().getBaseUrl();
if (!apiUrl.equals(Dataflow.DEFAULT_BASE_URL)) {
dataflowApiOverridePrefix = String.format("%s=%s ", ENDPOINT_OVERRIDE_ENV_VAR, apiUrl);
}
// Assemble cancel command from optional prefix and project/job parameters.
return String.format("%s%s jobs --project=%s cancel %s",
dataflowApiOverridePrefix, GCLOUD_DATAFLOW_PREFIX, options.getProject(), jobId);
}
public static State toState(String stateName) {
return MoreObjects.firstNonNull(DATAFLOW_STATE_TO_JOB_STATE.get(stateName),
State.UNKNOWN);
}
}
|
shakamunyi/beam
|
sdks/java/core/src/main/java/com/google/cloud/dataflow/sdk/util/MonitoringUtil.java
|
Java
|
apache-2.0
| 8,343
|
function validate() {
$("#app-form").bootstrapValidator({
message: "This value is not valid",
feedbackIcons: {
valid: "glyphicon glyphicon-ok",
invalid: "glyphicon glyphicon-remove",
validating: "glyphicon glyphicon-refresh"
},
fields: {
appName: {
validators: {
notEmpty: {
message: $.i18n.prop("app-name-not-null")
},
stringLength: {
max: 100,
message: $.i18n.prop("app-name-length-limit")
},
callback: {
message: $.i18n.prop("app-name-exists"),
callback: function() {
var appName = $("#app-name").val();
var result = true;
$.ajax({
url: "/api/app/" + appName,
contentType: "application/json",
async: false,
success: function(data) {
if (null !== data) {
result = false;
}
}
});
return result;
}
}
}
},
bootstrapScript: {
validators: {
notEmpty: {
message: $.i18n.prop("app-bootstrap-script-not-null")
}
}
},
cpuCount: {
validators: {
notEmpty: {
message: $.i18n.prop("app-cpu-count-not-null")
},
regexp: {
regexp: /^(-?\d+)(\.\d+)?$/,
message: $.i18n.prop("app-cpu-count-regexp-limit")
}
}
},
appMemory: {
validators: {
notEmpty: {
message: $.i18n.prop("app-memory-not-null")
}
}
},
eventTraceSamplingCount: {
validators: {
notEmpty: {
message: $.i18n.prop("event-trace-sampling-count-not-null")
}
}
},
appURL: {
validators: {
notEmpty: {
message: $.i18n.prop("app-url-not-null")
}
}
}
}
});
}
function submitConfirm(type, modal) {
$("#save-button").on("click", function() {
var bootstrapValidator = $("#app-form").data("bootstrapValidator");
bootstrapValidator.validate();
if(bootstrapValidator.isValid()) {
$.ajax({
type: type,
dataType: "json",
data: JSON.stringify(getApp()),
url: "/api/app",
contentType: "application/json",
success: function(data) {
modal.modal("hide");
$("#app-table").bootstrapTable("refresh");
$(".modal-backdrop").remove();
$("body").removeClass("modal-open");
refreshAppNavTag();
}
});
}
});
}
function getApp() {
return {
appName: $("#app-name").val(),
cpuCount: $("#cpu-count").val(),
memoryMB: $("#app-memory").val(),
bootstrapScript: $("#bootstrap-script").val(),
appCacheEnable: $("#app-cache-enable").prop("checked"),
appURL: $("#app-url").val(),
eventTraceSamplingCount: $("#event-trace-sampling-count").val()
};
}
|
Esjob-Cloud-DevOps/elastic-job
|
elastic-job-cloud/elastic-job-cloud-scheduler/src/main/resources/console/js/app/app_common.js
|
JavaScript
|
apache-2.0
| 4,039
|
# Copyright (c) 2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial
from swift.common.utils import json
from swift3.response import InvalidArgument, MalformedACLError, \
S3NotImplemented, InvalidRequest, AccessDenied
from swift3.etree import Element, SubElement
from swift3.utils import LOGGER, sysmeta_header
from swift3.cfg import CONF
from swift3.exception import InvalidSubresource
XMLNS_XSI = 'http://www.w3.org/2001/XMLSchema-instance'
PERMISSIONS = ['FULL_CONTROL', 'READ', 'WRITE', 'READ_ACP', 'WRITE_ACP']
LOG_DELIVERY_USER = '.log_delivery'
"""
An entry point of this approach is here.
We should understand what we have to design to achieve real S3 ACL.
S3's ACL Model is as follows:
AccessControlPolicy:
Owner:
AccessControlList:
Grant[n]:
(Grantee, Permission)
Each bucket or object has its own acl consists of Owner and
AcessControlList. AccessControlList can contain some Grants.
By default, AccessControlList has only one Grant to allow FULL
CONTROLL to owner. Each Grant includes single pair with Grantee,
Permission. Grantee is the user (or user group) allowed the given
permission.
If you wanna get more information about S3's ACL model in detail,
please see official documentation here,
http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html
"""
def encode_acl(resource, acl):
"""
Encode an ACL instance to Swift metadata.
Given a resource type and an ACL instance, this method returns HTTP
headers, which can be used for Swift metadata.
"""
header_value = {"Owner": acl.owner.id}
grants = []
for grant in acl.grants:
grant = {"Permission": grant.permission,
"Grantee": str(grant.grantee)}
grants.append(grant)
header_value.update({"Grant": grants})
headers = {}
key = sysmeta_header(resource, 'acl')
headers[key] = json.dumps(header_value, separators=(',', ':'))
return headers
def decode_acl(resource, headers):
"""
Decode Swift metadata to an ACL instance.
Given a resource type and HTTP headers, this method returns an ACL
instance.
"""
value = ''
key = sysmeta_header(resource, 'acl')
if key in headers:
value = headers[key]
if value == '':
# Fix me: In the case of value is empty or not dict instance,
# I want an instance of Owner as None.
# However, in the above process would occur error in reference
# to an instance variable of Owner.
return ACL(Owner(None, None), [])
try:
encode_value = json.loads(value)
if not isinstance(encode_value, dict):
return ACL(Owner(None, None), [])
id = None
name = None
grants = []
if 'Owner' in encode_value:
id = encode_value['Owner']
name = encode_value['Owner']
if 'Grant' in encode_value:
for grant in encode_value['Grant']:
grantee = None
# pylint: disable-msg=E1101
for group in Group.__subclasses__():
if group.__name__ == grant['Grantee']:
grantee = group()
if not grantee:
grantee = User(grant['Grantee'])
permission = grant['Permission']
grants.append(Grant(grantee, permission))
return ACL(Owner(id, name), grants)
except Exception as e:
LOGGER.debug(e)
pass
raise InvalidSubresource((resource, 'acl', value))
class Grantee(object):
"""
Base class for grantee.
:Definition (methods):
init -> create a Grantee instance
elem -> create an ElementTree from itself
:Definition (static methods):
from_header -> convert a grantee string in the HTTP header
to an Grantee instance.
from_elem -> convert a ElementTree to an Grantee instance.
TODO (not yet):
NOTE: Needs confirmation whether we really need these methods or not.
encode (method) -> create a JSON which includes whole own elements
encode_from_elem (static method) -> convert from an ElementTree to a JSON
elem_from_json (static method) -> convert from a JSON to an ElementTree
from_json (static method) -> convert a Json string to an Grantee instance.
"""
def __contains__(self, key):
"""
The key argument is a S3 user id. This method checks that the user id
belongs to this class.
"""
raise S3NotImplemented()
def elem(self):
"""
Get an etree element of this instance.
"""
raise S3NotImplemented()
@staticmethod
def from_elem(elem):
type = elem.get('{%s}type' % XMLNS_XSI)
if type == 'CanonicalUser':
value = elem.find('./ID').text
return User(value)
elif type == 'Group':
value = elem.find('./URI').text
subclass = get_group_subclass_from_uri(value)
return subclass()
elif type == 'AmazonCustomerByEmail':
raise S3NotImplemented()
else:
raise MalformedACLError()
@staticmethod
def from_header(grantee):
"""
Convert a grantee string in the HTTP header to an Grantee instance.
"""
type, value = grantee.split('=', 1)
value = value.strip('"\'')
if type == 'id':
return User(value)
elif type == 'emailAddress':
raise S3NotImplemented()
elif type == 'uri':
# retrun a subclass instance of Group class
subclass = get_group_subclass_from_uri(value)
return subclass()
else:
raise InvalidArgument(type, value,
'Argument format not recognized')
class User(Grantee):
"""
Canonical user class for S3 accounts.
"""
type = 'CanonicalUser'
def __init__(self, name):
self.id = name
self.display_name = name
def __contains__(self, key):
return key == self.id
def elem(self):
elem = Element('Grantee', nsmap={'xsi': XMLNS_XSI})
elem.set('{%s}type' % XMLNS_XSI, self.type)
SubElement(elem, 'ID').text = self.id
SubElement(elem, 'DisplayName').text = self.display_name
return elem
def __str__(self):
return self.display_name
class Owner(object):
"""
Owner class for S3 accounts
"""
def __init__(self, id, name):
self.id = id
self.name = name
def get_group_subclass_from_uri(uri):
"""
Convert a URI to one of the predefined groups.
"""
for group in Group.__subclasses__(): # pylint: disable-msg=E1101
if group.uri == uri:
return group
raise InvalidArgument('uri', uri, 'Invalid group uri')
class Group(Grantee):
"""
Base class for Amazon S3 Predefined Groups
"""
type = 'Group'
uri = ''
def __init__(self):
# Initialize method to clarify this has nothing to do
pass
def elem(self):
elem = Element('Grantee', nsmap={'xsi': XMLNS_XSI})
elem.set('{%s}type' % XMLNS_XSI, self.type)
SubElement(elem, 'URI').text = self.uri
return elem
def __str__(self):
return self.__class__.__name__
def canned_acl_grantees(bucket_owner, object_owner=None):
"""
A set of predefined grants supported by AWS S3.
"""
owner = object_owner or bucket_owner
return {
'private': [
('FULL_CONTROL', User(owner.name)),
],
'public-read': [
('READ', AllUsers()),
('FULL_CONTROL', User(owner.name)),
],
'public-read-write': [
('READ', AllUsers()),
('WRITE', AllUsers()),
('FULL_CONTROL', User(owner.name)),
],
'authenticated-read': [
('READ', AuthenticatedUsers()),
('FULL_CONTROL', User(owner.name)),
],
'bucket-owner-read': [
('READ', User(bucket_owner.name)),
('FULL_CONTROL', User(owner.name)),
],
'bucket-owner-full-control': [
('FULL_CONTROL', User(owner.name)),
('FULL_CONTROL', User(bucket_owner.name)),
],
'log-delivery-write': [
('WRITE', LogDelivery()),
('READ_ACP', LogDelivery()),
('FULL_CONTROL', User(owner.name)),
],
}
class AuthenticatedUsers(Group):
"""
This group represents all AWS accounts. Access permission to this group
allows any AWS account to access the resource. However, all requests must
be signed (authenticated).
"""
uri = 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers'
def __contains__(self, key):
# Swift3 handles only signed requests.
return True
class AllUsers(Group):
"""
Access permission to this group allows anyone to access the resource. The
requests can be signed (authenticated) or unsigned (anonymous). Unsigned
requests omit the Authentication header in the request.
Note: Swift3 regards unsigned requests as Swift API accesses, and bypasses
them to Swift. As a result, AllUsers behaves completely same as
AuthenticatedUsers.
"""
uri = 'http://acs.amazonaws.com/groups/global/AllUsers'
def __contains__(self, key):
return True
class LogDelivery(Group):
"""
WRITE and READ_ACP permissions on a bucket enables this group to write
server access logs to the bucket.
"""
uri = 'http://acs.amazonaws.com/groups/s3/LogDelivery'
def __contains__(self, key):
if ':' in key:
tenant, user = key.split(':', 1)
else:
user = key
return user == LOG_DELIVERY_USER
class Grant(object):
"""
Grant Class which includes both Grantee and Permission
"""
def __init__(self, grantee, permission):
"""
:param grantee: a grantee class or its subclass
:param permission: string
"""
if permission.upper() not in PERMISSIONS:
raise S3NotImplemented()
if not isinstance(grantee, Grantee):
raise
self.grantee = grantee
self.permission = permission
@classmethod
def from_elem(cls, elem):
"""
Convert an ElementTree to an ACL instance
"""
grantee = Grantee.from_elem(elem.find('./Grantee'))
permission = elem.find('./Permission').text
return cls(grantee, permission)
def elem(self):
"""
Create an etree element.
"""
elem = Element('Grant')
elem.append(self.grantee.elem())
SubElement(elem, 'Permission').text = self.permission
return elem
def allow(self, grantee, permission):
return permission == self.permission and grantee in self.grantee
class ACL(object):
"""
S3 ACL class.
Refs (S3 API - acl-overview:
http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html):
The sample ACL includes an Owner element identifying the owner via the
AWS account's canonical user ID. The Grant element identifies the grantee
(either an AWS account or a predefined group), and the permission granted.
This default ACL has one Grant element for the owner. You grant permissions
by adding Grant elements, each grant identifying the grantee and the
permission.
"""
metadata_name = 'acl'
root_tag = 'AccessControlPolicy'
max_xml_length = 200 * 1024
def __init__(self, owner, grants=[]):
"""
:param owner: Owner Class for ACL instance
"""
self.owner = owner
self.grants = grants
@classmethod
def from_elem(cls, elem):
"""
Convert an ElementTree to an ACL instance
"""
id = elem.find('./Owner/ID').text
try:
name = elem.find('./Owner/DisplayName').text
except AttributeError:
name = id
grants = [Grant.from_elem(e)
for e in elem.findall('./AccessControlList/Grant')]
return cls(Owner(id, name), grants)
def elem(self):
"""
Decode the value to an ACL instance.
"""
elem = Element(self.root_tag)
owner = SubElement(elem, 'Owner')
SubElement(owner, 'ID').text = self.owner.id
SubElement(owner, 'DisplayName').text = self.owner.name
SubElement(elem, 'AccessControlList').extend(
g.elem() for g in self.grants
)
return elem
def check_owner(self, user_id):
"""
Check that the user is an owner.
"""
if not CONF.s3_acl:
# Ignore Swift3 ACL.
return
if not self.owner.id:
if CONF.allow_no_owner:
# No owner means public.
return
raise AccessDenied()
if user_id != self.owner.id:
raise AccessDenied()
def check_permission(self, user_id, permission):
"""
Check that the user has a permission.
"""
if not CONF.s3_acl:
# Ignore Swift3 ACL.
return
try:
# owners have full control permission
self.check_owner(user_id)
return
except AccessDenied:
pass
if permission in PERMISSIONS:
for g in self.grants:
if g.allow(user_id, 'FULL_CONTROL') or \
g.allow(user_id, permission):
return
raise AccessDenied()
@classmethod
def from_headers(cls, headers, bucket_owner, object_owner=None,
as_private=True):
"""
Convert HTTP headers to an ACL instance.
"""
grants = []
try:
for key, value in headers.items():
if key.lower().startswith('x-amz-grant-'):
permission = key[len('x-amz-grant-'):]
permission = permission.upper().replace('-', '_')
if permission not in PERMISSIONS:
continue
for grantee in value.split(','):
grants.append(
Grant(Grantee.from_header(grantee), permission))
if 'x-amz-acl' in headers:
try:
acl = headers['x-amz-acl']
if len(grants) > 0:
err_msg = 'Specifying both Canned ACLs and Header ' \
'Grants is not allowed'
raise InvalidRequest(err_msg)
grantees = canned_acl_grantees(
bucket_owner, object_owner)[acl]
for permission, grantee in grantees:
grants.append(Grant(grantee, permission))
except KeyError:
# expects canned_acl_grantees()[] raises KeyError
raise InvalidArgument('x-amz-acl', headers['x-amz-acl'])
except (KeyError, ValueError):
# TODO: think about we really catch this except sequence
raise InvalidRequest()
if len(grants) == 0:
# No ACL headers
if as_private:
return ACLPrivate(bucket_owner, object_owner)
else:
return None
return cls(object_owner or bucket_owner, grants)
class CannedACL(object):
"""
A dict-like object that returns canned ACL.
"""
def __getitem__(self, key):
def acl(key, bucket_owner, object_owner=None):
grants = []
grantees = canned_acl_grantees(bucket_owner, object_owner)[key]
for permission, grantee in grantees:
grants.append(Grant(grantee, permission))
return ACL(object_owner or bucket_owner, grants)
return partial(acl, key)
canned_acl = CannedACL()
ACLPrivate = canned_acl['private']
ACLPublicRead = canned_acl['public-read']
ACLPublicReadWrite = canned_acl['public-read-write']
ACLAuthenticatedRead = canned_acl['authenticated-read']
ACLBucketOwnerRead = canned_acl['bucket-owner-read']
ACLBucketOwnerFullControl = canned_acl['bucket-owner-full-control']
ACLLogDeliveryWrite = canned_acl['log-delivery-write']
|
KoreaCloudObjectStorage/swift3
|
swift3/subresource.py
|
Python
|
apache-2.0
| 16,885
|
package jef.orm.multitable2;
import java.io.Serializable;
import javax.persistence.Entity;
@Entity
public class TextValuePair implements Comparable<TextValuePair>,Serializable{
private static final long serialVersionUID = -2213222495346597158L;
private String text;
private String value;
public TextValuePair() {
}
public TextValuePair(String text, String value) {
this.text = text;
this.value = value;
}
public String getText() {
return text;
}
// @TypeAdapters(value={
// @TypeAdapter(converter = DateToStringConvert.class, parameters = "yyyy-MM-dd")
// })
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
// @TypeAdapters(value={
// @TypeAdapter(converter = DateToStringConvert.class, parameters = "yyyy-MM-dd")
// })
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
if(text==null)return value;
if(value==null)return text;
return new StringBuilder(text.length()+value.length()+2).append('[').append(value).append(']').append(text).toString();
}
@Override
public int hashCode() {
return text.hashCode()+value.hashCode();
}
public int compareTo(TextValuePair o) {
if(o==null)return 1;
if(o.value==null)return 1;
return this.value.compareTo(o.value);
}
}
|
xuse/ef-orm
|
orm-test/src/test/java/jef/orm/multitable2/TextValuePair.java
|
Java
|
apache-2.0
| 1,320
|
// Copyright 2015 The Serviced 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.
// +build unit
package btrfs
import (
"fmt"
"github.com/stretchr/testify/assert"
"math"
"testing"
)
type ParseDFTest struct {
label string
in []string
out []BtrfsDFData
outmsg string
err error
errmsg string
}
/*
type BtrfsDFData struct {
DataType string
Level string
Total uint64
Used uint64
}*/
const (
GiB = uint64(1024 * 1024 * 1024)
MiB = uint64(1024 * 1024)
KiB = uint64(1024)
B = uint64(1)
)
var parsedftests = []ParseDFTest{
{
label: "output from btrfs fi df (v3.12)",
in: []string{
"Data, single: total=9.00GiB, used=8.67GiB",
"System, DUP: total=32.00MiB, used=16.00KiB",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
},
out: []BtrfsDFData{
{DataType: "Data", Level: "single", Total: toBytes(9.00, GiB), Used: toBytes(8.67, GiB)},
{DataType: "System", Level: "DUP", Total: toBytes(32.00, MiB), Used: toBytes(16.00, KiB)},
{DataType: "Metadata", Level: "DUP", Total: toBytes(1.00, GiB), Used: toBytes(466.88, MiB)},
},
outmsg: "output did not match expectation",
err: nil,
errmsg: "error was not nil",
},
{
label: "empty lines should be tolerated in input",
in: []string{
"Data, single: total=9.00GiB, used=8.67GiB",
"System, DUP: total=32.00MiB, used=16.00KiB",
"",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
"",
},
out: []BtrfsDFData{
{DataType: "Data", Level: "single", Total: toBytes(9.00, GiB), Used: toBytes(8.67, GiB)},
{DataType: "System", Level: "DUP", Total: toBytes(32.00, MiB), Used: toBytes(16.00, KiB)},
{DataType: "Metadata", Level: "DUP", Total: toBytes(1.00, GiB), Used: toBytes(466.88, MiB)},
},
outmsg: "output did not match expectation",
err: nil,
errmsg: "error was not nil",
},
{
label: "output from btrfs fi df (v3.17)",
in: []string{
"System, DUP: total=8.00MiB, used=16.00KiB",
"System, single: total=4.00MiB, used=0.00B",
"Metadata, DUP: total=51.19MiB, used=112.00KiB",
"Metadata, single: total=8.00MiB, used=0.00B",
"GlobalReserve, single: total=16.00MiB, used=0.00B",
},
out: []BtrfsDFData{
{DataType: "System", Level: "DUP", Total: toBytes(8.00, MiB), Used: toBytes(16.00, KiB)},
{DataType: "System", Level: "single", Total: toBytes(4.00, MiB), Used: toBytes(0.00, B)},
{DataType: "Metadata", Level: "DUP", Total: toBytes(51.19, MiB), Used: toBytes(112.00, KiB)},
{DataType: "Metadata", Level: "single", Total: toBytes(8.00, MiB), Used: toBytes(0.00, B)},
{DataType: "GlobalReserve", Level: "single", Total: toBytes(16.00, MiB), Used: toBytes(0.00, B)},
},
outmsg: "output did not match expectation",
err: nil,
errmsg: "error was not nil",
},
{
label: "output from btrfs fi df --raw (v3.17)",
in: []string{
"System, DUP: total=8388608, used=16384",
"System, single: total=4194304, used=0",
"Metadata, DUP: total=53673984, used=114688",
"Metadata, single: total=8388608, used=0",
"GlobalReserve, single: total=16777216, used=0",
},
out: []BtrfsDFData{
{DataType: "System", Level: "DUP", Total: uint64(8388608), Used: uint64(16384)},
{DataType: "System", Level: "single", Total: uint64(4194304), Used: uint64(0)},
{DataType: "Metadata", Level: "DUP", Total: uint64(53673984), Used: uint64(114688)},
{DataType: "Metadata", Level: "single", Total: uint64(8388608), Used: uint64(0)},
{DataType: "GlobalReserve", Level: "single", Total: uint64(16777216), Used: uint64(0)},
},
outmsg: "output did not match expectation",
err: nil,
errmsg: "error was not nil",
},
{
label: "bad line in output (wrong number of fields)",
in: []string{
"Data, single: total=9.00GiB, used=8.67GiB",
"System, DUP: total=32.00MiB, used=16.00KiB",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
"arglebarglefoo",
},
out: []BtrfsDFData{},
outmsg: "output should be empty",
err: fmt.Errorf("Wrong number of fields (%d, expected 4) in line %q", 1, "arglebarglefoo"),
errmsg: "error did not match expectation",
},
{
label: "bad line in output (bad first field name)",
in: []string{
"NotReal, single: total=9.00GiB, used=8.67GiB",
"System, DUP: total=32.00MiB, used=16.00KiB",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
},
out: []BtrfsDFData{},
outmsg: "output should be empty",
err: fmt.Errorf("Unrecognized field %q in line %q", "NotReal", "NotReal, single: total=9.00GiB, used=8.67GiB"),
errmsg: "error did not match expectation",
},
{
label: "bad line in output (wrong number of fields - too many)",
in: []string{
"Data, single: total=9.00GiB, used=8.67GiB, extraField=1.23KiB",
"System, DUP: total=32.00MiB, used=16.00KiB",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
},
out: []BtrfsDFData{},
outmsg: "output should be empty",
err: fmt.Errorf("Wrong number of fields (%d, expected 4) in line %q", 5, "Data, single: total=9.00GiB, used=8.67GiB, extraField=1.23KiB"),
errmsg: "error did not match expectation",
},
{
label: "bad line in output (wrong number of fields - too few)",
in: []string{
"Data, single: total=9.00GiB",
"System, DUP: total=32.00MiB, used=16.00KiB",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
},
out: []BtrfsDFData{},
outmsg: "output should be empty",
err: fmt.Errorf("Wrong number of fields (%d, expected 4) in line %q", 3, "Data, single: total=9.00GiB"),
errmsg: "error did not match expectation",
},
{
label: "bad line in output (total field missing)",
in: []string{
"Data, single: nottotal=9.00GiB, used=8.67GiB",
"System, DUP: total=32.00MiB, used=16.00KiB",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
},
out: []BtrfsDFData{},
outmsg: "output should be empty",
err: fmt.Errorf("expected total field, not found in line %q", "Data, single: nottotal=9.00GiB, used=8.67GiB"),
errmsg: "error did not match expectation",
},
{
label: "bad line in output (used field missing)",
in: []string{
"Data, single: total=9.00GiB, notused=8.67GiB",
"System, DUP: total=32.00MiB, used=16.00KiB",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
},
out: []BtrfsDFData{},
outmsg: "output should be empty",
err: fmt.Errorf("expected used field, not found in line %q", "Data, single: total=9.00GiB, notused=8.67GiB"),
errmsg: "error did not match expectation",
},
{
label: "too few lines in output",
in: []string{
"System, DUP: total=32.00MiB, used=16.00KiB",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
},
out: []BtrfsDFData{},
outmsg: "output should be empty",
err: fmt.Errorf("insufficient output: %v",
"System, DUP: total=32.00MiB, used=16.00KiB\nMetadata, DUP: total=1.00GiB, used=466.88MiB"),
errmsg: "error did not match expectation",
},
{
label: "too few lines in output - with blank lines",
in: []string{
"System, DUP: total=32.00MiB, used=16.00KiB",
"",
"Metadata, DUP: total=1.00GiB, used=466.88MiB",
},
out: []BtrfsDFData{},
outmsg: "output should be empty",
err: fmt.Errorf("insufficient output: %v",
"System, DUP: total=32.00MiB, used=16.00KiB\nMetadata, DUP: total=1.00GiB, used=466.88MiB"),
errmsg: "error did not match expectation",
},
}
func toBytes(value float64, multiplier uint64) uint64 {
return uint64(math.Floor(value * float64(multiplier)))
}
func TestStub(t *testing.T) {
assert.True(t, true, "Test environment set up properly.")
}
func TestParseDF(t *testing.T) {
for _, tc := range parsedftests {
result, err := parseDF(tc.in)
assert.Equal(t, err, tc.err, fmt.Sprintf("%s: %s", tc.label, tc.errmsg))
assert.Equal(t, result, tc.out, fmt.Sprintf("%s: %s", tc.label, tc.outmsg))
}
}
|
control-center/serviced
|
volume/btrfs/btrfs_unit_test.go
|
GO
|
apache-2.0
| 8,237
|
---
layout: vakit_dashboard
title: MORINGEN, ALMANYA için iftar, namaz vakitleri ve hava durumu - ilçe/eyalet seç
permalink: /ALMANYA/MORINGEN
---
## MORINGEN (ALMANYA) için iftar, namaz vakitleri ve hava durumu görmek için bir ilçe/eyalet seç
Aşağıdaki listeden bir şehir ya da semt seçin
* [ (MORINGEN, ALMANYA) için iftar ve namaz vakitleri](/ALMANYA/MORINGEN/)
<script type="text/javascript">
var GLOBAL_COUNTRY = 'ALMANYA';
var GLOBAL_CITY = 'MORINGEN';
var GLOBAL_STATE = 'MORINGEN';
</script>
|
hakanu/iftar
|
_posts_/vakit/ALMANYA/MORINGEN/2017-02-01-MORINGEN.markdown
|
Markdown
|
apache-2.0
| 525
|
import gdb
# This is not quite right, as local vars may override symname
def read_global_var (symname):
return gdb.selected_frame().read_var(symname)
def g_quark_to_string (quark):
if quark == None:
return None
quark = long(quark)
if quark == 0:
return None
try:
val = read_global_var ("quarks")
max_q = long(read_global_var ("quark_seq_id"))
except:
try:
val = read_global_var ("g_quarks")
max_q = long(read_global_var ("g_quark_seq_id"))
except:
return None;
if quark < max_q:
return val[quark].string()
return None
# We override the node printers too, so that node->next is not expanded
class GListNodePrinter:
"Prints a GList node"
def __init__ (self, val):
self.val = val
def to_string (self):
return "{data=%s, next=0x%x, prev=0x%x}" % (str(self.val["data"]), long(self.val["next"]), long(self.val["prev"]))
class GSListNodePrinter:
"Prints a GSList node"
def __init__ (self, val):
self.val = val
def to_string (self):
return "{data=%s, next=0x%x}" % (str(self.val["data"]), long(self.val["next"]))
class GListPrinter:
"Prints a GList"
class _iterator:
def __init__(self, head, listtype):
self.link = head
self.listtype = listtype
self.count = 0
def __iter__(self):
return self
def next(self):
if self.link == 0:
raise StopIteration
data = self.link['data']
self.link = self.link['next']
count = self.count
self.count = self.count + 1
return ('[%d]' % count, data)
def __init__ (self, val, listtype):
self.val = val
self.listtype = listtype
def children(self):
return self._iterator(self.val, self.listtype)
def to_string (self):
return "0x%x" % (long(self.val))
def display_hint (self):
return "array"
class GHashPrinter:
"Prints a GHashTable"
class _iterator:
def __init__(self, ht, keys_are_strings):
self.ht = ht
if ht != 0:
self.keys = ht["keys"]
self.values = ht["values"]
self.hashes = ht["hashes"]
self.size = ht["size"]
self.pos = 0
self.keys_are_strings = keys_are_strings
self.value = None
def __iter__(self):
return self
def next(self):
if self.ht == 0:
raise StopIteration
if self.value != None:
v = self.value
self.value = None
return v
while long(self.pos) < long(self.size):
self.pos = self.pos + 1
if long (self.hashes[self.pos]) >= 2:
key = self.keys[self.pos]
val = self.values[self.pos]
if self.keys_are_strings:
key = key.cast (gdb.lookup_type("char").pointer())
# Queue value for next result
self.value = ('[%dv]'% (self.pos), val)
# Return key
return ('[%dk]'% (self.pos), key)
raise StopIteration
def __init__ (self, val):
self.val = val
self.keys_are_strings = False
try:
string_hash = read_global_var ("g_str_hash")
except:
string_hash = None
if self.val != 0 and string_hash != None and self.val["hash_func"] == string_hash:
self.keys_are_strings = True
def children(self):
return self._iterator(self.val, self.keys_are_strings)
def to_string (self):
return "0x%x" % (long(self.val))
def display_hint (self):
return "map"
def pretty_printer_lookup (val):
if is_g_type_instance (val):
return GTypePrettyPrinter (val)
def pretty_printer_lookup (val):
# None yet, want things like hash table and list
type = val.type.unqualified()
# If it points to a reference, get the reference.
if type.code == gdb.TYPE_CODE_REF:
type = type.target ()
if type.code == gdb.TYPE_CODE_PTR:
type = type.target().unqualified()
t = str(type)
if t == "GList":
return GListPrinter(val, "GList")
if t == "GSList":
return GListPrinter(val, "GSList")
if t == "GHashTable":
return GHashPrinter(val)
else:
t = str(type)
if t == "GList":
return GListNodePrinter(val)
if t == "GSList *":
return GListPrinter(val, "GSList")
return None
def register (obj):
if obj == None:
obj = gdb
obj.pretty_printers.append(pretty_printer_lookup)
class ForeachCommand (gdb.Command):
"""Foreach on list"""
def __init__ (self):
super (ForeachCommand, self).__init__ ("gforeach",
gdb.COMMAND_DATA,
gdb.COMPLETE_SYMBOL)
def valid_name (self, name):
if not name[0].isalpha():
return False
return True
def parse_args (self, arg):
i = arg.find(" ")
if i <= 0:
raise Exception ("No var specified")
var = arg[:i]
if not self.valid_name(var):
raise Exception ("Invalid variable name")
while i < len (arg) and arg[i].isspace():
i = i + 1
if arg[i:i+2] != "in":
raise Exception ("Invalid syntax, missing in")
i = i + 2
while i < len (arg) and arg[i].isspace():
i = i + 1
colon = arg.find (":", i)
if colon == -1:
raise Exception ("Invalid syntax, missing colon")
val = arg[i:colon]
colon = colon + 1
while colon < len (arg) and arg[colon].isspace():
colon = colon + 1
command = arg[colon:]
return (var, val, command)
def do_iter(self, arg, item, command):
item = item.cast (gdb.lookup_type("void").pointer())
item = long(item)
to_eval = "set $%s = (void *)0x%x\n"%(arg, item)
gdb.execute(to_eval)
gdb.execute(command)
def slist_iterator (self, arg, container, command):
l = container.cast (gdb.lookup_type("GSList").pointer())
while long(l) != 0:
self.do_iter (arg, l["data"], command)
l = l["next"]
def list_iterator (self, arg, container, command):
l = container.cast (gdb.lookup_type("GList").pointer())
while long(l) != 0:
self.do_iter (arg, l["data"], command)
l = l["next"]
def pick_iterator (self, container):
t = container.type.unqualified()
if t.code == gdb.TYPE_CODE_PTR:
t = t.target().unqualified()
t = str(t)
if t == "GSList":
return self.slist_iterator
if t == "GList":
return self.list_iterator
raise Exception("Invalid container type %s"%(str(container.type)))
def invoke (self, arg, from_tty):
(var, container, command) = self.parse_args(arg)
container = gdb.parse_and_eval (container)
func = self.pick_iterator(container)
func(var, container, command)
ForeachCommand ()
|
jonnyniv/boost_converter
|
host/gui/GTK+/share/glib-2.0/gdb/glib.py
|
Python
|
apache-2.0
| 7,426
|
#----------------------------------------------------------------
# Generated CMake target import file for configuration "".
#----------------------------------------------------------------
# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)
# Import target "childproject" for configuration ""
set_property(TARGET childproject APPEND PROPERTY IMPORTED_CONFIGURATIONS NOCONFIG)
set_target_properties(childproject PROPERTIES
IMPORTED_LOCATION_NOCONFIG "${_IMPORT_PREFIX}/lib/libchildproject.so"
IMPORTED_SONAME_NOCONFIG "libchildproject.so"
)
list(APPEND _IMPORT_CHECK_TARGETS childproject )
list(APPEND _IMPORT_CHECK_FILES_FOR_childproject "${_IMPORT_PREFIX}/lib/libchildproject.so" )
# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)
|
hughperkins/pub-prototyping
|
cmake/testextinc/install/lib/childproject-noconfig.cmake
|
CMake
|
apache-2.0
| 821
|
/*
* Copyright 2018 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.swarm.microprofile.faulttolerance.deployment;
import io.smallrye.faulttolerance.DefaultHystrixConcurrencyStrategy;
import javax.annotation.Resource;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.BeforeBeanDiscovery;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import javax.enterprise.util.AnnotationLiteral;
/**
*
* @author Martin Kouba
*/
public class MicroProfileFaultToleranceExtension implements Extension {
void beforeBeanDiscovery(@Observes BeforeBeanDiscovery event, BeanManager beanManager) {
event.addAnnotatedType(beanManager.createAnnotatedType(RequestContextCommandListener.class), RequestContextCommandListener.class.getName());
event.addAnnotatedType(beanManager.createAnnotatedType(WeldCommandListenersProvider.class), WeldCommandListenersProvider.class.getName());
}
// workaround for WFLY-11373, see also THORN-2271
void processAnnotatedType(@Observes ProcessAnnotatedType<DefaultHystrixConcurrencyStrategy> event) {
event.configureAnnotatedType()
.filterFields(field -> "managedThreadFactory".equals(field.getJavaMember().getName()))
.forEach(field -> {
field.remove(annotation -> Resource.class.equals(annotation.annotationType()));
field.add(ResourceLiteral.lookup("java:jboss/ee/concurrency/factory/default"));
});
}
static class ResourceLiteral extends AnnotationLiteral<Resource> implements Resource {
private static final long serialVersionUID = 1L;
private final String name;
private final String lookup;
private final Class<?> type;
private final AuthenticationType authenticationType;
private final boolean shareable;
private final String mappedName;
private final String description;
static ResourceLiteral lookup(String lookup) {
return new ResourceLiteral(null, lookup, null, null, null, null, null);
}
private ResourceLiteral(String name, String lookup, Class<?> type, AuthenticationType authenticationType,
Boolean shareable, String mappedName, String description) {
this.name = name == null ? "" : name;
this.lookup = lookup == null ? "" : lookup;
this.type = type == null ? Object.class : type;
this.authenticationType = authenticationType == null ? AuthenticationType.CONTAINER : authenticationType;
this.shareable = shareable == null ? true : shareable.booleanValue();
this.mappedName = mappedName == null ? "" : mappedName;
this.description = description == null ? "" : description;
}
@Override
public String name() {
return name;
}
@Override
public String lookup() {
return lookup;
}
@Override
public Class<?> type() {
return type;
}
@Override
public AuthenticationType authenticationType() {
return authenticationType;
}
@Override
public boolean shareable() {
return shareable;
}
@Override
public String mappedName() {
return mappedName;
}
@Override
public String description() {
return description;
}
}
}
|
wildfly-swarm/wildfly-swarm
|
fractions/microprofile/microprofile-fault-tolerance/src/main/java/org/wildfly/swarm/microprofile/faulttolerance/deployment/MicroProfileFaultToleranceExtension.java
|
Java
|
apache-2.0
| 4,158
|
/*
* 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.phoenix.util;
import java.io.Closeable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import org.apache.phoenix.schema.types.PDataType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
/**
* Executes upsert statements on a provided {@code PreparedStatement} based on incoming
* {@code RECORDS}. An {@link UpsertListener} is notified each time the prepared statement
* is executed.
*/
public abstract class UpsertExecutor<RECORD, FIELD> implements Closeable {
/**
* A listener that is called for events based on incoming JSON data.
*/
public interface UpsertListener<RECORD> {
/**
* Called when an upsert has been sucessfully completed. The given upsertCount is the total number of upserts
* completed on the caller up to this point.
*
* @param upsertCount total number of upserts that have been completed
*/
void upsertDone(long upsertCount);
/**
* Called when executing a prepared statement has failed on a given record.
*
* @param record the JSON record that was being upserted when the error occurred
*/
void errorOnRecord(RECORD record, Throwable throwable);
}
private static final Logger LOGGER = LoggerFactory.getLogger(UpsertExecutor.class);
protected final Connection conn;
protected final List<ColumnInfo> columnInfos;
protected final List<PDataType> dataTypes;
protected final List<Function<FIELD, Object>> conversionFunctions;
protected final PreparedStatement preparedStatement;
protected final UpsertListener<RECORD> upsertListener;
protected long upsertCount = 0L;
protected boolean initFinished = false; // allow subclasses to finish initialization
private static PreparedStatement createStatement(Connection conn, String tableName,
List<ColumnInfo> columnInfoList) {
PreparedStatement preparedStatement;
try {
String upsertSql = QueryUtil.constructUpsertStatement(tableName, columnInfoList);
LOGGER.info("Upserting SQL data with {}", upsertSql);
preparedStatement = conn.prepareStatement(upsertSql);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return preparedStatement;
}
/**
* Construct with the definition of incoming columns, and the statement upon which upsert
* statements are to be performed.
*/
public UpsertExecutor(Connection conn, String tableName,
List<ColumnInfo> columnInfoList, UpsertListener<RECORD> upsertListener) {
this(conn, columnInfoList, createStatement(conn, tableName, columnInfoList), upsertListener);
}
/** Testing constructor. Do not use in prod. */
@VisibleForTesting
protected UpsertExecutor(Connection conn, List<ColumnInfo> columnInfoList,
PreparedStatement preparedStatement, UpsertListener<RECORD> upsertListener) {
this.conn = conn;
this.upsertListener = upsertListener;
this.columnInfos = columnInfoList;
this.preparedStatement = preparedStatement;
this.dataTypes = Lists.newArrayList();
this.conversionFunctions = Lists.newArrayList();
}
/**
* Awkward protocol allows subclass constructors to finish initializing context before
* proceeding to record processing.
*/
protected void finishInit() {
for (ColumnInfo columnInfo : columnInfos) {
PDataType dataType = PDataType.fromTypeId(columnInfo.getSqlType());
dataTypes.add(dataType);
conversionFunctions.add(createConversionFunction(dataType));
}
this.initFinished = true;
}
/**
* Execute upserts for each JSON record contained in the given iterable, notifying this instance's
* {@code UpsertListener} for each completed upsert.
*
* @param records iterable of JSON records to be upserted
*/
public void execute(Iterable<RECORD> records) {
if (!initFinished) {
finishInit();
}
for (RECORD record : records) {
execute(record);
}
}
/**
* Upsert a single record.
*
* @param record JSON record containing the data to be upserted
*/
protected abstract void execute(RECORD record);
@Override
public void close() throws IOException {
try {
preparedStatement.close();
} catch (SQLException e) {
// An exception while closing the prepared statement is most likely a sign of a real problem, so we don't
// want to hide it with closeQuietly or something similar
throw new RuntimeException(e);
}
}
protected abstract Function<FIELD, Object> createConversionFunction(PDataType dataType);
}
|
apurtell/phoenix
|
phoenix-core/src/main/java/org/apache/phoenix/util/UpsertExecutor.java
|
Java
|
apache-2.0
| 5,876
|
<?php
include_once(dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR."modules.php");
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR."config.php");
?>
var chatScroll, lobbyScroll, chatroomScroll, woScroll, cruserScroll, baseurl = "<?php echo BASE_URL; ?>";
var cookie_prefix = '<?php echo $cookiePrefix; ?>';
<?php
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR."js".DIRECTORY_SEPARATOR."jquery.nicescroll.js");
?>
var enableType = '<?php echo $enableType ?>';
var winheight = '';
(function($){
$.mobilewebapp = (function(){
return {
init: function(){
winheight = $(window).height();
if(typeof (jqcc.chatmobilewebapp)!=='undefined'){
jqcc.chatmobilewebapp.chatinit();
}
jqcc.mobilewebapp.detect();
},
addscroll: function(){
$.browser.device = (/iphone|ipad/i.test(navigator.userAgent.toLowerCase()));
if($.browser.device==false){
setTimeout(function(){
chatScroll = $("#chatcontent").niceScroll({horizrailenabled: false, bouncescroll: true, nativeparentscrolling: true, railalign: "right"});
chatroomScroll = $("#chatroomcontent").niceScroll({horizrailenabled: false, bouncescroll: true, nativeparentscrolling: true});
lobbyScroll = $("#lobbycontent").niceScroll({horizrailenabled: false, bouncescroll: true, nativeparentscrolling: true});
woScroll = $("#wocontent").niceScroll({horizrailenabled: false, bouncescroll: true, nativeparentscrolling: true});
cruserScroll = $("#chatroomusercontent").niceScroll({horizrailenabled: false, bouncescroll: true, nativeparentscrolling: true});
}, 200);
}
},
detect: function(){
if(window.orientation==90||window.orientation==-90){
$("div.chatlink_icon").css({'height':'20px', 'top':'15px'});
$("div.chatroomlink_icon").css({'height':'20px', 'top':'15px'});
$('div.chatlink_txt').css('display', 'none');
$('div.chatroomlink_txt').css('display', 'none');
}else{
$("div.chatlink_icon").css({'height':'30px', 'top':'-1px'});
$("div.chatroomlink_icon").css({'height':'30px', 'top':'-1px'});
$('div.chatlink_txt').css('display', 'block');
$('div.chatroomlink_txt').css('display', 'block');
}
var headerHeight;
var baseHeight = window.innerHeight;
var footerbtnHeight = 0;
var footerHeight = $("#chatfooter").outerHeight();
var cheaderHeight = $('#cheader').height();
var crheaderHeight = $('#crheadertop').height();
var footerCRHeight = $("#chatroomfooter").outerHeight();
var headerHeight = $('#header').height();
if($('#footer').length==0){
footerbtnHeight = 0;
}else{
footerbtnHeight = $('#footer').height();
}
$('body').css({'height':(baseHeight)+'px', 'min-height':(baseHeight)+'px', 'max-height':(baseHeight)+'px', 'width':'100%'});
$.browser.device = (/ipad/i.test(navigator.userAgent.toLowerCase()));
if($.browser.device==true){
$("#options").css('width', '20%');
$("div.chatoptions").css('width', '20%');
$("#lobbyhome").css('width', '20%');
$("#buddyhome").css('width', '20%');
$("#backbtnChat").css('width', '20%');
$("#backbtnChatroom").css('width', '20%');
$("#backbtnChatroomuser").css('width', '20%');
$("#backbtnCreateChatroom").css('width', '20%');
if(window.orientation==90||window.orientation==-90){
if(baseHeight<winheight){
$("#chatroomcontent").css('height', '86.5%');
$("#chatcontent").css('height', '86.5%');
}else{
$("#chatroomcontent").css('height', (baseHeight-crheaderHeight-footerHeight-50)+'px');
$("#chatcontent").css('height', (baseHeight-cheaderHeight-footerHeight+5)+'px');
}
}else{
if(baseHeight<winheight){
$("#chatroomcontent").css('height', '90%');
$("#chatcontent").css('height', '90%');
}else{
$("#chatroomcontent").css('height', (baseHeight-crheaderHeight-footerHeight-50)+'px');
$("#chatcontent").css('height', (baseHeight-cheaderHeight-footerHeight+5)+'px');
}
}
}
$.browser.device = (/android|iphone|ipad/i.test(navigator.userAgent.toLowerCase()));
if($.browser.device==false){
$("#chatcontent").css({'height':(baseHeight-headerHeight-footerHeight)+'px', 'min-height':(baseHeight-headerHeight-footerHeight)+'px', 'max-height':(baseHeight-headerHeight-footerHeight)+'px'}).getNiceScroll().resize();
$("#chatroomcontent").css({'height':(baseHeight-headerHeight-footerCRHeight)+'px', 'min-height':(baseHeight-headerHeight-footerCRHeight)+'px', 'max-height':(baseHeight-headerHeight-footerCRHeight)+'px'}).getNiceScroll().resize();
$("#chatroomusercontent").css({'max-height':(baseHeight-headerHeight)+'px !important', 'bottom':'1px', 'overflow-y':'auto'}).getNiceScroll().resize();
}
$.browser.device = (/android|iphone/i.test(navigator.userAgent.toLowerCase()));
if($.browser.device==true){
if(window.orientation==90||window.orientation==-90){
var baseinnerHeight = window.innerHeight;
var baseHeight = $(window).height();
var headtop = baseHeight-baseinnerHeight;
$("#chatfooter").css({'position':'', 'bottom':'0', 'height':'50px', 'width':'100%'});
$("#chatroomfooter").css({'position':'', 'bottom':'0', 'height':'50px', 'width':'100%'});
$("#cheader").css({'position':'fixed', 'top':headtop+'px !important', 'height':'42px', 'width':'100%'});
$("#crheadertop").css({'position':'fixed', 'top':headtop+'px !important', 'height':'42px', 'width':'100%'});
$('#opt').css('top', (headtop+42)+'px');
var chathead = $('#cheader').height();
var chatfooter = $('#chatfooter').height();
var chatroomhead = $('#crheadertop').height();
var chatroomfooter = $('#chatroomfooter').height();
$("#chatcontent").css({'position':'', 'overflow-y':'scroll', 'height':(baseinnerHeight-chathead-chatfooter)+'px', 'width':'100%', 'bottom':'50px'});
$("#chatroomcontent").css({'position':'', 'overflow-y':'scroll', 'height':(baseinnerHeight-chatroomhead-chatroomfooter)+'px', 'width':'100%', 'bottom':'50px'});
}else{
$("#chatfooter").css({'position':'', 'bottom':'0', 'height':'50px', 'width':'100%'});
$("#chatroomfooter").css({'position':'', 'bottom':'0', 'height':'50px', 'width':'100%'});
$("#cheader").css({'position':'', 'top':'0px', 'height':'42px', 'width':'100%'});
$("#crheadertop").css({'position':'', 'top':'0px', 'height':'42px', 'width':'100%'});
var baseHeight = $(window).height();
var chathead = $('#cheader').height();
var chatfooter = $('#chatfooter').height();
var chatroomhead = $('#crheadertop').height();
var chatroomfooter = $('#chatroomfooter').height();
$("#chatcontent").css({'position':'', 'overflow-y':'scroll', 'height':(baseHeight-chathead-chatfooter)+'px', 'width':'100%', 'bottom':'50px'});
$("#chatroomcontent").css({'position':'', 'overflow-y':'scroll', 'height':(baseHeight-chatroomhead-chatroomfooter)+'px', 'width':'100%', 'bottom':'50px'});
}
$("#chatroomusercontent").css({'position':'', 'overflow-y':'scroll', 'max-height':(baseinnerHeight-headerHeight)+'px', 'min-height':(baseinnerHeight-headerHeight)+'px', 'height':(baseinnerHeight-headerHeight)+'px', 'width':'100%', 'bottom':'1px'});
}
$("#chatroom").css({'height':(baseHeight)+'px', 'min-height':(baseHeight)+'px', 'max-height':(baseHeight)+'px'});
var baseinnerHeight = window.innerHeight;
var head = $('#header').height();
var footer = $('#footer').height();
$("#wocontent").css({'bottom':footerbtnHeight+'px', 'height':(baseinnerHeight-head-footer)+'px', 'min-height':(baseinnerHeight-head-footer)+'px', 'max-height':(baseinnerHeight-head-footer)+'px'});
$("#lobbycontent").css({'bottom':footerbtnHeight+'px', 'height':(baseinnerHeight-head-footer)+'px', 'min-height':(baseinnerHeight-head-footer)+'px', 'max-height':(baseinnerHeight-head-footer)+'px'});
if(typeof (jqcc.chatmobilewebapp)!=='undefined'){
jqcc.chatmobilewebapp.chatdetect();
}
if(typeof (jqcc.mobilewebapp.chatroomdetect)=='function'){
jqcc.mobilewebapp.chatroomdetect();
}
},
buddyList: function(data){
if(typeof (jqcc.chatmobilewebapp)!=='undefined'){
jqcc.chatmobilewebapp.chatbuddyList(data);
}
},
userStatus: function(item){
jqcc.cometchat.setThemeVariable('userid', item.id);
jqcc.cometchat.setThemeArray('buddylistStatus', item.id, item.status);
jqcc.cometchat.setThemeArray('buddylistMessage', item.id, item.message);
jqcc.cometchat.setThemeArray('buddylistName', item.id, item.n);
jqcc.cometchat.setThemeArray('buddylistAvatar', item.id, item.a);
jqcc.cometchat.setThemeArray('buddylistLink', item.id, item.l);
},
loadData: function(id, data){
if(typeof (jqcc.chatmobilewebapp)!=='undefined'){
jqcc.chatmobilewebapp.chatloadData(id, data);
}
},
txtfocus: function(){
$('#cometchat_container_report').find('.cometchat_closebox').click();
$('#opt').css('display', 'none');
},
get_user: function(){
var searchc = document.getElementById('searchtxt').value;
$("li.userlists").css("display", "none");
$("span.search_name:containsIgnoreCase('"+searchc+"')").parent().parent().css("display", "block");
},
get_chatroom: function(){
var searchc = document.getElementById('searchtxtCR').value;
$("li.crlists").css("display", "none");
$("span.lobby_room_1:containsIgnoreCase('"+searchc+"')").parent().parent().css("display", "block");
},
pathRedirect: function(showdiv){
$("#buddy").hide();
$("#lobby").hide();
$("#chat").hide();
$("#chatroom").hide();
$("#chatroomuser").hide();
$("#createChatroom").hide();
if(showdiv!=''){
if(showdiv=='#lobby'){
$("#lobby").css('display', 'block');
}else if(showdiv=='#buddy'){
$("#buddy").css('display', 'block');
}else{
$(showdiv).css('display', 'block');
}
}else{
$("#buddy").css('display', 'block');
}
},
loggedOut: function(){
alert(jqcc.cometchat.getLanguage(56));
location.href = jqcc.cometchat.getBaseUrl()+'../';
},
scrollToBottom: function(){
if($('#cwlist').length > 0 && $('#cwlist').find("li").length > 0)
$('#chatcontent').scrollTop($('#cwlist').find("li").last().position().top+$('#cwlist').find("li").last().height());
},
crscrollToBottom: function(){
if($('#currentroom_convotext').find('div').length)
$('#chatroomcontent').scrollTop($('#currentroom_convotext').find('div').last().position().top+$('#currentroom_convotext').find('div').last().height());
},
refreshLists: function(id){
$('#'+id).listview("refresh");
},
addChatroomMessage: function(fromid, incomingmessage, incomingid, selfadded, sent, fromname){
jqcc.mobilewebapp.ChatroomMessage(fromid, incomingmessage, incomingid, selfadded, sent, fromname);
},
loadChatbox: function(){
jqcc.mobilewebapp.pathRedirect('#chat');
},
loadChatboxReverse: function(){
jqcc.mobilewebapp.pathRedirect('#buddy');
if(typeof (jqcc.chatmobilewebapp)!=='undefined'){
jqcc.chatmobilewebapp.back();
}
$('#buddy_link').click();
},
loadChatroom: function(){
jqcc.mobilewebapp.pathRedirect('#chatroom');
},
loadChatroomReverse: function(){
jqcc.mobilewebapp.pathRedirect('#chatroom');
},
loadLobbyReverse: function(){
jqcc.mobilewebapp.pathRedirect('#lobby');
if(typeof (jqcc.mobilewebapp)!=='undefined'){
jqcc.mobilewebapp.backchatroom();
}
$('#chatroomlink').click();
},
showChatroomUser: function(){
jqcc.mobilewebapp.pathRedirect('#chatroomuser');
},
chatwith: function(){
jqcc.mobilewebapp.pathRedirect('#chat');
return true;
},
createChatroom: function(){
jqcc.mobilewebapp.pathRedirect('#createChatroom');
},
refreshPage: function(){
location.reload();
},
getCookieInfo: function(cookieName){
var i, x, y, ARRcookies = document.cookie.split(";");
for(i = 0; i<ARRcookies.length; i++)
{
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x = x.replace(/^\s+|\s+$/g, "");
if(x==cookieName){
return unescape(y);
}
}
},
addMessages: function(data){
if(typeof (jqcc.chatmobilewebapp)!=='undefined'){
jqcc.chatmobilewebapp.attachMessage(data);
}
},
loadUserData: function(id, data){
if(typeof (jqcc.chatmobilewebapp)!=='undefined'){
jqcc.chatmobilewebapp.chatloadUserData(id, data);
}
},
checkSmiley: function(message){
message = message.replace('\ud83d\udd51', ' :clock2: ');
message = message.replace('\ud83d\udd5d', ' :clock230: ');
message = message.replace('\ud83d\udd52', ' :clock3: ');
message = message.replace('\ud83d\udd5e', ' :clock330: ');
message = message.replace('\ud83d\udd53', ' :clock4: ');
message = message.replace('\ud83d\udd5f', ' :clock430: ');
message = message.replace('\ud83d\udd54', ' :clock5: ');
message = message.replace('\ud83d\udd60', ' :clock530: ');
message = message.replace('\ud83d\udd55', ' :clock6: ');
message = message.replace('\ud83d\udd61', ' :clock630: ');
message = message.replace('\ud83d\udd56', ' :clock7: ');
message = message.replace('\ud83d\udd62', ' :clock730: ');
message = message.replace('\ud83d\udd57', ' :clock8: ');
message = message.replace('\ud83d\udd63', ' :clock830: ');
message = message.replace('\ud83d\udd58', ' :clock9: ');
message = message.replace('\ud83d\udd64', ' :clock930: ');
message = message.replace('\u3297', ' :congratulations: ');
message = message.replace('\ud83c\udd92', ' :cool: ');
message = message.replace('\u00a9', ' :copyright: ');
message = message.replace('\u27b0', ' :curly_loop: ');
message = message.replace('\ud83d\udcb1', ' :currency_exchange: ');
message = message.replace('\ud83d\udec3', ' :customs: ');
message = message.replace('\ud83d\udca0', ' :diamond_shape_with_a_dot_inside: ');
message = message.replace('\ud83d\udeaf', ' :do_not_litter: ');
message = message.replace('\u0038\u20e3', ' :eight: ');
message = message.replace('\u2734', ' :eight_pointed_black_star: ');
message = message.replace('\u2733', ' :eight_spoked_asterisk: ');
message = message.replace('\ud83d\udd1a', ' :end: ');
message = message.replace('\u23e9', ' :fast_forward: ');
message = message.replace('\u0035\u20e3', ' :five: ');
message = message.replace('\u0034\u20e3', ' :four: ');
message = message.replace('\ud83c\udd93', ' :free: ');
message = message.replace('\u264a', ' :gemini: ');
message = message.replace('\u0023\u20e3', ' :hash: ');
message = message.replace('\ud83d\udc9f', ' :heart_decoration: ');
message = message.replace('\u2714', ' :heavy_check_mark: ');
message = message.replace('\u2797', ' :heavy_division_sign: ');
message = message.replace('\ud83d\udcb2', ' :heavy_dollar_sign: ');
message = message.replace('\u2757', ' :heavy_exclamation_mark: ');
message = message.replace('\u2796', ' :heavy_minus_sign: ');
message = message.replace('\u2716', ' :heavy_multiplication_x: ');
message = message.replace('\u2795', ' :heavy_plus_sign: ');
message = message.replace('\ud83c\udd94', ' :id: ');
message = message.replace('\ud83c\ude50', ' :ideograph_advantage: ');
message = message.replace('\u2139', ' :information_source: ');
message = message.replace('\u2049', ' :interrobang: ');
message = message.replace('\ud83d\udd1f', ' :keycap_ten: ');
message = message.replace('\ud83c\ude01', ' :koko: ');
message = message.replace('\ud83d\udd35', ' :large_blue_circle: ');
message = message.replace('\ud83d\udd37', ' :large_blue_diamond: ');
message = message.replace('\ud83d\udd36', ' :large_orange_diamond: ');
message = message.replace('\ud83d\udec5', ' :left_luggage: ');
message = message.replace('\u2194', ' :left_right_arrow: ');
message = message.replace('\u21a9', ' :leftwards_arrow_with_hook: ');
message = message.replace('\u264c', ' :leo: ');
message = message.replace('\u264e', ' :libra: ');
message = message.replace('\ud83d\udd17', ' :link: ');
message = message.replace('\u24c2', ' :m: ');
message = message.replace('\ud83d\udeb9', ' :mens: ');
message = message.replace('\ud83d\ude87', ' :metro: ');
message = message.replace('\ud83d\udcf4', ' :mobile_phone_off: ');
message = message.replace('\u274e', ' :negative_squared_cross_mark: ');
message = message.replace('\ud83c\udd95', ' :new: ');
message = message.replace('\ud83c\udd96', ' :ng: ');
message = message.replace('\u0039\u20e3', ' :nine: ');
message = message.replace('\ud83d\udeb3', ' :no_bicycles: ');
message = message.replace('\u26d4', ' :no_entry: ');
message = message.replace('\ud83d\udeab', ' :no_entry_sign: ');
message = message.replace('\ud83d\udcf5', ' :no_mobile_phones: ');
message = message.replace('\ud83d\udeb7', ' :no_pedestrians: ');
message = message.replace('\ud83d\udead', ' :no_smoking: ');
message = message.replace('\ud83d\udeb1', ' :non-potable_water: ');
message = message.replace('\u2b55', ' :o: ');
message = message.replace('\ud83c\udd7e', ' :o2: ');
message = message.replace('\ud83c\udd97', ' :ok: ');
message = message.replace('\ud83d\udd1b', ' :on: ');
message = message.replace('\u0031\u20e3', ' :one: ');
message = message.replace('\u26ce', ' :ophiuchus: ');
message = message.replace('\ud83c\udd7f', ' :parking: ');
message = message.replace('\u303d', ' :part_alternation_mark: ');
message = message.replace('\ud83d\udec2', ' :passport_control: ');
message = message.replace('\u2653', ' :pisces: ');
message = message.replace('\ud83d\udeb0', ' :potable_water: ');
message = message.replace('\ud83d\udeae', ' :put_litter_in_its_place: ');
message = message.replace('\ud83d\udd18', ' :radio_button: ');
message = message.replace('\u267b', ' :recycle: ');
message = message.replace('\ud83d\udd34', ' :red_circle: ');
message = message.replace('\u00ae', ' :registered: ');
message = message.replace('\ud83d\udd01', ' :repeat: ');
message = message.replace('\ud83d\udd02', ' :repeat_one: ');
message = message.replace('\ud83d\udebb', ' :restroom: ');
message = message.replace('\u23ea', ' :rewind: ');
message = message.replace('\ud83c\ude02', ' :sa: ');
message = message.replace('\u2650', ' :sagittarius: ');
message = message.replace('\u264f', ' :scorpius: ');
message = message.replace('\u3299', ' :secret: ');
message = message.replace('\u0037\u20e3', ' :seven: ');
message = message.replace(':shipit:', ' :shipit: ');
message = message.replace('\ud83d\udcf6', ' :signal_strength: ');
message = message.replace('\u0036\u20e3', ' :six: ');
message = message.replace('\ud83d\udd2f', ' :six_pointed_star: ');
message = message.replace('\ud83d\udd39', ' :small_blue_diamond: ');
message = message.replace('\ud83d\udd38', ' :small_orange_diamond: ');
message = message.replace('\ud83d\udd3a', ' :small_red_triangle: ');
message = message.replace('\ud83d\udd3b', ' :small_red_triangle_down: ');
message = message.replace('\ud83d\udd1c', ' :soon: ');
message = message.replace('\ud83c\udd98', ' :sos: ');
message = message.replace('\ud83d\udd23', ' :symbols1: ');
message = message.replace('\u2649', ' :taurus: ');
message = message.replace('\u0033\u20e3', ' :three: ');
message = message.replace('\u2122', ' :tm: ');
message = message.replace('\ud83d\udd1d', ' :top: ');
message = message.replace('\ud83d\udd31', ' :trident: ');
message = message.replace('\ud83d\udd00', ' :twisted_rightwards_arrows: ');
message = message.replace('\u0032\u20e3', ' :two: ');
message = message.replace('\ud83c\ude39', ' :u5272: ');
message = message.replace('\ud83c\ude34', ' :u5408: ');
message = message.replace('\ud83c\ude3a', ' :u55b6: ');
message = message.replace('\ud83c\ude2f', ' :u6307: ');
message = message.replace('\ud83c\ude37', ' :u6708: ');
message = message.replace('\ud83c\ude36', ' :u6709: ');
message = message.replace('\ud83c\ude35', ' :u6e80: ');
message = message.replace('\ud83c\ude1a', ' :u7121: ');
message = message.replace('\ud83c\ude38', ' :u7533: ');
message = message.replace('\ud83c\ude32', ' :u7981: ');
message = message.replace('\ud83c\ude33', ' :u7a7a: ');
message = message.replace('\ud83d\udd1e', ' :underage: ');
message = message.replace('\ud83c\udd99', ' :up: ');
message = message.replace('\ud83d\udcf3', ' :vibration_mode: ');
message = message.replace('\u264d', ' :virgo: ');
message = message.replace('\ud83c\udd9a', ' :vs: ');
message = message.replace('\u3030', ' :wavy_dash: ');
message = message.replace('\ud83d\udebe', ' :wc: ');
message = message.replace('\u267f', ' :wheelchair: ');
message = message.replace('\u2705', ' :white_check_mark: ');
message = message.replace('\u26aa', ' :white_circle: ');
message = message.replace('\ud83d\udcae', ' :white_flower: ');
message = message.replace('\u25fb', ' :white_square: ');
message = message.replace('\ud83d\udd33', ' :white_square_button: ');
message = message.replace('\ud83d\udeba', ' :womens: ');
message = message.replace('\u274c', ' :x: ');
message = message.replace('\u0030\u20e3', ' :zero: ');
message = message.replace('\u2708', ' :airplane: ');
message = message.replace('\ud83d\ude91', ' :ambulance: ');
message = message.replace('\u2693', ' :anchor: ');
message = message.replace('\ud83d\ude9b', ' :articulated_lorry: ');
message = message.replace('\ud83c\udfe7', ' :atm: ');
message = message.replace('\ud83c\udfe6', ' :bank: ');
message = message.replace('\ud83d\udc88', ' :barber: ');
message = message.replace('\ud83d\udd30', ' :beginner: ');
message = message.replace('\ud83d\udeb2', ' :bike: ');
message = message.replace('\ud83d\ude99', ' :blue_car: ');
message = message.replace('\u26f5', ' :boat: ');
message = message.replace('\ud83c\udf09', ' :bridge_at_night: ');
message = message.replace('\ud83d\ude85', ' :bullettrain_front: ');
message = message.replace('\ud83d\ude84', ' :bullettrain_side: ');
message = message.replace('\ud83d\ude8c', ' :bus: ');
message = message.replace('\ud83d\ude8f', ' :busstop: ');
message = message.replace('\ud83d\ude97', ' :car: ');
message = message.replace('\ud83c\udfa0', ' :carousel_horse: ');
message = message.replace('\ud83c\udfc1', ' :checkered_flag: ');
message = message.replace('\u26ea', ' :church: ');
message = message.replace('\ud83c\udfaa', ' :circus_tent: ');
message = message.replace('\ud83c\udf07', ' :city_sunrise: ');
message = message.replace('\ud83c\udf06', ' :city_sunset: ');
message = message.replace('\ud83c\udde8\ud83c\uddf3', ' :cn: ');
message = message.replace('\ud83d\udea7', ' :construction: ');
message = message.replace('\ud83c\udfea', ' :convenience_store: ');
message = message.replace('\ud83c\udf8c', ' :crossed_flags: ');
message = message.replace('\ud83c\udde9\ud83c\uddea', ' :de: ');
message = message.replace('\ud83c\udfec', ' :department_store: ');
message = message.replace('\ud83c\uddea\ud83c\uddf8', ' :es: ');
message = message.replace('\ud83c\udff0', ' :european_castle: ');
message = message.replace('\ud83c\udfe4', ' :european_post_office: ');
message = message.replace('\ud83c\udfed', ' :factory: ');
message = message.replace('\ud83c\udfa1', ' :ferris_wheel: ');
message = message.replace('\ud83d\ude92', ' :fire_engine: ');
message = message.replace('\u26f2', ' :fountain: ');
message = message.replace('\ud83c\uddeb\ud83c\uddf7', ' :fr: ');
message = message.replace('\u26fd', ' :fuelpump: ');
message = message.replace('\ud83c\uddec\ud83c\udde7', ' :gb: ');
message = message.replace('\ud83d\ude81', ' :helicopter: ');
message = message.replace('\ud83c\udfe5', ' :hospital: ');
message = message.replace('\ud83c\udfe8', ' :hotel: ');
message = message.replace('\u2668', ' :hotsprings: ');
message = message.replace('\ud83c\udfe0', ' :house: ');
message = message.replace('\ud83c\udfe1', ' :house_with_garden: ');
message = message.replace('\ud83c\uddee\ud83c\uddf9', ' :it: ');
message = message.replace('\ud83c\udfee', ' :izakaya_lantern: ');
message = message.replace('\ud83d\uddfe', ' :japan: ');
message = message.replace('\ud83c\udfef', ' :japanese_castle: ');
message = message.replace('\ud83c\uddef\ud83c\uddf5', ' :jp: ');
message = message.replace('\ud83c\uddf0\ud83c\uddf7', ' :kr: ');
message = message.replace('\ud83d\ude88', ' :light_rail: ');
message = message.replace('\ud83c\udfe9', ' :love_hotel: ');
message = message.replace('\ud83d\ude90', ' :minibus: ');
message = message.replace('\ud83d\ude9d', ' :monorail: ');
message = message.replace('\ud83d\uddfb', ' :mount_fuji: ');
message = message.replace('\ud83d\udea0', ' :mountain_cableway: ');
message = message.replace('\ud83d\ude9e', ' :mountain_railway: ');
message = message.replace('\ud83d\uddff', ' :moyai: ');
message = message.replace('\ud83c\udfe2', ' :office: ');
message = message.replace('\ud83d\ude98', ' :oncoming_automobile: ');
message = message.replace('\ud83d\ude8d', ' :oncoming_bus: ');
message = message.replace('\ud83d\ude94', ' :oncoming_police_car: ');
message = message.replace('\ud83d\ude96', ' :oncoming_taxi: ');
message = message.replace('\ud83c\udfad', ' :performing_arts: ');
message = message.replace('\ud83d\ude93', ' :police_car: ');
message = message.replace('\ud83c\udfe3', ' :post_office: ');
message = message.replace('\ud83d\ude83', ' :railway_car: ');
message = message.replace('\ud83c\udf08', ' :rainbow: ');
message = message.replace('\ud83d\ude97', ' :red_car: ');
message = message.replace('\ud83d\ude80', ' :rocket: ');
message = message.replace('\ud83c\udfa2', ' :roller_coaster: ');
message = message.replace('\ud83d\udea8', ' :rotating_light: ');
message = message.replace('\ud83d\udccd', ' :round_pushpin: ');
message = message.replace('\ud83d\udea3', ' :rowboat: ');
message = message.replace('\ud83c\uddf7\ud83c\uddfa', ' :ru: ');
message = message.replace('\u26f5', ' :sailboat: ');
message = message.replace('\ud83c\udfeb', ' :school: ');
message = message.replace('\ud83d\udea2', ' :ship: ');
message = message.replace('\ud83c\udfb0', ' :slot_machine: ');
message = message.replace('\ud83d\udea4', ' :speedboat: ');
message = message.replace('\ud83c\udf03', ' :stars: ');
message = message.replace('\ud83d\ude89', ' :station: ');
message = message.replace('\ud83d\uddfd', ' :statue_of_liberty: ');
message = message.replace('\ud83d\ude82', ' :steam_locomotive: ');
message = message.replace('\ud83c\udf05', ' :sunrise: ');
message = message.replace('\ud83c\udf04', ' :sunrise_over_mountains: ');
message = message.replace('\ud83d\ude9f', ' :suspension_railway: ');
message = message.replace('\ud83d\ude95', ' :taxi: ');
message = message.replace('\u26fa', ' :tent: ');
message = message.replace('\ud83c\udfab', ' :ticket: ');
message = message.replace('\ud83d\uddfc', ' :tokyo_tower: ');
message = message.replace('\ud83d\ude9c', ' :tractor: ');
message = message.replace('\ud83d\udea5', ' :traffic_light: ');
message = message.replace('\ud83d\ude83', ' :train: ');
message = message.replace('\ud83d\ude86', ' :train2: ');
message = message.replace('\ud83d\ude8a', ' :tram: ');
message = message.replace('\ud83d\udea9', ' :triangular_flag_on_post: ');
message = message.replace('\ud83d\ude8e', ' :trolleybus: ');
message = message.replace('\ud83d\ude9a', ' :truck: ');
message = message.replace('\ud83c\uddec\ud83c\udde7', ' :uk: ');
message = message.replace('\ud83c\uddfa\ud83c\uddf8', ' :us: ');
message = message.replace('\ud83d\udea6', ' :vertical_traffic_light: ');
message = message.replace('\u26a0', ' :warning: ');
message = message.replace('\ud83d\udc92', ' :wedding: ');
message = message.replace('\ud83d\udc7d', ' :alien: ');
message = message.replace('\ud83d\udc7c', ' :angel: ');
message = message.replace('\ud83d\udca2', ' :anger: ');
message = message.replace('\ud83d\ude20', ' :angry: ');
message = message.replace('\ud83d\ude27', ' :anguished: ');
message = message.replace('\ud83d\ude32', ' :astonished: ');
message = message.replace('\ud83d\udc76', ' :baby: ');
message = message.replace('\ud83d\udc99', ' :blue_heart: ');
message = message.replace('\ud83d\ude0a', ' :blush: ');
message = message.replace('\ud83d\udca5', ' :boom: ');
message = message.replace('\ud83d\ude47', ' :bow: ');
message = message.replace(':bowtie:', ' :bowtie: ');
message = message.replace('\ud83d\udc66', ' :boy: ');
message = message.replace('\ud83d\udc70', ' :bride_with_veil: ');
message = message.replace('\ud83d\udc94', ' :broken_heart: ');
message = message.replace('\ud83d\udc64', ' :bust_in_silhouette: ');
message = message.replace('\ud83d\udc65', ' :busts_in_silhouette: ');
message = message.replace('\ud83d\udc4f', ' :clap: ');
message = message.replace('\ud83d\ude30', ' :cold_sweat: ');
message = message.replace('\ud83d\udca5', ' :collision: ');
message = message.replace('\ud83d\ude16', ' :confounded: ');
message = message.replace('\ud83d\ude15', ' :confused: ');
message = message.replace('\ud83d\udc77', ' :construction_worker: ');
message = message.replace('\ud83d\udc6e', ' :cop: ');
message = message.replace('\ud83d\udc6b', ' :couple: ');
message = message.replace('\ud83d\udc91', ' :couple_with_heart: ');
message = message.replace('\ud83d\udc8f', ' :couplekiss: ');
message = message.replace('\ud83d\ude22', ' :cry: ');
message = message.replace('\ud83d\ude3f', ' :crying_cat_face: ');
message = message.replace('\ud83d\udc98', ' :cupid: ');
message = message.replace('\ud83d\udc83', ' :dancer: ');
message = message.replace('\ud83d\udc6f', ' :dancers: ');
message = message.replace('\ud83d\udca8', ' :dash: ');
message = message.replace('\ud83d\ude1e', ' :disappointed: ');
message = message.replace('\ud83d\ude25', ' :disappointed_relieved: ');
message = message.replace('\ud83d\udcab', ' :dizzy: ');
message = message.replace('\ud83d\ude35', ' :dizzy_face: ');
message = message.replace('\ud83d\udca7', ' :droplet: ');
message = message.replace('\ud83d\udc42', ' :ear: ');
message = message.replace('\u2757', ' :exclamation: ');
message = message.replace('\ud83d\ude11', ' :expressionless: ');
message = message.replace('\ud83d\udc40', ' :eyes: ');
message = message.replace('\ud83d\udc6a', ' :family: ');
message = message.replace('\ud83d\ude28', ' :fearful: ');
message = message.replace(':feelsgood:', ' :feelsgood: ');
message = message.replace('\ud83d\udc63', ' :feet: ');
message = message.replace(':finnadie:', ' :finnadie: ');
message = message.replace('\ud83d\udd25', ' :fire: ');
message = message.replace('\u270a', ' :fist: ');
message = message.replace('\ud83d\ude33', ' :flushed: ');
message = message.replace('\ud83d\ude26', ' :frowning: ');
message = message.replace(':fu:', ' :fu: ');
message = message.replace('\ud83d\udc67', ' :girl: ');
message = message.replace(':goberserk:', ' :goberserk: ');
message = message.replace(':godmode:', ' :godmode: ');
message = message.replace('\ud83d\udc9a', ' :green_heart: ');
message = message.replace('\u2755', ' :grey_exclamation: ');
message = message.replace('\u2754', ' :grey_question: ');
message = message.replace('\ud83d\ude01', ' :grimacing: ');
message = message.replace('\ud83d\ude2c', ' :grin: ');
message = message.replace('\ud83d\ude00', ' :grinning: ');
message = message.replace('\ud83d\udc82', ' :guardsman: ');
message = message.replace('\ud83d\udc87', ' :haircut: ');
message = message.replace('\u270b', ' :hand: ');
message = message.replace('\ud83d\ude49', ' :hear_no_evil: ');
message = message.replace('\u2764', ' :heart: ');
message = message.replace('\ud83d\ude0d', ' :heart_eyes: ');
message = message.replace('\ud83d\ude3b', ' :heart_eyes_cat: ');
message = message.replace('\ud83d\udc93', ' :heartbeat: ');
message = message.replace('\ud83d\udc97', ' :heartpulse: ');
message = message.replace(':hurtrealbad:', ' :hurtrealbad: ');
message = message.replace('\ud83d\ude2f', ' :hushed: ');
message = message.replace('\ud83d\udc7f', ' :imp: ');
message = message.replace('\ud83d\udc81', ' :information_desk_person: ');
message = message.replace('\ud83d\ude07', ' :innocent: ');
message = message.replace('\ud83d\udc7a', ' :japanese_goblin: ');
message = message.replace('\ud83d\udc79', ' :japanese_ogre: ');
message = message.replace('\ud83d\ude02', ' :joy: ');
message = message.replace('\ud83d\ude39', ' :joy_cat: ');
message = message.replace('\ud83d\udc8b', ' :kiss: ');
message = message.replace('\ud83d\ude17', ' :kissing: ');
message = message.replace('\ud83d\ude3d', ' :kissing_cat: ');
message = message.replace('\ud83d\ude1a', ' :kissing_closed_eyes: ');
message = message.replace('\ud83d\ude18', ' :kissing_heart: ');
message = message.replace('\ud83d\ude19', ' :kissing_smiling_eyes: ');
message = message.replace('\ud83d\ude06', ' :laughing: ');
message = message.replace('\ud83d\udc44', ' :lips: ');
message = message.replace('\ud83d\udc8c', ' :love_letter: ');
message = message.replace('\ud83d\udc68', ' :man: ');
message = message.replace('\ud83d\udc72', ' :man_with_gua_pi_mao: ');
message = message.replace('\ud83d\udc73', ' :man_with_turban: ');
message = message.replace('\ud83d\ude37', ' :mask: ');
message = message.replace('\ud83d\udc86', ' :massage: ');
message = message.replace(':metal:', ' :metal: ');
message = message.replace('\ud83d\udcaa', ' :muscle: ');
message = message.replace('\ud83c\udfb5', ' :musical_note: ');
message = message.replace('\ud83d\udc85', ' :nail_care: ');
message = message.replace(':neckbeard:', ' :neckbeard: ');
message = message.replace('\ud83d\ude10', ' :neutral_face: ');
message = message.replace('\ud83d\ude45', ' :no_good: ');
message = message.replace('\ud83d\ude36', ' :no_mouth: ');
message = message.replace('\ud83d\udc43', ' :nose: ');
message = message.replace('\ud83c\udfb6', ' :notes: ');
message = message.replace('\ud83d\udc4c', ' :ok_hand: ');
message = message.replace('\ud83d\ude46', ' :ok_woman: ');
message = message.replace('\ud83d\udc74', ' :older_man: ');
message = message.replace('\ud83d\udc75', ' :older_woman: ');
message = message.replace('\ud83d\udc50', ' :open_hands: ');
message = message.replace('\ud83d\ude2E', ' :open_mouth: ');
message = message.replace('\ud83d\ude14', ' :pensive: ');
message = message.replace('\ud83d\ude23', ' :persevere: ');
message = message.replace('\ud83d\de4d', ' :person_frowning: ');
message = message.replace('\ud83d\udc71', ' :person_with_blond_hair: ');
message = message.replace('\ud83d\ude4e', ' :person_with_pouting_face: ');
message = message.replace('\ud83d\udc47', ' :point_down: ');
message = message.replace('\ud83d\udc48', ' :point_left: ');
message = message.replace('\ud83d\udc49', ' :point_right: ');
message = message.replace('\u261d', ' :point_up: ');
message = message.replace('\ud83d\udc46', ' :point_up_2: ');
message = message.replace('\ud83d\ude3e', ' :pouting_cat: ');
message = message.replace('\ud83d\ude4f', ' :pray: ');
message = message.replace('\ud83d\udc78', ' :princess: ');
message = message.replace('\ud83d\udc4a', ' :punch: ');
message = message.replace('\ud83d\udc9c', ' :purple_heart: ');
message = message.replace('\u2753', ' :question: ');
message = message.replace('\ud83d\ude21', ' :rage: ');
message = message.replace('\u270b', ' :raised_hand: ');
message = message.replace('\ud83d\ude4c', ' :raised_hands: ');
message = message.replace('\ud83d\ude4b', ' :raising_hand: ');
message = message.replace('\u263a', ' :relaxed: ');
message = message.replace('\ud83d\ude0c', ' :relieved: ');
message = message.replace('\ud83d\udc9e', ' :revolving_hearts: ');
message = message.replace('\ud83c\udfc3', ' :runner: ');
message = message.replace('\ud83c\udfc3', ' :running: ');
message = message.replace('\ud83d\ude06', ' :satisfied: ');
message = message.replace('\ud83d\ude31', ' :scream: ');
message = message.replace('\ud83d\ude40', ' :scream_cat: ');
message = message.replace('\ud83d\ude48', ' :see_no_evil: ');
message = message.replace('\ud83d\udca9', ' :shit: ');
message = message.replace('\ud83d\udc80', ' :skull: ');
message = message.replace('\ud83d\ude34', ' :sleeping: ');
message = message.replace('\ud83d\ude2a', ' :sleepy: ');
message = message.replace('\ud83d\ude03', ' :smile: ');
message = message.replace('\ud83d\ude38', ' :smile_cat: ');
message = message.replace('\ud83d\ude04', ' :smiley: ');
message = message.replace('\ud83d\ude3a', ' :smiley_cat: ');
message = message.replace('\ud83d\ude08', ' :smiling_imp: ');
message = message.replace('\ud83d\ude0f', ' :smirk: ');
message = message.replace('\ud83d\ude3c', ' :smirk_cat: ');
message = message.replace('\ud83d\ude2d', ' :sob: ');
message = message.replace('\u2728', ' :sparkles: ');
message = message.replace('\ud83d\udc96', ' :sparkling_heart: ');
message = message.replace('\ud83d\ude4a', ' :speak_no_evil: ');
message = message.replace('\ud83d\udcac', ' :speech_balloon: ');
message = message.replace('\u2b50', ' :star: ');
message = message.replace('\ud83c\udf1f', ' :star2: ');
message = message.replace('\ud83d\ude1b', ' :stuck_out_tongue: ');
message = message.replace('\ud83d\ude1d', ' :stuck_out_tongue_closed_eyes: ');
message = message.replace('\ud83d\ude1c', ' :stuck_out_tongue_winking_eye: ');
message = message.replace('\ud83d\ude0e', ' :sunglasses: ');
message = message.replace(':suspect:', ' :suspect: ');
message = message.replace('\ud83d\ude13', ' :sweat: ');
message = message.replace('\ud83d\udca6', ' :sweat_drops: ');
message = message.replace('\ud83d\ude05', ' :sweat_smile: ');
message = message.replace('\ud83d\udcad', ' :thought_balloon: ');
message = message.replace('\ud83d\udc4e', ' :thumbsdown: ');
message = message.replace('\ud83d\udc4d', ' :thumbsup: ');
message = message.replace('\ud83d\ude2b', ' :tired_face: ');
message = message.replace('\ud83d\udc45', ' :tongue: ');
message = message.replace('\ud83d\ude24', ' :triumph: ');
message = message.replace(':trollface:', ' :trollface: ');
message = message.replace('\ud83d\udc95', ' :two_hearts: ');
message = message.replace('\ud83d\udc6c', ' :two_men_holding_hands: ');
message = message.replace('\ud83d\udc6d', ' :two_women_holding_hands: ');
message = message.replace('\ud83d\ude12', ' :unamused: ');
message = message.replace('\u270c', ' :v: ');
message = message.replace('\ud83d\udeb6', ' :walking: ');
message = message.replace('\ud83d\udc4b', ' :wave: ');
message = message.replace('\ud83d\ude29', ' :weary: ');
message = message.replace('\ud83d\ude09', ' :wink: ');
message = message.replace('\ud83d\udc69', ' :woman: ');
message = message.replace('\ud83d\ude1f', ' :worried: ');
message = message.replace('\ud83d\udc9b', ' :yellow_heart: ');
message = message.replace('\ud83d\ude0b', ' :yum: ');
message = message.replace('\ud83d\udca4', ' :zzz: ');
message = message.replace('\ud83c\udfb1', ' :n8ball: ');
message = message.replace('\u23f0', ' :alarm_clock: ');
message = message.replace('\ud83c\udf4e', ' :apple: ');
message = message.replace('\ud83c\udfa8', ' :art: ');
message = message.replace('\ud83c\udf7c', ' :baby_bottle: ');
message = message.replace('\ud83c\udf88', ' :balloon: ');
message = message.replace('\ud83c\udf8d', ' :bamboo: ');
message = message.replace('\ud83c\udf4c', ' :banana: ');
message = message.replace('\ud83d\udcca', ' :bar_chart: ');
message = message.replace('\u26be', ' :baseball: ');
message = message.replace('\ud83c\udfc0', ' :basketball: ');
message = message.replace('\ud83d\udec0', ' :bath: ');
message = message.replace('\ud83d\udec1', ' :bathtub: ');
message = message.replace('\ud83d\udd0b', ' :battery: ');
message = message.replace('\ud83c\udf7a', ' :beer: ');
message = message.replace('\ud83c\udf7b', ' :beers: ');
message = message.replace('\ud83d\udd14 ', ' :bell: ');
message = message.replace('\ud83c\udf71', ' :bento: ');
message = message.replace('\ud83d\udeb4', ' :bicyclist: ');
message = message.replace('\ud83d\udc59', ' :bikini: ');
message = message.replace('\ud83c\udf82', ' :birthday: ');
message = message.replace('\ud83c\udccf', ' :black_joker: ');
message = message.replace('\u2712', ' :black_nib: ');
message = message.replace('\ud83d\udcd8', ' :blue_book: ');
message = message.replace('\ud83d\udca3', ' :bomb: ');
message = message.replace('\ud83d\udcd6', ' :book: ');
message = message.replace('\ud83d\udd16', ' :bookmark: ');
message = message.replace('\ud83d\udcd1', ' :bookmark_tabs: ');
message = message.replace('\ud83d\udcda', ' :books: ');
message = message.replace('\ud83d\udc62', ' :boot: ');
message = message.replace('\ud83c\udfb3', ' :bowling: ');
message = message.replace('\ud83c\udf5e', ' :bread: ');
message = message.replace('\ud83d\udcbc', ' :briefcase: ');
message = message.replace('\ud83d\udca1', ' :bulb: ');
message = message.replace('\ud83c\udf70', ' :cake: ');
message = message.replace('\ud83d\udcc6', ' :calendar: ');
message = message.replace('\ud83d\udcf2', ' :calling: ');
message = message.replace('\ud83d\udcf7', ' :camera: ');
message = message.replace('\ud83c\udf6c', ' :candy: ');
message = message.replace('\ud83d\udcc7', ' :card_index: ');
message = message.replace('\ud83d\udcbf', ' :cd: ');
message = message.replace('\ud83d\udcc9', ' :chart_with_downwards_trend: ');
message = message.replace('\ud83d\udcc8', ' :chart_with_upwards_trend: ');
message = message.replace('\ud83c\udf52', ' :cherries: ');
message = message.replace('\ud83c\udf6b', ' :chocolate_bar: ');
message = message.replace('\ud83c\udf84', ' :christmas_tre: ');
message = message.replace('\ud83c\udfac', ' :clapper: ');
message = message.replace('\ud83d\udccb', ' :clipboard: ');
message = message.replace('\ud83d\udcd5', ' :closed_book: ');
message = message.replace('\ud83d\udd10', ' :closed_lock_with_key: ');
message = message.replace('\ud83c\udf02', ' :closed_umbrella: ');
message = message.replace('\u2663', ' :clubs: ');
message = message.replace('\ud83c\udf78', ' :cocktail: ');
message = message.replace('\u2615', ' :coffee: ');
message = message.replace('\ud83d\udcbb', ' :computer: ');
message = message.replace('\ud83c\udf8a', ' :confetti_ball: ');
message = message.replace('\ud83c\udf6a', ' :cookie: ');
message = message.replace('\ud83c\udf3d', ' :corn: ');
message = message.replace('\ud83d\udcb3', ' :credit_card: ');
message = message.replace('\ud83d\udc51', ' :crown: ');
message = message.replace('\ud83d\udd2e', ' :crystal_ball: ');
message = message.replace('\ud83c\udf5b', ' :curry: ');
message = message.replace('\ud83c\udf6e', ' :custard: ');
message = message.replace('\ud83c\udf61', ' :dango: ');
message = message.replace('\ud83c\udfaf', ' :dart: ');
message = message.replace('\ud83d\udcc5', ' :date: ');
message = message.replace('\u2666', ' :diamonds: ');
message = message.replace('\ud83d\udcb5', ' :dollar: ');
message = message.replace('\ud83c\udf8e', ' :dolls: ');
message = message.replace('\ud83d\udeaa', ' :door: ');
message = message.replace('\ud83c\udf69', ' :doughnut: ');
message = message.replace('\ud83d\udc57', ' :dress: ');
message = message.replace('\ud83d\udcc0', ' :dvd: ');
message = message.replace('\ud83d\udce7', ' :e-mail: ');
message = message.replace('\ud83c\udf73', ' :egg: ');
message = message.replace('\ud83c\udf46', ' :eggplant: ');
message = message.replace('\ud83d\udd0c', ' :electric_plug: ');
message = message.replace('\ud83d\udce9', ' :email: ');
message = message.replace('\u2709', ' :envelope: ');
message = message.replace('\ud83d\udcb6', ' :euro: ');
message = message.replace('\ud83d\udc53', ' :eyeglasses: ');
message = message.replace('\ud83d\udce0', ' :fax: ');
message = message.replace('\ud83d\udcc1', ' :file_folder: ');
message = message.replace('\ud83c\udf86 ', ' :fireworks: ');
message = message.replace('\ud83c\udf65', ' :fish_cake: ');
message = message.replace('\ud83c\udfa3', ' :fishing_pole_and_fish: ');
message = message.replace('\ud83c\udf8f', ' :flags: ');
message = message.replace('\ud83d\udd26', ' :flashlight: ');
message = message.replace('\ud83d\udcbe', ' :floppy_disk: ');
message = message.replace('\ud83c\udfb4', ' :flower_playing_cards: ');
message = message.replace('\ud83c\udfc8', ' :football: ');
message = message.replace('\ud83c\udf74', ' :fork_and_knife: ');
message = message.replace('\ud83c\udf64', ' :fried_shrimp: ');
message = message.replace('\ud83c\udf5f', ' :fries: ');
message = message.replace('\ud83c\udfb2', ' :game_die: ');
message = message.replace('\ud83d\udc8e', ' :gem: ');
message = message.replace('\ud83d\udc7b', ' :ghost: ');
message = message.replace('\ud83c\udf81', ' :gift: ');
message = message.replace('\ud83d\udc9d', ' :gift_heart: ');
message = message.replace('\u26f3', ' :golf: ');
message = message.replace('\ud83c\udf47', ' :grapes: ');
message = message.replace('\ud83c\udf4f', ' :green_apple: ');
message = message.replace('\ud83d\udcd7', ' :green_book: ');
message = message.replace('\ud83c\udfb8', ' :guitar: ');
message = message.replace('\ud83d\udd2b', ' :gun: ');
message = message.replace('\ud83c\udf54', ' :hamburger: ');
message = message.replace('\ud83d\udd28', ' :hammer: ');
message = message.replace('\ud83d\udc5c', ' :handbag: ');
message = message.replace('\ud83c\udfa7', ' :headphones: ');
message = message.replace('\u2665', ' :hearts: ');
message = message.replace('\ud83d\udd06', ' :high_brightness: ');
message = message.replace('\ud83d\udc60', ' :high_heel: ');
message = message.replace('\ud83d\udd2a', ' :hocho: ');
message = message.replace('\ud83c\udf6f', ' :honey_pot: ');
message = message.replace('\ud83c\udfc7', ' :horse_racing: ');
message = message.replace('\u231b', ' :hourglass: ');
message = message.replace('\u23f3', ' :hourglass_flowing_sand: ');
message = message.replace('\ud83c\udf68', ' :ice_cream: ');
message = message.replace('\ud83c\udf66', ' :icecream: ');
message = message.replace('\ud83d\udce5', ' :inbox_tray: ');
message = message.replace('\ud83d\udce8', ' :incoming_envelope: ');
message = message.replace('\ud83d\udcf1', ' :iphone: ');
message = message.replace('\ud83c\udf83', ' :jack_o_lantern: ');
message = message.replace('\ud83d\udc56', ' :jeans: ');
message = message.replace('\ud83d\udd11', ' :key: ');
message = message.replace('\ud83d\udc58', ' :kimono: ');
message = message.replace('\ud83d\udcd2', ' :ledger: ');
message = message.replace('\ud83c\udf4b', ' :lemon: ');
message = message.replace('\ud83d\udc84', ' :lipstick: ');
message = message.replace('\ud83d\udd12', ' :lock: ');
message = message.replace('\ud83d\udd0f ', ' :lock_with_ink_pen: ');
message = message.replace('\ud83c\udf6d', ' :lollipop: ');
message = message.replace('\u27bf', ' :loop: ');
message = message.replace('\ud83d\udce2', ' :loudspeaker: ');
message = message.replace('\ud83d\udd05', ' :low_brightness: ');
message = message.replace('\ud83d\udd0d', ' :mag: ');
message = message.replace('\ud83d\udd0e', ' :mag_right: ');
message = message.replace('\ud83c\udc04', ' :mahjong: ');
message = message.replace('\ud83d\udceb', ' :mailbox: ');
message = message.replace('\ud83d\udcea', ' :mailbox_closed: ');
message = message.replace('\ud83d\udcec', ' :mailbox_with_mail: ');
message = message.replace('\ud83d\udced', ' :mailbox_with_no_mail: ');
message = message.replace('\ud83d\udc5e', ' :mans_shoe: ');
message = message.replace('\ud83c\udf56', ' :meat_on_bone: ');
message = message.replace('\ud83d\udce3', ' :mega: ');
message = message.replace('\ud83c\udf48', ' :melon: ');
message = message.replace('\ud83d\udcdd', ' :memo: ');
message = message.replace('\ud83c\udfa4', ' :microphone: ');
message = message.replace('\ud83d\udd2C', ' :microscope: ');
message = message.replace('\ud83d\udcbd', ' :minidisc: ');
message = message.replace('\ud83d\udcb8', ' :money_with_wings: ');
message = message.replace('\ud83d\udcb0', ' :moneybag: ');
message = message.replace('\ud83c\udf93', ' :mortar_board: ');
message = message.replace('\ud83d\udeb5', ' :mountain_bicyclist: ');
message = message.replace('\ud83c\udfa5', ' :movie_camera: ');
message = message.replace('\ud83c\udfb9', ' :musical_keyboard: ');
message = message.replace('\ud83c\udfbc', ' :musical_score: ');
message = message.replace('\ud83d\udd07', ' :mute: ');
message = message.replace('\ud83d\udcdb', ' :name_badge: ');
message = message.replace('\ud83d\udc54', ' :necktie: ');
message = message.replace('\ud83d\udcf0 ', ' :newspaper: ');
message = message.replace('\ud83d\udd15', ' :no_bell: ');
message = message.replace('\ud83d\udcd3', ' :notebook: ');
message = message.replace('\ud83d\udcd4', ' :notebook_with_decorative_cover: ');
message = message.replace('\ud83d\udd29', ' :nut_and_bolt: ');
message = message.replace('\ud83c\udf62', ' :oden: ');
message = message.replace('\ud83d\udcc2', ' :open_file_folder: ');
message = message.replace('\ud83d\udcd9', ' :orange_book: ');
message = message.replace('\ud83d\udce4', ' :outbox_tray: ');
message = message.replace('\ud83d\udcc4 ', ' :page_facing_up: ');
message = message.replace('\ud83d\udcc3', ' :page_with_curl: ');
message = message.replace('\ud83d\udcdf', ' :pager: ');
message = message.replace('\ud83d\udcces', ' :paperclip: ');
message = message.replace('\ud83c\udf51', ' :peach: ');
message = message.replace('\ud83c\udf50', ' :pear: ');
message = message.replace('\u270f', ' :pencil: ');
message = message.replace('\u270f', ' :pencil2: ');
message = message.replace('\u260e', ' :phone: ');
message = message.replace('\ud83d\udc8a', ' :pill: ');
message = message.replace('\ud83c\udf4d', ' :pineapple: ');
message = message.replace('\ud83c\udf55', ' :pizza: ');
message = message.replace('\ud83d\udcef', ' :postal_horn: ');
message = message.replace('\ud83d\udcee', ' :postbox: ');
message = message.replace('\ud83d\udc5d', ' :pouch: ');
message = message.replace('\ud83c\udf57', ' :poultry_leg: ');
message = message.replace('\ud83d\udcb7', ' :pound: ');
message = message.replace('\ud83d\udc5b', ' :purse: ');
message = message.replace('\ud83d\udccc', ' :pushpin: ');
message = message.replace('\ud83d\udcfb ', ' :radio: ');
message = message.replace('\ud83c\udf5c', ' :ramen: ');
message = message.replace('\ud83c\udf80', ' :ribbon: ');
message = message.replace('\ud83c\udf5a', ' :rice: ');
message = message.replace('\ud83c\udf59', ' :rice_ball: ');
message = message.replace('\ud83c\udf58', ' :rice_cracker: ');
message = message.replace('\ud83c\udf91', ' :rice_scene: ');
message = message.replace('\ud83d\udc8d', ' :ring: ');
message = message.replace('\ud83c\udfc9', ' :rugby_football: ');
message = message.replace('\ud83c\udfbd', ' :running_sirt_with_sash: ');
message = message.replace('\ud83c\udf76', ' :sake: ');
message = message.replace('\ud83d\udc61', ' :sandal: ');
message = message.replace('\ud83c\udf85', ' :santa: ');
message = message.replace('\ud83d\udce1', ' :satellite: ');
message = message.replace('\ud83c\udfb7', ' :saxophone: ');
message = message.replace('\ud83c\udf92', ' :school_satchel: ');
message = message.replace('\u2702', ' :scissors: ');
message = message.replace('\ud83d\udcdc', ' :scroll: ');
message = message.replace('\ud83d\udcba', ' :seat: ');
message = message.replace('\ud83c\udf67', ' :shaved_ice: ');
message = message.replace('\ud83d\udc55', ' :shirt: ');
message = message.replace('\ud83d\udc5f', ' :shoe: ');
message = message.replace('\ud83d\udebf', ' :shower: ');
message = message.replace('\ud83c\udfbf', ' :ski: ');
message = message.replace('\ud83d\udeac', ' :smoking: ');
message = message.replace('\ud83c\udfc2', ' :snowboarder: ');
message = message.replace('\u26bd', ' :soccer: ');
message = message.replace('\ud83d\udd09', ' :sound: ');
message = message.replace('\ud83d\udc7e', ' :space_invader: ');
message = message.replace('\u2660', ' :spades: ');
message = message.replace('\ud83c\udf5d', ' :spaghetti: ');
message = message.replace('\ud83c\udf87', ' :sparkler: ');
message = message.replace('\ud83d\udd0a', ' :speaker: ');
message = message.replace('\ud83c\udf72', ' :stew: ');
message = message.replace('\ud83d\udccf', ' :straight_ruler: ');
message = message.replace('\ud83c\udf53', ' :strawberry: ');
message = message.replace('\ud83c\udfc4', ' :surfer: ');
message = message.replace('\ud83c\udf63', ' :sushi: ');
message = message.replace('\ud83c\udf60', ' :sweet_potato: ');
message = message.replace('\ud83c\udfca', ' :swimmer: ');
message = message.replace('\ud83d\udc89', ' :syringe: ');
message = message.replace('\ud83c\udf89', ' :tada: ');
message = message.replace('\ud83c\udf8b', ' :tanabata_tree:');
message = message.replace('\ud83c\udf4a', ' :tangerine: ');
message = message.replace('\ud83c\udf75', ' :tea: ');
message = message.replace('\u260e', ' :telephone: ');
message = message.replace('\ud83d\udcde', ' :telephone_receiver: ');
message = message.replace('\ud83d\udd2d', ' :telescope: ');
message = message.replace('\ud83c\udfbe', ' :tennis: ');
message = message.replace('\ud83d\udebd', ' :toilet: ');
message = message.replace('\ud83c\udf45', ' :tomato: ');
message = message.replace('\ud83c\udfa9', ' :tophat: ');
message = message.replace('\ud83d\udcd0', ' :triangular_ruler: ');
message = message.replace('\ud83c\udfc6', ' :trophy: ');
message = message.replace('\ud83c\udf79', ' :tropical_drink: ');
message = message.replace('\ud83c\udfba', ' :trumpet: ');
message = message.replace('\ud83d\udc55', ' :tshirt: ');
message = message.replace('\ud83d\udcfa', ' :tv: ');
message = message.replace('\ud83d\udd13', ' :unlock: ');
message = message.replace('\ud83d\udcfc', ' :vhs: ');
message = message.replace('\ud83d\udcf9', ' :video_camera: ');
message = message.replace('\ud83c\udfae', ' :video_game: ');
message = message.replace('\ud83c\udfbb', ' :violin: ');
message = message.replace('\u231a', ' :watch: ');
message = message.replace('\ud83c\udf49', ' :watermelon: ');
message = message.replace('\ud83c\udf90', ' :wind_chime: ');
message = message.replace('\ud83c\udf77', ' :wine_glass: ');
message = message.replace('\ud83d\udc5a', ' :womans_clothes: ');
message = message.replace('\ud83d\udc52', ' :womans_hat: ');
message = message.replace('\ud83d\udd27', ' :wrench: ');
message = message.replace('\ud83d\udcb4', ' :yen: ');
message = message.replace('\ud83d\udc1c', ' :ant: ');
message = message.replace('\ud83d\udc24', ' :baby_chick: ');
message = message.replace('\ud83d\udc3b', ' :bear: ');
message = message.replace('\ud83d\udc1e', ' :beetle: ');
message = message.replace('\ud83d\udc26', ' :bird: ');
message = message.replace('\ud83c\udf3c', ' :blossom: ');
message = message.replace('\ud83d\udc21', ' :blowfish: ');
message = message.replace('\ud83d\udc17', ' :boar: ');
message = message.replace('\ud83d\udc90', ' :bouquet: ');
message = message.replace('\ud83d\udc1b', ' :bug: ');
message = message.replace('\ud83c\udf35', ' :cactus: ');
message = message.replace('\ud83d\udc2b', ' :camel: ');
message = message.replace('\ud83d\udc31', ' :cat: ');
message = message.replace('\ud83d\udc08', ' :cat2: ');
message = message.replace('\ud83c\udf38', ' :cherry_blossom: ');
message = message.replace('\ud83c\udf30', ' :chestnut: ');
message = message.replace('\ud83d\udc14', ' :chicken: ');
message = message.replace('\u2601', ' :cloud: ');
message = message.replace('\ud83d\udc2e', ' :cow: ');
message = message.replace('\ud83d\udc04', ' :cow2: ');
message = message.replace('\ud83d\udc0a', ' :crocodile: ');
message = message.replace('\ud83c\udf00', ' :cyclone: ');
message = message.replace('\ud83c\udf33', ' :deciduous_tree: ');
message = message.replace('\ud83d\udc36', ' :dog: ');
message = message.replace('\ud83d\udc15', ' :dog2: ');
message = message.replace('\ud83d\udc2c', ' :dolphin: ');
message = message.replace('\ud83d\udc09', ' :dragon: ');
message = message.replace('\ud83d\udc32', ' :dragon_face: ');
message = message.replace('\ud83d\udc2a', ' :dromedary_camel:');
message = message.replace('\ud83c\udf3e', ' :ear_of_rice: ');
message = message.replace('\ud83c\udf0d', ' :earth_africa: ');
message = message.replace('\ud83c\udf0e', ' :earth_americas: ');
message = message.replace('\ud83c\udf0f', ' :earth_asia: ');
message = message.replace('\ud83d\udc18', ' :elephant: ');
message = message.replace('\ud83c\udf32', ' :evergreen_tree: ');
message = message.replace('\ud83c\udf42', ' :fallen_leaf: ');
message = message.replace('\ud83c\udf13', ' :first_quarter_moon: ');
message = message.replace('\ud83c\udf1b', ' :first_quarter_moon_with_face: ');
message = message.replace('\ud83d\udc1f', ' :fish: ');
message = message.replace('\ud83c\udf01', ' :foggy: ');
message = message.replace('\ud83c\udf40', ' :four_leaf_clover: ');
message = message.replace('\ud83d\udc38', ' :frog: ');
message = message.replace('\ud83c\udf15', ' :full_moon: ');
message = message.replace('\ud83c\udf1d', ' :full_moon_with_face: ');
message = message.replace('\ud83c\udf10', ' :globe_with_meridians: ');
message = message.replace('\ud83d\udc10', ' :goat: ');
message = message.replace('\ud83d\udc39', ' :hamster: ');
message = message.replace('\ud83d\udc25', ' :hatched_chick: ');
message = message.replace('\ud83d\udc23', ' :hatching_chick: ');
message = message.replace('\ud83c\udf3f', ' :herb: ');
message = message.replace('\ud83c\udf3a', ' :hibiscus: ');
message = message.replace('\ud83d\udc1d', ' :honeybee: ');
message = message.replace('\ud83d\udc34', ' :horse: ');
message = message.replace('\ud83d\udc28', ' :koala: ');
message = message.replace('\ud83c\udf17', ' :last_quarter_moon: ');
message = message.replace('\ud83c\udf1c', ' :last_quarter_moon_with_face: ');
message = message.replace('\ud83c\udf43', ' :leaves: ');
message = message.replace('\ud83d\udc06', ' :leopard: ');
message = message.replace('\ud83c\udf41', ' :maple_leaf: ');
message = message.replace('\ud83c\udf0c', ' :milky_way: ');
message = message.replace('\ud83d\udc12', ' :monkey: ');
message = message.replace('\ud83d\udc35', ' :monkey_face: ');
message = message.replace('\ud83c\udf19', ' :moon: ');
message = message.replace('\ud83d\udc2d', ' :mouse: ');
message = message.replace('\ud83d\udc01', ' :mouse2: ');
message = message.replace('\ud83c\udf44', ' :mushroom:');
message = message.replace('\ud83c\udf11', ' :new_moon: ');
message = message.replace('\ud83c\udf1a', ' :new_moon_with_face: ');
message = message.replace('\ud83c\udf0a', ' :ocean: ');
message = message.replace('\ud83d\udc7f', ' :octocat: ');
message = message.replace('\ud83d\udc19', ' :octopus: ');
message = message.replace('\ud83d\udc02', ' :ox: ');
message = message.replace('\ud83c\udf34', ' :palm_tree: ');
message = message.replace('\ud83d\udc3c', ' :panda_face: ');
message = message.replace('\u26c5', ' :partly_sunny: ');
message = message.replace('\ud83d\udc3e', ' :paw_prints: ');
message = message.replace('\ud83d\udc27', ' :penguin: ');
message = message.replace('\ud83d\udc37', ' :pig: ');
message = message.replace('\ud83d\udc16', ' :pig2: ');
message = message.replace('\ud83d\udc3d', ' :pig_nose: ');
message = message.replace('\ud83d\udc29', ' :poodle: ');
message = message.replace('\ud83d\udc30', ' :rabbit: ');
message = message.replace('\ud83d\udc07', ' :rabbit2: ');
message = message.replace('\ud83d\udc0e', ' :racehorse: ');
message = message.replace('\ud83d\udc0f', ' :ram: ');
message = message.replace('\ud83d\udc00', ' :rat: ');
message = message.replace('\ud83d\udc13', ' :rooster: ');
message = message.replace('\ud83c\udf39', ' :rose: ');
message = message.replace('\ud83c\udf31', ' :seedling: ');
message = message.replace('\ud83d\udc11', ' :sheep: ');
message = message.replace('\ud83d\udc1a', ' :shell: ');
message = message.replace('\ud83d\udc0c', ' :snail: ');
message = message.replace('\ud83d\udc0d', ' :snake: ');
message = message.replace('\u2744', ' :snowflake: ');
message = message.replace('\u26c4', ' :snowman: ');
message = message.replace(':squirrel:', ' :squirrel: ');
message = message.replace('\ud83c\udf1e', ' :sun_with_face: ');
message = message.replace('\ud83c\udf3b', ' :sunflower: ');
message = message.replace('\u2600', ' :sunny: ');
message = message.replace('\ud83d\udc2f', ' :tiger: ');
message = message.replace('\ud83d\udc05', ' :tiger2: ');
message = message.replace('\ud83d\udc20', ' :tropical_fish: ');
message = message.replace('\ud83c\udf37', ' :tulip: ');
message = message.replace('\ud83d\udc22', ' :turtle: ');
message = message.replace('\u2614', ' :umbrella: ');
message = message.replace('\ud83c\udf0b', ' :volcano: ');
message = message.replace('\ud83c\udf18', ' :waning_crescent_moon: ');
message = message.replace('\ud83c\udf16', ' :waning_gibbous_moon: ');
message = message.replace('\ud83d\udc03', ' :water_buffalo: ');
message = message.replace('\ud83c\udf12', ' :waxing_crescent_moon: ');
message = message.replace('\ud83c\udf14', ' :waxing_gibbous_moon: ');
message = message.replace('\ud83d\udc33', ' :whale: ');
message = message.replace('\ud83d\udc0b', ' :whale2: ');
message = message.replace('\ud83d\udc3a', ' :wolf: ');
message = message.replace('\u26a1', ' :zap: ');
return message;
}
};
})();
})(jqcc);
$(document).ready(function(){
$.extend($.expr[":"], {
"containsIgnoreCase": function(elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
setInterval(function(){
$('span.notifier').each(function(){
if($(this).html()==0){
$(this).css('display', 'none');
}else{
$(this).css('display', 'block');
}
});
}, 100);
});
<?php
if($enableType == 0 || $enableType == 2){
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR."js".DIRECTORY_SEPARATOR."chat.js");
}
if($enableType == 0 || $enableType == 1){
include_once(dirname(__FILE__).DIRECTORY_SEPARATOR."js".DIRECTORY_SEPARATOR."chatrooms.js");
}
?>
|
networksoft/erp.roshlife
|
cometchat/extensions/mobilewebapp/mobilewebapp.js
|
JavaScript
|
apache-2.0
| 77,592
|
/*
* Copyright 2016 The BigDL 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 com.intel.analytics.bigdl.nn.ops
import com.intel.analytics.bigdl.nn.abstractnn.{AbstractModule, Activity}
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric
import scala.reflect.ClassTag
/**
* Wrap a nn module to an [[Operation]]
*
* @param module an nn module
* @tparam T Numeric type. Only support float/double now
*/
class ModuleToOperation[T: ClassTag]
(val module: AbstractModule[Activity, Activity, T])
(implicit ev: TensorNumeric[T])
extends Operation[Activity, Activity, T]{
override def updateOutput(input: Activity): Activity = {
output = module.forward(input)
output
}
}
object ModuleToOperation {
def apply[T: ClassTag](model: AbstractModule[_, _, T])
(implicit ev: TensorNumeric[T]): ModuleToOperation[T] =
new ModuleToOperation(model.asInstanceOf[AbstractModule[Activity, Activity, T]])
}
|
qiuxin2012/BigDL
|
spark/dl/src/main/scala/com/intel/analytics/bigdl/nn/ops/ModuleToOperation.scala
|
Scala
|
apache-2.0
| 1,518
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.