text:
<?php
ob_start();
include('param/bdd.php');
if(isset($_COOKIE['isConnected']) and $_COOKIE['isConnected']==1) {
$requete = "SELECT * FROM message inner join membres on membres.ID=message.message_user WHERE message_discussion = :discussion order by message_ts";
$req_prep = $connect->prepare($requete);
$req_prep->execute(array(':discussion'=>1));
?>

                    C'est Ok ?2

<?php
while ($donnees = $req_prep->fetch())
{
?>

                    <div class="
                         <?php
                            if($_COOKIE['pseudo']==$donnees['pseudo']) {
                                echo 'col-xs-10 col-xs-offset-2 bg-info message';
                            } else {
                                echo 'col-xs-10 bg-warning message';
                                }
                         ?>
                         ">
                        <?php
                            if($_COOKIE['pseudo']==$donnees['pseudo']) {
                                echo $donnees['message_txt'];
                            } else {
                                echo ''.$donnees['pseudo'].' : '.$donnees['message_txt'];
                            }
                        ?>

<?php
}
?>

<?php

$req_prep->closeCursor();
}else{
 echo 'Connecte toi !   ';
}
?>


text:
8. One way to create random file or directory names is to produce a random BigInt and convert it to base 36, yielding a string such as "qsnvbevtomcj38o06kul". Poke around Scaladoc to find a way of doing this in Scala.

> `toString(radix)` - Returns the String representation in the specified radix(meaning root, refers to base) of this BigInt.

```scala
import scala.util.Random;
import scala.math.BigInt.probablePrime;

probablePrime(100, Random).toString(36) // res0: String = 241jrkd98jwy9pp4n4az
```

redpajama_set_name: RedPajamaGithub


text:
package me.minidigger.projecttd.systems;

import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;

import me.minidigger.projecttd.components.TransformComponent;
import me.minidigger.projecttd.components.VelocityComponent;

/**
 * Created by Martin on 02.04.2017.
 */
public class MovementSystem extends IteratingSystem {

    private ComponentMapper<TransformComponent> pm = ComponentMapper.getFor(TransformComponent.class);
    private ComponentMapper<VelocityComponent> vm = ComponentMapper.getFor(VelocityComponent.class);

    public MovementSystem() {
        super(Family.all(TransformComponent.class, VelocityComponent.class).get());
    }

    @Override
    public void processEntity(Entity entity, float deltaTime) {
        TransformComponent transform = pm.get(entity);
        VelocityComponent velocity = vm.get(entity);

        transform.position.x += velocity.linear.x * deltaTime;
        transform.position.y += velocity.linear.y * deltaTime;

        transform.rotation += velocity.angular * deltaTime;
    }
}


text:
package org.apache.camel.component.spring.ws;

import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.spring.ws.bean.CamelEndpointMapping;
import org.apache.camel.component.spring.ws.jaxb.QuoteRequest;
import org.apache.camel.component.spring.ws.jaxb.QuoteResponse;
import org.apache.camel.model.dataformat.JaxbDataFormat;
import org.apache.camel.spi.Registry;
import org.apache.camel.support.SimpleRegistry;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.apache.camel.test.spring.junit5.CamelSpringTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.ws.client.core.WebServiceTemplate;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

@ContextConfiguration
@CamelSpringTest
public class ConsumerMarshallingRouteTest extends CamelTestSupport {

    @Autowired
    private CamelEndpointMapping endpointMapping;

    @Autowired
    private WebServiceTemplate webServiceTemplate;

    @Override
    @BeforeEach
    public void setUp() throws Exception {
        super.setUp();
        context.setTracing(true);
    }

    @Override
    protected Registry createCamelRegistry() throws Exception {
        Registry registry = new SimpleRegistry();
        registry.bind("endpointMapping", this.endpointMapping);
        registry.bind("webServiceTemplate", this.webServiceTemplate);
        return registry;
    }

    @Test
    public void consumeWebserviceWithPojoRequest() throws Exception {
        consumePojoRequestStringResponseWithEnpoint("direct:webservice-marshall");
    }

    @Test
    public void consumeWebserviceWithPojoRequestAndPojoResponse() throws Exception {
        QuoteRequest request = new QuoteRequest();
        request.setSymbol("GOOG");

        Object result = template.requestBody("direct:webservice-marshall-unmarshall", request);

        assertNotNull(result);
        assertTrue(result instanceof QuoteResponse);
        QuoteResponse quoteResponse = (QuoteResponse) result;
        assertEquals("Google Inc.", quoteResponse.getName());
    }

    @Test
    public void consumeWebserviceWithPojoRequestAsInOnly() throws Exception {
        QuoteRequest request = new QuoteRequest();
        request.setSymbol("GOOG");

        Object result = template.requestBody("direct:webservice-marshall-asinonly", request);

        assertNull(result);
    }

    @Test
    public void consumeWebserviceWithPojoRequestAsIn() throws Exception {
        consumePojoRequestStringResponseWithEnpoint("direct:webservice-marshall-asin");
    }

    private void consumePojoRequestStringResponseWithEnpoint(String endpoint) {
        QuoteRequest request = new QuoteRequest();
        request.setSymbol("GOOG");

        Object result = template.requestBody(endpoint, request);

        assertNotNull(result);
        assertTrue(result instanceof String);
        String resultMessage = (String) result;
        assertTrue(resultMessage.contains("Google Inc."));
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {

            @Override
            public void configure() throws Exception {
                JaxbDataFormat jaxb = new JaxbDataFormat(false);
                jaxb.setContextPath("org.apache.camel.component.spring.ws.jaxb");

                // request webservice
                from("direct:webservice-marshall")
                        .marshal(jaxb)
                        .to("spring-ws:http://localhost/?soapAction=http://www.stockquotes.edu/GetQuote&webServiceTemplate=#webServiceTemplate")
                        .convertBodyTo(String.class);

                // request webservice
                from("direct:webservice-marshall-unmarshall")
                        .marshal(jaxb)
                        .to("spring-ws:http://localhost/?soapAction=http://www.stockquotes.edu/GetQuote&webServiceTemplate=#webServiceTemplate")
                        .unmarshal(jaxb);

                // provide web service
                from("spring-ws:soapaction:http://www.stockquotes.edu/GetQuote?endpointMapping=#endpointMapping").process(
                        new StockQuoteResponseProcessor());

                // request webservice
                from("direct:webservice-marshall-asinonly")
                        .marshal(jaxb)
                        .to("spring-ws:http://localhost/?soapAction=http://www.stockquotes.edu/GetQuoteAsInOnly&webServiceTemplate=#webServiceTemplate")
                        .convertBodyTo(String.class);

                // provide web service
                from("spring-ws:soapaction:http://www.stockquotes.edu/GetQuoteAsInOnly?endpointMapping=#endpointMapping")
                        .setExchangePattern(ExchangePattern.InOnly)
                        .process(new StockQuoteResponseProcessor());

                // request webservice
                from("direct:webservice-marshall-asin")
                        .marshal(jaxb)
                        .to("spring-ws:http://localhost/?soapAction=http://www.stockquotes.edu/GetQuoteAsIn&webServiceTemplate=#webServiceTemplate")
                        .convertBodyTo(String.class);

                // provide web service
                from("spring-ws:soapaction:http://www.stockquotes.edu/GetQuoteAsIn?endpointMapping=#endpointMapping")
                        .setHeader("setin", constant("true"))
                        .process(new StockQuoteResponseProcessor());

            }
        };
    }

}


text:
package org.apache.xml.security.encryption;

import java.io.IOException;

import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.utils.resolver.ResourceResolver;
import org.apache.xml.security.utils.resolver.ResourceResolverException;
import org.apache.xml.security.exceptions.Base64DecodingException;
import org.apache.xml.security.signature.XMLSignatureInput;
import org.apache.xml.security.transforms.TransformationException;
import org.w3c.dom.Attr;
import org.apache.xml.security.utils.Base64;

/**
 * XMLCipherInput is used to wrap input passed into the
 * XMLCipher encryption operations.
 *
 * In decryption mode, it takes a CipherData object and allows
 * callers to dereference the CipherData into the encrypted bytes that it
 * actually represents.  This takes care of all base64 encoding etc.
 *
 * While primarily an internal class, this can be used by applications to
 * quickly and easily retrieve the encrypted bytes from an EncryptedType
 * object
 *
 * @author Berin Lautenbach
 */
public class XMLCipherInput {

    private static org.slf4j.Logger log =
        org.slf4j.LoggerFactory.getLogger(XMLCipherInput.class);

    /** The data we are working with */
    private CipherData cipherData;

    /** MODES */
    private int mode;

    private boolean secureValidation;

    /**
     * Constructor for processing encrypted octets
     *
     * @param data The CipherData object to read the bytes from
     * @throws XMLEncryptionException {@link XMLEncryptionException}
     */
    public XMLCipherInput(CipherData data) throws XMLEncryptionException {
        cipherData = data;
        mode = XMLCipher.DECRYPT_MODE;
        if (cipherData == null) {
            throw new XMLEncryptionException("CipherData is null");
        }
    }

    /**
     * Constructor for processing encrypted octets
     *
     * @param input The EncryptedType object to read
     * the bytes from.
     * @throws XMLEncryptionException {@link XMLEncryptionException}
     */
    public XMLCipherInput(EncryptedType input) throws XMLEncryptionException {
        cipherData = input == null ? null : input.getCipherData();
        mode = XMLCipher.DECRYPT_MODE;
        if (cipherData == null) {
            throw new XMLEncryptionException("CipherData is null");
        }
    }

    /**
     * Set whether secure validation is enabled or not. The default is false.
     */
    public void setSecureValidation(boolean secureValidation) {
        this.secureValidation = secureValidation;
    }

    /**
     * Dereferences the input and returns it as a single byte array.
     *
     * @throws XMLEncryptionException
     * @return The decripted bytes.
     */
    public byte[] getBytes() throws XMLEncryptionException {
        if (mode == XMLCipher.DECRYPT_MODE) {
            return getDecryptBytes();
        }
        return null;
    }

