text:
package org.apache.hadoop.hbase.replication;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Abortable;
import org.apache.hadoop.hbase.CompoundConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.BytesBytesPair;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameStringPair;
import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
import org.apache.hadoop.hbase.replication.ReplicationPeer.PeerState;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.apache.hadoop.hbase.zookeeper.ZKUtil.ZKUtilOp;
import org.apache.zookeeper.KeeperException;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

/**
 * This class provides an implementation of the ReplicationPeers interface using Zookeeper. The
 * peers znode contains a list of all peer replication clusters and the current replication state of
 * those clusters. It has one child peer znode for each peer cluster. The peer znode is named with
 * the cluster id provided by the user in the HBase shell. The value of the peer znode contains the
 * peers cluster key provided by the user in the HBase Shell. The cluster key contains a list of
 * zookeeper quorum peers, the client port for the zookeeper quorum, and the base znode for HBase.
 * For example:
 *
 *  /hbase/replication/peers/1 [Value: zk1.host.com,zk2.host.com,zk3.host.com:2181:/hbase]
 *  /hbase/replication/peers/2 [Value: zk5.host.com,zk6.host.com,zk7.host.com:2181:/hbase]
 *
 * Each of these peer znodes has a child znode that indicates whether or not replication is enabled
 * on that peer cluster. These peer-state znodes do not have child znodes and simply contain a
 * boolean value (i.e. ENABLED or DISABLED). This value is read/maintained by the
 * ReplicationPeer.PeerStateTracker class. For example:
 *
 * /hbase/replication/peers/1/peer-state [Value: ENABLED]
 *
 * Each of these peer znodes has a child znode that indicates which data will be replicated
 * to the peer cluster. These peer-tableCFs znodes do not have child znodes and only have a
 * table/cf list config. This value is read/maintained by the ReplicationPeer.TableCFsTracker
 * class. For example:
 *
 * /hbase/replication/peers/1/tableCFs [Value: "table1; table2:cf1,cf3; table3:cfx,cfy"]
 */
@InterfaceAudience.Private
public class ReplicationPeersZKImpl extends ReplicationStateZKBase implements ReplicationPeers {

  // Map of peer clusters keyed by their id
  private Map<String, ReplicationPeerZKImpl> peerClusters;
  private final String tableCFsNodeName;

  private static final Log LOG = LogFactory.getLog(ReplicationPeersZKImpl.class);

  public ReplicationPeersZKImpl(final ZooKeeperWatcher zk, final Configuration conf,
      Abortable abortable) {
    super(zk, conf, abortable);
    this.tableCFsNodeName = conf.get("zookeeper.znode.replication.peers.tableCFs", "tableCFs");
    this.peerClusters = new ConcurrentHashMap<String, ReplicationPeerZKImpl>();
  }

  @Override
  public void init() throws ReplicationException {
    try {
      if (ZKUtil.checkExists(this.zookeeper, this.peersZNode) < 0) {
        ZKUtil.createWithParents(this.zookeeper, this.peersZNode);
      }
    } catch (KeeperException e) {
      throw new ReplicationException("Could not initialize replication peers", e);
    }
    addExistingPeers();
  }

  @Override
  public void addPeer(String id, ReplicationPeerConfig peerConfig, String tableCFs)
      throws ReplicationException {
    try {
      if (peerExists(id)) {
        throw new IllegalArgumentException("Cannot add a peer with id=" + id
            + " because that id already exists.");
      }

      if(id.contains("-")){
        throw new IllegalArgumentException("Found invalid peer name:" + id);
      }

      ZKUtil.createWithParents(this.zookeeper, this.peersZNode);
      List<ZKUtilOp> listOfOps = new ArrayList<ZKUtil.ZKUtilOp>();
      ZKUtilOp op1 = ZKUtilOp.createAndFailSilent(ZKUtil.joinZNode(this.peersZNode, id),
        toByteArray(peerConfig));
      // There is a race (if hbase.zookeeper.useMulti is false)
      // b/w PeerWatcher and ReplicationZookeeper#add method to create the
      // peer-state znode. This happens while adding a peer
      // The peer state data is set as "ENABLED" by default.
      ZKUtilOp op2 = ZKUtilOp.createAndFailSilent(getPeerStateNode(id), ENABLED_ZNODE_BYTES);
      String tableCFsStr = (tableCFs == null) ? "" : tableCFs;
      ZKUtilOp op3 = ZKUtilOp.createAndFailSilent(getTableCFsNode(id), Bytes.toBytes(tableCFsStr));
      listOfOps.add(op1);
      listOfOps.add(op2);
      listOfOps.add(op3);
      ZKUtil.multiOrSequential(this.zookeeper, listOfOps, false);
      // A peer is enabled by default
    } catch (KeeperException e) {
      throw new ReplicationException("Could not add peer with id=" + id
          + ", peerConfif=>" + peerConfig, e);
    }
  }

  @Override
  public void removePeer(String id) throws ReplicationException {
    try {
      if (!peerExists(id)) {
        throw new IllegalArgumentException("Cannot remove peer with id=" + id
            + " because that id does not exist.");
      }
      ZKUtil.deleteNodeRecursively(this.zookeeper, ZKUtil.joinZNode(this.peersZNode, id));
    } catch (KeeperException e) {
      throw new ReplicationException("Could not remove peer with id=" + id, e);
    }
  }

  @Override
  public void enablePeer(String id) throws ReplicationException {
    changePeerState(id, ZooKeeperProtos.ReplicationState.State.ENABLED);
    LOG.info("peer " + id + " is enabled");
  }

  @Override
  public void disablePeer(String id) throws ReplicationException {
    changePeerState(id, ZooKeeperProtos.ReplicationState.State.DISABLED);
    LOG.info("peer " + id + " is disabled");
  }

  @Override
  public String getPeerTableCFsConfig(String id) throws ReplicationException {
    try {
      if (!peerExists(id)) {
        throw new IllegalArgumentException("peer " + id + " doesn't exist");
      }
      try {
        return Bytes.toString(ZKUtil.getData(this.zookeeper, getTableCFsNode(id)));
      } catch (Exception e) {
        throw new ReplicationException(e);
      }
    } catch (KeeperException e) {
      throw new ReplicationException("Unable to get tableCFs of the peer with id=" + id, e);
    }
  }

  @Override
  public void setPeerTableCFsConfig(String id, String tableCFsStr) throws ReplicationException {
    try {
      if (!peerExists(id)) {
        throw new IllegalArgumentException("Cannot set peer tableCFs because id=" + id
            + " does not exist.");
      }
      String tableCFsZKNode = getTableCFsNode(id);
      byte[] tableCFs = Bytes.toBytes(tableCFsStr);
      if (ZKUtil.checkExists(this.zookeeper, tableCFsZKNode) != -1) {
        ZKUtil.setData(this.zookeeper, tableCFsZKNode, tableCFs);
      } else {
        ZKUtil.createAndWatch(this.zookeeper, tableCFsZKNode, tableCFs);
      }
      LOG.info("Peer tableCFs with id= " + id + " is now " + tableCFsStr);
    } catch (KeeperException e) {
      throw new ReplicationException("Unable to change tableCFs of the peer with id=" + id, e);
    }
  }

  @Override
  public Map<TableName, List<String>> getTableCFs(String id) throws IllegalArgumentException {
    ReplicationPeer replicationPeer = this.peerClusters.get(id);
    if (replicationPeer == null) {
      throw new IllegalArgumentException("Peer with id= " + id + " is not connected");
    }
    return replicationPeer.getTableCFs();
  }

  @Override
  public boolean getStatusOfPeer(String id) {
    ReplicationPeer replicationPeer = this.peerClusters.get(id);
    if (replicationPeer == null) {
      throw new IllegalArgumentException("Peer with id= " + id + " is not connected");
    }
    return replicationPeer.getPeerState() == PeerState.ENABLED;
  }

  @Override
  public boolean getStatusOfPeerFromBackingStore(String id) throws ReplicationException {
    try {
      if (!peerExists(id)) {
        throw new IllegalArgumentException("peer " + id + " doesn't exist");
      }
      String peerStateZNode = getPeerStateNode(id);
      try {
        return ReplicationPeerZKImpl.isStateEnabled(ZKUtil.getData(this.zookeeper, peerStateZNode));
      } catch (KeeperException e) {
        throw new ReplicationException(e);
      } catch (DeserializationException e) {
        throw new ReplicationException(e);
      }
    } catch (KeeperException e) {
      throw new ReplicationException("Unable to get status of the peer with id=" + id +
          " from backing store", e);
    } catch (InterruptedException e) {
      throw new ReplicationException(e);
    }
  }

  @Override
  public Map<String, ReplicationPeerConfig> getAllPeerConfigs() {
    Map<String, ReplicationPeerConfig> peers = new TreeMap<String, ReplicationPeerConfig>();
    List<String> ids = null;
    try {
      ids = ZKUtil.listChildrenNoWatch(this.zookeeper, this.peersZNode);
      for (String id : ids) {
        ReplicationPeerConfig peerConfig = getReplicationPeerConfig(id);
        if (peerConfig == null) {
          LOG.warn("Failed to get replication peer configuration of clusterid=" + id
            + " znode content, continuing.");
          continue;
        }
        peers.put(id, peerConfig);
      }
    } catch (KeeperException e) {
      this.abortable.abort("Cannot get the list of peers ", e);
    } catch (ReplicationException e) {
      this.abortable.abort("Cannot get the list of peers ", e);
    }
    return peers;
  }

  @Override
  public ReplicationPeer getPeer(String peerId) {
    return peerClusters.get(peerId);
  }

  @Override
  public Set<String> getPeerIds() {
    return peerClusters.keySet(); // this is not thread-safe
  }

  /**
   * Returns a ReplicationPeerConfig from the znode or null for the given peerId.
   */
  @Override
  public ReplicationPeerConfig getReplicationPeerConfig(String peerId)
      throws ReplicationException {
    String znode = ZKUtil.joinZNode(this.peersZNode, peerId);
    byte[] data = null;
    try {
      data = ZKUtil.getData(this.zookeeper, znode);
    } catch (InterruptedException e) {
      LOG.warn("Could not get configuration for peer because the thread " +
          "was interrupted. peerId=" + peerId);
      Thread.currentThread().interrupt();
      return null;
    } catch (KeeperException e) {
      throw new ReplicationException("Error getting configuration for peer with id="
          + peerId, e);
    }
    if (data == null) {
      LOG.error("Could not get configuration for peer because it doesn't exist. peerId=" + peerId);
      return null;
    }

    try {
      return parsePeerFrom(data);
    } catch (DeserializationException e) {
      LOG.warn("Failed to parse cluster key from peerId=" + peerId
          + ", specifically the content from the following znode: " + znode);
      return null;
    }
  }

