text:
package org.opensplice.mobile.dev.common

import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.ReentrantLock
import scala.collection.mutable.Queue

object DAActor2 {

  def getExecutor(name: String, poolSize: Int = 1) = {
    new DAActorExecutor(name, poolSize)
  }

  def getDummyExecutor(name: String) = DAActor2

  def post(foo: () => Unit) {
    foo()
  }

  class DAActorExecutor(name: String, poolSize: Int) {
    //val queue = new LinkedBlockingQueue[() => Unit]()
    val queue2 = new Queue[() => Unit]()

    /** The capacity bound, or Integer.MAX_VALUE if none */
    val capacity = Integer.MAX_VALUE;

    /** Current number of elements */
    val count = new AtomicInteger(0)
    /** Lock held by take, poll, etc */
    val takeLock = new ReentrantLock()

    /** Wait queue for waiting takes */
    val notEmpty = takeLock.newCondition()

    /** Lock held by put, offer, etc */
    val putLock = new ReentrantLock()

    /** Wait queue for waiting puts */
    val notFull = putLock.newCondition()

    def placeHolder() {}

    def signalNotFull() {
      val putLock = this.putLock;
      putLock.lock();
      try {
        notFull.signal();
      } finally {
        putLock.unlock();
      }
    }

    def take() = {
      var x: () => Unit = placeHolder
      var c = -1;
      val count = this.count;
      val takeLock = this.takeLock;
      takeLock.lockInterruptibly();
      try {
        while (count.get() == 0) {
          notEmpty.await();
        }
        x = queue2.dequeue();
        c = count.getAndDecrement();
        if (c > 1)
          notEmpty.signal();
      } finally {
        takeLock.unlock();
      }
      if (c == capacity)
        signalNotFull();
      x;
    }

    def signalNotEmpty() {
      val takeLock = this.takeLock;
      takeLock.lock();
      try {
        notEmpty.signal();
      } finally {
        takeLock.unlock();
      }
    }

    def put(e: () => Unit) {
      if (e == null) throw new NullPointerException();

      var c = -1
      val putLock = this.putLock;
      val count = this.count;
      putLock.lockInterruptibly();
      try {
        /*
             * Note that count is used in wait guard even though it is
             * not protected by lock. This works because count can
             * only decrease at this point (all other puts are shut
             * out by lock), and we (or some other waiting put) are
             * signalled if it ever changes from capacity. Similarly
             * for all other uses of count in other wait guards.
             */
        while (count.get() == capacity) {
          notFull.await();
        }
        queue2.enqueue(e);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
          notFull.signal();
      } finally {
        putLock.unlock();
      }
      if (c == 0)
        signalNotEmpty();
    }

    val pool = Executors.newFixedThreadPool(1)

    new Thread(new DAActorThread(), name).start()

    def post(foo: () => Unit) {
      put(foo)

    }

    def getScheduleTask(foo: () => Unit) = {
      val thread = new DAActorScheduleTask(foo)
      new Thread(thread).start()
      thread
    }

    class DAActorThread() extends Runnable {

      override def run {
        while (true) {
          val foo = take()
          foo()
        }
      }
    }

    class DAActorScheduleTask(foo: () => Unit) extends Runnable {
      var scheduled = false

      def schedule() {
        if (!scheduled)
          scheduled = true
      }

      override def run {
        while (true) {
          java.util.concurrent.locks.LockSupport.parkNanos(50000)
          if (scheduled) {
            put(foo)
            scheduled = false
          }

        }

      }

    }

  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of SIRHEN</title>
  <meta name="keywords" content="SIRHEN">
  <meta name="description" content="SIRHEN: Sandia InfraRed HEterodyNe analysis program">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../../m2html.css">

Home >  .. > SMASHtoolbox > programs > SIRHEN > SIRHEN.m

SIRHEN

PURPOSE

SIRHEN: Sandia InfraRed HEterodyNe analysis program

SYNOPSIS

function varargout=SIRHEN(varargin)

DESCRIPTION