    /**
     * Internal method to get bytes in decryption mode
     * @return the decrypted bytes
     * @throws XMLEncryptionException
     */
    private byte[] getDecryptBytes() throws XMLEncryptionException {
        String base64EncodedEncryptedOctets = null;

        if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
            // Fun time!
            if (log.isDebugEnabled()) {
                log.debug("Found a reference type CipherData");
            }
            CipherReference cr = cipherData.getCipherReference();

            // Need to wrap the uri in an Attribute node so that we can
            // Pass to the resource resolvers

            Attr uriAttr = cr.getURIAsAttr();
            XMLSignatureInput input = null;

            try {
                ResourceResolver resolver =
                    ResourceResolver.getInstance(uriAttr, null, secureValidation);
                input = resolver.resolve(uriAttr, null, secureValidation);
            } catch (ResourceResolverException ex) {
                throw new XMLEncryptionException(ex);
            }

            if (input != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Managed to resolve URI \"" + cr.getURI() + "\"");
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Failed to resolve URI \"" + cr.getURI() + "\"");
                }
            }

            // Lets see if there are any transforms
            Transforms transforms = cr.getTransforms();
            if (transforms != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Have transforms in cipher reference");
                }
                try {
                    org.apache.xml.security.transforms.Transforms dsTransforms =
                        transforms.getDSTransforms();
                    dsTransforms.setSecureValidation(secureValidation);
                    input = dsTransforms.performTransforms(input);
                } catch (TransformationException ex) {
                    throw new XMLEncryptionException(ex);
                }
            }

            try {
                return input.getBytes();
            } catch (IOException ex) {
                throw new XMLEncryptionException(ex);
            } catch (CanonicalizationException ex) {
                throw new XMLEncryptionException(ex);
            }

            // retrieve the cipher text
        } else if (cipherData.getDataType() == CipherData.VALUE_TYPE) {
            base64EncodedEncryptedOctets = cipherData.getCipherValue().getValue();
        } else {
            throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value");
        }

        if (log.isDebugEnabled()) {
            log.debug("Encrypted octets:\n" + base64EncodedEncryptedOctets);
        }

        try {
            return Base64.decode(base64EncodedEncryptedOctets);
        } catch (Base64DecodingException bde) {
            throw new XMLEncryptionException(bde);
        }
    }
}


text:
/*
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * Copyright (C) 2006 University of Waikato
 */

package weka.core.converters;

import weka.core.CheckGOE;
import weka.core.CheckOptionHandler;
import weka.core.Instances;
import weka.core.OptionHandler;
import weka.core.TestInstances;

import junit.framework.TestCase;

/**
 * Abstract Test class for Converters.
 *
 * @author FracPete (fracpete at waikato dot ac dot nz)
 * @version $Revision: 8034 $
 */
public abstract class AbstractConverterTest
  extends TestCase {

  /** whether the option handling is fully enabled */
  public final static boolean TEST_OPTION_HANDLING = false;

  /** for generating test data */
  protected TestInstances m_TestInstances;

  /** the loader */
  protected AbstractLoader m_Loader;

  /** the saver */
  protected AbstractSaver m_Saver;

  /** the OptionHandler tester for the loader */
  protected CheckOptionHandler m_OptionTesterLoader;

  /** the OptionHandler tester for the saver */
  protected CheckOptionHandler m_OptionTesterSaver;

  /** for testing GOE stuff for the loader */
  protected CheckGOE m_GOETesterLoader;

  /** for testing GOE stuff for the saver */
  protected CheckGOE m_GOETesterSaver;

  /** the reference dataset */
  protected Instances m_Instances;

  /**
   * Constructs the AbstractConverterTest. Called by subclasses.
   *
   * @param name the name of the test class
   */
  public AbstractConverterTest(String name) {
    super(name);
  }

  /**
   * returns the loader used in the tests
   *
   * @return the configured loader
   */
  public abstract AbstractLoader getLoader();

  /**
   * returns the saver used in the tests
   *
   * @return the configured saver
   */
  public abstract AbstractSaver getSaver();

  /**
   * Configures the CheckOptionHandler uses for testing the optionhandling.
   * Sets the scheme to test.
   *
   * @param o	the object to test
   * @return	the fully configured CheckOptionHandler
   */
  protected CheckOptionHandler getOptionTester(Object o) {
    CheckOptionHandler		result;

    result = new CheckOptionHandler();
    if (o instanceof OptionHandler)
      result.setOptionHandler((OptionHandler) o);
    else
      result.setOptionHandler(null);
    result.setUserOptions(new String[0]);
    result.setSilent(true);

    return result;
  }

  /**
   * Configures the CheckGOE used for testing GOE stuff.
   *
   * @param o	the object to test
   * @return	the fully configured CheckGOE
   */
  protected CheckGOE getGOETester(Object o) {
    CheckGOE		result;

    result = new CheckGOE();
    result.setObject(o);
    result.setIgnoredProperties(result.getIgnoredProperties() + ",instances");
    result.setSilent(true);

    return result;
  }

  /**
   * Configures the CheckOptionHandler used for testing the option handling
   * of the loader.
   * Sets the scheme to test.
   *
   * @return	the fully configured CheckOptionHandler
   */
  protected CheckOptionHandler getOptionTesterLoader() {
    return getOptionTester(getLoader());
  }

  /**
   * Configures the CheckOptionHandler used for testing the option handling
   * of the saver.
   * Sets the scheme to test.
   *
   * @return	the fully configured CheckOptionHandler
   */
  protected CheckOptionHandler getOptionTesterSaver() {
    return getOptionTester(getSaver());
  }

  /**
   * Configures the CheckGOE used for testing the option handling
   * of the loader.
   * Sets the scheme to test.
   *
   * @return	the fully configured CheckGOE
   */
  protected CheckGOE getGOETesterLoader() {
    return getGOETester(getLoader());
  }

  /**
   * Configures the CheckGOE used for testing the option handling
   * of the saver.
   * Sets the scheme to test.
   *
   * @return	the fully configured CheckGOE
   */
  protected CheckGOE getGOETesterSaver() {
    return getGOETester(getSaver());
  }

  /**
   * returns the test data generator
   *
   * @return 	the configured test data generator
   */
  protected TestInstances getTestInstances() {
    return new TestInstances();
  }

  /**
   * Called by JUnit before each test method. This implementation creates
   * the default converters (loader/saver) to test and loads a test set of
   * Instances.
   *
   * @throws Exception if an error occurs reading the example instances.
   */
  protected void setUp() throws Exception {
    super.setUp();

    m_Loader             = getLoader();
    m_Saver              = getSaver();

    m_OptionTesterLoader = getOptionTesterLoader();
    m_OptionTesterSaver  = getOptionTesterSaver();
    m_GOETesterLoader    = getGOETesterLoader();
    m_GOETesterSaver     = getGOETesterSaver();

    m_TestInstances      = getTestInstances();
    m_Instances          = m_TestInstances.generate();
  }

  /**
   * Called by JUnit after each test method
   */
  protected void tearDown() throws Exception {
    m_Loader             = null;
    m_Saver              = null;

    m_OptionTesterLoader = null;
    m_OptionTesterSaver  = null;
    m_GOETesterLoader    = null;
    m_GOETesterSaver     = null;

    m_TestInstances      = null;
    m_Instances          = null;

    super.tearDown();
  }

  /**
   * tests the listing of the options
   */
  public void testListOptions() {
    if (m_OptionTesterLoader.getOptionHandler() != null) {
      if (!m_OptionTesterLoader.checkListOptions())
	fail("Loader: Options cannot be listed via listOptions.");
    }

    if (m_OptionTesterSaver.getOptionHandler() != null) {
      if (!m_OptionTesterSaver.checkListOptions())
	fail("Saver: Options cannot be listed via listOptions.");
    }
  }

  /**
   * tests the setting of the options
   */
  public void testSetOptions() {
    // TODO: currently disabled
    if (!TEST_OPTION_HANDLING)
      return;

    if (m_OptionTesterLoader.getOptionHandler() != null) {
      if (!m_OptionTesterLoader.checkSetOptions())
	fail("Loader: setOptions method failed.");
    }

    if (m_OptionTesterSaver.getOptionHandler() != null) {
      if (!m_OptionTesterSaver.checkSetOptions())
	fail("Saver: setOptions method failed.");
    }
  }

  /**
   * tests whether there are any remaining options
   */
  public void testRemainingOptions() {
    // TODO: currently disabled
    if (!TEST_OPTION_HANDLING)
      return;

    if (m_OptionTesterLoader.getOptionHandler() != null) {
      if (!m_OptionTesterLoader.checkRemainingOptions())
	fail("Loader: There were 'left-over' options.");
    }

    if (m_OptionTesterSaver.getOptionHandler() != null) {
      if (!m_OptionTesterSaver.checkRemainingOptions())
	fail("Saver: There were 'left-over' options.");
    }
  }

  /**
   * tests the whether the user-supplied options stay the same after setting.
   * getting, and re-setting again.
   */
  public void testCanonicalUserOptions() {
    // TODO: currently disabled
    if (!TEST_OPTION_HANDLING)
      return;

    if (m_OptionTesterLoader.getOptionHandler() != null) {
      if (!m_OptionTesterLoader.checkCanonicalUserOptions())
	fail("Loader: setOptions method failed");
    }

    if (m_OptionTesterSaver.getOptionHandler() != null) {
      if (!m_OptionTesterSaver.checkCanonicalUserOptions())
	fail("Saver: setOptions method failed");
    }
  }

  /**
   * tests the resetting of the options to the default ones
   */
  public void testResettingOptions() {
    // TODO: currently disabled
    if (!TEST_OPTION_HANDLING)
      return;

    if (m_OptionTesterLoader.getOptionHandler() != null) {
      if (!m_OptionTesterLoader.checkSetOptions())
	fail("Loader: Resetting of options failed");
    }

    if (m_OptionTesterSaver.getOptionHandler() != null) {
      if (!m_OptionTesterSaver.checkSetOptions())
	fail("Saver: Resetting of options failed");
    }
  }

  /**
   * tests for a globalInfo method
   */
  public void testGlobalInfo() {
    if (!m_GOETesterLoader.checkGlobalInfo())
      fail("Loader: No globalInfo method");

    if (!m_GOETesterSaver.checkGlobalInfo())
      fail("Saver: No globalInfo method");
  }

  /**
   * tests the tool tips
   */
  public void testToolTips() {
    if (!m_GOETesterLoader.checkToolTips())
      fail("Loader: Tool tips inconsistent");

    if (!m_GOETesterSaver.checkToolTips())
      fail("Saver: Tool tips inconsistent");
  }
}


text:
package net.sourceforge.squirrel_sql.client.mainframe.action;