  @Override
  public Pair<ReplicationPeerConfig, Configuration> getPeerConf(String peerId)
      throws ReplicationException {
    ReplicationPeerConfig peerConfig = getReplicationPeerConfig(peerId);

    if (peerConfig == null) {
      return null;
    }

    Configuration otherConf = new Configuration(this.conf);
    try {
      if (peerConfig.getClusterKey() != null && !peerConfig.getClusterKey().isEmpty()) {
        ZKUtil.applyClusterKeyToConf(otherConf, peerConfig.getClusterKey());
      }
    } catch (IOException e) {
      LOG.error("Can't get peer configuration for peerId=" + peerId + " because:", e);
      return null;
    }

    if (!peerConfig.getConfiguration().isEmpty()) {
      CompoundConfiguration compound = new CompoundConfiguration();
      compound.add(otherConf);
      compound.addStringMap(peerConfig.getConfiguration());
      return new Pair<ReplicationPeerConfig, Configuration>(peerConfig, compound);
    }

    return new Pair<ReplicationPeerConfig, Configuration>(peerConfig, otherConf);
  }

  /**
   * List all registered peer clusters and set a watch on their znodes.
   */
  @Override
  public List<String> getAllPeerIds() {
    List<String> ids = null;
    try {
      ids = ZKUtil.listChildrenAndWatchThem(this.zookeeper, this.peersZNode);
    } catch (KeeperException e) {
      this.abortable.abort("Cannot get the list of peers ", e);
    }
    return ids;
  }

  /**
   * A private method used during initialization. This method attempts to add all registered
   * peer clusters. This method does not set a watch on the peer cluster znodes.
   */
  private void addExistingPeers() throws ReplicationException {
    List<String> znodes = null;
    try {
      znodes = ZKUtil.listChildrenNoWatch(this.zookeeper, this.peersZNode);
    } catch (KeeperException e) {
      throw new ReplicationException("Error getting the list of peer clusters.", e);
    }
    if (znodes != null) {
      for (String z : znodes) {
        createAndAddPeer(z);
      }
    }
  }

  @Override
  public boolean peerAdded(String peerId) throws ReplicationException {
    return createAndAddPeer(peerId);
  }

  @Override
  public void peerRemoved(String peerId) {
    ReplicationPeer rp = this.peerClusters.get(peerId);
    if (rp != null) {
      ((ConcurrentMap<String, ReplicationPeerZKImpl>) peerClusters).remove(peerId, rp);
    }
  }

  /**
   * Attempt to connect to a new remote slave cluster.
   * @param peerId a short that identifies the cluster
   * @return true if a new connection was made, false if no new connection was made.
   */
  public boolean createAndAddPeer(String peerId) throws ReplicationException {
    if (peerClusters == null) {
      return false;
    }
    if (this.peerClusters.containsKey(peerId)) {
      return false;
    }

    ReplicationPeerZKImpl peer = null;
    try {
      peer = createPeer(peerId);
    } catch (Exception e) {
      throw new ReplicationException("Error adding peer with id=" + peerId, e);
    }
    if (peer == null) {
      return false;
    }
    ReplicationPeerZKImpl previous =
      ((ConcurrentMap<String, ReplicationPeerZKImpl>) peerClusters).putIfAbsent(peerId, peer);
    if (previous == null) {
      LOG.info("Added new peer cluster=" + peer.getPeerConfig().getClusterKey());
    } else {
      LOG.info("Peer already present, " + previous.getPeerConfig().getClusterKey() +
        ", new cluster=" + peer.getPeerConfig().getClusterKey());
    }
    return true;
  }

  private String getTableCFsNode(String id) {
    return ZKUtil.joinZNode(this.peersZNode, ZKUtil.joinZNode(id, this.tableCFsNodeName));
  }

  private String getPeerStateNode(String id) {
    return ZKUtil.joinZNode(this.peersZNode, ZKUtil.joinZNode(id, this.peerStateNodeName));
  }

  /**
   * Update the state znode of a peer cluster.
   * @param id
   * @param state
   */
  private void changePeerState(String id, ZooKeeperProtos.ReplicationState.State state)
      throws ReplicationException {
    try {
      if (!peerExists(id)) {
        throw new IllegalArgumentException("Cannot enable/disable peer because id=" + id
            + " does not exist.");
      }
      String peerStateZNode = getPeerStateNode(id);
      byte[] stateBytes =
          (state == ZooKeeperProtos.ReplicationState.State.ENABLED) ? ENABLED_ZNODE_BYTES
              : DISABLED_ZNODE_BYTES;
      if (ZKUtil.checkExists(this.zookeeper, peerStateZNode) != -1) {
        ZKUtil.setData(this.zookeeper, peerStateZNode, stateBytes);
      } else {
        ZKUtil.createAndWatch(this.zookeeper, peerStateZNode, stateBytes);
      }
      LOG.info("Peer with id= " + id + " is now " + state.name());
    } catch (KeeperException e) {
      throw new ReplicationException("Unable to change state of the peer with id=" + id, e);
    }
  }

  /**
   * Helper method to connect to a peer
   * @param peerId peer's identifier
   * @return object representing the peer
   * @throws ReplicationException
   */
  private ReplicationPeerZKImpl createPeer(String peerId) throws ReplicationException {
    Pair<ReplicationPeerConfig, Configuration> pair = getPeerConf(peerId);
    if (pair == null) {
      return null;
    }
    Configuration peerConf = pair.getSecond();

    ReplicationPeerZKImpl peer = new ReplicationPeerZKImpl(peerConf, peerId, pair.getFirst());
    try {
      peer.startStateTracker(this.zookeeper, this.getPeerStateNode(peerId));
    } catch (KeeperException e) {
      throw new ReplicationException("Error starting the peer state tracker for peerId=" +
          peerId, e);
    }

    try {
      peer.startTableCFsTracker(this.zookeeper, this.getTableCFsNode(peerId));
    } catch (KeeperException e) {
      throw new ReplicationException("Error starting the peer tableCFs tracker for peerId=" +
          peerId, e);
    }

    return peer;
  }

  /**
   * @param bytes Content of a peer znode.
   * @return ClusterKey parsed from the passed bytes.
   * @throws DeserializationException
   */
  private static ReplicationPeerConfig parsePeerFrom(final byte[] bytes)
      throws DeserializationException {
    if (ProtobufUtil.isPBMagicPrefix(bytes)) {
      int pblen = ProtobufUtil.lengthOfPBMagic();
      ZooKeeperProtos.ReplicationPeer.Builder builder =
          ZooKeeperProtos.ReplicationPeer.newBuilder();
      ZooKeeperProtos.ReplicationPeer peer;
      try {
        peer = builder.mergeFrom(bytes, pblen, bytes.length - pblen).build();
      } catch (InvalidProtocolBufferException e) {
        throw new DeserializationException(e);
      }
      return convert(peer);
    } else {
      if (bytes.length > 0) {
        return new ReplicationPeerConfig().setClusterKey(Bytes.toString(bytes));
      }
      return new ReplicationPeerConfig().setClusterKey("");
    }
  }

  private static ReplicationPeerConfig convert(ZooKeeperProtos.ReplicationPeer peer) {
    ReplicationPeerConfig peerConfig = new ReplicationPeerConfig();
    if (peer.hasClusterkey()) {
      peerConfig.setClusterKey(peer.getClusterkey());
    }
    if (peer.hasReplicationEndpointImpl()) {
      peerConfig.setReplicationEndpointImpl(peer.getReplicationEndpointImpl());
    }

    for (BytesBytesPair pair : peer.getDataList()) {
      peerConfig.getPeerData().put(pair.getFirst().toByteArray(), pair.getSecond().toByteArray());
    }

    for (NameStringPair pair : peer.getConfigurationList()) {
      peerConfig.getConfiguration().put(pair.getName(), pair.getValue());
    }
    return peerConfig;
  }

  private static ZooKeeperProtos.ReplicationPeer convert(ReplicationPeerConfig  peerConfig) {
    ZooKeeperProtos.ReplicationPeer.Builder builder = ZooKeeperProtos.ReplicationPeer.newBuilder();
    if (peerConfig.getClusterKey() != null) {
      builder.setClusterkey(peerConfig.getClusterKey());
    }
    if (peerConfig.getReplicationEndpointImpl() != null) {
      builder.setReplicationEndpointImpl(peerConfig.getReplicationEndpointImpl());
    }

    for (Map.Entry<byte[], byte[]> entry : peerConfig.getPeerData().entrySet()) {
      builder.addData(BytesBytesPair.newBuilder()
        .setFirst(ByteString.copyFrom(entry.getKey()))
        .setSecond(ByteString.copyFrom(entry.getValue()))
          .build());
    }

    for (Map.Entry<String, String> entry : peerConfig.getConfiguration().entrySet()) {
      builder.addConfiguration(NameStringPair.newBuilder()
        .setName(entry.getKey())
        .setValue(entry.getValue())
        .build());
    }

    return builder.build();
  }

  /**
   * @param peerConfig
   * @return Serialized protobuf of <code>peerConfig</code> with pb magic prefix prepended suitable
   *         for use as content of a this.peersZNode; i.e. the content of PEER_ID znode under
   *         /hbase/replication/peers/PEER_ID
   */
  private static byte[] toByteArray(final ReplicationPeerConfig peerConfig) {
    byte[] bytes = convert(peerConfig).toByteArray();
    return ProtobufUtil.prependPBMagic(bytes);
  }

}


text:
namespace gpu {
namespace gles2 {

// static
scoped_refptr<MailboxManager> MailboxManager::Create(
    const GpuPreferences& gpu_preferences) {
  if (gpu_preferences.enable_threaded_texture_mailboxes)
    return scoped_refptr<MailboxManager>(new MailboxManagerSync);
  return scoped_refptr<MailboxManager>(new MailboxManagerImpl);
}

}  // namespage gles2
}  // namespace gpu

redpajama_set_name: RedPajamaGithub


text:
from django.conf.urls import patterns, url
from django.contrib import admin
from django.views.generic import TemplateView

admin.autodiscover()

urlpatterns = patterns('brainstorming.views',
                       url(r'^$', 'index', name='home'),
                       url(r'^(?P<brainstorming_id>\w{12})/notification$', 'notification', name='notification'),
                       url(r'^(?P<brainstorming_id>\w{12})/edit$', 'edit', name='edit'),
                       url(r'^(?P<brainstorming_id>\w{12})/export$', 'export', name='export'),
                       url(r'^(?P<brainstorming_id>\w{12})/?', 'brainstorming', name='brainstorming'),
                       url(r'^.*$', TemplateView.as_view(template_name="index.html")),
)


text:
import time
from base_handler import BlogHandler
from models import User
from utility import valid_email, valid_username, valid_password, hash_str