 SIRHEN: Sandia InfraRed HEterodyNe analysis program

CROSS-REFERENCE INFORMATION

This function calls:

SIRHEN	SIRHEN: Sandia InfraRed HEterodyNe analysis program

This function is called by:

SIRHEN	SIRHEN: Sandia InfraRed HEterodyNe analysis program

SUBFUNCTIONS

function exitSIRHEN(varargin)

SOURCE CODE

0001 % SIRHEN: Sandia InfraRed HEterodyNe analysis program
0002 function varargout=SIRHEN(varargin)
0003
0004 if isdeployed
0005     varargout{1}=true;
0006 end
0007
0008 % see if program is already running
0009 basetag='SIRHEN';
0010 Nbase=numel(basetag);
0011 openfig=allchild(0);
0012 for ii=1:numel(openfig)
0013     tag=get(openfig(ii),'Tag');
0014     visible=get(openfig(ii),'Visible');
0015     if strncmp(tag,basetag,Nbase) && strcmp(visible,'on');
0016         fprintf('Program is already running!\n');
0017         figure(openfig(ii));
0018         return
0019     end
0020 end
0021
0022 % create figures
0023 hwait=waitbar(0,'Launching SIRHEN...please wait',...
0024     'Name','Launching SIRHEN');
0025 fig=[];
0026 fig(end+1)=SelectionScreen;
0027 waitbar(1/2,hwait);
0028 fig(end+1)=AnalysisScreen;
0029 waitbar(2/2,hwait);
0030 set(fig,'HandleVisibility','callback','CloseRequestFcn',@exitSIRHEN);
0031 set(fig,'Visible','off');
0032 figure(fig(1));
0033
0034 % store admin data
0035 data=get(fig(1),'UserData');
0036 N=numel(fig);
0037 data.handle=cell(1,N);
0038 for n=1:N
0039     data.handle{n}=guihandles(fig(n));
0040 end
0041 data.update.signal=false;
0042 data.update.fullSTFT=false;
0043 data.update.ref_frequency=false;
0044 data.update.experimentSTFT=false;
0045 data.update.history=false;
0046 set(fig,'UserData',data);
0047
0048 % store function handle
0049 old=pwd;
0050 pathname=mfilename('fullpath');
0051 [pathname,filename]=fileparts(pathname);
0052 cd(pathname);
0053 data.fhandle=@SIRHEN;
0054 cd(old);
0055 hmenu=findall(fig,'Type','uimenu','Tag','StartOver');
0056 set(hmenu,'UserData',data);
0057
0058 delete(hwait);
0059 figure(fig(1));
0060
0061 %%%%%%%%%%%%%%%%%
0062 % exit strategy %
0063 %%%%%%%%%%%%%%%%%
0064 function exitSIRHEN(varargin)
0065
0066 button=questdlg('Are you sure you want to exit?','Exit SIRHEN?','No');
0067 if strcmpi(button,'yes')
0068     %setting={};
0069     basetag='SIRHEN_';
0070     Nbase=numel(basetag);
0071     fig=allchild(0);
0072     for ii=1:numel(fig)
0073         tag=get(fig(ii),'Tag');
0074         if strncmp(tag,basetag,Nbase)
0075             delete(fig(ii));
0076         end
0077     end
0078 end

<address>Generated on Tue 10-Nov-2020 17:53:50 by m2html © 2005</address>

redpajama_set_name: RedPajamaGithub


text:
var async = require('async');
var _ = require('underscore');
module.exports = function(app){
	app.logic.outputs.EquipInventoryObject = function(options){
		var default_options = {
			type:'UseInventoryObject'
		}
		_.extend( options, default_options);
		var logic_node_base = new app.OutputNodeBase(options);

		logic_node_base.exe_function(_.bind(function(data, cb){

			//Find your target npc
			var target = data.target;
			if(!target._is_inventory_object){
				//invalid target
				return cb()
			}
			return target.ingest(logic_node_base.npc, data, cb);

		}, logic_node_base));
		return logic_node_base;
	}
}


text:
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Resources.Models;

namespace Azure.ResourceManager.Compute.Models
{
    public partial class LoadBalancerFrontendIPConfiguration : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("name");
            writer.WriteStringValue(Name);
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(PublicIPAddress))
            {
                writer.WritePropertyName("publicIPAddress");
                JsonSerializer.Serialize(writer, PublicIPAddress);
            }
            if (Optional.IsDefined(Subnet))
            {
                writer.WritePropertyName("subnet");
                JsonSerializer.Serialize(writer, Subnet);
            }
            if (Optional.IsDefined(PrivateIPAddress))
            {
                writer.WritePropertyName("privateIPAddress");
                writer.WriteStringValue(PrivateIPAddress);
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static LoadBalancerFrontendIPConfiguration DeserializeLoadBalancerFrontendIPConfiguration(JsonElement element)
        {
            string name = default;
            Optional<WritableSubResource> publicIPAddress = default;
            Optional<WritableSubResource> subnet = default;
            Optional<string> privateIPAddress = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("publicIPAddress"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            publicIPAddress = JsonSerializer.Deserialize<WritableSubResource>(property0.Value.ToString());
                            continue;
                        }
                        if (property0.NameEquals("subnet"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            subnet = JsonSerializer.Deserialize<WritableSubResource>(property0.Value.ToString());
                            continue;
                        }
                        if (property0.NameEquals("privateIPAddress"))
                        {
                            privateIPAddress = property0.Value.GetString();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new LoadBalancerFrontendIPConfiguration(name, publicIPAddress, subnet, privateIPAddress.Value);
        }
    }
}


text:
 Selected Event:

{{SelectedEvent.title}}

{{SelectedEvent.description}}

      add

note_add
Evento

web
Calendario

perm_contact_calendar
Contacto

business
Cliente

          <button type="button" class="close" data-dismiss="modal">×</button>

Cliente

          <form>

              Nombre:
              <input type="text" class="form-control" id="name" name="name">

              Direccion:
              <input type="text" class="form-control" id="address" name="address">

              Web:
              <input type="text" class="form-control" id="web" name="web">

              Email:
              <input type="email" class="form-control" id="email" name="email">

              Phone:
              <input type="text" class="form-control" id="phone" name="phone">

            <input type="submit" name="create-client-submit" id="create-client-submit" tabindex="4" class="form-control btn btn-default" value="Crear">
          </form>

          <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Calendario

          <form>

              Nombre
              <input type="text" class="form-control" id="calendar_name" name="calendar_name">

              Cliente vinculado
                <select class="form-control"  id="calendar_client" name="calendar_client">
                  <?php
                  foreach($clientes as $key => $value):
                    echo '<option value="'. $value["key"] .'">' .$value["nombre"]. '</option>';
                  endforeach;
                  ?>
                </select>

            <input type="submit" name="create-calendar-submit" id="create-calendar-submit" tabindex="4" class="form-control btn btn-default" value="Crear">
          </form>

          <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Evento

          <form>

              Descripción:
              <input type="text" class="form-control" id="desc" name="desc">

              Fecha desde:
              <input type="text" class="form-control" id="fechaDesde" name="fechaDesde">

              Fecha hasta:
              <input type="text" class="form-control" id="fechaHasta" name="fechaHasta">

              Hora desde:
              <input type="email" class="form-control" id="horaDesde" name="horaDesde">

              Hora hasta:
              <input type="text" class="form-control" id="horaHasta" name="horaHasta">

              Calendario
              <input type="text" class="form-control" id="cal" name="cal">

            <input type="submit" name="create-calendar-submit" id="create-calendar-submit" tabindex="4" class="form-control btn btn-default" value="Crear">
          </form>

          <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EaToGliffy.Gliffy.Model
{
    public class GliffyStartConstraint
    {
        public string Type { get; private set; }
        public GliffyConstraint StartPositionConstraint { get; set; }

        public GliffyStartConstraint()
        {
            Type = "StartPositionConstraint";
            StartPositionConstraint = new GliffyConstraint();
        }
    }
}


text:
<!DOCTYPE html>

    <title>Error</title>

An error occurred.

Sorry, the page you are looking for doesn't exists.

If you are the system administrator of this resource then you should check
       the error log for details.

Faithfully yours, nginx.


text:
package com.google.flatbuffers;

/**
 * Interface to represent a read-write buffer. This interface will be used to access and write
 * FlexBuffers message.
 */
public interface ReadWriteBuf extends ReadBuf {

    /**
     * Clears (resets) the buffer so that it can be reused. Write position will be set to the
     * start.
     */
    void clear();

    /**
     * Put a boolean into the buffer at {@code writePosition()} . Booleans as stored as single
     * byte. Write position will be incremented.
     * @return boolean element
     */
    void putBoolean(boolean value);

    /**
     * Put an array of bytes into the buffer at {@code writePosition()}. Write position will be
     * incremented.
     * @param value the data to be copied
     * @param start initial position on value to be copied
     * @param length amount of bytes to be copied
     */
    void put (byte[] value, int start, int length);

    /**
     * Write a byte into the buffer at {@code writePosition()}. Write position will be
     * incremented.
     */
    void put(byte value);

    /**
     * Write a 16-bit into in the buffer at {@code writePosition()}. Write position will be
     * incremented.
     */
    void putShort(short value);

    /**
     * Write a 32-bit into in the buffer at {@code writePosition()}. Write position will be
     * incremented.
     */
    void putInt(int value);

    /**
     * Write a 64-bit into in the buffer at {@code writePosition()}. Write position will be
     * incremented.
     */
    void putLong(long value);

    /**
     * Write a 32-bit float into the buffer at {@code writePosition()}. Write position will be
     * incremented.
     */
    void putFloat(float value);

    /**
     * Write a 64-bit float into the buffer at {@code writePosition()}. Write position will be
     * incremented.
     */
    void putDouble(double value);

    /**
     * Write boolean into a given position on the buffer. Booleans as stored as single byte.
     * @param index position of the element in buffer
     */
    void setBoolean(int index, boolean value);

    /**
     * Read a byte from data.
     * @param index position of the element in the buffer
     * @return a byte
     */
    void set(int index, byte value);

    /**
     * Write an array of bytes into the buffer.
     * @param index initial position of the buffer to be written
     * @param value the data to be copied
     * @param start initial position on value to be copied
     * @param length amount of bytes to be copied
     */
    void set(int index, byte[] value, int start, int length);

    /**
     * Read a short from data.
     * @param index position of the element in ReadBuf
     * @return a short
     */
    void setShort(int index, short value);

    /**
     * Read a 32-bit int from data.
     * @param index position of the element in ReadBuf
     * @return an int
     */
    void setInt(int index, int value);

    /**
     * Read a 64-bit long from data.
     * @param index position of the element in ReadBuf
     * @return a long
     */
    void setLong(int index, long value);

    /**
     * Read a 32-bit float from data.
     * @param index position of the element in ReadBuf
     * @return a float
     */
    void setFloat(int index, float value);

    /**
     * Read a 64-bit float from data.
     * @param index position of the element in ReadBuf
     * @return a double
     */
    void setDouble(int index, double value);

    int writePosition();
    /**
     * Defines the size of the message in the buffer. It also determines last position that buffer
     * can be read or write. Last byte to be accessed is in position {@code limit() -1}.
     * @return indicate last position
     */
    int limit();

    /**
     * Request capacity of the buffer. In case buffer is already larger
     * than the requested, this method will just return true. Otherwise
     * It might try to resize the buffer.
     *
     * @return true if buffer is able to offer
     * the requested capacity
     */
    boolean requestCapacity(int capacity);
}


text:
package org.jboss.arquillian.ajocado.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;

/**
 * Provides URL manipulations and functionality.
 *
 * @author Lukas Fryc
 * @version $Revision$
 */
public final class URLUtils {

    private static final int MD5_BUFFER_SIZE = 8192;
    private static final int HEX_RADIX = 16;

    private URLUtils() {
    }

    /**
     * Use URL context and one or more relocations to build end URL.
     *
     * @param context first URL used like a context root for all relocation changes
     * @param relocations array of relocation URLs
     * @return end url after all changes made on context with relocations
     * @throws AssertionError when context or some of relocations are malformed URLs
     */
    public static URL buildUrl(String context, String... relocations) {
        try {
            return buildUrl(new URL(context), relocations);
        } catch (MalformedURLException e) {
            throw new AssertionError("URL('" + context + "') isn't valid URL");
        }
    }

    /**
     * Use URL context and one or more relocations to build end URL.
     *
     * @param context first URL used like a context root for all relocation changes
     * @param relocations array of relocation URLs
     * @return end url after all changes made on context with relocations
     * @throws AssertionError when context or some of relocations are malformed URLs
     */
    public static URL buildUrl(URL context, String... relocations) {
        URL url = context;

        for (String move : relocations) {
            try {
                url = new URL(url, move);
            } catch (MalformedURLException e) {
                throw new AssertionError("URL('" + url + "', '" + move + "') isn't valid URL");
            }
        }

        return url;
    }

    /**
     * Gets a MD5 digest of some resource obtains as input stream from connection to URL given by URL string.
     *
     * @param url of the resource
     * @return MD5 message digest of resource
     * @throws IOException when connection to URL fails
     */
    public static String resourceMd5Digest(String url) throws IOException {
        URLConnection connection = new URL(url).openConnection();

        InputStream in = connection.getInputStream();
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            throw new IllegalStateException("MD5 hashing is unsupported", ex);
        }
        byte[] buffer = new byte[MD5_BUFFER_SIZE];
        int read = 0;

        while ((read = in.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }

        byte[] md5sum = digest.digest();
        BigInteger bigInt = new BigInteger(1, md5sum);
        return bigInt.toString(HEX_RADIX);
    }

    /**
     * Encodes credentials using Base64 encoding, which can be used to build a header for HTTP Basic authorization
     *
     * @param username User name to be encoded
     * @param password Password to be encoded
     * @return A string {@code username:password} encoded with Base64
     */
    public static String encodeBase64Credentials(String username, String password) {
        String credentials = username + ":" + password;
        try {
            String defaultCharsetName = Charset.defaultCharset().displayName();
            byte[] credentialsAsBytes = credentials.getBytes(defaultCharsetName);
            byte[] encodedCredentials = Base64.encodeBase64(credentialsAsBytes);
            return new String(encodedCredentials, defaultCharsetName);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }
}


text:
module Azure::DataFactory::Mgmt::V2017_09_01_preview
  module Models
    #
    # A copy activity Document Database Collection source.
    #
    class DocumentDbCollectionSource < CopySource

      include MsRestAzure

      def initialize
        @type = "DocumentDbCollectionSource"
      end

      attr_accessor :type

      # @return Documents query. Type: string (or Expression with resultType
      # string).
      attr_accessor :query

      # @return Nested properties separator. Type: string (or Expression with
      # resultType string).
      attr_accessor :nesting_separator

      #
      # Mapper for DocumentDbCollectionSource class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'DocumentDbCollectionSource',
          type: {
            name: 'Composite',
            class_name: 'DocumentDbCollectionSource',
            model_properties: {
              additional_properties: {
                client_side_validation: true,
                required: false,
                type: {
                  name: 'Dictionary',
                  value: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ObjectElementType',
                      type: {
                        name: 'Object'
                      }
                  }
                }
              },
              source_retry_count: {
                client_side_validation: true,
                required: false,
                serialized_name: 'sourceRetryCount',
                type: {
                  name: 'Object'
                }
              },
              source_retry_wait: {
                client_side_validation: true,
                required: false,
                serialized_name: 'sourceRetryWait',
                type: {
                  name: 'Object'
                }
              },
              type: {
                client_side_validation: true,
                required: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              query: {
                client_side_validation: true,
                required: false,
                serialized_name: 'query',
                type: {
                  name: 'Object'
                }
              },
              nesting_separator: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nestingSeparator',
                type: {
                  name: 'Object'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>zstack</artifactId>
        <groupId>org.zstack</groupId>
        <version>1.10.0</version>
        <relativePath>..</relativePath>
    </parent>
    <artifactId>plugin</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>nfsPrimaryStorage</module>
        <module>kvm</module>
        <module>sftpBackupStorage</module>
        <module>virtualRouterProvider</module>
        <module>securityGroup</module>
        <module>portForwarding</module>
        <module>applianceVm</module>
        <module>vip</module>
        <module>eip</module>
        <module>mediator</module>
        <module>localstorage</module>
        <module>ceph</module>
        <module>fusionstor</module>
        <module>loadBalancer</module>
        <module>flatNetworkProvider</module>
        <module>sharedMountPointPrimaryStorage</module>
        <module>ldap</module>
        <module>vxlan</module>
    </modules>
    <dependencies>
        <dependency>
            <groupId>org.zstack</groupId>
            <artifactId>header</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.zstack</groupId>
            <artifactId>core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.zstack</groupId>
            <artifactId>core-groovy</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.zstack</groupId>
            <artifactId>utils</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.zstack</groupId>
            <artifactId>search</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.zstack</groupId>
            <artifactId>identity</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.zstack</groupId>
            <artifactId>tag</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>       <!-- use this goal to weave all your main classes -->
                            <goal>test-compile</goal>  <!-- use this goal to weave all your test classes -->
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <source>${project.java.version}</source>
                    <target>${project.java.version}</target>
                    <complianceLevel>${project.java.version}</complianceLevel>
                    <XnoInline>true</XnoInline>
                    <aspectLibraries>
                        <aspectLibrary>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-aspects</artifactId>
                        </aspectLibrary>
                        <aspectLibrary>
                            <groupId>org.zstack</groupId>
                            <artifactId>core</artifactId>
                        </aspectLibrary>
                        <aspectLibrary>
                            <groupId>org.zstack</groupId>
                            <artifactId>header</artifactId>
                        </aspectLibrary>
                    </aspectLibraries>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
package com.sequenceiq.cloudbreak.core.flow2.cluster.datalake.upgrade.validation.event;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sequenceiq.cloudbreak.cloud.context.CloudContext;
import com.sequenceiq.cloudbreak.cloud.model.CloudCredential;
import com.sequenceiq.cloudbreak.cloud.model.CloudStack;
import com.sequenceiq.cloudbreak.reactor.api.event.StackEvent;

public class ClusterUpgradeUpdateCheckFinishedEvent extends StackEvent {

    private final CloudCredential cloudCredential;

    private final CloudStack cloudStack;

    private final CloudContext cloudContext;

    @JsonCreator
    public ClusterUpgradeUpdateCheckFinishedEvent(
            @JsonProperty("resourceId") Long stackId,
            @JsonProperty("cloudStack") CloudStack cloudStack,
            @JsonProperty("cloudCredential") CloudCredential cloudCredential,
            @JsonProperty("cloudContext") CloudContext cloudContext) {
        super(ClusterUpgradeValidationStateSelectors.FINISH_CLUSTER_UPGRADE_CLOUDPROVIDER_UPDATECHECK_EVENT.name(), stackId);
        this.cloudStack = cloudStack;
        this.cloudCredential = cloudCredential;
        this.cloudContext = cloudContext;
    }

    public CloudCredential getCloudCredential() {
        return cloudCredential;
    }

    public CloudStack getCloudStack() {
        return cloudStack;
    }

    public CloudContext getCloudContext() {
        return cloudContext;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<order xmlns="urn:switchyard-quickstart-demo:multiapp:1.0">
    <orderId>PO-19838-XYZ</orderId>
    <itemId>BUTTER</itemId>
    <quantity>200</quantity>
</order>


text:
"""
Utility functions for handling DoubleClick for Publishers (DFP) API.

For more information about DFP API, please refer to https://developers.google.com/doubleclick-publishers/.

Requires Google Ads APIs Python Client Libraries - https://github.com/googleads/googleads-python-legacy-lib.
"""

import os
import sys
import time
import datetime
import tempfile
import gzip

import googleads.dfp
import googleads.errors

DFP_VERSION = 'v201505'

CLIENT = googleads.dfp.DfpClient.LoadFromStorage()

def create_report_service_job(days_ago=2, country=None):
  """
  Create a job for a DFP report service to fetch creative ids.

  :param days_ago: a number that represents days the creatives are served.
  :param country: a comma-delimited country names. If this option is set, the creative only served in
    this countries are downloaded.
  :return: a job for DFP report service.
  """
  days = datetime.date.today() - datetime.timedelta(days=days_ago)
  date_obj = {
    'year': str(days.year),
    'month': str(days.month),
    'day': str(days.day)
  }
  report_job = {
    'reportQuery': {
      'dimensions': ['CREATIVE_ID'],
      'statement': '',
      'columns': ['AD_SERVER_IMPRESSIONS'],
      'dateRangeType': 'CUSTOM_DATE',
      'startDate': date_obj,
      'endDate': date_obj
    }
  }

  if country:
    countries = country.split(',')
    report_job['reportQuery']['statement'] = {'query': 'WHERE COUNTRY_NAME IN (\'%s\')' % '\',\''.join(countries)}

  return report_job

def run_report_service_job(report_job):
  """
  Run the report job and return a list of creative ids.

  :param report_job: a report job.
  :return: a list of creative ids.
  """
  data_downloader = CLIENT.GetDataDownloader(version=DFP_VERSION)
  try:
    report_job_id = data_downloader.WaitForReport(report_job)
  except googleads.errors.DfpReportError, e:
    print 'Failed to generate report. [Error] %s' % e
    raise e
  report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
  data_downloader.DownloadReportToFile(report_job_id, 'CSV_DUMP', report_file)
  report_file.close()

  report = gzip.open(report_file.name)
  ids = [r.split(',')[0] for r in report]
  report.close()

  os.remove(report_file.name)
  # Ignore the first line, which contains this line "Dimension.CREATIVE_ID,Column.AD_SERVER_IMPRESSIONS"
  return ids[1:]

def create_creative_service_statement(creative_ids, offset=0, only_new=True, days_ago=2):
  """
  Download creatives from DFP.

  :param creative_ids: a list of creative ids.
  :param offset: the offset for the list to start download from.
  :param only_new: a boolean that indicates whether downloading only recently updated creatives or not.
  :param days_ago: a number that represents days the creatives are served.
  :return: a list of creatives.
  """
  values = []
  date_setting = ''

  if only_new:
    date_setting = 'lastModifiedDateTime > :date AND'
    days = datetime.date.today() - datetime.timedelta(days=days_ago)
    values.append({
      'key': 'date',
      'value': {
        'xsi_type': 'TextValue',
        'value': days.strftime('%Y-%m-%dT%H:%M:%S')
      }
    })
    print 'Only recently updated creatives will be downloaded.'
  else:
    print 'At most, %d creatives will be downloaded.' % len(creative_ids)

  id_str = ','.join(str(i) for i in creative_ids)

  statements = []
  for offset in range(offset, len(creative_ids), googleads.dfp.SUGGESTED_PAGE_LIMIT):
    statements.append({
      'query': 'WHERE %s id IN (%s) LIMIT %d OFFSET %d' % (date_setting, id_str, googleads.dfp.SUGGESTED_PAGE_LIMIT, offset),
      'values': values
    })
  return statements

def run_creative_service_statements(statements):
  """
  Download creatives from DFP.

  :param statements: a list of CreativeService statements to download creatives.
  :return: a list of creatives.
  """
  print '%d statements will be executed on DFP Creative Service' % len(statements)

  creative_service = CLIENT.GetService('CreativeService', version=DFP_VERSION)

  creatives = []
  for stmt in statements:
    response = creative_service.getCreativesByStatement(stmt)
    results = response['results'] if 'results' in response else []

    print 'Fetched data size: %d.' % len(results)

    if len(results) > 0:
      creatives.extend(results)
    else:
      break
  return creatives

def upload_creatives(dfp_creatives):
  """
  Upload the creatives to DFP.

  :param dfp_creatives: a list of DFP creatives.
  :return: a list of updated creatives.
  """
  creative_service = CLIENT.GetService('CreativeService', version=DFP_VERSION)
  return creative_service.updateCreatives(dfp_creatives)


text:
typedef void (^MDCaptureManagerCaptureBlock)(ALAsset *asset, NSError *error);

@protocol MDCaptureManagerDelegate;

@interface MDCaptureManager : NSObject

@property (nonatomic, copy) void (^captureCallback)(ALAsset *asset, NSError *error);
@property (strong, nonatomic) AVCaptureSession *session;
@property (strong, nonatomic) AVCaptureStillImageOutput *stillImageOutput;
@property (strong, nonatomic) AVCaptureDeviceInput *videoInput;
@property (assign, nonatomic) AVCaptureVideoOrientation orientation;
@property AVCaptureDevicePosition devicePosition;
@property AVCaptureFlashMode flashMode;

@property (assign) id <MDCaptureManagerDelegate> delegate;

- (void)createCaptureSession:(AVCaptureDevicePosition)position;
- (void)captureStillImage;
- (void)changeFlashMode:(AVCaptureFlashMode)mode;
- (void)closeCaptureSession;
@end

@protocol MDCaptureManagerDelegate <NSObject>
@optional
- (void) captureManager:(MDCaptureManager *)captureManager didFailWithError:(NSError *)error;
- (void) captureManagerStillImageCaptured:(UIImage *)image;
- (void) captureManagerDeviceConfigurationChanged:(MDCaptureManager *)captureManager;

@end


text:
package com.vladsch.flexmark.ext.aside.internal;

import com.vladsch.flexmark.ast.ListItem;
import com.vladsch.flexmark.ast.util.Parsing;
import com.vladsch.flexmark.ext.aside.AsideBlock;
import com.vladsch.flexmark.ext.aside.AsideExtension;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.parser.block.*;
import com.vladsch.flexmark.parser.core.*;
import com.vladsch.flexmark.util.ast.Block;
import com.vladsch.flexmark.util.data.DataHolder;
import com.vladsch.flexmark.util.misc.CharPredicate;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import com.vladsch.flexmark.util.sequence.mappers.SpecialLeadInHandler;
import com.vladsch.flexmark.util.sequence.mappers.SpecialLeadInStartsWithCharsHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class AsideBlockParser extends AbstractBlockParser {

    final public static char MARKER_CHAR = '|';
    final private AsideBlock block = new AsideBlock();
    final private boolean allowLeadingSpace;
    final private boolean continueToBlankLine;
    final private boolean ignoreBlankLine;
    final private boolean interruptsParagraph;
    final private boolean interruptsItemParagraph;
    final private boolean withLeadSpacesInterruptsItemParagraph;
    private int lastWasBlankLine = 0;

    public AsideBlockParser(DataHolder options, BasedSequence marker) {
        block.setOpeningMarker(marker);
        continueToBlankLine = AsideExtension.EXTEND_TO_BLANK_LINE.get(options);
        allowLeadingSpace = AsideExtension.ALLOW_LEADING_SPACE.get(options);
        ignoreBlankLine = AsideExtension.IGNORE_BLANK_LINE.get(options);
        interruptsParagraph = AsideExtension.INTERRUPTS_PARAGRAPH.get(options);
        interruptsItemParagraph = AsideExtension.INTERRUPTS_ITEM_PARAGRAPH.get(options);
        withLeadSpacesInterruptsItemParagraph = AsideExtension.WITH_LEAD_SPACES_INTERRUPTS_ITEM_PARAGRAPH.get(options);
    }

    @Override
    public boolean isContainer() {
        return true;
    }

    @Override
    public boolean isPropagatingLastBlankLine(BlockParser lastMatchedBlockParser) {
        return false;
    }

    @Override
    public boolean canContain(ParserState state, BlockParser blockParser, Block block) {
        return true;
    }

    @Override
    public AsideBlock getBlock() {
        return block;
    }

    @Override
    public void closeBlock(ParserState state) {
        block.setCharsFromContent();

        if (!Parser.BLANK_LINES_IN_AST.get(state.getProperties())) {
            removeBlankLines();
        }
    }

    @Override
    public BlockContinue tryContinue(ParserState state) {
        int nextNonSpace = state.getNextNonSpaceIndex();
        boolean isMarker;
        if (!state.isBlank() && ((isMarker = isMarker(state, nextNonSpace, false, false, allowLeadingSpace, interruptsParagraph, interruptsItemParagraph, withLeadSpacesInterruptsItemParagraph)) || (continueToBlankLine && lastWasBlankLine == 0))) {
            int newColumn = state.getColumn() + state.getIndent();
            lastWasBlankLine = 0;

            if (isMarker) {
                newColumn++;
                // optional following space or tab
                if (Parsing.isSpaceOrTab(state.getLine(), nextNonSpace + 1)) {
                    newColumn++;
                }
            }
            return BlockContinue.atColumn(newColumn);
        } else {
            if (ignoreBlankLine && state.isBlank()) {
                lastWasBlankLine++;
                int newColumn = state.getColumn() + state.getIndent();
                return BlockContinue.atColumn(newColumn);
            }
            return BlockContinue.none();
        }
    }

    static boolean isMarker(
            final ParserState state,
            final int index,
            final boolean inParagraph,
            final boolean inParagraphListItem,
            final boolean allowLeadingSpace,
            final boolean interruptsParagraph,
            final boolean interruptsItemParagraph,
            final boolean withLeadSpacesInterruptsItemParagraph
    ) {
        CharSequence line = state.getLine();
        if ((!inParagraph || interruptsParagraph) && index < line.length() && line.charAt(index) == MARKER_CHAR) {
            if ((allowLeadingSpace || state.getIndent() == 0) && (!inParagraphListItem || interruptsItemParagraph)) {
                if (inParagraphListItem && !withLeadSpacesInterruptsItemParagraph) {
                    return state.getIndent() == 0;
                } else {
                    return state.getIndent() < state.getParsing().CODE_BLOCK_INDENT;
                }
            }
        }
        return false;
    }

    static boolean endsWithMarker(BasedSequence line) {
        int tailBlanks = line.countTrailing(CharPredicate.WHITESPACE_NBSP);
        return tailBlanks + 1 < line.length() && line.charAt(line.length() - tailBlanks - 1) == MARKER_CHAR;
    }

    public static class Factory implements CustomBlockParserFactory {
        @Nullable
        @SuppressWarnings("UnnecessaryLocalVariable")
        @Override
        public Set<Class<?>> getAfterDependents() {
            HashSet<Class<?>> set = new HashSet<>();
            //set.add(BlockQuoteParser.Factory.class);
            return set;
        }

        @Nullable
        @Override
        public Set<Class<?>> getBeforeDependents() {
            return new HashSet<>(Arrays.asList(
                    //BlockQuoteParser.Factory.class,
                    HeadingParser.Factory.class,
                    FencedCodeBlockParser.Factory.class,
                    HtmlBlockParser.Factory.class,
                    ThematicBreakParser.Factory.class,
                    ListBlockParser.Factory.class,
                    IndentedCodeBlockParser.Factory.class
            ));
        }

        @Override
        public @Nullable SpecialLeadInHandler getLeadInHandler(@NotNull DataHolder options) {
            return AsideLeadInHandler.HANDLER;
        }

        @Override
        public boolean affectsGlobalScope() {
            return false;
        }

        @NotNull
        @Override
        public BlockParserFactory apply(@NotNull DataHolder options) {
            return new BlockFactory(options);
        }
    }

    static class AsideLeadInHandler {
        final static SpecialLeadInHandler HANDLER = SpecialLeadInStartsWithCharsHandler.create('|');
    }

    private static class BlockFactory extends AbstractBlockParserFactory {
        final private boolean allowLeadingSpace;
        final private boolean interruptsParagraph;
        final private boolean interruptsItemParagraph;
        final private boolean withLeadSpacesInterruptsItemParagraph;

        BlockFactory(DataHolder options) {
            super(options);
            allowLeadingSpace = AsideExtension.ALLOW_LEADING_SPACE.get(options);
            interruptsParagraph = AsideExtension.INTERRUPTS_PARAGRAPH.get(options);
            interruptsItemParagraph = AsideExtension.INTERRUPTS_ITEM_PARAGRAPH.get(options);
            withLeadSpacesInterruptsItemParagraph = AsideExtension.WITH_LEAD_SPACES_INTERRUPTS_ITEM_PARAGRAPH.get(options);
        }

        public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {
            int nextNonSpace = state.getNextNonSpaceIndex();
            BlockParser matched = matchedBlockParser.getBlockParser();
            boolean inParagraph = matched.isParagraphParser();
            boolean inParagraphListItem = inParagraph && matched.getBlock().getParent() instanceof ListItem && matched.getBlock() == matched.getBlock().getParent().getFirstChild();

            if (!endsWithMarker(state.getLine()) && isMarker(state, nextNonSpace, inParagraph, inParagraphListItem, allowLeadingSpace, interruptsParagraph, interruptsItemParagraph, withLeadSpacesInterruptsItemParagraph)) {
                int newColumn = state.getColumn() + state.getIndent() + 1;
                // optional following space or tab
                if (Parsing.isSpaceOrTab(state.getLine(), nextNonSpace + 1)) {
                    newColumn++;
                }
                return BlockStart.of(new AsideBlockParser(state.getProperties(), state.getLine().subSequence(nextNonSpace, nextNonSpace + 1))).atColumn(newColumn);
            } else {
                return BlockStart.none();
            }
        }
    }
}


text:
/**
 * The google authenticator.
 */
package net.krotscheck.kangaroo.authz.common.authenticator.google;


text:
package aima.core.probability.proposition;

import java.util.Map;

import aima.core.probability.RandomVariable;

public class ConjunctiveProposition extends AbstractProposition implements
		BinarySentenceProposition {

	private Proposition left = null;
	private Proposition right = null;
	//
	private String toString = null;

	public ConjunctiveProposition(Proposition left, Proposition right) {
		if (null == left) {
			throw new IllegalArgumentException(
					"Left side of conjunction must be specified.");
		}
		if (null == right) {
			throw new IllegalArgumentException(
					"Right side of conjunction must be specified.");
		}
		// Track nested scope
		addScope(left.getScope());
		addScope(right.getScope());
		addUnboundScope(left.getUnboundScope());
		addUnboundScope(right.getUnboundScope());

		this.left = left;
		this.right = right;
	}

	@Override
	public boolean holds(Map<RandomVariable, Object> possibleWorld) {
		return left.holds(possibleWorld) && right.holds(possibleWorld);
	}

	@Override
	public String toString() {
		if (null == toString) {
			StringBuilder sb = new StringBuilder();
			sb.append("(");
			sb.append(left.toString());
			sb.append(" AND ");
			sb.append(right.toString());
			sb.append(")");

			toString = sb.toString();
		}

		return toString;
	}
}


text:
<?php
/**
 * A button that allows a user to view readonly details of a record. This is
 * disabled by default and intended for use in readonly grid fields.
 *
 * @package framework
 */
class GridFieldViewButton implements GridField_ColumnProvider {

	public function augmentColumns($field, &$cols) {
		if(!in_array('Actions', $cols)) $cols[] = 'Actions';
	}

	public function getColumnsHandled($field) {
		return array('Actions');
	}

	public function getColumnContent($field, $record, $col) {
		if($record->canView()) {
			$data = new ArrayData(array(
				'Link' => Controller::join_links($field->Link('item'), $record->ID, 'view')
			));
			return $data->renderWith('GridFieldViewButton');
		}
	}

	public function getColumnAttributes($field, $record, $col) {
		return array('class' => 'col-buttons');
	}

	public function getColumnMetadata($gridField, $col) {
		return array('title' => null);
	}

}


text:
"use strict";
var config = require("config"),
    fs = require("fs"),
    path = require("path"),
    seeder = require("./seed"),
    startupHooks = require("../startup_hooks");

let mongoose = require("./mongoose");
let debug = require("debug")("app:persistence");
let models = {};

/**
 * Dynamically load model types
 */
function getModels() {
    let modelNames = fs.readdirSync(path.join(__dirname, "models")),
        loadModel = (modelName) => {
            debug(`loading model ${modelName}`);
            let modelFunction = require(`./models/${modelName}`);
            debug(`preparing model ${modelName}`);
            models[modelName] = modelFunction(mongoose);
        };

    modelNames.forEach(loadModel);
}

/**
 * Populate seed data
 * @returns {*}
 */
function populateSeed() {
    if (config.database.populateSeedData) {
        debug("loading seed data");
        let seedingPromise = seeder.seedData(models);
        startupHooks.addHook(seedingPromise);
    }
}

debug("Initializing Persistence");
getModels();
populateSeed();

module.exports = {models};


text:
@interface TMYSuburbItem : XTYModelItem

@property (nonatomic, assign) NSInteger SuburbId;
@property (nonatomic, strong) NSString *Name;
@property (nonatomic, assign) NSInteger Count;

@end

@interface TMYDistrictItem : XTYModelItem

@property (nonatomic, assign) NSInteger DistrictId;
@property (nonatomic, strong) NSString *Name;
@property (nonatomic, strong) NSArray<TMYSuburbItem *> *Suburbs;
@property (nonatomic, assign) NSInteger Count;

@end

@interface TMYLocalityItem : XTYModelItem

@property (nonatomic, assign) NSInteger LocalityId;
@property (nonatomic, strong) NSString *Name;
@property (nonatomic, strong) NSArray<TMYDistrictItem *> *Districts;
@property (nonatomic, assign) NSInteger Count;

@end


text:
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Test {
  public void test(double[] array) {
    IntStream.<caret>range(1, 5).mapToDouble(x -> array[x]).collect(Collectors.toList());
  }
}


text:
from django.utils.translation import ugettext_lazy as _

from horizon_lib import exceptions
from horizon_lib import tabs

from openstack_horizon.api import nova
from openstack_horizon.dashboards.admin.hypervisors.compute import tables

class ComputeHostTab(tabs.TableTab):
    table_classes = (tables.ComputeHostTable,)
    name = _("Compute Host")
    slug = "compute_host"
    template_name = "horizon_lib/common/_detail_table.html"

    def get_compute_host_data(self):
        try:
            services = nova.service_list(self.tab_group.request)
            return [service for service in services
                    if service.binary == 'nova-compute']
        except Exception:
            msg = _('Unable to get nova services list.')
            exceptions.handle(self.tab_group.request, msg)


text:
package com.alibaba.aliper.core.conf;

public class AgentConfig {

}


text:
return function(block)
    local genomes_set = {}
    for fragment in block:iterFragments() do
        local genome = assert(fragment:sequence():genome(),
                "Can't get genome of " .. fragment:id())
        if not genomes_set[genome] then
            genomes_set[genome] = true
        end
    end
    local genomes = {}
    for genome, _ in pairs(genomes_set) do
        table.insert(genomes, genome)
    end
    return genomes
end


text:
@interface DateSelectViewController : UITableViewController
@property (nonatomic, strong, readonly) NSDate *fromDate;
@property (nonatomic, strong, readonly) NSDate *toDate;
@end


text:
<TITLE>Review for Face/Off (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Face/Off (1997)

reviewed by
Michael Legeros

Face/Off (1997)

A movie review by Michael J. Legeros
Copyright 1997 by Michael J. Legeros

(Paramount)
Directed by     John Woo
Written by      Mike Werb and Michael Colleary
Cast            John Travolta, Nicolas Cage, Joan Allen, Gina Gershon,
                Alessandro Nivola, Dominique Swain, Nick Cassavetes,
                Harve Presnell, Colm Feore, Margaret Cho
MPAA Rating     "R" (presumably for violence and language)
Running Time    140 minutes
Reviewed at     Carmike 7 Cinemas, Raleigh, NC (27JUN97)

==

     Dis/appointing.  The talkiest thrill-ride of the summer stars John
Travolta and Nicholas Cage, as two guys who swap faces.  Literally.
Cage plays a terrorist and Travolta plays a terrorist tracker and each
ends up with the other's face, and identity, through a series of events
that writers Mike Werb and Michael Colleary, along with director John
Woo (BROKEN ARROW, HARD TARGET), take great pains to make believable.
They explain the entire medical process and how the facial skin is re-
moved and what's done about scars, hair lines, and body fat.  Surpris-
ingly, this premise-- set in the near-future, if that helps-- is one of
the more *plausible* components of the movie.  It's so utterly over-the-
top that it blends perfectly with the accompanying action, Action a la
Woo, a gracefully choreographed carnival of all things flinging, flying,
shooting, and exploding.  What's much more *difficult* to believe are
the smaller, subsequent story details, ranging from the circumstances
surrounding a character's heart attack to a wife who fails to notice a
scar that her husband no longer has.  (Not to mention other physical
differences that are never, ah, expanded upon!)

     Those only familiar with the John Woo of BROKEN ARROW are in for a
treat, as the world-renowned director is almost back to his old self.  I
say, I say, *almost*.  He's returned to the world of Grand Guignol, but
without enough lighting!  Three, maybe, four sequences are damn diffi-
cult to follow, shot for shot.  (From what I recall of his more-recent
HARD TARGET and HARD BOILED, the photography was much...  cleaner.)
Worse, there isn't *enough* action to keep these pulpy characters in-
teresting.  (At least an hour passes without any gun battles, which is a
l-o-n-g time to spend with Cage's good guy, all stooped shoulders and
stupored stares.) That said, there's still enough here to satisfy most
moviegoers.  The surgery sequence is an armrest gripper.  The body count
is refreshingly high.  Travolta is wicked fun playing Cage's character
playing Travolta's.  Olivia Newton-John sings "Over the Rainbow."  And
two late sequences-- a Mexican standoff in a church (complete with flut-
tering white doves) and a high-speed powerboat chase (is there any other
kind?)-- bring everything home.  For those fast, furious, fleeting
moments, it's why we go to the movies.  (Rated "R"/140 min.)

     Grade: B

--
Mike Legeros - Movie Hell
http://www.nonvirtual.com/hell/

--
Mike Legeros
Corporate Training
SAS Institute Inc, Cary, NC, USA, Earth
mailto: legeros@unx.sas.com (w) legeros@pagesz.net (h)
"Fortissimo at last!" - Gustav Mahler, on seeing Niagara Falls

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
import json

import requests

from .exceptions import TelegraphException, RetryAfterError
from .utils import html_to_nodes, nodes_to_html, FilesOpener, json_dumps

class TelegraphApi:
    """ Telegraph API Client

    :param access_token: access_token
    :type access_token: str

    :param domain: domain (e.g. alternative mirror graph.org)
    """

    __slots__ = ('access_token', 'domain', 'session')

    def __init__(self, access_token=None, domain='telegra.ph'):
        self.access_token = access_token
        self.domain = domain
        self.session = requests.Session()

    def method(self, method, values=None, path=''):
        values = values.copy() if values is not None else {}

        if 'access_token' not in values and self.access_token:
            values['access_token'] = self.access_token

        response = self.session.post(
            'https://api.{}/{}/{}'.format(self.domain, method, path),
            data=values
        ).json()

        if response.get('ok'):
            return response['result']

        error = response.get('error')
        if isinstance(error, str) and error.startswith('FLOOD_WAIT_'):
            retry_after = int(error.rsplit('_', 1)[-1])
            raise RetryAfterError(retry_after)
        else:
            raise TelegraphException(error)

    def upload_file(self, f):
        """ Upload file. NOT PART OF OFFICIAL API, USE AT YOUR OWN RISK
            Returns a list of dicts with `src` key.
            Allowed only .jpg, .jpeg, .png, .gif and .mp4 files.

        :param f: filename or file-like object.
        :type f: file, str or list
        """
        with FilesOpener(f) as files:
            response = self.session.post(
                'https://{}/upload'.format(self.domain),
                files=files
            ).json()

        if isinstance(response, list):
            error = response[0].get('error')
        else:
            error = response.get('error')

        if error:
            if isinstance(error, str) and error.startswith('FLOOD_WAIT_'):
                retry_after = int(error.rsplit('_',1)[-1])
                raise RetryAfterError(retry_after)
            else:
                raise TelegraphException(error)

        return response

class Telegraph:
    """ Telegraph API client helper

    :param access_token: access token
    :param domain: domain (e.g. alternative mirror graph.org)
    """

    __slots__ = ('_telegraph',)

    def __init__(self, access_token=None, domain='telegra.ph'):
        self._telegraph = TelegraphApi(access_token, domain)

    def get_access_token(self):
        """Get current access_token"""
        return self._telegraph.access_token

    def create_account(self, short_name, author_name=None, author_url=None,
                       replace_token=True):
        """ Create a new Telegraph account

        :param short_name: Account name, helps users with several
                           accounts remember which they are currently using.
                           Displayed to the user above the "Edit/Publish"
                           button on Telegra.ph, other users don't see this name
        :param author_name: Default author name used when creating new articles
        :param author_url: Default profile link, opened when users click on the
                           author's name below the title. Can be any link,
                           not necessarily to a Telegram profile or channels
        :param replace_token: Replaces current token to a new user's token
        """
        response = self._telegraph.method('createAccount', values={
            'short_name': short_name,
            'author_name': author_name,
            'author_url': author_url
        })

        if replace_token:
            self._telegraph.access_token = response.get('access_token')

        return response

    def edit_account_info(self, short_name=None, author_name=None,
                          author_url=None):
        """ Update information about a Telegraph account.
            Pass only the parameters that you want to edit

        :param short_name: Account name, helps users with several
                           accounts remember which they are currently using.
                           Displayed to the user above the "Edit/Publish"
                           button on Telegra.ph, other users don't see this name
        :param author_name: Default author name used when creating new articles
        :param author_url: Default profile link, opened when users click on the
                           author's name below the title. Can be any link,
                           not necessarily to a Telegram profile or channels
        """
        return self._telegraph.method('editAccountInfo', values={
            'short_name': short_name,
            'author_name': author_name,
            'author_url': author_url
        })

    def revoke_access_token(self):
        """ Revoke access_token and generate a new one, for example,
            if the user would like to reset all connected sessions, or
            you have reasons to believe the token was compromised.
            On success, returns dict with new access_token and auth_url fields
        """
        response = self._telegraph.method('revokeAccessToken')

        self._telegraph.access_token = response.get('access_token')

        return response

    def get_page(self, path, return_content=True, return_html=True):
        """ Get a Telegraph page

        :param path: Path to the Telegraph page (in the format Title-12-31,
                     i.e. everything that comes after https://telegra.ph/)
        :param return_content: If true, content field will be returned
        :param return_html: If true, returns HTML instead of Nodes list
        """
        response = self._telegraph.method('getPage', path=path, values={
            'return_content': return_content
        })

        if return_content and return_html:
            response['content'] = nodes_to_html(response['content'])

        return response

    def create_page(self, title, content=None, html_content=None,
                    author_name=None, author_url=None, return_content=False):
        """ Create a new Telegraph page

        :param title: Page title
        :param content: Content in nodes list format (see doc)
        :param html_content: Content in HTML format
        :param author_name: Author name, displayed below the article's title
        :param author_url: Profile link, opened when users click on
                           the author's name below the title
        :param return_content: If true, a content field will be returned
        """
        if content is None:
            content = html_to_nodes(html_content)

        content_json = json_dumps(content)

        return self._telegraph.method('createPage', values={
            'title': title,
            'author_name': author_name,
            'author_url': author_url,
            'content': content_json,
            'return_content': return_content
        })

    def edit_page(self, path, title, content=None, html_content=None,
                  author_name=None, author_url=None, return_content=False):
        """ Edit an existing Telegraph page

        :param path: Path to the page
        :param title: Page title
        :param content: Content in nodes list format (see doc)
        :param html_content: Content in HTML format
        :param author_name: Author name, displayed below the article's title
        :param author_url: Profile link, opened when users click on
                           the author's name below the title
        :param return_content: If true, a content field will be returned
        """
        if content is None:
            content = html_to_nodes(html_content)

        content_json = json_dumps(content)

        return self._telegraph.method('editPage', path=path, values={
            'title': title,
            'author_name': author_name,
            'author_url': author_url,
            'content': content_json,
            'return_content': return_content
        })

    def get_account_info(self, fields=None):
        """ Get information about a Telegraph account

        :param fields: List of account fields to return. Available fields:
                       short_name, author_name, author_url, auth_url, page_count

                       Default: ["short_name","author_name","author_url"]
        """
        return self._telegraph.method('getAccountInfo', {
            'fields': json_dumps(fields) if fields else None
        })

    def get_page_list(self, offset=0, limit=50):
        """ Get a list of pages belonging to a Telegraph account
            sorted by most recently created pages first

        :param offset: Sequential number of the first page to be returned
                       (default = 0)
        :param limit: Limits the number of pages to be retrieved
                      (0-200, default = 50)
        """
        return self._telegraph.method('getPageList', {
            'offset': offset,
            'limit': limit
        })

    def get_views(self, path, year=None, month=None, day=None, hour=None):
        """ Get the number of views for a Telegraph article

        :param path: Path to the Telegraph page
        :param year: Required if month is passed. If passed, the number of
                     page views for the requested year will be returned
        :param month: Required if day is passed. If passed, the number of
                      page views for the requested month will be returned
        :param day: Required if hour is passed. If passed, the number of
                    page views for the requested day will be returned
        :param hour: If passed, the number of page views for
                     the requested hour will be returned
        """
        return self._telegraph.method('getViews', path=path, values={
            'year': year,
            'month': month,
            'day': day,
            'hour': hour
        })

    def upload_file(self, f):
        """ Upload file. NOT PART OF OFFICIAL API, USE AT YOUR OWN RISK
            Returns a list of dicts with `src` key.
            Allowed only .jpg, .jpeg, .png, .gif and .mp4 files.

        :param f: filename or file-like object.
        :type f: file, str or list
        """
        return self._telegraph.upload_file(f)


text:
#include "VariableDeclaration.h"

#include "ModelBase/src/nodes/TypedList.hpp"
template class Model::TypedList<OOModel::VariableDeclaration>;

namespace OOModel {

DEFINE_COMPOSITE_EMPTY_CONSTRUCTORS(VariableDeclaration)
DEFINE_COMPOSITE_TYPE_REGISTRATION_METHODS(VariableDeclaration)

DEFINE_ATTRIBUTE(VariableDeclaration, typeExpression, Expression, false, false, true)
DEFINE_ATTRIBUTE(VariableDeclaration, initialValue, Expression, true, true, true)
DEFINE_ATTRIBUTE(VariableDeclaration, initKind, Integer, false, false, true)

VariableDeclaration::VariableDeclaration(const QString& name, Expression* type)
: Super{nullptr, VariableDeclaration::getMetaData()}
{
	setName(name);
	if (type) setTypeExpression(type);
}

VariableDeclaration::VariableDeclaration(const QString& name, Expression* type, Expression* initialValue)
: Super{nullptr, VariableDeclaration::getMetaData()}
{
	setName(name);
	if (type) setTypeExpression(type);
	if (initialValue) setInitialValue(initialValue);
}

VariableDeclaration::VariableDeclaration(const QString& name, Expression* type, Modifier::Modifiers mod,
		Expression* initialValue)
: Super{nullptr, VariableDeclaration::getMetaData()}
{
	setName(name);
	if (type) setTypeExpression(type);
	modifiers()->set(mod);
	if (initialValue) setInitialValue(initialValue);
}

VariableDeclaration::SymbolTypes VariableDeclaration::symbolType() const
{
	return VARIABLE;
}

}


text:
using System;
/*Problem 13. Binary to Decimal Number
--------------------------------------------------------------------------------------
Using loops write a program that converts a binary integer number to its decimal form.
The input is entered as string. The output should be a variable of type long.
Do not use the built-in .NET functionality.
Examples:

binary							decimal
0								0
11								3
1010101010101011				43691
1110000110000101100101000000	236476736
*/

class BinToDec
{
	static void Main()
	{
		string bin = Console.ReadLine();

		var dec = 0;
		for (int i = 0; i < bin.Length; i++)
		{
			// we start with the least significant digit, and work our way to the left
			if (bin[bin.Length - i - 1] == '0') continue;
			dec += (int)Math.Pow(2, i);
		}
		Console.WriteLine(dec);
	}
}


text:
StockSharp Studio Change log
========================
## v4.1.10-4.2.47
Available on [forum](http://stocksharp.com/forum/yaf_postst2540_S--Studio---platforma-dlia-torghovykh-robotov.aspx)


text:
SuperbTest
==========

This is a coding test I took. The goal was to create this app (design was explained only using two pictures and a short description of what it was supposed to do) in roughly 3 hours. Completeness was more important than the time limit.


text:
import * as Debug from 'debug';
import config from '../../config';
import * as Models from '../../models';
import * as listValidation from '../validation/list';
import { ListButtonRow } from './listButtonRow';
import { ListHeader } from './listHeader';
import { ListInfoItem } from './listInfoItem';
import { ListItem } from './listItem';
import { ListTileRow } from './listTileRow';

const debug = Debug('neeo:device:list:builder');

const DEFAULT_OFFSET = 0;

export default class implements Models.ListBuilder {
  public readonly items: Models.ListItem[] = [];
  // tslint:disable-next-line:variable-name
  public _meta: Models.ListMetadata = {};
  public title: string;
  private limit: number;
  private offset: number;
  private totalMatchingItems: number;
  private browseIdentifier?: string;

  constructor({
    title,
    limit,
    offset,
    totalMatchingItems,
    browseIdentifier,
  }: Models.ListParameters = {}) {
    this.title = title || '';
    this.limit = listValidation.validateLimit(limit);
    this.offset = offset && Number.isFinite(offset) && offset >= 0 ? offset : DEFAULT_OFFSET;
    this.totalMatchingItems =
      totalMatchingItems && Number.isFinite(totalMatchingItems) ? totalMatchingItems : 0;
    this.browseIdentifier = browseIdentifier;
    this.build();

    return this;
  }

  public setListTitle(name: string) {
    this.title = name || '';
    this.build();

    return this;
  }

  public setTotalMatchingItems(totalMatchingItems: number) {
    this.totalMatchingItems = Number.isFinite(totalMatchingItems) ? totalMatchingItems : 0;
    this.build();

    return this;
  }

  public addListItem(params: Models.ListItemParameters, updateList = true) {
    listValidation.validateItemParams(params);
    const listItem = new ListItem(params);
    this.items.push(listItem);
    if (updateList) {
      this.build();
    }

    return this;
  }

  public addListItems(rawItems: ReadonlyArray<Models.ListItemParameters>) {
    const itemsToAdd = this.prepareItemsAccordingToOffsetAndLimit(rawItems);
    itemsToAdd.forEach((listItem) => this.addListItem(listItem, false));
    this.build();

    return this;
  }

  public addListHeader(title: string) {
    const header = new ListHeader(title);
    this.items.push(header);
    this.build();

    return this;
  }

  public addListTiles(params: ReadonlyArray<Models.ListTileParameters>) {
    const tileRow = new ListTileRow(params);
    this.items.push(tileRow.getTiles());
    this.build();

    return this;
  }

  public addListInfoItem(params: Models.ListInfoItemParameters) {
    const tile = new ListInfoItem(params);
    this.items.push(tile);
    this.build();

    return this;
  }

  public addListButtons(params: ReadonlyArray<Models.ListButtonParameters>) {
    const row = new ListButtonRow(params);
    this.items.push(row.getButtons());
    this.build();

    return this;
  }

  /**
   * This function applies the list limit and offset to a given list.
   * @param array Prepared files that might be wrong according to offset and limit
   * @return Items that can be added to the list according to the given offset and limit
   * @example
   *    .prepareItemsAccordingToOffsetAndLimit([
   *      { name: 'foo' },
   *      { name: 'bar' }
   *    ])
   */
  private prepareItemsAccordingToOffsetAndLimit<T>(array: ReadonlyArray<T>): ReadonlyArray<T> {
    const { offset, limit, items } = this;
    const offsetNextIndex = offset ? offset - 1 : 0;
    const effectiveLimit = limit || config.maxListItemsPerPage;
    const currentEntriesCount = items.length;
    const entriesToAdd = effectiveLimit - currentEntriesCount;
    if (entriesToAdd < 1) {
      debug('WARNING_LIST_FULL %o', {
        offsetNextIndex,
        effectiveLimit,
        currentEntriesCount,
      });

      return [];
    }

    return array.slice(offsetNextIndex, offsetNextIndex + entriesToAdd);
  }

  private build() {
    this.buildMetadata();
    this.verifyFullList();
  }

  private buildMetadata() {
    const { items, totalMatchingItems, offset, limit, browseIdentifier } = this;
    const meta: Models.ListMetadata = (this._meta = {
      totalItems: items.length,
      totalMatchingItems: Number.isFinite(totalMatchingItems) ? totalMatchingItems : items.length,
      current: { offset, limit, browseIdentifier },
    });
    const nonSpecial = items.filter((item) => {
      return (
        !item.isTile && !item.isHeader && !item.isInfoItem && !item.isButton && !item.isIconButton
      );
    });
    const nextOffset = offset + nonSpecial.length;
    if (Number.isFinite(offset) && meta.totalMatchingItems! > nextOffset) {
      meta.next = {
        offset: nextOffset,
        limit,
        browseIdentifier,
      };
    }
    if (offset > 0) {
      meta.previous = {
        offset: Math.max(offset - limit, 0),
        limit: Math.min(limit, offset),
        browseIdentifier,
      };
    }
  }

  private verifyFullList() {
    return listValidation.validateList(this);
  }
}


text:
  <meta charset="UTF-8">
  <title>Document</title>

{{Ui.get('testState') ? 'true' : 'false' }}

{{Ui.referenceCount('testState')}}

{{Ui.has('testState') ? 'true' : 'false' }}

{{myVar}}

  <button id="turnOn" ui-turn-on="testState">Turn On</button>
  <button id="turnOff" ui-turn-off="testState">Turn Off</button>
  <button id="toggle" ui-toggle="testState">Toggle</button>

  Turn On and Ng Click

  Attach elem 2
  Detach elem 1
  Detach elem 2


text:
package v1

// TestJobListerExpansion allows custom methods to be added to
// TestJobLister.
type TestJobListerExpansion interface{}

// TestJobNamespaceListerExpansion allows custom methods to be added to
// TestJobNamespaceLister.
type TestJobNamespaceListerExpansion interface{}


text:
"use strict";

exports.__esModule = true;
exports.useIntersectionObserver = void 0;

var _react = require("react");

var _intersectionObserver = require("../../utils/intersection-observer");

const useIntersectionObserver = _ref => {
  let {
    observedComponentRef,
    options
  } = _ref;
  const Observer = new _intersectionObserver.IntersectionObserverClass(options);
  const [withIntersectionObserver, setIntersectionObserver] = (0, _react.useState)(false);
  (0, _react.useEffect)(() => {
    if (!observedComponentRef || observedComponentRef && !observedComponentRef.current) {
      console.warn('observedComponentRef.current does not exist, useIntersectionObserver will return true');
      setIntersectionObserver(true);
      return;
    }

    Observer.observe(observedComponentRef.current, () => setIntersectionObserver(true));
    return () => Observer.unobserve(observedComponentRef.current);
  }, []);
  return withIntersectionObserver;
};

exports.useIntersectionObserver = useIntersectionObserver;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>MDInsider ♥ Open Source / Gilt Goes to Nodeland: A Recap of NodeConf.eu</title>

    <meta name="author" content="MDInsider, Inc.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="/assets/themes//img/favicon.ico">
    <link href="/atom.xml" type="application/atom+xml" rel="alternate" title="Sitewide ATOM Feed">
    <link href="/rss.xml" type="application/rss+xml" rel="alternate" title="Sitewide RSS Feed">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/assets/themes//css/github-light.css">
    <link rel="stylesheet/less" href="/assets/themes//css/style.less">

    Join MD Insider Tech
    MDInsider.com

            Categories

              <input type="search" placeholder="Search …" title="Search for:" />

            <menu id="categories-menu">

              <menuitem>
                AWS
              </menuitem>

              <menuitem>
                Leadership
              </menuitem>

              <menuitem>
                agile
              </menuitem>

              <menuitem>
                analytics
              </menuitem>

              <menuitem>
                aws
              </menuitem>

              <menuitem>
                blog
              </menuitem>

              <menuitem>
                conferences
              </menuitem>

              <menuitem>
                culture
              </menuitem>

              <menuitem>
                deployment
              </menuitem>

              <menuitem>
                front-end
              </menuitem>

              <menuitem>
                mobile
              </menuitem>

              <menuitem>
                scala
              </menuitem>

              <menuitem>
                swift
              </menuitem>

              <menuitem>
                tech
              </menuitem>

              <menuitem>
                tvOS
              </menuitem>

            </menu>
            <menu id="search-results">
            </menu>

Tech Blog

Gilt Goes to Nodeland: A Recap of NodeConf.eu

    <time>22 September 2014</time>

More than 150 Node.js aficionados on the grounds of a 15th-century castle, on an island resort in County Waterford, Ireland. Throw in two Node.js neophytes from Gilt’s engineering team in Dublin (my colleague, Nick Rogers, and myself), and what do you get? You get NodeConfEU: A lively conference for developers, spread over five days, featuring fun, sun, some great talks and interesting workshops.

Check out the ultra-modern conference venue!

There were too many talks to describe each of them, so we've picked out a few that particularly resonated with us:

Alex Liu from Netflix gave insights into how his team manages templates and assets across large sites. Netflix is doing some very cool stuff around producing conditional bundles of assets based on the A/B tests a user is in. Netflix can generate a possible 2.5 million asset bundles based on their A/B testing matrix. Hey Netflix: it might be a good idea to open source this (hint, hint!).

Fred George, father of the post-agile process termed “Programmer Anarchy,” spoke about the battle between asynchronous and synchronous microservices and some of the challenges going forward. Conclusion: synchronous isn't so great. At a Node conference, that position wasn't too controversial.

Jeff Harrell from PayPal gave an engaging talk on transitioning a large engineering department from Java to Node (a move that LinkedIn made in 2013). He wrote about nine node anti-patterns here.

StrongLoop co-founder Bert Belder gave a call to arms to the community around resolving the next stage of development for the Node core. He also expressed some opinions about promises which were present in Node in 2009. I think he might want them back!

Thorsten Lorenz from NodeSource presented a wonderfully geeky dig into the internals of how V8 stores objects. Key takeaway: be predictable and define types up front.

And speaking of geeky, University of Wisconsin grad student Mikola Lysenko demonstrated how special relativity theory might apply to synchronization in online games by using Cauchy surfaces to prevent causality anomalies.

PeerCDN founder Feross Aboukhadijeh gave a great talk and demonstration of WebRTC (Web Real Time Communication). His pre-alpha release of webtorrent, his browser-based torrent client, was very impressive. And by pre-alpha, Feross told us he had only got it to work the previous day!

Raquel Vélez from npm gave a talk on robotics and Node that involved the creation of some *cough* beautiful art.

As for the workshops: Other than for the session on robotics–which involved getting to work/play with lots of LittleBits, some nodecopters and a few Tessels (how could anyone not love it?)—the highlight was Ben Acker's boundless enthusiasm and help teaching us how to be hapi.

As for what else we learned:

Baseball skills seem to be fairly readily transferable to hurling, as we discovered when the "magical mystery tour" on Tuesday night included a trip to a local Gaelic Athletic Association (GAA) club.

Make sure that the person who calls you a taxi knows whether they are calling it for 6am or 6pm.

If you ever need directions to a GAA club in Waterford, we can help. We've been to them all.

Thanks so much to Cian, Richard, Agata and all the folks at NearForm for organising such an enjoyable conference!

    nodeconf 1

    javascript 9

    waterford 1

    Node.js 7

    Aidan Hollinshead 1

    Nick Rogers 3

    Dublin 47

    Ireland 14

    Gilt 340

    Gilt Groupe 282

    Gilt Tech 287

    gilttech 332

    conferences 25

    Fred George 1

    Alex Liu 1

    Jeff Harrell 1

    Bert Belder 1

    Thorsten Lorenz 1

    V8 1

    Mikola Lysenko 1

    PeerCDN 1

    Feross Aboukhadijeh 1

    WebRTC 2

    webtorrent 1

    Raquel Velez 1

    npm 2

    LittleBits 1

    Tessels 1

    Ben Acker 1

    Join MD Insider Tech
    MDInsider.com

          © 2015 MDInsider, Inc. • Archives


text:
package org.springframework.cloud.dataflow.server.single;

import java.util.List;

import io.pivotal.scheduler.SchedulerClient;
import org.cloudfoundry.client.CloudFoundryClient;
import org.cloudfoundry.client.v2.info.GetInfoResponse;
import org.cloudfoundry.reactor.TokenProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import reactor.core.publisher.Mono;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.dataflow.core.TaskPlatform;
import org.springframework.cloud.dataflow.server.config.cloudfoundry.CloudFoundryPlatformClientProvider;
import org.springframework.cloud.dataflow.server.config.cloudfoundry.CloudFoundryPlatformTokenProvider;
import org.springframework.cloud.dataflow.server.config.cloudfoundry.CloudFoundrySchedulerClientProvider;
import org.springframework.cloud.dataflow.server.service.SchedulerService;
import org.springframework.cloud.deployer.spi.scheduler.cloudfoundry.CloudFoundrySchedulerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author David Turanski
 **/
@ActiveProfiles("cloud")
@SpringBootTest(
	classes = { DataFlowServerApplication.class, CloudFoundrySchedulerTests.TestConfig.class },
	webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
	properties = {
	"spring.cloud.dataflow.features.schedules-enabled=true",
	"VCAP_SERVICES=foo",
	"spring.cloud.dataflow.task.platform.cloudfoundry.accounts[cf].connection.url=https://localhost",
	"spring.cloud.dataflow.task.platform.cloudfoundry.accounts[cf].connection.org=org",
	"spring.cloud.dataflow.task.platform.cloudfoundry.accounts[cf].connection.space=space",
	"spring.cloud.scheduler.cloudfoundry.scheduler-url=https://localhost"
	})
@RunWith(SpringRunner.class)
public class CloudFoundrySchedulerTests {

	@Autowired
	List<TaskPlatform> taskPlatforms;

	@Autowired
	SchedulerService schedulerService;

	@Test
	public void schedulerServiceCreated() {
		for (TaskPlatform taskPlatform: taskPlatforms) {
			if (taskPlatform.isPrimary()) {
				assertThat(taskPlatform.getName()).isEqualTo("Cloud Foundry");
			}
		}

		assertThat(schedulerService).isNotNull();
	}

	@Configuration
	static class TestConfig {
		private CloudFoundryClient cloudFoundryClient = mock(CloudFoundryClient.class);

		private TokenProvider tokenProvider = mock(TokenProvider.class);

		@Bean
		@Primary
		public CloudFoundryPlatformClientProvider mockCloudFoundryClientProvider() {
			when(cloudFoundryClient.info())
				.thenReturn(getInfoRequest -> Mono.just(GetInfoResponse.builder().apiVersion("0.0.0").build()));
			CloudFoundryPlatformClientProvider cloudFoundryClientProvider = mock(
				CloudFoundryPlatformClientProvider.class);
			when(cloudFoundryClientProvider.cloudFoundryClient(anyString())).thenAnswer(invocation -> {
				System.out.println("Returning " + cloudFoundryClient);
				return cloudFoundryClient;
			});
			return cloudFoundryClientProvider;
		}

		@Bean
		@Primary
		public CloudFoundrySchedulerClientProvider mockCloudFoundryShedulerClientProvider() {
			CloudFoundrySchedulerClientProvider cloudFoundrySchedulerClientProvider =
				mock(CloudFoundrySchedulerClientProvider.class);
			when(cloudFoundrySchedulerClientProvider.cloudFoundrySchedulerClient(anyString()))
				.thenReturn(mock(SchedulerClient.class));
			when(cloudFoundrySchedulerClientProvider.schedulerProperties()).thenReturn(
				new CloudFoundrySchedulerProperties());
			return cloudFoundrySchedulerClientProvider;
		}

		@Bean
		@Primary
		public CloudFoundryPlatformTokenProvider mockPlatformTokenProvider() {
			CloudFoundryPlatformTokenProvider platformTokenProvider = mock(CloudFoundryPlatformTokenProvider.class);
			when(platformTokenProvider.tokenProvider(anyString())).thenReturn(tokenProvider);
			return platformTokenProvider;
		}
	}

}


text:
/*  */

#include "orwell/game/Item.hpp"

#pragma once

#include <string>
#include <memory>

namespace orwell
{
namespace game
{
namespace item
{

class Flag : public Item
{
public :
	Flag(
			std::string const & iName,
			std::set< std::string > const & iRfids,
			boost::posix_time::milliseconds const & iTimeToCapture,
			uint32_t const iPointsOnCapture);

	Flag(
			std::string const & iName,
			int32_t const iColourCode,
			boost::posix_time::milliseconds const & iTimeToCapture,
			uint32_t const iPointsOnCapture);

	virtual ~Flag();

private :
	uint32_t m_pointsOnCapture;

	void innerCapture(Team & ioTeam) override;
};

} // item
} // game
} // orwell


text: Fill in the gaps to make the tests pass (use pytest to run them).


text:
package com.github.harunhasdal.livecycle;

import static org.junit.Assert.*;
import org.junit.Test;

public class ProcessLoggerTest {

	@Test
	public void testLogWithNullParameters() {
		ProcessLogger logger = new ProcessLoggerImpl();
		try{
			logger.log(null, null, null);
		} catch (Exception e) {
			fail("Should not throw exception");
		}
	}

	@Test
	public void testLogWithEmptyParameters() {
		ProcessLogger logger = new ProcessLoggerImpl();
		try{
			logger.log("", "", "");
		} catch (Exception e) {
			fail("Should not throw exception");
		}
	}

	@Test
	public void testLogWithUnrecognisedLevel() {
		ProcessLogger logger = new ProcessLoggerImpl();
		try{
			logger.log("NonExistent", "", "");
		} catch (Exception e) {
			fail("Should not throw exception");
		}
	}

}


text:
package dynamiccertificates

import "testing"

func TestDynamicCertificateContentEquals(t *testing.T) {
	tests := []struct {
		name     string
		lhs      *dynamicCertificateContent
		rhs      *dynamicCertificateContent
		expected bool
	}{
		{
			name:     "both nil",
			expected: true,
		},
		{
			name:     "lhs nil",
			rhs:      &dynamicCertificateContent{},
			expected: false,
		},
		{
			name:     "rhs nil",
			lhs:      &dynamicCertificateContent{},
			expected: false,
		},
		{
			name: "same",
			lhs: &dynamicCertificateContent{
				clientCA: caBundleContent{caBundle: []byte("foo")},
			},
			rhs: &dynamicCertificateContent{
				clientCA: caBundleContent{caBundle: []byte("foo")},
			},
			expected: true,
		},
		{
			name: "different",
			lhs: &dynamicCertificateContent{
				clientCA: caBundleContent{caBundle: []byte("foo")},
			},
			rhs: &dynamicCertificateContent{
				clientCA: caBundleContent{caBundle: []byte("bar")},
			},
			expected: false,
		},
		{
			name: "same with serving",
			lhs: &dynamicCertificateContent{
				clientCA:    caBundleContent{caBundle: []byte("foo")},
				servingCert: certKeyContent{cert: []byte("foo"), key: []byte("foo")},
			},
			rhs: &dynamicCertificateContent{
				clientCA:    caBundleContent{caBundle: []byte("foo")},
				servingCert: certKeyContent{cert: []byte("foo"), key: []byte("foo")},
			},
			expected: true,
		},
		{
			name: "different serving cert",
			lhs: &dynamicCertificateContent{
				clientCA:    caBundleContent{caBundle: []byte("foo")},
				servingCert: certKeyContent{cert: []byte("foo"), key: []byte("foo")},
			},
			rhs: &dynamicCertificateContent{
				clientCA:    caBundleContent{caBundle: []byte("foo")},
				servingCert: certKeyContent{cert: []byte("bar"), key: []byte("foo")},
			},
			expected: false,
		},
		{
			name: "different serving key",
			lhs: &dynamicCertificateContent{
				clientCA:    caBundleContent{caBundle: []byte("foo")},
				servingCert: certKeyContent{cert: []byte("foo"), key: []byte("foo")},
			},
			rhs: &dynamicCertificateContent{
				clientCA:    caBundleContent{caBundle: []byte("foo")},
				servingCert: certKeyContent{cert: []byte("foo"), key: []byte("bar")},
			},
			expected: false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			actual := test.lhs.Equal(test.rhs)
			if actual != test.expected {
				t.Error(actual)
			}
		})
	}
}

func TestCABundleContentEquals(t *testing.T) {
	tests := []struct {
		name     string
		lhs      *caBundleContent
		rhs      *caBundleContent
		expected bool
	}{
		{
			name:     "both nil",
			expected: true,
		},
		{
			name:     "lhs nil",
			rhs:      &caBundleContent{},
			expected: false,
		},
		{
			name:     "rhs nil",
			lhs:      &caBundleContent{},
			expected: false,
		},
		{
			name:     "same",
			lhs:      &caBundleContent{caBundle: []byte("foo")},
			rhs:      &caBundleContent{caBundle: []byte("foo")},
			expected: true,
		},
		{
			name:     "different",
			lhs:      &caBundleContent{caBundle: []byte("foo")},
			rhs:      &caBundleContent{caBundle: []byte("bar")},
			expected: false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			actual := test.lhs.Equal(test.rhs)
			if actual != test.expected {
				t.Error(actual)
			}
		})
	}
}


text:
const path = require('path');

module.exports = {
  entry: "./test/services/AllTests.js",
  output: {
    path: path.resolve(__dirname, "."),
    filename: "bundle.test.js"
  },
  mode: "none"
};


text:
SpreeCartToggle
===============

Ability ot turn the cart and add button on/off.

Copyright (c) 2011 [name of extension creator], released under the New BSD License