import net.sourceforge.squirrel_sql.client.IApplication;
import net.sourceforge.squirrel_sql.client.gui.db.DriversListInternalFrame;
import net.sourceforge.squirrel_sql.client.gui.desktopcontainer.SelectWidgetAction;

import java.awt.event.ActionEvent;

/**
 * This Action displays the Drivers Tool Window.
 *
 * @author Colin Bell
 */
public class ViewDriversAction extends SelectWidgetAction
{
   private DriversListInternalFrame m_window;

   /**
	 * Ctor.
	 *
	 * @throws	IllegalArgumentException
	 *			Thrown if <TT>null</TT> <TT>DriversToolWindow</TT> or
	 *			<TT>IApplication</TT> object passed.
	 */
	public ViewDriversAction(IApplication app, DriversListInternalFrame window)
	{
		super(window);
		if (app == null)
		{
			throw new IllegalArgumentException("null IApplication passed");
		}
		if (window == null)
		{
			throw new IllegalArgumentException("null DriversToolWindow passed");
		}

      m_window = window;
      app.getResources().setupAction(this, app.getSquirrelPreferences().getShowColoriconsInToolbar());
	}

   public void actionPerformed(ActionEvent evt)
   {
      super.actionPerformed(evt);

      if(null != m_window)
      {
         m_window.nowVisible(true);
      }
   }

}


text:
<snap-drawer>

                {{item.text}}

</snap-drawer>


text:
package sun.jvm.hotspot.oops;

// A HeapVisitor is used for visiting all object in the heap

public interface HeapVisitor {
  // This is called at the beginning of the iteration to provide the
  // HeapVisitor with information about the amount of memory which
  // will be traversed (for example, for displaying a progress bar)
  public void prologue(long usedSize);

  // Callback method for each object
  // Return true if the iteration should be stopped.
  public boolean doObj(Oop obj);

  // This is called after the traversal is complete
  public void epilogue();
};


text:
<!--
 *******************************************************************************
 *
 * Copyright (c) 2004-2009 Oracle Corporation.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *
 *    Kohsuke Kawaguchi
 *
 *******************************************************************************
-->

<html><head/><body>
        Model objects that represent JUnit test reports.
    </body></html>


text:
local mod = {}

--固定步长
function mod.calcTime(interval, step, start, stop)
    return (math.abs(stop - start)) / step * interval;
end

function mod.fadeIn(ani, bone, progress)
    local org_opacity = bone["__current_opacity__"]
    if org_opacity == nil then
        bone["__current_opacity__"] = bone:getOpacity()
        org_opacity = bone["__current_opacity__"];
    end

    new_opacity = org_opacity + (1.0 - org_opacity) * progress
    bone:applyCSS(string.format("{opacity: %f;}", new_opacity))
    if progress == 1 then
        bone["__current_opacity__"] = nil
    end
end

function mod.fadeOut(ani, bone, progress)
    local org_opacity = bone["__current_opacity__"]
    if org_opacity == nil then
        bone["__current_opacity__"] = bone:getOpacity()
        org_opacity = bone["__current_opacity__"];
    end

    new_opacity = (org_opacity) * (1 - progress)
    bone:applyCSS(string.format("{opacity: %f;}", new_opacity))
    if progress == 1 then
        bone["__current_opacity__"] = nil
    end
end

print("load animate")
return mod;


text:
omhttpfs: Hadoop HTTPFS Output Module
============================================

===========================  ===========================================================================
**Module Name:**             **omhttpfs**
**Available Since:**         **8.10.0**
**Author:**                  `sskaje <https://sskaje.me/2014/12/omhttpfs-rsyslog-hdfs-output-plugin/>`_ <sskaje@gmail.com>
===========================  ===========================================================================

This module is an alternative to omhdfs via `Hadoop HDFS over HTTP <http://hadoop.apache.org/docs/current/hadoop-hdfs-httpfs/index.html>`_.

**Dependencies**

* libcurl

**Configure**
::
    ./configure --enable-omhttpfs

**Config options**

Legacy config **NOT** supported.

-  **host**
    HttpFS server host. Default: *127.0.0.1*

-  **port**
    HttpFS server port. Default: *14000*

-  **user**
    HttpFS auth user. Default: *hdfs*

-  **https** \ <on/**off**>
    Turn on if your HttpFS runs on HTTPS. Default: *off*

-  **file**
    File to write, or a template name.

-  **isdynfile** \ <on/**off**>
    Turn this on if your **file** is a template name.

    See examples below.

-  **template**
    Format your message when writing to **file**. Default: *RSYSLOG_FileFormat*

**Examples**

::

    module(load="omhttpfs")
    template(name="hdfs_tmp_file" type="string" string="/tmp/%$YEAR%/test.log")
    template(name="hdfs_tmp_filecontent" type="string" string="%$YEAR%-%$MONTH%-%$DAY% %MSG% ==\n")
    local4.*    action(type="omhttpfs" host="10.1.1.161" port="14000" https="off" file="hdfs_tmp_file" isDynFile="on")
    local5.*    action(type="omhttpfs" host="10.1.1.161" port="14000" https="off" file="hdfs_tmp_file" isDynFile="on" template="hdfs_tmp_filecontent")


text:
from constants import *
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(SERVO_PIN, GPIO.OUT)

def manual_control():
    while(True):
        if(int(float(input("0 or 1?"))) == 1):
            GPIO.output(SERVO_PIN, GPIO.HIGH)
        else:
            GPIO.output(SERVO_PIN, GPIO.LOW)

def scan_control(scan):
    if scan:
        GPIO.output(SERVO_PIN, GPIO.HIGH)
    else:
        GPIO.output(SERVO_PIN, GPIO.LOW)

manual_control()


text:
.class Lcom/android/internal/view/IInputConnectionWrapper$MyHandler;
.super Landroid/os/Handler;
.source "IInputConnectionWrapper.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/view/IInputConnectionWrapper;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "MyHandler"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/view/IInputConnectionWrapper;

# direct methods
.method constructor <init>(Lcom/android/internal/view/IInputConnectionWrapper;Landroid/os/Looper;)V
    .locals 0
    .param p2, "looper"    # Landroid/os/Looper;

    .prologue
    .line 74
    iput-object p1, p0, Lcom/android/internal/view/IInputConnectionWrapper$MyHandler;->this$0:Lcom/android/internal/view/IInputConnectionWrapper;

    .line 75
    invoke-direct {p0, p2}, Landroid/os/Handler;-><init>(Landroid/os/Looper;)V

    .line 76
    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 1
    .param p1, "msg"    # Landroid/os/Message;

    .prologue
    .line 80
    iget-object v0, p0, Lcom/android/internal/view/IInputConnectionWrapper$MyHandler;->this$0:Lcom/android/internal/view/IInputConnectionWrapper;

    invoke-virtual {v0, p1}, Lcom/android/internal/view/IInputConnectionWrapper;->executeMessage(Landroid/os/Message;)V

    .line 81
    return-void
.end method


text:
using System;

public static class Test
{
	public static string Test_1 (this string s)
	{
		return ":";
	}
}


text:
package org.springframework.expression.spel;

import java.awt.Color;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.jupiter.api.Test;

import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ParseException;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

///CLOVER:OFF

/**
 * Testcases showing the common scenarios/use-cases for picking up the expression language support.
 * The first test shows very basic usage, just drop it in and go.  By 'standard infrastructure', it means:

 *

 *
The context classloader is used (so, the default classpath)
 *
Some basic type converters are included
 *
properties/methods/constructors are discovered and invoked using reflection
 *

 * The scenarios after that then how to plug in extensions:

 *

 *
Adding entries to the classpath that will be used to load types and define well known 'imports'
 *
Defining variables that are then accessible in the expression
 *
Changing the root context object against which non-qualified references are resolved
 *
Registering java methods as functions callable from the expression
 *
Adding a basic property resolver
 *
Adding an advanced (better performing) property resolver
 *
Adding your own type converter to support conversion between any types you like
 *

 *
 * @author Andy Clement
 */
public class ExpressionLanguageScenarioTests extends AbstractExpressionTests {

	/**
	 * Scenario: using the standard infrastructure and running simple expression evaluation.
	 */
	@Test
	public void testScenario_UsingStandardInfrastructure() {
		try {
			// Create a parser
			SpelExpressionParser parser = new SpelExpressionParser();
			// Parse an expression
			Expression expr = parser.parseRaw("new String('hello world')");
			// Evaluate it using a 'standard' context
			Object value = expr.getValue();
			// They are reusable
			value = expr.getValue();

			assertThat(value).isEqualTo("hello world");
			assertThat(value.getClass()).isEqualTo(String.class);
		}
		catch (EvaluationException | ParseException ex) {
			throw new AssertionError(ex.getMessage(), ex);
		}
	}

	/**
	 * Scenario: using the standard context but adding your own variables
	 */
	@Test
	public void testScenario_DefiningVariablesThatWillBeAccessibleInExpressions() throws Exception {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Use the standard evaluation context
		StandardEvaluationContext ctx = new StandardEvaluationContext();
		ctx.setVariable("favouriteColour","blue");
		List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17);
		ctx.setVariable("primes",primes);

		Expression expr = parser.parseRaw("#favouriteColour");
		Object value = expr.getValue(ctx);
		assertThat(value).isEqualTo("blue");

		expr = parser.parseRaw("#primes.get(1)");
		value = expr.getValue(ctx);
		assertThat(value).isEqualTo(3);