class RegistrationHandler(BlogHandler):
    def get(self):
        self.render("register.html")
    def post(self):
        has_error = False
        error_list = []

        fullname = self.request.get('fullname')
        location = self.request.get('location')
        email = self.request.get('email')
        u_name = self.request.get('username')
        password = self.request.get('password')
        conf_pass = self.request.get('confirm_password')

        if fullname and email and u_name and password and conf_pass and location:
            if not valid_username(u_name):
                error_list.append('The Username is not valid!\
                    Username should not have any special characters!')
            if not valid_email(email):
                error_list.append('The Email is not valid!\
                    Email should be of the format : abc@example.com!')
                has_error = True
            if not valid_password(password):
                error_list.append("password should be greater than 3 \
                    characters and less than 20 characters!")
                has_error = True
            elif password != conf_pass:
                error_list.append("Both Passwords should match!")
                has_error = True

            user = User.query(User.email == email).get()
            if user:
                error_list.append("That email address already exists!")
                has_error = True

            user = User.query(User.user_name == u_name).get()
            if user:
                error_list.append('Sorry that username is already taken!\
                    Try another username!')
                has_error = True

            if has_error:
                self.render('register.html', fullname=fullname,
                            location=location,
                            email=email,
                            user_name=u_name,
                            error_list=error_list)
            else:
                new_user = User(fullname=fullname,
                                location=location,
                                email=email,
                                user_name=u_name,
                                password=hash_str(password))
                new_user_key = new_user.put()

                # new_user_photo_obj = UserPhoto(user=new_user_key)
                # new_user_photo_obj.put()

                time.sleep(0.2)
                # message = mail.EmailMessage(
                #                 sender='hello@your-own-blog.appspotmail.com',
                #                 subject="Thank You for Connecting with Us!")

                # message.to = email
                # message.body = """Dear %s:

                #         Your your-own-blog account has been approved.  You can now visit
                #         http://your-own-blog.appspot.com and sign in using your Google Account to
                #         access new features.

                #         Please let us know if you have any questions.

                #         The your-own-blog Team
                #         """ % (fullname)
                # message.send()
                self.render('login.html', new_user=new_user.fullname)
        else:
            error_list.append("You did not fill atleast one of the fields!")
            self.render('register.html', fullname=fullname,
                        location=location,
                        email=email,
                        user_name=u_name,
                        error_list=error_list)


text:
require File.expand_path "../lib/Mollie/API/Client", File.dirname(__FILE__)

begin
  #
  # Initialize the Mollie API library with your API key.
  #
  # See: https://www.mollie.nl/beheer/account/profielen/
  #
  mollie = Mollie::API::Client.new
  mollie.setApiKey "test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM"

  #
  # Generate a unique order id for this example. It is important to include this unique attribute
  # in the redirectUrl (below) so a proper return page can be shown to the customer.
  #
  order_id = Time.now.to_i

  #
  # Determine the url parts to these example files.
  #
  protocol = $request.secure? && "https" || "http"
  hostname = $request.host || "localhost"
  port     = $request.port || 80
  path     = $request.script_name || ""

  #
  # Payment parameters:
  #   amount        Amount in EUROs. This example creates a € 10,- payment.
  #   description   Description of the payment.
  #   redirectUrl   Redirect location. The customer will be redirected there after the payment.
  #   metadata      Custom metadata that is stored with the payment.
  #
  payment = mollie.payments.create \
    :amount       => 10.00,
    :description  => "My first API payment",
    :redirectUrl  => "#{protocol}://#{hostname}:#{port}#{path}/3-return-page?order_id=#{order_id}",
    :metadata     => {
      :order_id => order_id
    }

  #
  # In this example we store the order with its payment status in a database.
  #
  database_write order_id, payment.status

  #
  # Send the customer off to complete the payment.
  #
  $response.redirect payment.getPaymentUrl
rescue Mollie::API::Exception => e
  $response.body << "API call failed: " << (CGI.escapeHTML e.message)
end


text:
using System;
using System.Xml.Serialization;

namespace EZOper.NetSiteUtilities.AopApi
{
    /// <summary>
    /// BankCardInfo Data Structure.
    /// </summary>
    [Serializable]
    public class BankCardInfo : AopObject
    {
        /// <summary>
        /// 银行卡持卡人姓名
        /// </summary>
        [XmlElement("card_name")]
        public string CardName { get; set; }

        /// <summary>
        /// 银行卡号
        /// </summary>
        [XmlElement("card_no")]
        public string CardNo { get; set; }
    }
}


text:
"use strict";

import Future = require("fibers/future");
import path = require("path");
import shell = require("shelljs");
import util = require("util");
import xcode = require("xcode");
import constants = require("./../constants");
import helpers = require("./../common/helpers");
import projectServiceBaseLib = require("./platform-project-service-base");

class IOSProjectService extends projectServiceBaseLib.PlatformProjectServiceBase implements  IPlatformProjectService {
	private static XCODE_PROJECT_EXT_NAME = ".xcodeproj";
	private static XCODEBUILD_MIN_VERSION = "6.0";
	private static IOS_PROJECT_NAME_PLACEHOLDER = "__PROJECT_NAME__";
	private static IOS_PLATFORM_NAME = "ios";

	private get $npmInstallationManager(): INpmInstallationManager {
		return this.$injector.resolve("npmInstallationManager");
	}

	constructor(private $projectData: IProjectData,
		$fs: IFileSystem,
		private $childProcess: IChildProcess,
		private $errors: IErrors,
		private $logger: ILogger,
		private $iOSEmulatorServices: Mobile.IEmulatorPlatformServices,
		private $options: IOptions,
		private $injector: IInjector) {
			super($fs);
		}

	public get platformData(): IPlatformData {
		var projectRoot = path.join(this.$projectData.platformsDir, "ios");

		return {
			frameworkPackageName: "tns-ios",
			normalizedPlatformName: "iOS",
			appDestinationDirectoryPath: path.join(projectRoot, this.$projectData.projectName),
			appResourcesDestinationDirectoryPath: path.join(projectRoot, this.$projectData.projectName, "Resources", "icons"),
			platformProjectService: this,
			emulatorServices: this.$iOSEmulatorServices,
			projectRoot: projectRoot,
			deviceBuildOutputPath: path.join(projectRoot, "build", "device"),
			emulatorBuildOutputPath: path.join(projectRoot, "build", "emulator"),
			validPackageNamesForDevice: [
				this.$projectData.projectName + ".ipa"
			],
			validPackageNamesForEmulator: [
				this.$projectData.projectName + ".app"
			],
			frameworkFilesExtensions: [".a", ".framework", ".bin"],
			frameworkDirectoriesExtensions: [".framework"],
			frameworkDirectoriesNames: ["Metadata"],
			targetedOS: ['darwin'],
			configurationFileName: this.$projectData.projectName+"-Info.plist",
			configurationFilePath: path.join(projectRoot, this.$projectData.projectName,  this.$projectData.projectName+"-Info.plist")
		};
	}

	public validate(): IFuture<void> {
		return (() => {
			try {
				this.$childProcess.exec("which xcodebuild").wait();
			} catch(error) {
				this.$errors.fail("Xcode is not installed. Make sure you have Xcode installed and added to your PATH");
			}

			var xcodeBuildVersion = this.$childProcess.exec("xcodebuild -version | head -n 1 | sed -e 's/Xcode //'").wait();
			var splitedXcodeBuildVersion = xcodeBuildVersion.split(".");
			if(splitedXcodeBuildVersion.length === 3) {
				xcodeBuildVersion = util.format("%s.%s", splitedXcodeBuildVersion[0], splitedXcodeBuildVersion[1]);
			}

			if(helpers.versionCompare(xcodeBuildVersion, IOSProjectService.XCODEBUILD_MIN_VERSION) < 0) {
				this.$errors.fail("NativeScript can only run in Xcode version %s or greater", IOSProjectService.XCODEBUILD_MIN_VERSION);
			}

		}).future<void>()();
	}

	public createProject(projectRoot: string, frameworkDir: string): IFuture<void> {
		return (() => {
			if(this.$options.symlink) {
				this.$fs.ensureDirectoryExists(path.join(projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER)).wait();
				var xcodeProjectName = util.format("%s.xcodeproj", IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER);

				shell.cp("-R", path.join(frameworkDir, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, "*"), path.join(projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER));
				shell.cp("-R", path.join(frameworkDir, xcodeProjectName), projectRoot);

				var directoryContent = this.$fs.readDirectory(frameworkDir).wait();
				var frameworkFiles = _.difference(directoryContent, [IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, xcodeProjectName]);
				_.each(frameworkFiles, (file: string) => {
					this.$fs.symlink(path.join(frameworkDir, file), path.join(projectRoot, file)).wait();
				});

			}  else {
				shell.cp("-R", path.join(frameworkDir, "*"), projectRoot);
			}
		}).future<void>()();
	}

	public interpolateData(projectRoot: string): IFuture<void> {
		return (() => {
			var infoPlistFilePath = path.join(projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, util.format("%s-%s", IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, "Info.plist"));
			shell.sed('-i', "__CFBUNDLEIDENTIFIER__", this.$projectData.projectId, infoPlistFilePath);

			this.replaceFileName("-Info.plist", path.join(projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER)).wait();
			this.replaceFileName("-Prefix.pch", path.join(projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER)).wait();
			this.replaceFileName(IOSProjectService.XCODE_PROJECT_EXT_NAME, projectRoot).wait();

			var pbxprojFilePath = path.join(projectRoot, this.$projectData.projectName + IOSProjectService.XCODE_PROJECT_EXT_NAME, "project.pbxproj");
			this.replaceFileContent(pbxprojFilePath).wait();

			var mainFilePath = path.join(projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, "main.m");
			this.replaceFileContent(mainFilePath).wait();
		}).future<void>()();
	}

	public afterCreateProject(projectRoot: string): IFuture<void> {
		return (() => {
			this.$fs.rename(path.join(projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER),
				path.join(projectRoot, this.$projectData.projectName)).wait();
		}).future<void>()();
	}

	public buildProject(projectRoot: string): IFuture<void> {
		return (() => {
			let basicArgs = [
				"-configuration", this.$options.release ? "Release" : "Debug",
				"build",
				'SHARED_PRECOMPS_DIR=' + path.join(projectRoot, 'build', 'sharedpch')
			];

			let xcworkspacePath = path.join(projectRoot, this.$projectData.projectName + ".xcworkspace");
			if(this.$fs.exists(xcworkspacePath).wait()) {
				basicArgs.push("-workspace", xcworkspacePath);
				basicArgs.push("-scheme", this.$projectData.projectName);
			} else {
				basicArgs.push("-project", path.join(projectRoot, this.$projectData.projectName + ".xcodeproj"));
				basicArgs.push("-target", this.$projectData.projectName);
			}

			let args: string[] = [];
			if(this.$options.forDevice) {
				args = basicArgs.concat([
					"-xcconfig", path.join(projectRoot, this.$projectData.projectName, "build.xcconfig"),
					"-sdk", "iphoneos",
					'ARCHS=armv7 arm64',
					'VALID_ARCHS=armv7 arm64',
					"CONFIGURATION_BUILD_DIR=" + path.join(projectRoot, "build", "device")
				]);
			} else {
				args = basicArgs.concat([
					"-sdk", "iphonesimulator",
					"-arch", "i386",
					"VALID_ARCHS=\"i386\"",
					"CONFIGURATION_BUILD_DIR=" + path.join(projectRoot, "build", "emulator")
				]);
			}

			this.$childProcess.spawnFromEvent("xcodebuild", args, "exit", {cwd: this.$options, stdio: 'inherit'}).wait();

			if(this.$options.forDevice) {
				var buildOutputPath = path.join(projectRoot, "build", "device");

				// Produce ipa file
				var xcrunArgs = [
					"-sdk", "iphoneos",
					"PackageApplication",
					"-v", path.join(buildOutputPath, this.$projectData.projectName + ".app"),
					"-o", path.join(buildOutputPath, this.$projectData.projectName + ".ipa")
				];

				this.$childProcess.spawnFromEvent("xcrun", xcrunArgs, "exit", {cwd: this.$options, stdio: 'inherit'}).wait();
			}
		}).future<void>()();
	}