		// all prime numbers > 10 from the list (using selection ?{...})
		expr = parser.parseRaw("#primes.?[#this>10]");
		value = expr.getValue(ctx);
		assertThat(value.toString()).isEqualTo("[11, 13, 17]");
	}

	static class TestClass {
		public String str;
		private int property;
		public int getProperty() { return property; }
		public void setProperty(int i) { property = i; }
	}

	/**
	 * Scenario: using your own root context object
	 */
	@Test
	public void testScenario_UsingADifferentRootContextObject() throws Exception {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Use the standard evaluation context
		StandardEvaluationContext ctx = new StandardEvaluationContext();

		TestClass tc = new TestClass();
		tc.setProperty(42);
		tc.str = "wibble";
		ctx.setRootObject(tc);

		// read it, set it, read it again
		Expression expr = parser.parseRaw("str");
		Object value = expr.getValue(ctx);
		assertThat(value).isEqualTo("wibble");
		expr = parser.parseRaw("str");
		expr.setValue(ctx, "wobble");
		expr = parser.parseRaw("str");
		value = expr.getValue(ctx);
		assertThat(value).isEqualTo("wobble");
		// or using assignment within the expression
		expr = parser.parseRaw("str='wabble'");
		value = expr.getValue(ctx);
		expr = parser.parseRaw("str");
		value = expr.getValue(ctx);
		assertThat(value).isEqualTo("wabble");

		// private property will be accessed through getter()
		expr = parser.parseRaw("property");
		value = expr.getValue(ctx);
		assertThat(value).isEqualTo(42);

		// ... and set through setter
		expr = parser.parseRaw("property=4");
		value = expr.getValue(ctx);
		expr = parser.parseRaw("property");
		value = expr.getValue(ctx);
		assertThat(value).isEqualTo(4);
	}

	public static String repeat(String s) { return s+s; }

	/**
	 * Scenario: using your own java methods and calling them from the expression
	 */
	@Test
	public void testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem() throws SecurityException, NoSuchMethodException {
		try {
			// Create a parser
			SpelExpressionParser parser = new SpelExpressionParser();
			// Use the standard evaluation context
			StandardEvaluationContext ctx = new StandardEvaluationContext();
			ctx.registerFunction("repeat",ExpressionLanguageScenarioTests.class.getDeclaredMethod("repeat",String.class));

			Expression expr = parser.parseRaw("#repeat('hello')");
			Object value = expr.getValue(ctx);
			assertThat(value).isEqualTo("hellohello");

		}
		catch (EvaluationException | ParseException ex) {
			throw new AssertionError(ex.getMessage(), ex);
		}
	}

	/**
	 * Scenario: add a property resolver that will get called in the resolver chain, this one only supports reading.
	 */
	@Test
	public void testScenario_AddingYourOwnPropertyResolvers_1() throws Exception {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Use the standard evaluation context
		StandardEvaluationContext ctx = new StandardEvaluationContext();

		ctx.addPropertyAccessor(new FruitColourAccessor());
		Expression expr = parser.parseRaw("orange");
		Object value = expr.getValue(ctx);
		assertThat(value).isEqualTo(Color.orange);
		assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
				expr.setValue(ctx, Color.blue))
			.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL));
	}

	@Test
	public void testScenario_AddingYourOwnPropertyResolvers_2() throws Exception {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Use the standard evaluation context
		StandardEvaluationContext ctx = new StandardEvaluationContext();

		ctx.addPropertyAccessor(new VegetableColourAccessor());
		Expression expr = parser.parseRaw("pea");
		Object value = expr.getValue(ctx);
		assertThat(value).isEqualTo(Color.green);

		assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
				expr.setValue(ctx, Color.blue))
			.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL));
	}

	/**
	 * Regardless of the current context object, or root context object, this resolver can tell you what colour a fruit is !
	 * It only supports property reading, not writing.  To support writing it would need to override canWrite() and write()
	 */
	private static class FruitColourAccessor implements PropertyAccessor {

		private static Map<String,Color> propertyMap = new HashMap<>();

		static {
			propertyMap.put("banana",Color.yellow);
			propertyMap.put("apple",Color.red);
			propertyMap.put("orange",Color.orange);
		}

		/**
		 * Null means you might be able to read any property, if an earlier property resolver hasn't beaten you to it
		 */
		@Override
		public Class<?>[] getSpecificTargetClasses() {
			return null;
		}

		@Override
		public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
			return propertyMap.containsKey(name);
		}

		@Override
		public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
			return new TypedValue(propertyMap.get(name));
		}

		@Override
		public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
			return false;
		}

		@Override
		public void write(EvaluationContext context, Object target, String name, Object newValue)
				throws AccessException {
		}

	}

	/**
	 * Regardless of the current context object, or root context object, this resolver can tell you what colour a vegetable is !
	 * It only supports property reading, not writing.
	 */
	private static class VegetableColourAccessor implements PropertyAccessor {

		private static Map<String,Color> propertyMap = new HashMap<>();

		static {
			propertyMap.put("carrot",Color.orange);
			propertyMap.put("pea",Color.green);
		}

		/**
		 * Null means you might be able to read any property, if an earlier property resolver hasn't beaten you to it
		 */
		@Override
		public Class<?>[] getSpecificTargetClasses() {
			return null;
		}

		@Override
		public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
			return propertyMap.containsKey(name);
		}

		@Override
		public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
			return new TypedValue(propertyMap.get(name));
		}

		@Override
		public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
			return false;
		}

		@Override
		public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {
		}

	}

}


text:
namespace Antlr.Runtime
{
    public class AstParserRuleReturnScope<TTree, TToken> : ParserRuleReturnScope<TToken>, IAstRuleReturnScope<TTree>, IAstRuleReturnScope
    {
        private TTree _tree;

        public TTree Tree
        {
            get
            {
                return _tree;
            }

            set
            {
                _tree = value;
            }
        }

        object IAstRuleReturnScope.Tree
        {
            get
            {
                return Tree;
            }
        }
    }
}


text:
	#pragma import on
#endif

PP_Begin_Namespace_PowerPlant

// ===========================================================================
//		¥ LUDPEndpoint												[abstract]
// ===========================================================================
//	An abstract base class for UDP endpoints. UDP is the sessionless
//	protocol of the Internet, and is used by a handful of protocols such
//	as NTP (network time protocol).
//
//	In PowerPlant, there are two subclasses of LUDPEndpoint, named
//	LMacUDPEndpoint and LOpenTptUDPEndpoint. The appropriate class is
//	created automatically when you call UNetworkFactory::CreateUDPEndpoint.

class LUDPEndpoint : public LEndpoint {

public:
								LUDPEndpoint();
	virtual						~LUDPEndpoint();

	// UDP datagram messaging

	virtual void				SendPacketData(
										LInternetAddress&		inRemoteHost,
										void*					inData,
										UInt32					inDataSize) = 0;
	virtual bool				ReceiveFrom(
										LInternetAddress&		outRemoteAddress,
										void*					outDataBuffer,
										UInt32&					ioDataSize,
										UInt32					inTimeoutTicks = Timeout_None) = 0;

};

PP_End_Namespace_PowerPlant

#if PP_Uses_Pragma_Import
	#pragma import reset
#endif

#endif


text:
<!DOCTYPE html>

    <x-lotsa-blocks>

    </lotsa-blocks>


text:
using Xunit;

namespace System.Test
{
    public static class SpanConstructorTest
    {
        [SkippableFact]
        public static void Span_ctor_with_array_and_negative_length_throws()
        {
            var bytes = new byte[10];

            var argExcept = Assert.ThrowsAny<ArgumentOutOfRangeException>(() =>
            {
                _ = new Span<byte>(bytes, start: 0, length: -1);
            });
            Skip.IfNot("length" == argExcept.ParamName, "https://github.com/dotnet/corefx/issues/36014");
            Assert.Equal("length", argExcept.ParamName);
        }

        [SkippableFact]
        public static unsafe void Span_ctor_with_pointer_and_negative_length_throws()
        {
            var bytes = stackalloc byte[10];

            var argExcept = Assert.ThrowsAny<ArgumentOutOfRangeException>(() =>
            {
                _ = new Span<byte>(bytes, length: -1);
            });
            Skip.IfNot("length" == argExcept.ParamName, "https://github.com/dotnet/corefx/issues/36014");
            Assert.Equal("length", argExcept.ParamName);
        }
    }
}


text:
using System.Diagnostics;
using System.Security;

namespace System.Numerics
{
    // ATTENTION: always pass BitsBuffer by reference,
    // it's a structure for performance reasons. Furthermore
    // it's a mutable one, so use it only with care!

    internal static partial class BigIntegerCalculator
    {
        // To spare memory allocations a buffer helps reusing memory!
        // We just create the target array twice and switch between every
        // operation. In order to not compute unnecessarily with all those
        // leading zeros we take care of the current actual length.

        internal struct BitsBuffer
        {
            private uint[] _bits;
            private int _length;

            public BitsBuffer(int size, uint value)
            {
                Debug.Assert(size >= 1);

                _bits = new uint[size];
                _length = value != 0 ? 1 : 0;

                _bits[0] = value;
            }

            public BitsBuffer(int size, uint[] value)
            {
                Debug.Assert(value != null);
                Debug.Assert(size >= ActualLength(value));

                _bits = new uint[size];
                _length = ActualLength(value);

                Array.Copy(value, 0, _bits, 0, _length);
            }

            public unsafe void MultiplySelf(ref BitsBuffer value,
                                            ref BitsBuffer temp)
            {
                Debug.Assert(temp._length == 0);
                Debug.Assert(_length + value._length <= temp._bits.Length);

                // Executes a multiplication for this and value, writes the
                // result to temp. Switches this and temp arrays afterwards.

                fixed (uint* b = _bits, v = value._bits, t = temp._bits)
                {
                    if (_length < value._length)
                    {
                        Multiply(v, value._length,
                                 b, _length,
                                 t, _length + value._length);
                    }
                    else
                    {
                        Multiply(b, _length,
                                 v, value._length,
                                 t, _length + value._length);
                    }
                }

                Apply(ref temp, _length + value._length);
            }

            public unsafe void SquareSelf(ref BitsBuffer temp)
            {
                Debug.Assert(temp._length == 0);
                Debug.Assert(_length + _length <= temp._bits.Length);

                // Executes a square for this, writes the result to temp.
                // Switches this and temp arrays afterwards.

                fixed (uint* b = _bits, t = temp._bits)
                {
                    Square(b, _length,
                           t, _length + _length);
                }

                Apply(ref temp, _length + _length);
            }

            public void Reduce(ref FastReducer reducer)
            {
                // Executes a modulo operation using an optimized reducer.
                // Thus, no need of any switching here, happens in-line.

                _length = reducer.Reduce(_bits, _length);
            }

            public unsafe void Reduce(uint[] modulus)
            {
                Debug.Assert(modulus != null);

                // Executes a modulo operation using the divide operation.
                // Thus, no need of any switching here, happens in-line.

                if (_length >= modulus.Length)
                {
                    fixed (uint* b = _bits, m = modulus)
                    {
                        Divide(b, _length,
                               m, modulus.Length,
                               null, 0);
                    }

                    _length = ActualLength(_bits, modulus.Length);
                }
            }

            public unsafe void Reduce(ref BitsBuffer modulus)
            {
                // Executes a modulo operation using the divide operation.
                // Thus, no need of any switching here, happens in-line.

                if (_length >= modulus._length)
                {
                    fixed (uint* b = _bits, m = modulus._bits)
                    {
                        Divide(b, _length,
                               m, modulus._length,
                               null, 0);
                    }

                    _length = ActualLength(_bits, modulus._length);
                }
            }

            public void Overwrite(ulong value)
            {
                Debug.Assert(_bits.Length >= 2);

                if (_length > 2)
                {
                    // Ensure leading zeros
                    Array.Clear(_bits, 2, _length - 2);
                }

                uint lo = unchecked((uint)value);
                uint hi = (uint)(value >> 32);

                _bits[0] = lo;
                _bits[1] = hi;
                _length = hi != 0 ? 2 : lo != 0 ? 1 : 0;
            }

            public void Overwrite(uint value)
            {
                Debug.Assert(_bits.Length >= 1);

                if (_length > 1)
                {
                    // Ensure leading zeros
                    Array.Clear(_bits, 1, _length - 1);
                }

                _bits[0] = value;
                _length = value != 0 ? 1 : 0;
            }

            public uint[] GetBits()
            {
                return _bits;
            }

            public int GetSize()
            {
                return _bits.Length;
            }

            public int GetLength()
            {
                return _length;
            }

            public void Refresh(int maxLength)
            {
                Debug.Assert(_bits.Length >= maxLength);

                if (_length > maxLength)
                {
                    // Ensure leading zeros
                    Array.Clear(_bits, maxLength, _length - maxLength);
                }

                _length = ActualLength(_bits, maxLength);
            }

            private void Apply(ref BitsBuffer temp, int maxLength)
            {
                Debug.Assert(temp._length == 0);
                Debug.Assert(maxLength <= temp._bits.Length);

                // Resets this and switches this and temp afterwards.
                // The caller assumed an empty temp, the next will too.

                Array.Clear(_bits, 0, _length);

                uint[] t = temp._bits;
                temp._bits = _bits;
                _bits = t;

                _length = ActualLength(_bits, maxLength);
            }
        }
    }
}


text:
package nl.acidcats.tumblrlikes.util.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import org.greenrobot.greendao.database.Database;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import nl.acidcats.tumblrlikes.data.repo.photo.store.entity.DaoMaster;
import nl.acidcats.tumblrlikes.datalib.BuildConfig;
import nl.acidcats.tumblrlikes.util.database.migration.Migration;
import nl.acidcats.tumblrlikes.util.database.migration.MigrationV5;

/**
 * Created by stephan on 18/04/2017.
 */

public class DbOpenHelper extends DaoMaster.OpenHelper {
    private static final String TAG = DbOpenHelper.class.getSimpleName();

    private final Context _context;
    private final boolean _debug = BuildConfig.DEBUG;

    public DbOpenHelper(Context context, String name) {
        super(context, name);

        _context = context;
    }

    public DbOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);

        _context = context;
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        if (_debug) Log.d(TAG, "onUpgrade: from " + oldVersion + " to " + newVersion);

        for (Migration migration : getMigrations()) {
            if (migration.getVersion() <= newVersion) {
                migration.runMigration(db);
            }
        }

//        LocalBroadcastManager.getInstance(_context).sendBroadcast(new Intent(Broadcasts.DATABASE_RESET));
    }

    private List<Migration> getMigrations() {
        List<Migration> migrations = new ArrayList<>();
        migrations.add(new MigrationV5());

        // Sorting just to be safe, in case other people add migrations in the wrong order.
        Collections.sort(migrations, (m1, m2) -> m1.getVersion().compareTo(m2.getVersion()));

        return migrations;
    }

}


text:
package org.jetbrains.plugins.scala
package lang
package psi
package api
package toplevel
package typedef

import com.intellij.psi._
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.search.{LocalSearchScope, SearchScope}
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.util._
import org.jetbrains.plugins.scala.lang.psi.api.base.ScPrimaryConstructor
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScBlock
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunction
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.ScClassParameter
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.templates.{ScExtendsBlock, ScTemplateBody}
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaFileImpl
import org.jetbrains.plugins.scala.lang.psi.stubs.ScMemberOrLocal

import scala.collection.mutable.ArrayBuffer

/**
  * @author Alexander Podkhalyuzin
  * Date: 04.05.2008
  */
trait ScMember extends ScalaPsiElement with ScModifierListOwner with PsiMember {
  def getContainingClass: PsiClass = containingClass

  def isPrivate: Boolean = hasModifierPropertyScala("private")

  def isProtected: Boolean = hasModifierPropertyScala("protected")

  def isPublic: Boolean = !isPrivate && !isProtected

  def isInstance: Boolean = !isLocal

  /**
    * getContainingClassStrict(bar) == null in
    *
    * `object a { def foo { def bar = 0 }}`
    */
  def containingClass: ScTemplateDefinition = {
    val stub: StubElement[_ <: PsiElement] = this match {
      case file: PsiFileImpl => file.getStub
      case st: ScalaStubBasedElementImpl[_] => st.getStub
      case _ => null
    }
    stub match {
      case m: ScMemberOrLocal if m.isLocal => return null
      case _ =>
    }
    val context = getContext
    (getContainingClassLoose, this) match {
      case (null, _) => null
      case (found, fun: ScFunction) if fun.syntheticContainingClass.isDefined => fun.syntheticContainingClass.get
      case (found, fun: ScFunction) if fun.isSynthetic => found
      case (found, _: ScClassParameter | _: ScPrimaryConstructor) => found
      case (found, _) if context == found.extendsBlock || found.extendsBlock.templateBody.contains(context) ||
        found.extendsBlock.earlyDefinitions.contains(context) => found
      case (found, _) => null // See SCL-3178
    }
  }

  def getContainingClassLoose: ScTemplateDefinition = {
    val stub: StubElement[_ <: PsiElement] = this match {
      case file: PsiFileImpl => file.getStub
      case st: ScalaStubBasedElementImpl[_] => st.getStub
      case _ => null
    }
    if (stub != null) {
      stub.getParentStubOfType(classOf[ScTemplateDefinition])
    } else {
      child match {
        // TODO is all of this mess still necessary?!
        case c: ScClass if c.isCase =>
          this match {
            case fun: ScFunction if fun.isSyntheticApply || fun.isSyntheticUnapply ||
              fun.isSyntheticUnapplySeq =>
              //this is special case for synthetic apply and unapply methods
              ScalaPsiUtil.getCompanionModule(c) match {
                case Some(td) => return td
                case _ =>
              }
            case _ =>
          }
        case _ =>
      }
      PsiTreeUtil.getContextOfType(this, true, classOf[ScTemplateDefinition])
    }
  }

  def isLocal: Boolean = {
    val stub: StubElement[_ <: PsiElement] = this match {
      case file: PsiFileImpl => file.getStub
      case st: ScalaStubBasedElementImpl[_] => st.getStub
      case _ => null
    }
    stub match {
      case memberOrLocal: ScMemberOrLocal =>
        return memberOrLocal.isLocal
      case _ =>
    }
    containingClass == null
  }

  override def hasModifierProperty(name: String) = {
    if (name == PsiModifier.PUBLIC) {
      !hasModifierProperty("private") && !hasModifierProperty("protected")
    } else if (name == PsiModifier.STATIC) {
      containingClass.isInstanceOf[ScObject]
    } else super.hasModifierProperty(name)
  }

  protected def isSimilarMemberForNavigation(m: ScMember, isStrict: Boolean) = false

  override def getNavigationElement: PsiElement = getContainingFile match {
    case s: ScalaFileImpl if s.isCompiled => getSourceMirrorMember
    case _ => this
  }

  private def getSourceMirrorMember: ScMember = getParent match {
    case tdb: ScTemplateBody => tdb.getParent match {
      case eb: ScExtendsBlock => eb.getParent match {
        case td: ScTypeDefinition => td.getNavigationElement match {
          case c: ScTypeDefinition =>
            val membersIterator = c.members.iterator
            val buf: ArrayBuffer[ScMember] = new ArrayBuffer[ScMember]
            while (membersIterator.hasNext) {
              val member = membersIterator.next()
              if (isSimilarMemberForNavigation(member, isStrict = false)) buf += member
            }
            if (buf.length == 0) this
            else if (buf.length == 1) buf(0)
            else {
              val filter = buf.filter(isSimilarMemberForNavigation(_, isStrict = true))
              if (filter.length == 0) buf(0)
              else filter(0)
            }
          case _ => this
        }
        case _ => this
      }
      case _ => this
    }
    case c: ScTypeDefinition if this.isInstanceOf[ScPrimaryConstructor] => //primary constructor
      c.getNavigationElement match {
        case td: ScClass =>
          td.constructor match {
            case Some(constr) => constr
            case _ => this
          }
        case _ => this
      }
    case _ => this
  }

  abstract override def getUseScope: SearchScope = {
    ScalaPsiUtil.intersectScopes(super.getUseScope, this match {
      case m if m.getModifierList != null && m.getModifierList.accessModifier.exists(mod => mod.isPrivate && mod.isThis) =>
        Option(m.containingClass).map(new LocalSearchScope(_))
      case m if m.getModifierList != null && m.getModifierList.accessModifier.exists(_.isUnqualifiedPrivateOrThis) =>
        Option(m.containingClass).map(ScalaPsiUtil.withCompanionSearchScope)
      case cp: ScClassParameter => Option(super.getUseScope)
      case _ =>
        val blockOrMember = PsiTreeUtil.getContextOfType(this, true, classOf[ScBlock], classOf[ScMember])
        blockOrMember match {
          case null => None
          case block: ScBlock => Some(new LocalSearchScope(block))
          case member: ScMember => Some(member.getUseScope)
        }
    })
  }
}


text:
const { expect } = require('chai');
const path = require('path');
const { render, renderSync } = require('../src');
const { normalizePath } = require('../src/util');
const { types } = require('node-sass');

const ieHacksFile = path.join(__dirname, 'sass', 'ie-hacks.scss');

function verifyIeHacks(rendered, sourceFile) {
  expect(rendered.vars).to.exist;
  expect(rendered.vars).to.have.property('global');
  expect(rendered.vars.global).to.have.property('$my');

  expect(rendered.vars.global.$my.type).to.equal('SassString');
  expect(rendered.vars.global.$my.sources).to.have.length(1);
  expect(rendered.vars.global.$my.sources[0]).to.equal(normalizePath(sourceFile));
  expect(rendered.vars.global.$my.declarations).to.have.length(1);
  expect(rendered.vars.global.$my.declarations[0].expression).to.equal(`'variable'`);
  expect(rendered.vars.global.$my.declarations[0].flags.global).to.equal(false);
  expect(rendered.vars.global.$my.declarations[0].flags.default).to.equal(false);
  expect(rendered.vars.global.$my.value).to.equal('variable');
}