	public isPlatformPrepared(projectRoot: string): IFuture<boolean> {
		return this.$fs.exists(path.join(projectRoot, this.$projectData.projectName, constants.APP_FOLDER_NAME));
	}

	public addLibrary(libraryPath: string): IFuture<void> {
		return (() => {
			this.validateDynamicFramework(libraryPath).wait();
			var umbrellaHeader = this.getUmbrellaHeaderFromDynamicFramework(libraryPath).wait();

			let frameworkName = path.basename(libraryPath, path.extname(libraryPath));
			let targetPath = path.join("lib", this.platformData.normalizedPlatformName, frameworkName);
			let fullTargetPath = path.join(this.$projectData.projectDir, targetPath);
			this.$fs.ensureDirectoryExists(fullTargetPath).wait();
			shell.cp("-R", libraryPath, fullTargetPath);

			let project = this.createPbxProj();
			let frameworkPath = this.getFrameworkRelativePath(libraryPath);
			project.addFramework(frameworkPath, { customFramework: true, embed: true });
			project.updateBuildProperty("IPHONEOS_DEPLOYMENT_TARGET", "8.0");
			this.savePbxProj(project).wait();
			this.$logger.info("The iOS Deployment Target is now 8.0 in order to support Cocoa Touch Frameworks.");
		}).future<void>()();
	}

	public canUpdatePlatform(currentVersion: string, newVersion: string): IFuture<boolean> {
		return (() => {
			var currentXcodeProjectFile = this.buildPathToXcodeProjectFile(currentVersion);
			var currentXcodeProjectFileContent = this.$fs.readFile(currentXcodeProjectFile).wait();

			var newXcodeProjectFile = this.buildPathToXcodeProjectFile(newVersion);
			var newXcodeProjectFileContent = this.$fs.readFile(newXcodeProjectFile).wait();

			return currentXcodeProjectFileContent === newXcodeProjectFileContent;

		}).future<boolean>()();
	}

	public updatePlatform(currentVersion: string, newVersion: string): IFuture<void> {
		return (() => {
			// Copy old file to options["profile-dir"]
			var sourceFile = path.join(this.platformData.projectRoot, util.format("%s.xcodeproj", this.$projectData.projectName));
			var destinationFile = path.join(this.$options.profileDir, "xcodeproj");
			this.$fs.deleteDirectory(destinationFile).wait();
			shell.cp("-R", path.join(sourceFile, "*"), destinationFile);
			this.$logger.info("Backup file %s at location %s", sourceFile, destinationFile);
			this.$fs.deleteDirectory(path.join(this.platformData.projectRoot, util.format("%s.xcodeproj", this.$projectData.projectName))).wait();

			// Copy xcodeProject file
			var cachedPackagePath = path.join(this.$npmInstallationManager.getCachedPackagePath(this.platformData.frameworkPackageName, newVersion), constants.PROJECT_FRAMEWORK_FOLDER_NAME, util.format("%s.xcodeproj", IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER));
			shell.cp("-R", path.join(cachedPackagePath, "*"), path.join(this.platformData.projectRoot, util.format("%s.xcodeproj", this.$projectData.projectName)));
			this.$logger.info("Copied from %s at %s.", cachedPackagePath, this.platformData.projectRoot);

			var pbxprojFilePath = path.join(this.platformData.projectRoot, this.$projectData.projectName + IOSProjectService.XCODE_PROJECT_EXT_NAME, "project.pbxproj");
			this.replaceFileContent(pbxprojFilePath).wait();
		}).future<void>()();
	}

	public prepareProject(): IFuture<void> {
		return (() => {
			let project = this.createPbxProj();
			let resources = project.pbxGroupByName("Resources");

			if(resources) {
				let references = project.pbxFileReferenceSection();

				let xcodeProjectImages = _.map(<any[]>resources.children, resource => this.replace(references[resource.value].name));
				this.$logger.trace("Images from Xcode project");
				this.$logger.trace(xcodeProjectImages);

				let appResourcesImages = this.$fs.readDirectory(this.platformData.appResourcesDestinationDirectoryPath).wait();
				this.$logger.trace("Current images from App_Resources");
				this.$logger.trace(appResourcesImages);

				let imagesToAdd = _.difference(appResourcesImages, xcodeProjectImages);
				this.$logger.trace(`New images to add into xcode project: ${imagesToAdd.join(", ")}`);
				_.each(imagesToAdd, image => project.addResourceFile(path.relative(this.platformData.projectRoot, path.join( this.platformData.appResourcesDestinationDirectoryPath, image))));

				let imagesToRemove = _.difference(xcodeProjectImages, appResourcesImages);
				this.$logger.trace(`Images to remove from xcode project: ${imagesToRemove.join(", ")}`);
				_.each(imagesToRemove, image => project.removeResourceFile(path.join(this.platformData.appResourcesDestinationDirectoryPath, image)));

				this.savePbxProj(project).wait();
			}

		}).future<void>()();
	}

	public prepareAppResources(appResourcesDirectoryPath: string): IFuture<void> {
		return this.$fs.deleteDirectory(this.platformData.appResourcesDestinationDirectoryPath);
	}

	private replace(name: string): string {
		if(_.startsWith(name, '"')) {
			name = name.substr(1, name.length-2);
		}

		return name.replace(/\\\"/g, "\"");
	}

	private getFrameworkRelativePath(libraryPath: string): string {
		let frameworkName = path.basename(libraryPath, path.extname(libraryPath));
		let targetPath = path.join("lib", this.platformData.normalizedPlatformName, frameworkName);
		let frameworkPath = path.relative("platforms/ios", path.join(targetPath, frameworkName + ".framework"));
		return frameworkPath;
	}

	private get pbxProjPath(): string {
		return path.join(this.platformData.projectRoot, this.$projectData.projectName + ".xcodeproj", "project.pbxproj");
	}

	private createPbxProj(): any {
		let project = new xcode.project(this.pbxProjPath);
		project.parseSync();

		return project;
	}

	private savePbxProj(project: any): IFuture<void> {
		 return this.$fs.writeFile(this.pbxProjPath, project.writeSync());
	}

	public preparePluginNativeCode(pluginData: IPluginData): IFuture<void> {
		return (() => {
			let pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME);
			_.each(this.getAllDynamicFrameworksForPlugin(pluginData).wait(), fileName => this.addLibrary(path.join(pluginPlatformsFolderPath, fileName)).wait());
		}).future<void>()();
	}

	public removePluginNativeCode(pluginData: IPluginData): IFuture<void> {
		return (() => {
			let pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME);
			let project = this.createPbxProj();

			_.each(this.getAllDynamicFrameworksForPlugin(pluginData).wait(), fileName => {
				let fullFrameworkPath = path.join(pluginPlatformsFolderPath, fileName);
				let relativeFrameworkPath = this.getFrameworkRelativePath(fullFrameworkPath);
				project.removeFramework(relativeFrameworkPath, { customFramework: true, embed: true })
			});

			this.savePbxProj(project).wait();
		}).future<void>()();
	}

	private getAllDynamicFrameworksForPlugin(pluginData: IPluginData): IFuture<string[]> {
		let filterCallback = (fileName: string, pluginPlatformsFolderPath: string) => path.extname(fileName) === ".framework";
		return this.getAllNativeLibrariesForPlugin(pluginData, IOSProjectService.IOS_PLATFORM_NAME, filterCallback);
	}

	private buildPathToXcodeProjectFile(version: string): string {
		return path.join(this.$npmInstallationManager.getCachedPackagePath(this.platformData.frameworkPackageName, version), constants.PROJECT_FRAMEWORK_FOLDER_NAME, util.format("%s.xcodeproj", IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER), "project.pbxproj");
	}

	private validateDynamicFramework(libraryPath: string): IFuture<void> {
		return (() => {
			var infoPlistPath = path.join(libraryPath, "Info.plist");
			if (!this.$fs.exists(infoPlistPath).wait()) {
				this.$errors.failWithoutHelp("The bundle at %s does not contain an Info.plist file.", libraryPath);
			}

			var packageType = this.$childProcess.exec(`/usr/libexec/PlistBuddy -c "Print :CFBundlePackageType" "${infoPlistPath}"`).wait().trim();
			if (packageType !== "FMWK") {
				this.$errors.failWithoutHelp("The bundle at %s does not appear to be a dynamic framework.", libraryPath);
			}
		}).future<void>()();
	}

	private getUmbrellaHeaderFromDynamicFramework(libraryPath: string): IFuture<string> {
		return (() => {
			var modulemapPath = path.join(libraryPath, "Modules", "module.modulemap");
			if (!this.$fs.exists(modulemapPath).wait()) {
				this.$errors.failWithoutHelp("The framework at %s does not contain a module.modulemap file.", modulemapPath);
			}

			var modulemap = this.$fs.readText(modulemapPath).wait();
			var umbrellaRegex = /umbrella header "(.+\.h)"/g;
			var match = umbrellaRegex.exec(modulemap);
			if (!match) {
				this.$errors.failWithoutHelp("The modulemap at %s does not specify an umbrella header.", modulemapPath);
			}

			return match[1];
		}).future<string>()();
	}

	private replaceFileContent(file: string): IFuture<void> {
		return (() => {
			var fileContent = this.$fs.readText(file).wait();
			var replacedContent = helpers.stringReplaceAll(fileContent, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, this.$projectData.projectName);
			this.$fs.writeFile(file, replacedContent).wait();
		}).future<void>()();
	}

	private replaceFileName(fileNamePart: string, fileRootLocation: string): IFuture<void> {
		return (() => {
			var oldFileName = IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + fileNamePart;
			var newFileName = this.$projectData.projectName + fileNamePart;

			this.$fs.rename(path.join(fileRootLocation, oldFileName), path.join(fileRootLocation, newFileName)).wait();
		}).future<void>()();
	}
}
$injector.register("iOSProjectService", IOSProjectService);


text:
<?php
class Ajax extends CI_Controller{
    public function __construct()
    {
        parent::__construct();
        // Your own constructor code
    }
   public function testAJAX(){
        return "Message :";
    }
}


text:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>

using namespace cv;
using namespace std;

#include "WienerFilter.h"