describe('ie-hacks', () => {
  describe('sync', () => {
    it('should extract all variables', () => {
      const rendered = renderSync({ file: ieHacksFile });
      verifyIeHacks(rendered, ieHacksFile);
    });
  });

  describe('async', () => {
    it('should extract all variables', () => {
      return render({ file: ieHacksFile })
      .then(rendered => {
        verifyIeHacks(rendered, ieHacksFile);
      });
    });
  });
});


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>Mahdi Farang</title>
  <meta name="description" content="This is the portfolio of Mahdi Farang, an UI designer.">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="manifest" href="site.webmanifest">
  <link rel="apple-touch-icon" href="icon.png">

  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/font.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
  <link rel="stylesheet" href="css/magnific-popup.css">
  <link rel="stylesheet" href="css/pace-theme-center-simple.css">

  <link rel="stylesheet" href="css/tailwind.min.css">
  <link rel="stylesheet" href="css/main.css">

                Mahdi Farang

                The Portfolio

                            I'm Mahdi Farang, UI designer from Tehran, Iran. simplicity and briefness are my concern in design. I like designing app, web and words(=Typography). I spend some time on photography and graphic too.

                                Have a look around and don't hesitate to contact me;

                                +98 912 7052181

                                mahdi.farang[@]gmail.com

                Projects

M-F

current site

ArtGalleries

visual arts in Tehran

Mapfa

entertainment store

                            most

                             recent

V-Brands

fashion market

ArtShop

online art market

                Gallery

                        →

                    see more shots in detailed page for every projects

                Resume

Professional History

Mapfa

UI Designer - 2018

                           MAPFA is a company that provides VAS solutions for MNOs to enable them deliver various differentiated Value Added Services to their subscribers.

ArtGalleries

Founder/Front Developer - 2016/2017

                           ArtGalleries is an online platform for discovering art. Collect and buy art you'll love, featuring visual art exhibition in galleries accross Iran.

SimiaService

Designer/Front Developer - 2015

                           Simia Service is an online platform that offers online retailing, administrative affairs, and online counselling. The online retailer sells groceries and crafted gifts to its users. The counselling platform offers psychology-based counselling to its users.

pHow

Graphic Designer - 2014

                           pHow is an online how-to guide with a large number of articles in persian language offering step-by-step instructions. pHow articles and videos are created by freelancers and cover a wide variety of topics organized into a hierarchy of categories.

Education

M.A. in Urban Design

Islamic Azad University Central Tehran Branch - 2013

B.S. in Urbanism

Tehran University of Art - 2009

Skills

Coding

                           expert: HTML, CSS, Sass (I can convert almost every design into html/css)

                           familiar: JavaScript, JQuery

CSS Frameworks

                           expert: Bootstrap, Tailwind

Primary Tools

                           expert: Figma, Sketch, Framer, Atomic, Flinto, Photoshop, Zeplin

                           familiar: Origami

CMS

                           expert: Wordpress (run and maintain wordpress site, customize plugin and themes)

Team Working

                           Agile (Scrum Methodology), Task Management (Jira, Trello)

Award

IWMF

                           Web Design Final Candidate for artgalleries.ir - 2016

                Made by me with

                 &

                2018 © Mahdi Farang


text:
#if GOOGLE_CUDA

#define EIGEN_USE_GPU

#include "tensorflow/core/kernels/dense_update_ops.h"

#include "tensorflow/core/framework/register_types.h"

namespace tensorflow {

typedef Eigen::GpuDevice GPUDevice;

#define DEFINE_GPU_KERNELS(T)                              \
  template struct functor::DenseUpdate<GPUDevice, T, ADD>; \
  template struct functor::DenseUpdate<GPUDevice, T, SUB>;
TF_CALL_GPU_NUMBER_TYPES(DEFINE_GPU_KERNELS);
#undef DEFINE_GPU_KERNELS

#define DEFINE_GPU_KERNELS(T) \
  template struct functor::DenseUpdate<GPUDevice, T, ASSIGN>;
TF_CALL_GPU_ALL_TYPES(DEFINE_GPU_KERNELS);
#undef DEFINE_GPU_KERNELS

}  // end namespace tensorflow

#endif  // GOOGLE_CUDA


text:
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <id>com.deviget</id>
    <name>Hello Deviget</name>
    <version>1.0</version>
    <publisher>matyax</publisher>
    <url>http://deviget.com</url>
    <description>undefined</description>
    <copyright>2015 by matyax</copyright>
    <icon>appicon.png</icon>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>true</analytics>
    <guid>cb76d8a9-d774-46e0-9999-97450bc8ee1c</guid>
    <property name="ti.ui.defaultunit" type="string">dp</property>
    <ios>
        <plist>
            <dict>
                <key>UISupportedInterfaceOrientations~iphone</key>
                <array>
                    <string>UIInterfaceOrientationPortrait</string>
                </array>
                <key>UISupportedInterfaceOrientations~ipad</key>
                <array>
                    <string>UIInterfaceOrientationPortrait</string>
                    <string>UIInterfaceOrientationPortraitUpsideDown</string>
                    <string>UIInterfaceOrientationLandscapeLeft</string>
                    <string>UIInterfaceOrientationLandscapeRight</string>
                </array>
                <key>UIRequiresPersistentWiFi</key>
                <false/>
                <key>UIPrerenderedIcon</key>
                <false/>
                <key>UIStatusBarHidden</key>
                <false/>
                <key>UIStatusBarStyle</key>
                <string>UIStatusBarStyleDefault</string>
            </dict>
        </plist>
    </ios>
    <android xmlns:android="http://schemas.android.com/apk/res/android"/>
    <mobileweb>
        <precache/>
        <splash>
            <enabled>true</enabled>
            <inline-css-images>true</inline-css-images>
        </splash>
        <theme>default</theme>
    </mobileweb>
    <modules>
        <module platform="commonjs">ti.cloud</module>
    </modules>
    <deployment-targets>
        <target device="android">true</target>
        <target device="ipad">true</target>
        <target device="iphone">true</target>
        <target device="mobileweb">false</target>
        <target device="windows">false</target>
    </deployment-targets>
    <sdk-version>5.1.0.v20151002003633</sdk-version>
    <plugins>
        <plugin version="1.0">ti.alloy</plugin>
    </plugins>
    <property name="appc-app-id" type="string">564154ffa7adb5833cd2e44e</property>
    <property name="acs-authbase-url-development" type="string">https://secure-identity.cloud.appcelerator.com</property>
    <property name="acs-base-url-development" type="string">https://api.cloud.appcelerator.com</property>
    <property name="acs-oauth-secret-development" type="string">WSu3UCoQTmgUarHGb7mvR4ZjEve2qdgK</property>
    <property name="acs-oauth-key-development" type="string">hDFL5Qx5SnBUgYKzaQxQLEDdahqOWQoj</property>
    <property name="acs-api-key-development" type="string">MnH6SeWMlefgxDNN3iCV41XWOtO5xoao</property>
    <property name="acs-username-development" type="string">appc_app_user_dev</property>
    <property name="acs-password-development" type="string">Ja8eNPkyuEFFFmByNj</property>
    <property name="acs-authbase-url-production" type="string">https://secure-identity.cloud.appcelerator.com</property>
    <property name="acs-base-url-production" type="string">https://api.cloud.appcelerator.com</property>
    <property name="acs-oauth-secret-production" type="string">jrnnaXz6FVAVSyyMWN1L3w5cLvELKhPn</property>
    <property name="acs-oauth-key-production" type="string">0Jj3WLckEMBRech6MX5YNTAZYUKbxeSX</property>
    <property name="acs-api-key-production" type="string">D35NMVgL7JaYeUvOS1GRC4RBnqWThSAO</property>
    <property name="acs-username-production" type="string">appc_app_user</property>
    <property name="acs-password-production" type="string">W9nAx4rEddsD2x0TgZ</property>
    <property name="appc-org-id" type="string">100004740</property>
    <property name="appc-creator-user-id" type="string">cddca54a-dc90-4a01-869e-9182f7b7e00e</property>
</ti:app>


text:
#include <string.h>

#include "httpd.h"
#include "http_config.h"
#include "http_log.h"
#include "ap_config.h"
#include "ap_release.h"
#include "apr_strings.h"

/* Bad Apache polluting global defines! Bad bad bad! */
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION

/* Oh, hi there autoconf */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "mod_secure_headers.h"

int secure_headers_add(request_rec *r) {
	mod_cfg *c;
	mod_server_cfg *s;
	char *stsHeaderValue;

	ap_log_rerror(__FILE__, __LINE__, APLOG_DEBUG, 0, r, "Processing request for %s", r->filename);

	if(!r->handler) {
		return DECLINED;
	}

	c = (mod_cfg*)ap_get_module_config(r->per_dir_config, &secure_headers_module);
	s = (mod_server_cfg*)ap_get_module_config(r->server->module_config, &secure_headers_module);

	/* Do we add the X-Content-Type-Options header? */
	if(!c->mimeSniff) {
		ap_log_rerror(__FILE__, __LINE__, APLOG_DEBUG, 0, r, "Adding header X-Content-Type-Options: nosniff");
		apr_table_add(r->headers_out, "X-Content-Type-Options", "nosniff");
	}

	/* Do we add Strict-Transport-Security? */
	if(s->stsTimeout > 0) {
		stsHeaderValue = apr_psprintf(r->pool, "max-age=%d", s->stsTimeout);
		if(s->includeSubDomains) {
			stsHeaderValue = apr_psprintf(r->pool, "%s; includeSubDomains", stsHeaderValue);
		}
		ap_log_rerror(__FILE__, __LINE__, APLOG_DEBUG, 0, r, "Adding header Strict-Transport-Security: %s", stsHeaderValue);
		apr_table_add(r->headers_out, "Strict-Transport-Security", stsHeaderValue);
	}

	return OK;
}

void register_hooks(apr_pool_t *pool) {
	ap_hook_handler(secure_headers_add, NULL, NULL, APR_HOOK_MIDDLE);
}