int main(void)
{
	// This main applies the Adaptive Wiener Filter on a simple example
	// image and save results in the project installation folder

	string testImage = "ExampleImage.jpg";
	Mat1b src = imread(testImage, CV_LOAD_IMAGE_GRAYSCALE);
	Mat1b dst3x3, dst5x5, dst5x5_fixedNoise;

	if (src.empty()){
		cout << "The specified image '" << testImage << "' does not exists" << endl;
		exit(-1);
	}

	double estimatedNoiseVariance;

	// Call to WienerFilter function with a 3x3 kernel and estimated noise variances
	estimatedNoiseVariance = WienerFilter(src, dst3x3, Size(3, 3));

	// Call to WienerFilter function with default 5x5 kernel estimated noise variances
	estimatedNoiseVariance = WienerFilter(src, dst5x5);

	// Call to WienerFilter function with a default 5x5 kernel and fixed noise variances
	WienerFilter(src, dst5x5_fixedNoise, 5000);

	imwrite("Filtered3X3.png", dst3x3);
	imwrite("Filtered5X5.png", dst5x5);
	imwrite("Filtered5X5_fixedNoise.png", dst5x5_fixedNoise);

	return 0;
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Mozilla SMIL module.
 *
 * The Initial Developer of the Original Code is Brian Birtles.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Brian Birtles <birtles@gmail.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#ifndef NS_SMILMILESTONE_H_
#define NS_SMILMILESTONE_H_

/*
 * A significant moment in an nsSMILTimedElement's lifetime where a sample is
 * required.
 *
 * Animations register the next milestone in their lifetime with the time
 * container that they belong to. When the animation controller goes to run
 * a sample it first visits all the animations that have a registered milestone
 * in order of their milestone times. This allows interdependencies between
 * animations to be correctly resolved and events to fire in the proper order.
 *
 * A distinction is made between a milestone representing the end of an interval
 * and any other milestone. This is because if animation A ends at time t, and
 * animation B begins at the same time t (or has some other significant moment
 * such as firing a repeat event), SMIL's endpoint-exclusive timing model
 * implies that the interval end occurs first. In fact, interval ends can be
 * thought of as ending an infinitesimally small time before t. Therefore,
 * A should be sampled before B.
 *
 * Furthermore, this distinction between sampling the end of an interval and
 * a regular sample is used within the timing model (specifically in
 * nsSMILTimedElement) to ensure that all intervals ending at time t are sampled
 * before any new intervals are entered so that we have a fully up-to-date set
 * of instance times available before committing to a new interval. Once an
 * interval is entered, the begin time is fixed.
 */
class nsSMILMilestone
{
public:
  nsSMILMilestone(nsSMILTime aTime, PRBool aIsEnd)
    : mTime(aTime), mIsEnd(aIsEnd)
  { }

  nsSMILMilestone()
    : mTime(0), mIsEnd(PR_FALSE)
  { }

  PRBool operator==(const nsSMILMilestone& aOther) const
  {
    return mTime == aOther.mTime && mIsEnd == aOther.mIsEnd;
  }

  PRBool operator!=(const nsSMILMilestone& aOther) const
  {
    return !(*this == aOther);
  }

  PRBool operator<(const nsSMILMilestone& aOther) const
  {
    // Earlier times sort first, and for equal times end milestones sort first
    return mTime < aOther.mTime ||
          (mTime == aOther.mTime && mIsEnd && !aOther.mIsEnd);
  }

  PRBool operator<=(const nsSMILMilestone& aOther) const
  {
    return *this == aOther || *this < aOther;
  }

  PRBool operator>=(const nsSMILMilestone& aOther) const
  {
    return !(*this < aOther);
  }

  nsSMILTime   mTime;  // The milestone time. This may be in container time or
                       // parent container time depending on where it is used.
  PRPackedBool mIsEnd; // PR_TRUE if this milestone corresponds to an interval
                       // end, PR_FALSE otherwise.
};

#endif // NS_SMILMILESTONE_H_


text:
package urs

import (
	"crypto/elliptic"
	crand "crypto/rand"
	"fmt"
	"math/rand"
	"runtime"
	"testing"
)

const numOfKeys = 1000

var (
	DefaultCurve = elliptic.P256()
	keyring      *PublicKeyRing
	testkey      *PrivateKey
	testmsg      []byte
	testsig      *RingSign
)

func TestGenerateKey(t *testing.T) {
	runtime.GOMAXPROCS(4)
	var err error
	testkey, err = GenerateKey(DefaultCurve, crand.Reader)
	if err != nil {
		fmt.Println(err.Error())
		t.FailNow()
	}
}

func TestNewPublicKeyRing(t *testing.T) {
	keyring = NewPublicKeyRing(1)
	keyring.Add(testkey.PublicKey)
	expectedLen := 1
	if len(keyring.Ring) != expectedLen {
		t.Errorf("len(keyring)=%d, expected %d", len(keyring.Ring), expectedLen)
	}
}

func TestPopulateKeyRing(t *testing.T) {
	keyring = NewPublicKeyRing(numOfKeys)
	rand.Seed(23)
	k := rand.Intn(numOfKeys)
	fmt.Println("Index of my key: ", k)
	for i := 0; i < numOfKeys; i++ {
		key, err := GenerateKey(DefaultCurve, crand.Reader)
		if err != nil {
			fmt.Println(err.Error())
			t.FailNow()
		}
		if i == k { // designate this as my key
			testkey = key
		}
		// add the public key part to the ring
		keyring.Add(key.PublicKey)
	}
	if len(keyring.Ring) != numOfKeys {
		t.Errorf("len(keyring)=%d, expected %d", len(keyring.Ring), numOfKeys)
	}
}

func TestSign(t *testing.T) {
	testmsg = []byte("Hello, world.")
	var err error
	testsig, err = Sign(crand.Reader, testkey, keyring, testmsg)
	if err != nil {
		fmt.Println(err.Error())
		t.FailNow()
	}
	// fmt.Printf("%s\n", testsig)
}

func TestVerify(t *testing.T) {
	if !Verify(keyring, testmsg, testsig) {
		fmt.Println("urs: signature verification failed")
		t.FailNow()
	}
}

func BenchmarkSign(b *testing.B) {
	runtime.GOMAXPROCS(8)
	var err error
	for i := 0; i < b.N; i++ {
		testsig, err = Sign(crand.Reader, testkey, keyring, testmsg)
		if err != nil {
			fmt.Println(err.Error())
			b.FailNow()
		}
	}
}

func BenchmarkVerify(b *testing.B) {
	runtime.GOMAXPROCS(8)
	for i := 0; i < b.N; i++ {
		if !Verify(keyring, testmsg, testsig) {
			fmt.Println("urs: signature verification failed")
			b.FailNow()
		}
	}
}


text:
class Cloud

  def initialize()
    @cloud_numbers = 30
    @max_height    = 300
     @images        = [
       Gosu::Image.new("./media/p-cloud.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud2.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud3.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud4.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud5.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud6.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud7.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud8.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud9.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud10.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud11.png", :tileable => false),
       Gosu::Image.new("./media/p-cloud12.png", :tileable => false)
     ]
    @clouds = initial_clouds

  end

  def update
    @clouds.each do |item|
      # reset cloud position when it exceeds window with
      item[:x] = -300 if item[:x] >= 700

      # increment x-axis to make cloud movement based on it speed
      item[:x] += item[:speed]
    end
  end

  def draw
    @clouds.each do |item|
      # Draws the image rotated, with its rotational center at (x, y).
      item[:image].draw_rot(
        item[:x],
        item[:y],
        0,
        0,
        0.5,
        0.5,
        item[:size],
        item[:size],
        Gosu::Color.new(0xff_ffffff)
      )
    end
  end

  private

  # generate the clouds when the window is oppened
  def initial_clouds
    Array.new(@cloud_numbers) { generate_cloud }
  end

  # generate one cloud with randon configuration
  def generate_cloud
    {
      image: @images.sample,
      x:     rand(-100..600),
      y:     rand(-25..@max_height),
      speed: rand(0.1..0.3),
      size:  rand(0.1..1)
    }
  end
end


text:
<?php

require_once("OAuth.php");

/**
 * This class is used to sign all requests to dropbox.
 *
 * This specific class uses WordPress WP_Http to authenticate.
 */
class U1_OAuth_Curl extends U1_OAuth {

    /**
     *
     * @var string ConsumerKey
     */
    protected $consumerKey = null;

    /**
     *
     * @var string ConsumerSecret
     */
    protected $consumerSecret = null;

    /**
     *
     * @var string ProzessCallBack
     */
    public $ProgressFunction = false;

    /**
     * Constructor
     *
     * @param string $consumerName
     * @param string $consumerKey
     * @param string $consumerSecret
     */
    public function __construct($consumerName, $consumerKey = 'ubuntuone', $consumerSecret = 'hammertime') {
        if (!function_exists('curl_exec'))
            throw new U1_Exception('The PHP curl functions not available!', 0);

        $this->consumerKey = $consumerKey;
        $this->consumerSecret = $consumerSecret;
        $this->consumerName = $consumerName;
    }

    /**
     * Fetches a secured oauth url and returns the response body.
     *
     * @param string $uri
     * @param mixed $arguments
     * @param string $method
     * @param array $httpHeaders
     * @return string
     */
    public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array(), $contentType = '') {
		$uri=str_replace('http://', 'https://', $uri); // all https, upload makes problems if not

		if (is_string($arguments) and strtoupper($method) == 'POST') {
		    preg_match("/\?file=(.*)$/i", $uri, $matches);
			if (isset($matches[1])) {
                $uri = str_replace($matches[0], "", $uri);
                $filename = $matches[1];
				$httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, array("file" => $filename), $method));
            }
		} else {
			$httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, $arguments, $method));
		}

		$ch = curl_init();
		if (strtoupper($method) == 'POST') {
			curl_setopt($ch, CURLOPT_URL, $uri);
			curl_setopt($ch, CURLOPT_POST, true);
			if (is_array($arguments))
				$arguments=http_build_query($arguments);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);
			$httpHeaders['Content-Length']=strlen($arguments);
        } else if (strtoupper($method) == 'PUT') {
            curl_setopt($ch, CURLOPT_URL, $uri);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);
            $httpHeaders['Content-Length']=strlen($arguments);
            $httpHeaders['Content-Type']=$contentType;
		} else {
			curl_setopt($ch, CURLOPT_URL, $uri.'?'.http_build_query($arguments));
			curl_setopt($ch, CURLOPT_POST, false);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//2);
        curl_setopt($ch, CURLOPT_CAINFO, "rootca");
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
		//Build header
		$headers = array();
		foreach ($httpHeaders as $name => $value) {
			$headers[] = "{$name}: $value";
		}
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		if (!ini_get('safe_mode') && !ini_get('open_basedir'))
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
		if (function_exists($this->ProgressFunction) and defined('CURLOPT_PROGRESSFUNCTION')) {
			curl_setopt($ch, CURLOPT_NOPROGRESS, false);
			curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $this->ProgressFunction);
			curl_setopt($ch, CURLOPT_BUFFERSIZE, 512);
		}
		$response=curl_exec($ch);
		$errorno=curl_errno($ch);
		$error=curl_error($ch);
		$status=curl_getinfo($ch,CURLINFO_HTTP_CODE);
		curl_close($ch);

		if (!empty($errorno))
			throw new U1_Exception('Curl error: ('.$errorno.') '.$error."\n", 0);

		if ($status>=300) {
			$body = json_decode($response,true);
			switch ($status) {
				// Not modified
				case 304 :
					return array(
						'httpStatus' => 304,
						'body' => null,
					);
					break;
				case 401 :
					throw new U1_Exception('Bad Request.
						There is something wrong with the request data.
						' . $body["error"] . "\n", 401);
				case 403 :
					throw new U1_Exception('Forbidden.
						This could mean a bad OAuth request, or a file or folder already existing at the target location.
						' . $body["error"] . "\n", 403);
				case 404 :
					throw new U1_Exception('Resource at uri: ' . $uri . ' could not be found. ' .
							$body["error"] . "\n", 404);
				case 507 :
					throw new U1_Exception('This dropbox is full. ' .
							$body["error"] . "\n", 509);
			}
			if (!empty($body["error"]))
				throw new U1_Exception('Error: ('.$status.') '.$body["error"]."\n", 0);
		}

        return array(
			'body' => $response,
            'httpStatus' => $status
        );
    }

    /**
     * Returns named array with oauth parameters for further use
     * @return array Array with oauth_ parameters
     */
    private function getOAuthBaseParams() {
        $params['oauth_version'] = '1.0';
        $params['oauth_signature_method'] = 'HMAC-SHA1';

        $params['oauth_consumer_key'] = $this->consumerKey;
        $tokens = $this->getToken();
        if (isset($tokens['token']) && $tokens['token']) {
            $params['oauth_token'] = $tokens['token'];
        }
        $params['oauth_timestamp'] = time();
        $params['oauth_nonce'] = md5(microtime() . mt_rand());
        return $params;
    }

    /**
     * Creates valid Authorization header for OAuth, based on URI and Params
     *
     * @param string $uri
     * @param array $params
     * @param string $method GET or POST, standard is GET
     * @param array $oAuthParams optional, pass your own oauth_params here
     * @return array Array for request's headers section like
     * array('Authorization' => 'OAuth ...');
     */
    private function getOAuthHeader($uri, $params, $method = 'GET', $oAuthParams = null) {
        $oAuthParams = $oAuthParams ? $oAuthParams : $this->getOAuthBaseParams();

        // create baseString to encode for the sent parameters
        $baseString = $method . '&';
        $baseString .= $this->oauth_urlencode($uri) . "&";

        // OAuth header does not include GET-Parameters
        $signatureParams = array_merge($params, $oAuthParams);

        // sorting the parameters
        ksort($signatureParams);

        $encodedParams = array();
        foreach ($signatureParams as $key => $value) {
            $encodedParams[] = $this->oauth_urlencode($key) . '=' . $this->oauth_urlencode($value);
        }

        $baseString .= $this->oauth_urlencode(implode('&', $encodedParams));

        // encode the signature
        $tokens = $this->getToken();
        $hash = $this->hash_hmac_sha1($this->consumerSecret.'&'.$tokens['token_secret'], $baseString);
        $signature = base64_encode($hash);

        // add signature to oAuthParams
        $oAuthParams['oauth_signature'] = $signature;

        $oAuthEncoded = array();
        foreach ($oAuthParams as $key => $value) {
            $oAuthEncoded[] = $key . '="' . $this->oauth_urlencode($value) . '"';
        }

        return array('Authorization' => 'OAuth ' . implode(', ', $oAuthEncoded));
    }

    /**
     * Requests the OAuth request token.
     *
     * @return void
     */
    public function getRequestToken($callback = null) {
        $args = array();
        if ($callback) {
            $args["oauth_callback"] = $callback;
        }

        $result = $this->fetch(self::URI_REQUEST_TOKEN, $args, 'POST');

        if ($result['httpStatus'] == "200") {
            $tokens = array();
            parse_str($result['body'], $tokens);
            $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
            return $this->getToken();
        } else {
            throw new U1_Exception('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.', 403);
        }
    }

    /**
     * Requests the OAuth access tokens.
     *
     * This method requires the 'unauthorized' request tokens
     * and, if successful will set the authorized request tokens.
     *
     * @return void
     */
    public function getAccessToken($verifier) {
        $result = $this->fetch(self::URI_ACCESS_TOKEN, array("oauth_verifier" => $verifier), 'POST');

        if ($result['httpStatus'] == "200") {
            $tokens = array();
            parse_str($result['body'], $tokens);
            $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
            return $this->getToken();
        } else {
            throw new U1_Exception('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.', 403);
        }
    }

    /**
     * Helper function to properly urlencode parameters.
     * See http://php.net/manual/en/function.oauth-urlencode.php
     *
     * @param string $string
     * @return string
     */
    private function oauth_urlencode($string) {
        return str_replace('%E7', '~', rawurlencode($string));
    }

    /**
     * Hash function for hmac_sha1; uses native function if available.
     *
     * @param string $key
     * @param string $data
     * @return string
     */
    private function hash_hmac_sha1($key, $data) {
        if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) {
            return hash_hmac('sha1', $data, $key, true);
        } else {
            $blocksize = 64;
            $hashfunc = 'sha1';
            if (strlen($key) > $blocksize) {
                $key = pack('H*', $hashfunc($key));
            }

            $key = str_pad($key, $blocksize, chr(0x00));
            $ipad = str_repeat(chr(0x36), $blocksize);
            $opad = str_repeat(chr(0x5c), $blocksize);
            $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));

            return $hash;
        }
    }

}