const char *readparam(cmd_parms *cmd, void *cfg, const char *value) {
	mod_cfg *c = (mod_cfg*)cfg;
	//int i;
	//char d;

	if(0 == apr_strnatcmp(cmd->directive->directive, OBEY_CONTENT_TYPE)) {
		if(0 == apr_strnatcasecmp(value, "On")) {
			c->mimeSniff = FALSE; /* ObeyContentType On => Disallow MIME sniffing */
		}
		else if(0 == apr_strnatcasecmp(value, "Off")) {
			c->mimeSniff = TRUE;
		}
		else {
			return apr_psprintf(cmd->pool, "MOD_SECURE_HEADERS: Invalid argument to %s - must be 'On' or 'Off'", OBEY_CONTENT_TYPE);
		}
	}
	else {
		return apr_psprintf(cmd->pool, "MOD_SECURE_HEADERS: Invalid directive '%s'", cmd->directive->directive);
	}

	return NULL;
}

const char *readparamsvr(cmd_parms *cmd, void *cfg, const char *value) {
	mod_server_cfg *c = (mod_server_cfg*)cfg;
	int i;

	if(0 == apr_strnatcmp(cmd->directive->directive, STS_TIMEOUT)) {
		i = atoi(value);
		if(i >= 0) {
			c->stsTimeout = (unsigned int)i;
		}
		else {
			return apr_psprintf(cmd->pool, "MOD_SECURE_HEADERS: Invalid %s (%s) specified -- Must be 0 or greater", STS_TIMEOUT, value);
		}
	}
	else if(0 == apr_strnatcmp(cmd->directive->directive, STS_SUBDOMAINS)) {
		if(0 == apr_strnatcasecmp(value, "On")) {
			c->includeSubDomains = TRUE;
		}
		else if(0 == apr_strnatcasecmp(value, "Off")) {
			c->includeSubDomains = FALSE;
		}
		else {
			return apr_psprintf(cmd->pool, "MOD_SECURE_HEADERS: Invalid argument to %s - must be 'On' or 'Off'", STS_SUBDOMAINS);
		}
	}
	else {
		return apr_psprintf(cmd->pool, "MOD_SECURE_HEADERS: Invalid server directive '%s'", cmd->directive->directive);
	}

	return NULL;
}

void *create_dir_config(apr_pool_t *p, char *path) {
	mod_cfg *c = apr_pcalloc(p, sizeof(mod_cfg));

	c->mimeSniff = MIME_SNIFF_DEFAULT;

	return c;
}

void *merge_dir_config(apr_pool_t *p, void *BASE, void *ADD) {
	mod_cfg *c = apr_pcalloc(p, sizeof(mod_cfg));
	mod_cfg *base = (mod_cfg*)BASE;
	mod_cfg *add = (mod_cfg*)ADD;

	c->mimeSniff = add->mimeSniff != MIME_SNIFF_DEFAULT ? add->mimeSniff : base->mimeSniff;

	return c;
}

void *create_server_config(apr_pool_t *p, server_rec *s) {
	mod_server_cfg *c = apr_pcalloc(p, sizeof(mod_server_cfg));

	c->stsTimeout = STS_TIMEOUT_DEFAULT;
	c->includeSubDomains = STS_SUBDOMAINS_DEFAULT;

	return c;
}

void *merge_server_config(apr_pool_t *p, void *BASE, void *ADD) {
	mod_server_cfg *c = apr_pcalloc(p, sizeof(mod_server_cfg));
	mod_server_cfg *base = (mod_server_cfg*)BASE;
	mod_server_cfg *add = (mod_server_cfg*)ADD;

	c->stsTimeout = add->stsTimeout != STS_TIMEOUT_DEFAULT ? add->stsTimeout : base->stsTimeout;
	c->includeSubDomains = add->includeSubDomains != STS_SUBDOMAINS_DEFAULT ? add->includeSubDomains : base->includeSubDomains;

	return c;
}

/*
apr_byte_t isSSL(const request_rec *r) {
#ifdef APACHE2_0
	if(0 == apr_strnatcasecmp(ap_http_method(r), "https")) {
#else
	if(0 == apr_strnatcasecmp(ap_http_scheme(r), "https")) {
#endif
		return TRUE;
	}
	return FALSE;
}
*/

const command_rec cmds [] = {
	AP_INIT_TAKE1(OBEY_CONTENT_TYPE, readparam, (void*)APR_OFFSETOF(mod_cfg, mimeSniff), ACCESS_CONF, "Define whether to force browsers to trust the Content-Type header"),
	AP_INIT_TAKE1(STS_TIMEOUT, readparamsvr, (void*)APR_OFFSETOF(mod_server_cfg, stsTimeout), RSRC_CONF, "Define the Strict-Transport-Security timeout"),
	AP_INIT_TAKE1(STS_SUBDOMAINS, readparamsvr, (void*)APR_OFFSETOF(mod_server_cfg, includeSubDomains), RSRC_CONF, "Define whether Strict-Transport-Security includes sub-domains"),
	{ NULL }
};

module AP_MODULE_DECLARE_DATA secure_headers_module = {
	STANDARD20_MODULE_STUFF,
	create_dir_config,
	merge_dir_config,
	create_server_config,
	merge_server_config,
	cmds,
	register_hooks
};