text:
@interface JellyButton : VBFJellyView
@property (nonatomic) CGFloat pushMagnitude;

@end


text:
* * *

titul: "Bludiště: sekvence" pohled: page_curriculum téma: žádný

* * *

<%= partial('curriculum_header', :unittitle=>Kurz 1',: Lekce => 4,: titul => ' Bludiště: posloupnost ',: unplugged => false,: čas => 30) %>

[obsah]

[dohromady]

## Lekce – přehled

V této puzzel sérii studenti bude stavět na pochopení algoritmů, které se naučili v aktivitách Happy mapy a odpojených Přesunout to aktivitách . Představujeme postavy ze hry Angry Birds, studenti si budou vyvíjet sekvenční algoritmy přesunout pták z jedné strany bludiště k prasátku na druhé straně.

[Shrnutí]

## Přehled výuky

### **Začínáme**

[Úvod](#GetStarted)

### **Aktivita: Bludiště sekvence**

[Bludiště: sekvence](#Activity)

### **Rozšířená výuka**

[Aktivity jako rozšíření](#Extended)

[/ Shrnutí]

## Cíle lekce

### Studenti budou:

  * Pořadí příkazů pohybů jako postupné kroky v programu
  * Představují algoritmus jako počítačový program
  * Spočítat kolikrát by měly být akce provedena a představují si to jako instrukce v programu

[/ dohromady]

[dohromady]

## Začínáme

###  Úvod

Zeptejte se studentů, jestli jsou obeznámeni se hrou Angry Birds. Vysvětlete, že budou psát programy, aby pomohli rozhněvanému ptáku vyhledat prasátko.

  * Přehled základních směrů.
  * Používej ZPRÁVY symbolické nechť studenti vědí, že budou vidět ta písmena ve svých programech vedle směrové šipky.
  * Dostat ptáka k prasátku vyžaduje dát pokyny ve velmi specifickém pořadí nebo sekvenci.
  * Lze řešit hádanky pokud možná s nejmenším počtem bloků?

[/ dohromady]

[tip]

# Tip na lekci

Povzbuzujte studenty, aby i nadále používali metody programování ve dvojicích, kterou se naučil v poslední lekci. Požádejte je, aby si znovu určili role řidiče a navigátor.

[/tip]

[dohromady]

## Aktivita

###  [Bludiště: sekvence](http://learn.code.org/s/course1/stage/4/puzzle/1)

Jak studenti pracují prostřednictvím hádanek, pozorujte, jak si plánují cestu pro ptáka. Určete různé používané strategie a požádejte studenty, aby se o to podělili s celou třídou. To pomáhá studentům pochopit, že existuje mnoho způsobů, jak přistupovat k těmto problémům. Možná budete chtít projít pár hádanek na projektoru. Přitom můžete požádat jednoho studenta, aby sledoval cestu na obrazovce, zatímco jiný píše pokyny na tabuli.

[/ dohromady]

[dohromady]

## Rozšířená výuka

Používejte tyto aktivity k prohloubení učení studentů. Lze je použít jako mimoškolní aktivitu nebo jiné obohacení.

### Vytvořte si vlastní

V malých skupinách nechte studenty navrhnout si své vlastní bludiště a navzájem psát programy k jejich řešení. Přidá na zábavě, když je bludiště se studenty jako prasátko a pták.

[/ dohromady]

[standardy]

## Připojení a základní informace

### PARCC / chytřejší vyvážené zhodnocení schopností

  * Klepnout / poklepat
  * Přetažení
  * Vybrat objekt
  * Použít video přehrávač

### ISTE standardy (dříve NETS)

  * 1.a - uplatnit existující znalosti pro vytváření nových myšlenek, výrobků nebo procesů.
  * 1.c - Použití modelů a simulace ke zkoumání složitých systémů a problémů.
  * 4.b - plánovat a spravovat aktivity k vývoji řešení nebo dokončení projektu.
  * 6.a - porozumět a používat technologické systémy.
  * 6.c - systémy pro odstraňování potíží a aplikace.
  * 6.d - přenos současných znalostí k učení nových technologií.

### CSTA K-12 standardy informatiky

  * CD.L1:3-01. Používejte standardní vstupní a výstupní zařízení, aby úspěšně pracovaly na počítači a související technologie.
  * CT.L1:3-01. Používejte technologické prostředky (např, puzzly, programy na logické myšlení ) k řešení problémů odpovídající věku.
  * CL.L1:3-02. Kooperujte a spolupracujte s kolegy učiteli a dalšími používající technologie.
  * CPP.L1:6-05. Sestavte program jako soubor podrobných instrukcí, které musí být provedeny.
  * CPP.L1:6-06. Realizovat řešení problémů pomocí vizuálního programovacího jazyka blokově založeném.
  * CT.L2-01. Používejte základní kroky v algoritmické řešení problémů k návrhu řešení.
  * BTOL2-06 - popište a analyzujte posloupnost sledovaných instrukcí.
  * CT.L2-08. Používejte vizuální zobrazení problémových stavů, struktur a dat.
  * CT.L2-12. Používejte abstrakci k rozkladu problému na dílčí problémy.

### Next-Gen vědecké standardy

  * K.G.A.1 - popisují objekty v prostředí pomocí názvy obrazců a popisují vzájemné polohy těchto objektů pomocí termínů, jako nad, pod, vedle, před, za a vedle.
  * K-2-PS3-2. Používejte nástroje a materiály poskytnuté na návrh a vytváření zařízení, které řeší konkrétní problém nebo řeší specifický problém.

### Obecné základní matematické postupy

  *   1. Ujasnit problémy a vytrvat v jejich řešení.
  *   1. Zdůvodňovat abstraktně a kvantitativně.
  *   1. Používat strategicky vhodné nástroje.
  *   1. Dbát na přesnost.
  *   1. Vyhledávejte a využívejte struktury.
  *   1. Vyhledávejte a vyjádřete pravidelnost v opakujících úvahách.

### Obecné základní standardy matematiky

  * K.G.A.1 - popisují objekty v prostředí pomocí názvy obrazců a popisují vzájemné polohy těchto objektů pomocí termínů, jako nad, pod, vedle, před, za a vedle.
  * K.CC.B.4 - pochopit vztah mezi čísly a množství; propojte počítání na mohutnost.
  * K.OA.A.3 - rozložit čísla menší nebo rovné 10 do dvojic ve více než jedním způsobem, např. objekty nebo kresby a zaznamenat každý rozklad kresbou nebo rovnicí (např. 5 = 2 + 3 a 5 = 4 + 1).
  * K.OA.A.5 - plynule přičítat a odčítat v rozsahu 5.
  * 1.OA.A.1 - využití sčítání a odčítání do 20 k řešení slovních problémů zahrnující situace přidávání do, odebírání, dávání dohromady, rozebíraní a porovnávání s neznámými ve všech polohách, např. pomocí objektů, kreseb a rovnic se symbolem pro neznámé číslo představující problém.
  * 2.OA.A.1 - využití sčítání a odčítání do 100 k řešení problémů jednoho a dvou- slovných problémů, zahrnující situace přidávání do, odebírání, dávání dohromady, rozebírání a porovnání s neznámými ve všech polohách, např. s použitím kreseb a rovnic se symbolem pro neznámé číslo představující problém.
  * 2.G.A.2 - členění obdélníku do řádků a sloupců čtverců stejné velikosti a počtu ke zjištění celkového počtu.

### Obecné základní standardy umění jazyka

  * SL.K.1 - podílet se na společné rozhovory s rozmanitými partnery o tématech a texty o školce s vrstevníky a dospělými v malých a větších skupinách.
  * L.K.6 - používat slova a fráze, získané během konverzace, čtení a přečíst si je a reagovat na texty.
  * SL.K.1 - podílet se na společných rozhovorech s rozmanitými partnery o tématech a textech o školce s vrstevníky a dospělými, v malých a větších skupinách.
  * L.1.6 - používat slova a fráze, získaná prostřednictvím konverzace, čtení a přečtená, odpovídat na texty, včetně použití často se vyskytujících spojek signalizující jednoduché vztahy.
  * SL.K.1 - podílet se na společných rozhovorech s rozmanitými partnery o tématech a textech o školce s vrstevníky a dospělými, v malých a větších skupinách.
  * L.2.6 - použití slov a frází získaných prostřednictvím konverzace, čtení a čtení na, a reagovat na texty, včetně použití přídavných jmen a příslovcí popsat (např. když ostatní děti jsou šťastné, udělá mi to radost).

[/standardy]

[/ obsah]

<link rel="stylesheet" type="text/css" href="../docs/morestyle.css" />


text:
const log = require("ringo/logging").getLogger(module.id);
const {EventSource} = org.eclipse.jetty.servlets;
const {JavaEventEmitter} = require("ringo/events");

/**
 * Provides support for EventSource in the HTTP server.
 *
 * EventSource is an event emitter that supports the
 * following events:
 *
 *  * **open**: called when a new eventsource connection is accepted
 *  * **close**: called when an established eventsource connection closes
 * @name EventSource
 */
module.exports = function EventSourceWrapper() {
    let conn = null;

    /**
     * Closes the EventSource connection.
     * @name EventSource.instance.close
     */
    this.close = function() {
        if (conn) {
            conn.close();
            log.debug("Closed connection", conn);
        }
    };

    /**
     * Send a default event to the client
     * @param {String} msg a string
     * @name EventSource.instance.data
     */
    this.data = function(msg) {
        if (conn) {
            try {
                conn.data(msg);
            } catch (e) {
                if (log.isDebugEnabled()) {
                    log.error("Error sending data to {}:", conn, e);
                }
                conn = null;
                this.emit("close");
            }
        }
    };

    /**
     * Send a named event
     * @param {String} name a string
     * @param {String} msg a string
     * @name EventSource.instance.event
     */
    this.event = function(name, msg) {
        if (conn) {
            try {
                conn.event(name, msg);
            } catch (e) {
                if (log.isDebugEnabled()) {
                    log.error("Error sending '{}' event to {}:", name, conn, e);
                }
                conn = null;
                this.emit("close");
            }
        }
    };
    /**
     * Send a comment
     * @param {String} msg a string
     * @name EventSource.instance.comment
     */
    this.comment = function(msg) {
        if (conn) {
            try {
                conn.comment(msg);
            } catch (e) {
                if (log.isDebugEnabled()) {
                    log.error("Error sending comment to {}:", conn, e);
                }
                conn = null;
                this.emit("close");
            }
        }
    };

    /** @ignore **/
    this.setConnection = function(connection) {
        conn = connection;
    };

    JavaEventEmitter.call(this, [EventSource]);
    this.addListener("open", function(connection) {
        conn = connection;
    });

    return this;
};


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<parent>
		<groupId>com.bojinx</groupId>
		<artifactId>bojinx-as3-framework</artifactId>
		<version>1.0.1</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.bojinx</groupId>
	<artifactId>release</artifactId>
	<version>1.0.1</version>
	<name>Bojinx Release</name>
	<description>Release to FTP Package.</description>

	<!-- Console -->
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<!-- Site -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-site-plugin</artifactId>
				<version>3.0</version>
				<inherited>true</inherited>
				<configuration>
					<outputEncoding>utf-8</outputEncoding>
					<siteDirectory>${basedir}/../src/site</siteDirectory>
					<outputDirectory>../target/site/${project.artifactId}</outputDirectory>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>wagon-maven-plugin</artifactId>
				<executions>
					<execution>
						<id>upload-zip</id>
						<phase>deploy</phase>
						<goals>
							<goal>upload</goal>
						</goals>
						<configuration>
							<fromDir>../target/downloads</fromDir>
							<includes>*</includes>
							<url>ftp://${usr}:${pass}@ftp.bojinx.co.uk/httpdocs/releases/bojinx</url>
							<toDir>${output.version}/downloads</toDir>
						</configuration>
					</execution>
					<execution>
						<id>upload-site</id>
						<phase>deploy</phase>
						<goals>
							<goal>upload</goal>
						</goals>
						<configuration>
							<fromDir>../target/site</fromDir>
							<includes>**/*</includes>
							<url>ftp://${usr}:${pass}@ftp.bojinx.co.uk/httpdocs/releases/bojinx</url>
							<toDir>${output.version}/site</toDir>
						</configuration>
					</execution>
					<execution>
						<id>upload-examples</id>
						<phase>deploy</phase>
						<goals>
							<goal>upload</goal>
						</goals>
						<configuration>
							<fromDir>../target/examples</fromDir>
							<includes>**/*</includes>
							<url>ftp://${usr}:${pass}@ftp.bojinx.co.uk/httpdocs/releases/bojinx</url>
							<toDir>${output.version}/examples</toDir>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>


text:
'use strict';

const models = require('./index');

/**
 * The instance view of the container group. Only valid in response.
 *
 */
class ContainerGroupPropertiesInstanceView {
  /**
   * Create a ContainerGroupPropertiesInstanceView.
   * @member {array} [events] The events of this container group.
   * @member {string} [state] The state of the container group. Only valid in
   * response.
   */
  constructor() {
  }

  /**
   * Defines the metadata of ContainerGroupPropertiesInstanceView
   *
   * @returns {object} metadata of ContainerGroupPropertiesInstanceView
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ContainerGroup_properties_instanceView',
      type: {
        name: 'Composite',
        className: 'ContainerGroupPropertiesInstanceView',
        modelProperties: {
          events: {
            required: false,
            readOnly: true,
            serializedName: 'events',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'EventElementType',
                  type: {
                    name: 'Composite',
                    className: 'Event'
                  }
              }
            }
          },
          state: {
            required: false,
            readOnly: true,
            serializedName: 'state',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ContainerGroupPropertiesInstanceView;


text:
'use strict';

module.exports = {
    moduleType: 'trace',
    name: 'scatterpolar',
    basePlotModule: require('../../plots/polar'),
    categories: ['polar', 'symbols', 'showLegend', 'scatter-like'],

    attributes: require('./attributes'),
    supplyDefaults: require('./defaults').supplyDefaults,
    colorbar: require('../scatter/marker_colorbar'),
    formatLabels: require('./format_labels'),
    calc: require('./calc'),
    plot: require('./plot'),
    style: require('../scatter/style').style,
    styleOnSelect: require('../scatter/style').styleOnSelect,
    hoverPoints: require('./hover').hoverPoints,
    selectPoints: require('../scatter/select'),

    meta: {
        hrName: 'scatter_polar',
        description: [
            'The scatterpolar trace type encompasses line charts, scatter charts, text charts, and bubble charts',
            'in polar coordinates.',
            'The data visualized as scatter point or lines is set in',
            '`r` (radial) and `theta` (angular) coordinates',
            'Text (appearing either on the chart or on hover only) is via `text`.',
            'Bubble charts are achieved by setting `marker.size` and/or `marker.color`',
            'to numerical arrays.'
        ].join(' ')
    }
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GtkMessageDialog</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="index.html" title="GTK+ Reference Manual">
<link rel="up" href="WindowWidgets.html" title="Windows">
<link rel="prev" href="GtkInvisible.html" title="GtkInvisible">
<link rel="next" href="GtkWindow.html" title="GtkWindow">
<meta name="generator" content="GTK-Doc V1.15 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GTK+ Reference Manual

Top
                   |
                  Description
                   |
                  Object Hierarchy
                   |
                  Implemented Interfaces
                   |
                  Properties
                   |
                  Style Properties

GtkMessageDialog

GtkMessageDialog — A convenient message window

Synopsis

#include <gtk/gtk.h>

                    GtkMessageDialog;
enum                GtkMessageType;
enum                GtkButtonsType;
GtkWidget*          gtk_message_dialog_new              (GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         GtkMessageType type,
                                                         GtkButtonsType buttons,
                                                         const gchar *message_format,
                                                         ...);
GtkWidget*          gtk_message_dialog_new_with_markup  (GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         GtkMessageType type,
                                                         GtkButtonsType buttons,
                                                         const gchar *message_format,
                                                         ...);
void                gtk_message_dialog_set_markup       (GtkMessageDialog *message_dialog,
                                                         const gchar *str);
void                gtk_message_dialog_set_image        (GtkMessageDialog *dialog,
                                                         GtkWidget *image);
GtkWidget *         gtk_message_dialog_get_image        (GtkMessageDialog *dialog);
GtkWidget *         gtk_message_dialog_get_message_area (GtkMessageDialog *message_dialog);
void                gtk_message_dialog_format_secondary_text
                                                        (GtkMessageDialog *message_dialog,
                                                         const gchar *message_format,
                                                         ...);
void                gtk_message_dialog_format_secondary_markup
                                                        (GtkMessageDialog *message_dialog,
                                                         const gchar *message_format,
                                                         ...);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkMessageDialog

Implemented Interfaces

GtkMessageDialog implements
 AtkImplementorIface and  GtkBuildable.

Properties

  "buttons"                  GtkButtonsType        : Write / Construct Only
  "image"                    GtkWidget*            : Read / Write
  "message-area"             GtkWidget*            : Read
  "message-type"             GtkMessageType        : Read / Write / Construct
  "secondary-text"           gchar*                : Read / Write
  "secondary-use-markup"     gboolean              : Read / Write
  "text"                     gchar*                : Read / Write
  "use-markup"               gboolean              : Read / Write

Style Properties

  "message-border"           gint                  : Read
  "use-separator"            gboolean              : Read

Description

GtkMessageDialog presents a dialog with an image representing the type of
message (Error, Question, etc.) alongside some message text. It's simply a
convenience widget; you could construct the equivalent of GtkMessageDialog
from GtkDialog without too much effort, but GtkMessageDialog saves typing.

The easiest way to do a modal message dialog is to use gtk_dialog_run(), though
you can also pass in the GTK_DIALOG_MODAL flag, gtk_dialog_run() automatically
makes the dialog modal and waits for the user to respond to it. gtk_dialog_run()
returns when any dialog button is clicked.

Example 8. A modal dialog.

1
2
3
4
5
6
7
8

dialog = gtk_message_dialog_new (main_application_window,
                                 GTK_DIALOG_DESTROY_WITH_PARENT,
                                 GTK_MESSAGE_ERROR,
                                 GTK_BUTTONS_CLOSE,
                                 "Error loading file '%s': %s",
                                 filename, g_strerror (errno));
gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);

You might do a non-modal GtkMessageDialog as follows:

Example 9. A non-modal dialog.

1
2
3
4
5
6
7
8
9
10
11

dialog = gtk_message_dialog_new (main_application_window,
                                 GTK_DIALOG_DESTROY_WITH_PARENT,
                                 GTK_MESSAGE_ERROR,
                                 GTK_BUTTONS_CLOSE,
                                 "Error loading file '%s': %s",
                                 filename, g_strerror (errno));

/* Destroy the dialog when the user responds to it (e.g. clicks a button) */
g_signal_connect_swapped (dialog, "response",
                          G_CALLBACK (gtk_widget_destroy),
                          dialog);

GtkMessageDialog as GtkBuildable

The GtkMessageDialog implementation of the GtkBuildable interface exposes
the message area as an internal child with the name "message_area".

Details

GtkMessageDialog

typedef struct _GtkMessageDialog GtkMessageDialog;

enum GtkMessageType

typedef enum
{
  GTK_MESSAGE_INFO,
  GTK_MESSAGE_WARNING,
  GTK_MESSAGE_QUESTION,
  GTK_MESSAGE_ERROR,
  GTK_MESSAGE_OTHER
} GtkMessageType;

The type of message being displayed in the dialog.

<col align="left" valign="top">

GTK_MESSAGE_INFO

Informational message

GTK_MESSAGE_WARNING

Nonfatal warning message

GTK_MESSAGE_QUESTION

Question requiring a choice

GTK_MESSAGE_ERROR

Fatal error message

GTK_MESSAGE_OTHER

None of the above, doesn't get an icon

enum GtkButtonsType

typedef enum
{
  GTK_BUTTONS_NONE,
  GTK_BUTTONS_OK,
  GTK_BUTTONS_CLOSE,
  GTK_BUTTONS_CANCEL,
  GTK_BUTTONS_YES_NO,
  GTK_BUTTONS_OK_CANCEL
} GtkButtonsType;

Prebuilt sets of buttons for the dialog. If
none of these choices are appropriate, simply use GTK_BUTTONS_NONE
then call gtk_dialog_add_buttons().

Note

 Please note that GTK_BUTTONS_OK, GTK_BUTTONS_YES_NO
 and GTK_BUTTONS_OK_CANCEL are discouraged by the
 GNOME HIG.

<col align="left" valign="top">

GTK_BUTTONS_NONE

no buttons at all

GTK_BUTTONS_OK

an OK button

GTK_BUTTONS_CLOSE

a Close button

GTK_BUTTONS_CANCEL

a Cancel button

GTK_BUTTONS_YES_NO

Yes and No buttons

GTK_BUTTONS_OK_CANCEL

OK and Cancel buttons

gtk_message_dialog_new ()

GtkWidget*          gtk_message_dialog_new              (GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         GtkMessageType type,
                                                         GtkButtonsType buttons,
                                                         const gchar *message_format,
                                                         ...);

Creates a new message dialog, which is a simple dialog with an icon
indicating the dialog type (error, warning, etc.) and some text the
user may want to see. When the user clicks a button a "response"
signal is emitted with response IDs from GtkResponseType. See
GtkDialog for more details.

<col align="left" valign="top">

parent :

 transient parent, or NULL for none. [<acronym title="NULL is ok, both for passing and for returning.">allow-none</acronym>]

flags :

flags

type :

type of message

buttons :

set of buttons to use

message_format :

 printf()-style format string, or NULL. [<acronym title="NULL is ok, both for passing and for returning.">allow-none</acronym>]

... :

arguments for message_format

Returns :

 a new GtkMessageDialog. [<acronym title="Don't free data after the code is done.">transfer none</acronym>]

gtk_message_dialog_new_with_markup ()

GtkWidget*          gtk_message_dialog_new_with_markup  (GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         GtkMessageType type,
                                                         GtkButtonsType buttons,
                                                         const gchar *message_format,
                                                         ...);

Creates a new message dialog, which is a simple dialog with an icon
indicating the dialog type (error, warning, etc.) and some text which
is marked up with the Pango text markup language.
When the user clicks a button a "response" signal is emitted with
response IDs from GtkResponseType. See GtkDialog for more details.

Special XML characters in the printf() arguments passed to this
function will automatically be escaped as necessary.
(See g_markup_printf_escaped() for how this is implemented.)
Usually this is what you want, but if you have an existing
Pango markup string that you want to use literally as the
label, then you need to use gtk_message_dialog_set_markup()
instead, since you can't pass the markup string either
as the format (it might contain '%' characters) or as a string
argument.

1
2
3
4
5
6
7
8

GtkWidget *dialog;
dialog = gtk_message_dialog_new (main_application_window,
                                 GTK_DIALOG_DESTROY_WITH_PARENT,
                                 GTK_MESSAGE_ERROR,
                                 GTK_BUTTONS_CLOSE,
                                 NULL);
gtk_message_dialog_set_markup (GTK_MESSAGE_DIALOG (dialog),
                               markup);

<col align="left" valign="top">

parent :

 transient parent, or NULL for none. [<acronym title="NULL is ok, both for passing and for returning.">allow-none</acronym>]

flags :

flags

type :

type of message

buttons :

set of buttons to use

message_format :

 printf()-style format string, or NULL. [<acronym title="NULL is ok, both for passing and for returning.">allow-none</acronym>]

... :

arguments for message_format

Returns :

 a new GtkMessageDialog

Since 2.4

gtk_message_dialog_set_markup ()

void                gtk_message_dialog_set_markup       (GtkMessageDialog *message_dialog,
                                                         const gchar *str);

Sets the text of the message dialog to be str, which is marked
up with the <GTKDOCLINK HREF="PangoMarkupFormat">Pango text markup
language</GTKDOCLINK>.

<col align="left" valign="top">

message_dialog :

a GtkMessageDialog

str :

markup string (see Pango markup format)

Since 2.4

gtk_message_dialog_set_image ()

void                gtk_message_dialog_set_image        (GtkMessageDialog *dialog,
                                                         GtkWidget *image);

Sets the dialog's image to image.

<col align="left" valign="top">

dialog :

a GtkMessageDialog

image :

the image

Since 2.10

gtk_message_dialog_get_image ()

GtkWidget *         gtk_message_dialog_get_image        (GtkMessageDialog *dialog);

Gets the dialog's image.

<col align="left" valign="top">

dialog :

a GtkMessageDialog

Returns :

 the dialog's image

Since 2.14

gtk_message_dialog_get_message_area ()

GtkWidget *         gtk_message_dialog_get_message_area (GtkMessageDialog *message_dialog);

<col align="left" valign="top">

message_dialog :

a GtkMessageDialog

Returns :

 A GtkVBox corresponding to the "message area" in the
message_dialog.  This is the box where the dialog's primary and secondary
labels are packed.  You can add your own extra content to that box and it
will appear below those labels, on the right side of the dialog's image (or
on the left for right-to-left languages).  See gtk_dialog_get_content_area()
for the corresponding function in the parent GtkDialog.

Since 2.22

gtk_message_dialog_format_secondary_text ()

void                gtk_message_dialog_format_secondary_text
                                                        (GtkMessageDialog *message_dialog,
                                                         const gchar *message_format,
                                                         ...);

Sets the secondary text of the message dialog to be message_format
(with printf()-style).

Note that setting a secondary text makes the primary text become
bold, unless you have provided explicit markup.

<col align="left" valign="top">

message_dialog :

a GtkMessageDialog

message_format :

 printf()-style format string, or NULL. [<acronym title="NULL is ok, both for passing and for returning.">allow-none</acronym>]

... :

arguments for message_format

Since 2.6

gtk_message_dialog_format_secondary_markup ()

void                gtk_message_dialog_format_secondary_markup
                                                        (GtkMessageDialog *message_dialog,
                                                         const gchar *message_format,
                                                         ...);

Sets the secondary text of the message dialog to be message_format (with
printf()-style), which is marked up with the
Pango text markup language.

Note that setting a secondary text makes the primary text become
bold, unless you have provided explicit markup.

Due to an oversight, this function does not escape special XML characters
like gtk_message_dialog_new_with_markup() does. Thus, if the arguments
may contain special XML characters, you should use g_markup_printf_escaped()
to escape it.

1
2
3
4
5

gchar *msg;

msg = g_markup_printf_escaped (message_format, ...);
gtk_message_dialog_format_secondary_markup (message_dialog, "%s", msg);
g_free (msg);

<col align="left" valign="top">

message_dialog :

a GtkMessageDialog

message_format :

printf()-style markup string (see
     Pango markup format), or NULL

... :

arguments for message_format

Since 2.6

Property Details

The "buttons" property

  "buttons"                  GtkButtonsType        : Write / Construct Only

The buttons shown in the message dialog.

Default value: GTK_BUTTONS_NONE

The "image" property

  "image"                    GtkWidget*            : Read / Write

The image for this dialog.

Since 2.10

The "message-area" property

  "message-area"             GtkWidget*            : Read

The GtkVBox that corresponds to the message area of this dialog.  See
gtk_message_dialog_get_message_area() for a detailed description of this
area.

Since 2.22

The "message-type" property

  "message-type"             GtkMessageType        : Read / Write / Construct

The type of the message. The type is used to determine
the image that is shown in the dialog, unless the image is
explicitly set by the ::image property.

Default value: GTK_MESSAGE_INFO

The "secondary-text" property

  "secondary-text"           gchar*                : Read / Write

The secondary text of the message dialog.

Default value: NULL

Since 2.10

The "secondary-use-markup" property

  "secondary-use-markup"     gboolean              : Read / Write

TRUE if the secondary text of the dialog includes Pango markup.
See pango_parse_markup().

Default value: FALSE

Since 2.10

The "text" property

  "text"                     gchar*                : Read / Write

The primary text of the message dialog. If the dialog has
a secondary text, this will appear as the title.

Default value: ""

Since 2.10

The "use-markup" property

  "use-markup"               gboolean              : Read / Write

TRUE if the primary text of the dialog includes Pango markup.
See pango_parse_markup().

Default value: FALSE

Since 2.10

Style Property Details

The "message-border" style property

  "message-border"           gint                  : Read

Width of border around the label and image in the message dialog.

Allowed values: >= 0

Default value: 12

The "use-separator" style property

  "use-separator"            gboolean              : Read

Warning

GtkMessageDialog:use-separator has been deprecated since version 2.22 and should not be used in newly-written code. This style property will be removed in GTK+ 3

Whether to draw a separator line between the message label and the buttons
in the dialog.

Default value: FALSE

Since 2.4

See Also

GtkDialog

          Generated by GTK-Doc V1.15


text:
factory :email_address do

  ignore do
    confirmed false
  end

  sequence(:address) {|i| "factoried-#{i}@example.com"}
  confirmed_at { confirmed ? Time.now : nil }
end


text:
package ch.liquidmind.inflection.test.model;

public enum Gender
{
	MALE,
	FEMALE
}