text:
An [AWS Lambda](http://aws.amazon.com/lambda) template for building Alexa Skills.
This template provides the shell that can be used to set up a working Alexa Skill on AWS and the Amazon Echo.

Additionally, the template supports the following development practices through gulp:

| Available tasks         | Description                                                      |
| ----------------------- | ---------------------------------------------------------------- |
| assets                  | Compile/move assets files to dist                                |
| build-custom-slot-types | Build the custom slot types from source ** Aliases: slots        |
| build-intent-schema     | Build the intent schema from source ** Aliases: intent, intents  |
| build-lambda-code       | Process source and create dist.zip file to upload to AWS lambda ** Aliases: build|
| build-utterances        | Build the utterances from source ** Aliases: utterances          |
| clean                   | Clean out the dist folder and remove the compiled zip file       |
| config                  | Compile/move config files to dist                                |
| default                 | [help]                                                           |
| help                    | Display this help text.                                          |
| js                      | Compile/move javascript files to dist                            |
| lint                    | Lints all server side js                                         |
| node-mods               | Install npm packages to dist, ignoring devDependencies           |
| push-lambda-code        | Process source then upload to AWS lambda ** Aliases: push        |
| quick-push-lambda-code  | Process source then upload to AWS lambda without updating modules ** Aliases: quick, quick-push|
| test-lambda             | Run unit tests against AWS lambda ** Aliases: lambda             |
| test-local              | Run unit tests against local server ** Aliases: test             |
| upload                  | Upload zip file to lambda                                        |
| vendor                  | Compile/move vendor files to dist                                |
| watch                   | [watch-lint, watch-test]                                         |
| watch-lint              | Watch for changed files and run lint of the file that has changed|
| watch-test              | Watch for changed files and run unit tests when a file changes   |
| zip                     | Zip the dist directory                                           |

## Setup
This skill will run locally to support development and testing. When ready to push the code to AWS Lambda to test as an
actual Alexa skill, AWS Lambda needs to be configured and code pushed to it, and then the Alexa Skill needs to be set up.
Prior to the following steps, you will need to set up an
[AWS Developer account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) and get set up on the
[AWS Free Tier](https://aws.amazon.com/free/) to enable development, testing, and hosting for free for 12 months.

After successful sign-up of an AWS account, perform the following setups.

### AWS Template Installation
1. Copy from Template using `git://github.com/rickwargo/template.git`.
2. Remove node_modules and npm install in dest directory
3. gulp lint
4. gulp test (may need to test this)
5. edit config
6. node bin/createActivityLog.js (if using)
7. develop app
8. gulp build

### AWS Lambda Setup
1. Go to the [AWS Console](https://console.aws.amazon.com/console/home) and click on the [Lambda](https://console.aws.amazon.com/lambda/home) link. Note: ensure you are in `us-east` or you won't be able to use Alexa with Lambda.
2. Click on the [Create a Lambda Function](https://console.aws.amazon.com/lambda/home?region=us-east-1#create) or `Get Started Now` button.
3. The first step is to `Select blueprint`. Click on the `Skip` button to move on as we will start with an empty blueprint.
4. Name the Lambda Function with a name significant to your skill. This name will later be recorded in the config-lambda.js file.
5. Optionally add a description for the lambda function.
5. Select the runtime as `Node.js`.
6. In the root template directory, execute `gulp build-lambda-code`. This will lint the code, perform local unit tests, download node modules necessary for skill execution, build the intent schema, sample utterances, and custom slot types, and finally move all files to a dist directory and create a zip of those files named `dist.zip`.
7. Select Code entry type as `Upload a .ZIP file` and then upload the .zip file to AWS Lambda.
8. Keep the Handler as `index.handler`. This is defined in the alexa-app vendor module in index.js.
9. Select `lambda_dynamo` as the Role, if using DynamoDB in your skill. Otherwise select `lambda_basic_execution` for Role.
10. Leave the Advanced settings as the defaults. Depending on execution time for your function, you may want to revisit the timeout setting.
11. Click `Next` and review the settings then click `Create Function`.
12. Click the `Event Sources` tab and select `Add event source`.
13. Set the Event Source type as `Alexa Skills Kit` and Enable it now. Click `Submit`.
14. Copy the ARN from the top right to be used later in the Alexa Skill Setup. It will look something similar to `arn:aws:lambda:us-east-1:100000012345:function:My-Awesome-Alexa-Skill`.

### Alexa Skill Setup
1. Go to the [Alexa Console](https://developer.amazon.com/edw/home.html) and click `Get Started` under Alexa Skills Kit and then click the `Add a New Skill` button in the top right.
2. Set the `name` of the new skill name and an appropriate `invocation name` - this is what is used to activate your skill.
3. Optionally, set the version number of the skill, I recommend a 3-part version such as 1.0.0.
4. Select `Lambda ARN (Amazon Resource Name)` for the `Endpoint` and paste the ARN copied from the above step. Click `Next`.
5. Copy the Intent Schema from `assets/speech/IntentSchema.json`. This file was created from source during the gulp build step above.
5. Create the Custom Slot Types (if any) using the information from `assets/speech/CustomSlotTypes.txt`. This file was created from source during the gulp build step above.
6. Copy the Sample Utterances from `assets/speech/SampleUtterances.txt`. This file was created from source during the gulp build step above. Click `Next`.

### Source Setup
1. Go back to the `Skill Information` tab and copy the `Application Id`. Paste the `Application Id` into `package.json` and `config/lambda-config.js`.
2. Add the AWS Function Name to `config/lambda-config.js`.
3. If the timeout is changed from the default of 3, adjust the setting in config/lambda-config.js
4. Fill out the `Description` tab. You can use icons in images folder as a start but copy with your own icons.

### Prepare for Testing on Echo
1. Update the lambda source zip file with this change by using `gulp build` and upload to lambda again. You can also use `gulp push-lambda-code` to build the zip file and upload it to AWS Lambda. This assumes your information has been stored in the environment or in the `~/.aws/credentials` file.
3. You are now able to start testing your sample skill on the Amazon Echo! You should be able to go to the [Echo webpage](http://echo.amazon.com/#skills) and see your skill enabled.
3. In order to test it, try to say some of the Sample Utterances you created.
4. Your skill is now saved and once you are finished testing you can continue to publish your skill. Make sure to pay close attention to the information in [Submitting an Alexa Skill for Certification](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/publishing-an-alexa-skill), especially the [Submission Checklist](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-submission-checklist).
5. At some point prior to Submitting for Certification, you will need to complete the information on the `Publishing Information` tab. This can be done now and saved.


text:
package models

/**
 * Country data representation (in terms of countryInfo service, not country as a location nor a feature).
 *
 * @author Amadeusz Kosik <akosik@semantive.com>
 *
 * @param geonameId       geonameId (can be used to find location of the country from features table).
 * @param iso2Code        two-letter ISO code of the country.
 * @param iso3Code        three-letter ISO code of the country.
 * @param isoNumeric      numeric ISO code of the country.
 * @param population      fips code of the country.
 * @param continentId     id of the continent the country is located in.
 * @param topLevelDomain  tld given to the country.
 * @param currencyCode    currency used in the country.
 */
case class Country(
  geonameId:        Int,
  iso2Code:         String,
  iso3Code:         String,
  isoNumeric:       String,
  fipsCode:         Option[String],
  population:       Long,
  continentId:      Int,
  topLevelDomain:   String,
  currencyCode:     String
  // fixMe: languages representation
  // fixMe: neighbours representation
) extends AbstractEntity


text:
import React from 'react';
import PropTypes from 'prop-types';
import { min as d3Min, max as d3Max, mean as d3Mean } from 'd3-array';
import { isoParse as parseDate } from 'd3-time-format';
import { line, curveLinear } from 'd3-shape';
import { scaleLinear } from 'd3-scale';

import { formatMetricSvg } from '../utils/string-utils';

const HOVER_RADIUS_MULTIPLY = 1.5;
const HOVER_STROKE_MULTIPLY = 5;
const MARGIN = 2;

export default class Sparkline extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.x = scaleLinear();
    this.y = scaleLinear();
    this.line = line()
      .x(d => this.x(d.date))
      .y(d => this.y(d.value));
  }

  initRanges(hasCircle) {
    // adjust scales and leave some room for the circle on the right, upper, and lower edge
    let circleSpace = MARGIN;
    if (hasCircle) {
      circleSpace += Math.ceil(this.props.circleRadius * HOVER_RADIUS_MULTIPLY);
    }

    this.x.range([MARGIN, this.props.width - circleSpace]);
    this.y.range([this.props.height - circleSpace, circleSpace]);
    this.line.curve(curveLinear);
  }

  getGraphData() {
    // data is of shape [{date, value}, ...] and is sorted by date (ASC)
    let { data } = this.props;

    this.initRanges(true);

    // Convert dates into D3 dates
    data = data.map(d => ({
      date: parseDate(d.date),
      value: d.value
    }));

    // determine date range
    let firstDate = this.props.first ? parseDate(this.props.first) : data[0].date;
    let lastDate = this.props.last ? parseDate(this.props.last) : data[data.length - 1].date;
    // if last prop is after last value, we need to add that difference as
    // padding before first value to right-align sparkline
    const skip = lastDate - data[data.length - 1].date;
    if (skip > 0) {
      firstDate -= skip;
      lastDate -= skip;
    }
    this.x.domain([firstDate, lastDate]);

    // determine value range
    const minValue = this.props.min !== undefined ? this.props.min : d3Min(data, d => d.value);
    const maxValue = this.props.max !== undefined
      ? Math.max(this.props.max, d3Max(data, d => d.value)) : d3Max(data, d => d.value);
    this.y.domain([minValue, maxValue]);

    const lastValue = data[data.length - 1].value;
    const lastX = this.x(lastDate);
    const lastY = this.y(lastValue);
    const min = formatMetricSvg(d3Min(data, d => d.value), this.props);
    const max = formatMetricSvg(d3Max(data, d => d.value), this.props);
    const mean = formatMetricSvg(d3Mean(data, d => d.value), this.props);
    const title = `Last ${Math.round((lastDate - firstDate) / 1000)} seconds, ` +
      `${data.length} samples, min: ${min}, max: ${max}, mean: ${mean}`;

    return {
      title, lastX, lastY, data
    };
  }

  getEmptyGraphData() {
    this.initRanges(false);
    const first = new Date(0);
    const last = new Date(15);
    this.x.domain([first, last]);
    this.y.domain([0, 1]);

    return {
      title: '',
      lastX: this.x(last),
      lastY: this.y(0),
      data: [
        {date: first, value: 0},
        {date: last, value: 0},
      ],
    };
  }

  render() {
    const dash = 5;
    const hasData = this.props.data && this.props.data.length > 0;
    const strokeColor = this.props.hovered && hasData
      ? this.props.hoverColor
      : this.props.strokeColor;
    const strokeWidth = this.props.strokeWidth * (this.props.hovered ? HOVER_STROKE_MULTIPLY : 1);
    const strokeDasharray = hasData ? undefined : `${dash}, ${dash}`;
    const radius = this.props.circleRadius * (this.props.hovered ? HOVER_RADIUS_MULTIPLY : 1);
    const fillOpacity = this.props.hovered ? 1 : 0.6;
    const circleColor = hasData && this.props.hovered ? strokeColor : strokeColor;
    const graph = hasData ? this.getGraphData() : this.getEmptyGraphData();

    return (
      <div title={graph.title}>
        <svg width={this.props.width} height={this.props.height}>
          <path
            className="sparkline"
            fill="none"
            stroke={strokeColor}
            strokeWidth={strokeWidth}
            strokeDasharray={strokeDasharray}
            d={this.line(graph.data)}
          />
          {hasData && <circle
            className="sparkcircle"
            cx={graph.lastX}
            cy={graph.lastY}
            fill={circleColor}
            fillOpacity={fillOpacity}
            stroke="none"
            r={radius}
          />}
        </svg>
      </div>
    );
  }
}

Sparkline.propTypes = {
  width: PropTypes.number,
  height: PropTypes.number,
  strokeColor: PropTypes.string,
  strokeWidth: PropTypes.number,
  hoverColor: PropTypes.string,
  circleRadius: PropTypes.number,
  hovered: PropTypes.bool,
  data: PropTypes.arrayOf(PropTypes.object),
};

Sparkline.defaultProps = {
  width: 80,
  height: 24,
  strokeColor: '#7d7da8',
  strokeWidth: 0.5,
  hoverColor: '#7d7da8',
  circleRadius: 1.75,
  hovered: false,
  data: [],
};


text:
/*
 * Created by SharpDevelop.
 * User: Acer
 * Date: 01/28/2017
 * Time: 1:05 PM
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
namespace NewAshAIO
{
	partial class AboutForm
	{
		/// <summary>
		/// Designer variable used to keep track of non-visual components.
		/// </summary>
		private System.ComponentModel.IContainer components = null;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.RichTextBox richTextBox1;
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.Label label5;

		/// <summary>
		/// Disposes resources used by the form.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent()
		{
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutForm));
			this.label1 = new System.Windows.Forms.Label();
			this.label4 = new System.Windows.Forms.Label();
			this.richTextBox1 = new System.Windows.Forms.RichTextBox();
			this.button1 = new System.Windows.Forms.Button();
			this.label5 = new System.Windows.Forms.Label();
			this.SuspendLayout();
			//
			// label1
			//
			this.label1.Location = new System.Drawing.Point(121, 9);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(100, 23);
			this.label1.TabIndex = 1;
			this.label1.Text = "Credits";
			this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
			//
			// label4
			//
			this.label4.Location = new System.Drawing.Point(39, 272);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(100, 23);
			this.label4.TabIndex = 4;
			this.label4.Text = "For Splatoon 2.12";
			//
			// richTextBox1
			//
			this.richTextBox1.Location = new System.Drawing.Point(12, 35);
			this.richTextBox1.Name = "richTextBox1";
			this.richTextBox1.ReadOnly = true;
			this.richTextBox1.Size = new System.Drawing.Size(327, 226);
			this.richTextBox1.TabIndex = 6;
			this.richTextBox1.Text = resources.GetString("richTextBox1.Text");
			//
			// button1
			//
			this.button1.Location = new System.Drawing.Point(121, 293);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(100, 23);
			this.button1.TabIndex = 7;
			this.button1.Text = "Close";
			this.button1.UseVisualStyleBackColor = true;
			this.button1.Click += new System.EventHandler(this.Button1Click);
			//
			// label5
			//
			this.label5.Location = new System.Drawing.Point(145, 267);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(194, 23);
			this.label5.TabIndex = 9;
			this.label5.Text = "Copyright (c) ASH Team 2017";
			this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
			//
			// AboutForm
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(351, 323);
			this.Controls.Add(this.label5);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.richTextBox1);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.label1);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.MaximizeBox = false;
			this.Name = "AboutForm";
			this.ShowInTaskbar = false;
			this.Text = "About AshAIO";
			this.Load += new System.EventHandler(this.AboutFormLoad);
			this.ResumeLayout(false);

		}
	}
}


text:
@interface AnimOperation : NSOperation
@property (nonatomic,strong) PresentView *presentView;
@property (nonatomic,strong) UIView *listView;
@property (nonatomic,strong) GiftModel *model;
@property (nonatomic,assign) NSInteger index;
@property (nonatomic,copy) NSString *userID; // 新增用户唯一标示,记录礼物信息

// 回调参数增加了结束时礼物累计数
+ (instancetype)animOperationWithUserID:(NSString *)userID model:(GiftModel *)model finishedBlock:(void(^)(BOOL result,NSInteger finishCount))finishedBlock;

@end