text:
#ifndef ZEPHYR_INCLUDE_EMUL_EMUL_ISL923X_H_
#define ZEPHYR_INCLUDE_EMUL_EMUL_ISL923X_H_

#include <zephyr/device.h>
#include <zephyr/drivers/emul.h>
#include <zephyr/drivers/i2c_emul.h>

/**
 * @brief Get the emulator's parent bus device
 *
 * @param emulator The emulator to look-up
 * @return Pointer to the bus connecting to the emulator
 */
const struct device *isl923x_emul_get_parent(const struct emul *emulator);

/**
 * @brief Get pointer to emulator i2c_common_emul_cfg
 *
 * @param emulator The emulator to look-up
 * @return Pointer to the i2c_common_emul_cfg struct
 */
const struct i2c_common_emul_cfg *
isl923x_emul_get_cfg(const struct emul *emulator);

/**
 * @brief Reset all registers
 *
 * @param emulator The emulator to modify
 */
void isl923x_emul_reset_registers(const struct emul *emulator);

/**
 * @brief Set the manufacturer ID
 *
 * @param emulator The emulator to modify
 * @param manufacturer_id The new manufacturer ID
 */
void isl923x_emul_set_manufacturer_id(const struct emul *emulator,
				      uint16_t manufacturer_id);

/**
 * @brief Set the device ID
 *
 * @param emulator The emulator to modify
 * @param device_id The new device ID
 */
void isl923x_emul_set_device_id(const struct emul *emulator,
				uint16_t device_id);

/**
 * @brief Check whether or not learn mode is enabled
 *
 * @param emulator The emulator to probe
 * @return True if the emulator is in learn mode
 */
bool isl923x_emul_is_learn_mode_enabled(const struct emul *emulator);

/**
 * @brief Set the emulator's learn mode manually without affecting the driver
 *
 * @param emulator The emulator to modify
 * @param enabled Whether or not learn mode should be enabled
 */
void isl923x_emul_set_learn_mode_enabled(const struct emul *emulator,
					 bool enabled);

/**
 * @brief Set the emulator's ADC vbus register
 *
 * @param emulator The emulator to modify
 * @param vbus_mv  VBUS voltage in mV
 */
void isl923x_emul_set_adc_vbus(const struct emul *emulator, uint16_t vbus_mv);

/**
 * @brief Set the state of the ACOK pin, which is reflected in the INFO2
 *        register
 *
 * @param value If 1, AC adapter is present. If 0, no adapter is present
 */
void raa489000_emul_set_acok_pin(const struct emul *emulator, uint16_t value);

/**
 * @brief Peek at a register value. This function will assert if the requested
 *        register does is unimplemented.
 *
 * @param emulator Reference to the I2C emulator being used
 * @param reg The address of the register to query
 * @return The 16-bit value of the register
 */
uint16_t isl923x_emul_peek_reg(const struct emul *emul, int reg);

/**
 * @brief Returns pointer to i2c_common_emul_data for argument emul
 *
 * @param emul Pointer to ISL923X emulator
 * @return Pointer to i2c_common_emul_data from argument emul
 */
struct i2c_common_emul_data *
emul_isl923x_get_i2c_common_data(const struct emul *emul);

#endif /* ZEPHYR_INCLUDE_EMUL_EMUL_ISL923X_H_ */


text:
<?php

namespace Torann\MediaSort\Contracts;

interface Disk
{
    /**
     * Remove an attached file.
     *
     * @param array $files
     *
     * @return void
     */
    public function remove(array $files);

    /**
     * Move an uploaded file to it's intended target.
     *
     * @param string $source
     * @param string $target
     *
     * @return void
     */
    public function move(string $source, string $target);
}

redpajama_set_name: RedPajamaGithub


text:
module KitaguchiHelper
end


text:
namespace Manssiere.Core.DemoFlow
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Controls;
    using Manssiere.Core.Graphics.Transition;

    /// <summary>
    /// The demo flow controlls the order of the effects
    /// </summary>
    public abstract class AbstractDemoFlow
    {
        #region Delegates

        public delegate void StateChangedEventHandler(AbstractDemoFlow sender, StateChangeEventArgs args);

        #endregion

        private readonly List<ControlDefinition> _controls = new List<ControlDefinition>();
        private int _activeControl;

        /// <summary>
        /// Gets the state of the previous.
        /// </summary>
        /// <value>The state of the previous.</value>
        public ControlDefinition PreviousState
        {
            get { return _activeControl > 0 ? _controls[_activeControl - 1] : null; }
        }

        /// <summary>
        /// Gets the current scene.
        /// </summary>
        /// <value>The current scene.</value>
        public ControlDefinition CurrentScene
        {
            get { return _activeControl >= 0 && _activeControl < _controls.Count() ? _controls[_activeControl] : null; }
        }

        /// <summary>
        /// Show this effect without a transition.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        protected ControlDefinition Show<T>()
            where T : UserControl
        {
            var controlDefinition = new ControlDefinition(typeof(T), null, this);
            _controls.Add(controlDefinition);

            return new ControlDefinition(this);
        }

        /// <summary>
        /// Show this effect with a fadein.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        protected ControlDefinition FadeIn<T>()
            where T : UserControl
        {
            var controlDefinition = new ControlDefinition(typeof(T), typeof(FadeIn), this);
            _controls.Add(controlDefinition);

            return new ControlDefinition(this);
        }

        /// <summary>
        /// Show this effect with a fadein.
        /// </summary>
        /// <returns></returns>
        protected ControlDefinition FadeOut()
        {
            var controlDefinition = new ControlDefinition(null, typeof(FadeOut), this);
            _controls.Add(controlDefinition);

            return new ControlDefinition(this);
        }

        /// <summary>
        ///   Global audio sync event. Register to this point to receive
        ///   messages from the audio queue.
        /// </summary>
        public event StateChangedEventHandler StateChanged;

        /// <summary>
        /// Invokes the state changed.
        /// </summary>
        /// <param name="args">The <see cref="StateChangeEventArgs"/> instance containing the event data.</param>
        private void InvokeStateChanged(StateChangeEventArgs args)
        {
            var handler = StateChanged;
            if (handler != null) handler(this, args);
        }

        /// <summary>
        /// Moves to the next scene.
        /// </summary>
        public void NextScene()
        {
            if (_activeControl >= _controls.Count()) return;

            _activeControl++;

            if (_activeControl >= _controls.Count()) return;
            InvokeStateChanged(new StateChangeEventArgs(CurrentScene));
        }

        /// <summary>
        /// Moves to the previouse.
        /// </summary>
        public void PreviousScene()
        {
            if (_activeControl <= 0) return;

            _activeControl--;

            // on the back state we don't send a transition, this speeds up skipping & eliminates errors.
            // we could do the same for 'manual' forward moving. Myabe we can use differentt keys for this.
            if (_activeControl < 0) return;
            InvokeStateChanged(new StateChangeEventArgs(new ControlDefinition(CurrentScene.ControlType, null, this)));
        }

        /// <summary>
        /// Gets a value indicating whether this instance has scenes.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance has scenes; otherwise, <c>false</c>.
        /// </value>
        public bool HasScenes
        {
            get { return _controls.Any(); }
        }

        #region Nested type: ControlDefinition

        public class ControlDefinition
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="ControlDefinition"/> class.
            /// </summary>
            /// <param name="controlType">Type of the control.</param>
            /// <param name="transitionType">Type of the transition.</param>
            /// <param name="demoFlow">The demo flow.</param>
            public ControlDefinition(Type controlType, Type transitionType, AbstractDemoFlow demoFlow)
            {
                if (demoFlow == null) throw new ArgumentNullException("demoFlow");

                DemoFlow = demoFlow;
                ControlType = controlType;
                TransitionType = transitionType;
            }

            /// <summary>
            /// Initializes a new instance of the <see cref="ControlDefinition"/> class.
            /// </summary>
            /// <param name="demoFlow">The demo flow.</param>
            public ControlDefinition(AbstractDemoFlow demoFlow)
            {
                DemoFlow = demoFlow;
            }

            /// <summary>
            /// Gets or sets the demo flow.
            /// </summary>
            /// <value>The demo flow.</value>
            private AbstractDemoFlow DemoFlow { get; set; }

            /// <summary>
            /// Gets or sets the type of the control.
            /// </summary>
            /// <value>The type of the control.</value>
            public Type ControlType { get; private set; }

            /// <summary>
            /// Gets or sets the type of the transition.
            /// </summary>
            /// <value>The type of the transition.</value>
            public Type TransitionType { get; private set; }

            /// <summary>
            /// Define the new effect to show
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <returns></returns>
            public UsingDefinition TransitionTo<T>()
            {
                ControlType = typeof(T);

                DemoFlow._controls.Add(this);

                return new UsingDefinition(this);
            }

            #region Nested type: UsingDefinition

            public class UsingDefinition
            {
                private readonly ControlDefinition _controlDefinition;

                /// <summary>
                /// Initializes a new instance of the <see cref="UsingDefinition"/> class.
                /// </summary>
                /// <param name="controlDefinition">The control definition.</param>
                public UsingDefinition(ControlDefinition controlDefinition)
                {
                    _controlDefinition = controlDefinition;
                }

                /// <summary>
                /// Define a transition between the effects.
                /// </summary>
                /// <typeparam name="T"></typeparam>
                /// <returns></returns>
                public ControlDefinition Using<T>()
                    where T : ITransition
                {
                    _controlDefinition.TransitionType = typeof(T);
                    var controlDefinition = new ControlDefinition(_controlDefinition.DemoFlow);

                    return controlDefinition;
                }
            }

            #endregion
        }

        #endregion
    }
}


text:
START_ATF_NAMESPACE
    typedef _PROPSHEETPAGEW_V1 *LPCPROPSHEETPAGEW_V1;
END_ATF_NAMESPACE


text:
#ifdef MGT_MGT_H
#error "Multiple includes of mgt/mgt.h"
#endif
#define MGT_MGT_H

#include <stdint.h>

#include <sys/types.h>

#include "vdef.h"

#include "miniobj.h"
#include "vas.h"
#include "vcs.h"
#include "vqueue.h"
#include "vsb.h"

#include "common/common_param.h"

struct vjsn;
struct vsc_seg;
struct vsmw_cluster;
#include "VSC_mgt.h"

struct cli;
struct parspec;
struct vcc;
struct vclprog;

extern struct vev_root	*mgt_evb;
extern unsigned		d_flag;
extern int		exit_status;

/* builtin_vcl.c */

extern const char * const builtin_vcl;

/* mgt_acceptor.c */

void MAC_Arg(const char *);
int MAC_reopen_sockets(void);

/* mgt_child.c */
void MCH_Init(void);
int MCH_Running(void);
void MCH_Stop_Child(void);
int MCH_Start_Child(void);
void MCH_TrackHighFd(int fd);
void MCH_Cli_Fail(void);

/* mgt_cli.c */
extern struct VCLS	*mgt_cls;

typedef int mgt_cli_close_f(void *priv);
void mgt_cli_setup(int fdi, int fdo, int auth, const char *ident,
    mgt_cli_close_f *close_func, void *priv);
int mgt_cli_askchild(unsigned *status, char **resp, const char *fmt, ...)
    v_printflike_(3, 4);
void mgt_cli_start_child(int fdi, int fdo);
void mgt_cli_stop_child(void);
void mgt_cli_telnet(const char *T_arg);
void mgt_cli_master(const char *M_arg);
void mgt_cli_secret(const char *S_arg);
void mgt_cli_close_all(void);
void mgt_DumpRstCli(void);
void mgt_cli_init_cls(void);
#define MCF_NOAUTH	0	/* NB: zero disables here-documents */
#define MCF_AUTH	16

/* mgt_jail.c */

enum jail_subproc_e {
	JAIL_SUBPROC_VCC,
	JAIL_SUBPROC_CC,
	JAIL_SUBPROC_VCLLOAD,
	JAIL_SUBPROC_WORKER,
};

enum jail_master_e {
	JAIL_MASTER_LOW,
	JAIL_MASTER_FILE,
	JAIL_MASTER_STORAGE,
	JAIL_MASTER_PRIVPORT,
	JAIL_MASTER_KILL,
};

enum jail_fixfd_e {
	JAIL_FIXFD_FILE,
	JAIL_FIXFD_VSMMGT,
	JAIL_FIXFD_VSMWRK,
};

typedef int jail_init_f(char **);
typedef void jail_master_f(enum jail_master_e);
typedef void jail_subproc_f(enum jail_subproc_e);
typedef int jail_make_dir_f(const char *, const char *, struct vsb *);
typedef void jail_fixfd_f(int, enum jail_fixfd_e);

struct jail_tech {
	unsigned		magic;
#define JAIL_TECH_MAGIC		0x4d00fa4d
	const char		*name;
	jail_init_f		*init;
	jail_master_f		*master;
	jail_subproc_f		*subproc;
	jail_make_dir_f		*make_workdir;
	jail_make_dir_f		*make_subdir;
	jail_fixfd_f		*fixfd;
};

void VJ_Init(const char *);
void VJ_master(enum jail_master_e);
void VJ_subproc(enum jail_subproc_e);
int VJ_make_workdir(const char *);
int VJ_make_subdir(const char *, const char *, struct vsb *);
void VJ_fix_fd(int, enum jail_fixfd_e);

extern const struct jail_tech jail_tech_unix;
extern const struct jail_tech jail_tech_solaris;

/* mgt_main.c */
extern struct vsb *vident;
extern struct VSC_mgt	*VSC_C_mgt;
struct choice {
	const char      *name;
	const void	*ptr;
};

extern const char C_ERR[];	// Things are not as they should be
extern const char C_INFO[];	// Normal stuff, keep a record for later
extern const char C_DEBUG[];	// More detail than you'd normally want
extern const char C_SECURITY[];	// Security issues
extern const char C_CLI[];	// CLI traffic between master and child

/* mgt_param.c */
void MCF_InitParams(struct cli *);
enum mcf_which_e {
	MCF_DEFAULT = 32,
	MCF_MINIMUM = 33,
	MCF_MAXIMUM = 34,
};
void MCF_ParamConf(enum mcf_which_e, const char *param, const char *, ...)
    v_printflike_(3, 4);

void MCF_ParamSet(struct cli *, const char *param, const char *val);
void MCF_ParamProtect(struct cli *, const char *arg);
void MCF_DumpRstParam(void);
void MCF_AddParams(struct parspec *ps);
extern struct params mgt_param;

/* mgt_shmem.c */
void mgt_SHM_Init(void);
void mgt_SHM_static_alloc(const void *, ssize_t size,
    const char *class, const char *ident);
void mgt_SHM_Create(void);
void mgt_SHM_Destroy(int keep);

void mgt_SHM_ChildNew(void);
void mgt_SHM_ChildDestroy(void);

/* mgt_param_tcp.c */
void MCF_TcpParams(void);

/* mgt_util.c */
char *mgt_HostName(void);
void mgt_ProcTitle(const char *comp);
void mgt_DumpRstVsl(void);
struct vsb *mgt_BuildVident(void);
void MGT_Complain(const char *, const char *, ...) v_printflike_(2, 3);
const void *MGT_Pick(const struct choice *, const char *, const char *);
char **MGT_NamedArg(const char *, const char **, const char *);

/* stevedore_mgt.c */
void STV_Config(const char *spec);
void STV_Config_Transient(void);

/* mgt_vcc.c */
void mgt_DumpBuiltin(void);
char *mgt_VccCompile(struct cli *, struct vclprog *, const char *vclname,
    const char *vclsrc, const char *vclsrcfile, int C_flag);

void mgt_vcl_init(void);
void mgt_vcl_startup(struct cli *, const char *vclsrc, const char *origin,
    const char *vclname, int Cflag);
int mgt_push_vcls(struct cli *, unsigned *status, char **p);
int mgt_has_vcl(void);
extern char *mgt_cc_cmd;
extern const char *mgt_vcl_path;
extern const char *mgt_vmod_path;
extern unsigned mgt_vcc_err_unref;
extern unsigned mgt_vcc_allow_inline_c;
extern unsigned mgt_vcc_unsafe_path;

#if defined(PTHREAD_CANCELED) || defined(PTHREAD_MUTEX_DEFAULT)
#error "Keep pthreads out of in manager process"
#endif

#define MGT_FEATURE(x)	COM_FEATURE(mgt_param.feature_bits, x)
#define MGT_DO_DEBUG(x)	COM_DO_DEBUG(mgt_param.debug_bits, x)


text:
package ws.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

public class NettyWebSocketClient {

    static final String URL = System.getProperty("url", "ws://127.0.0.1:8080/websocket");

    public static void main(String[] args) throws Exception {
        URI uri = new URI(URL);
        String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final int port;
        if (uri.getPort() == -1) {
            if ("ws".equalsIgnoreCase(scheme)) {
                port = 80;
            } else if ("wss".equalsIgnoreCase(scheme)) {
                port = 443;
            } else {
                port = -1;
            }
        } else {
            port = uri.getPort();
        }

        if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
            System.err.println("Only WS(S) is supported.");
            return;
        }

        final boolean ssl = "wss".equalsIgnoreCase(scheme);
        final SslContext sslCtx;
        if (ssl) {
            sslCtx = SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            sslCtx = null;
        }

        //create boss;
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            //Á¬½Ó
            final WebSocketClientHandler handler = new WebSocketClientHandler(
                    WebSocketClientHandshakerFactory.newHandshaker(
                            uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()), null);
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (sslCtx != null) {
                        pipeline.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                    }
                    pipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                }
            });

            Channel ch = bootstrap.connect(uri.getHost(), port).sync().channel();
            handler.handshakeFuture().syncUninterruptibly();
            //Á¬½Ó½áÊø

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine();
                if (msg == null) {
                    break;
                } else if ("bye".equals(msg.toLowerCase())) {
                    ch.writeAndFlush(new CloseWebSocketFrame());
                    ch.closeFuture().sync();
                    break;
                } else if ("ping".equals(msg.toLowerCase())) {
                    WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[]{8, 1, 8, 1}));
                    ch.writeAndFlush(frame);
                } else {
                    WebSocketFrame frame = new TextWebSocketFrame(msg);
                    ch.writeAndFlush(frame);
                }
//                WebSocketFrame webSocketFrame = new BinaryWebSocketFrame();
            }
        } finally {
            group.shutdownGracefully();
        }

    }
}


text:
TEST_CASE("tcp_transport: init and deinit transport list", "[tcp_transport][leaks=0]")
{
    esp_transport_list_handle_t transport_list = esp_transport_list_init();
    esp_transport_handle_t tcp = esp_transport_tcp_init();
    esp_transport_list_add(transport_list, tcp, "tcp");
    TEST_ASSERT_EQUAL(ESP_OK, esp_transport_list_destroy(transport_list));
}

TEST_CASE("tcp_transport: using ssl transport separately", "[tcp_transport][leaks=0]")
{
    esp_transport_handle_t h = esp_transport_ssl_init();
    TEST_ASSERT_EQUAL(ESP_OK, esp_transport_destroy(h));
}

TEST_CASE("tcp_transport: using ws transport separately", "[tcp_transport][leaks=0]")
{
    esp_transport_handle_t tcp = esp_transport_tcp_init();
    esp_transport_handle_t ws = esp_transport_ws_init(tcp);
    TEST_ASSERT_EQUAL(ESP_OK, esp_transport_destroy(ws));
    TEST_ASSERT_EQUAL(ESP_OK, esp_transport_destroy(tcp));
}

TEST_CASE("transport: init and deinit multiple transport items", "[tcp_transport][leaks=0]")
{
    esp_transport_list_handle_t transport_list = esp_transport_list_init();
    esp_transport_handle_t tcp = esp_transport_tcp_init();
    esp_transport_list_add(transport_list, tcp, "tcp");
    esp_transport_handle_t ssl = esp_transport_ssl_init();
    esp_transport_list_add(transport_list, ssl, "ssl");
    esp_transport_handle_t ws = esp_transport_ws_init(tcp);
    esp_transport_list_add(transport_list, ws, "ws");
    esp_transport_handle_t wss = esp_transport_ws_init(ssl);
    esp_transport_list_add(transport_list, wss, "wss");
    TEST_ASSERT_EQUAL(ESP_OK, esp_transport_list_destroy(transport_list));
}


text:
body {
  background: #FF8888;
  display: -webkit-flex;
  display: flex;

  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;
}

.formWrapper {
  margin-top: 20px;
  padding: 15px;
  width: 300px;
  display: -webkit-flex;
  display:         flex;
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;

  border-radius:4px;
	border:1px solid #ffffff;
}

.inputWrapper {
  text-align: center;
}

.inputWrapper ~ .inputWrapper {
  margin-top: 15px;
}

.submit {
	-moz-box-shadow:inset 0px 39px 0px -24px #e67a73;
	-webkit-box-shadow:inset 0px 39px 0px -24px #e67a73;
	box-shadow:inset 0px 39px 0px -24px #e67a73;
	background-color:#e4685d;
	-moz-border-radius:4px;
	-webkit-border-radius:4px;
	border-radius:4px;
	border:1px solid #ffffff;
	display:inline-block;
	cursor:pointer;
	color:#ffffff;
	font-family:Arial;
	font-size:15px;
	padding:6px 15px;
	text-decoration:none;
	text-shadow:0px 1px 0px #b23e35;
}
.submit:hover {
	background-color:#eb675e;
}
.submit:active {
	position:relative;
	top:1px;
}

.submit ~ input {
  display: none;
}

.submitWrapper {
  margin-top: 25px;
  margin-bottom: 0;
}

@keyframes message_disappear {
  0% {
    opacity: 0;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

.message {
  position: fixed;
  top: 5px;
  right: 5px;
  background: #CC0000;
  border: 1px solid #FFFFFF;
  padding: 5px;
  color: white;

  display: -webkit-flex;
  display:         flex;
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;

  animation-duration: 5s;
  animation-direction: normal;
  animation-name: message_disappear;
  animation-fill-mode: forwards;
}


text:
title: Collection
is_parent_tag: true
overview: Entries are grouped into Collections and connected to this tag to provide you means to fetch, sort, filter, and arrange them in various ways. A Collection might contain blog posts, products, or even a pile of terrible knock-knock jokes. We don't judge, and neither does the Collection Tag.
description: Grab and filter the entries in a specified Collection.
parameters:
  -
    name: from|folder|use
    type: string|array
    description: 'The name of the collection(s). Pipe separate names to fetch entries from multiple collections.'
  -
    name: collection
    type: tag part
    description: 'The name of the collection when using the shorthand syntax. This is not actually a parameter, but part of the tag itself. For example, `{{ collection:blog }}`.'
  -
    name: show_unpublished
    type: 'boolean *false*'
    description: "Unpublished content is, by it's very nature, unpublished. That is, unless you show it by turning on this parameter."
  -
    name: show_published
    type: 'boolean *true*'
    description: 'Setting this to `false` will prevent published entries from being displayed. Pairs nicely with `show_unpublished="true"` to only show drafts.'
  -
    name: show_future
    type: 'boolean *false*'
    description: >
      Date-based entries from the future are
      excluded from results by default. Of
      course, if you want to show upcoming
      events or similar content, flip this
      switch.
  -
    name: show_past
    type: 'boolean *true*'
    description: >
      Just like `show_future`, but for entries
      in the past.
  -
    name: since
    type: string/var
    description: "Limits the date the earliest point in time from which date-based entries should be fetched. You can use plain English (PHP's `strtotime` method will interprit. eg. `last sunday`, `january 15th, 2013`, `yesterday`) or the name any date variable."
  -
    name: until
    type: string/var
    description: >
      The inverse of `since`, but sets the _max_
      date.
  -
    name: sort
    type: string
    description: >
      Sort entries by field name (or `random`). You may pipe-separate multiple fields for sub-sorting and specify sort direction of each field using a colon.
      For example, `sort="title"` or `sort="date:asc|title:desc"` to sort by date then by title.
      To sort numerically, use `sort="order"`. (Make sure to include `order: number` in your collection's folder.yaml file).
  -
    name: limit
    type: integer
    description: Limit the total results returned.
  -
    name: offset
    type: integer
    description: The number of entries the results should by offset by.
  -
    name: taxonomy
    type: mixed
    description: >
      A multitude of ways to filter by taxonomies. [More details](#taxonomies)
  -
    name: group_by_date
    type: string
    description: >
      Group entries by date, given a specified format.
  -
    name: filter
    type: wizardry
    description: >
      Filter the listing by either a custom
      class or using a special syntax, both of
      which are outlined in more detail below.
  -
    name: paginate
    type: 'boolean *false*'
    description: >
      Specify whether your entries should be paginated.
  -
    name: as
    type: string
    description: >
      Alias your entries into a new variable loop.
  -
    name: scope
    type: string
    description: >
      Scope your entries with a variable prefix.
  -
    name: supplement_taxonomies
    type: boolean *true*
    description: >
      By default, Statamic will convert taxonomy term values into actual term objects that you may loop through.
      This has some performance overhead, so you may disable this for a speed boost if taxonomies aren't necessary.
  -
    name: locale
    type: string
    description: Show the retrieved content in the selected locale.
variables:
  -
    name: first
    type: boolean
    description: Is this the first item in the loop?
  -
    name: last
    type: boolean
    description: Is this the last item in the loop?
  -
    name: index
    type: integer
    description: >
      The number/index of current iteration in the loop, starting from 1
  -
    name: zero_index
    type: integer
    description: >
      The number/index of current iteration in the loop, starting from 0
  -
    name: no_results
    type: boolean
    description: Returns true if there are no results.
  -
    name: total_results
    type: integer
    description: The total number of results in the loop when there are results. You should use `no_results` to check if any results exist.
  -
    name: page data
    type: mixed
    description: >
      Each page being iterated has access to all the variables inside that page. This includes things like `title`, `content`, etc.
id: 045a6e54-c792-483a-a109-f07251a79e47
---
## Example {#example}

The most basic example would be to iterate over entries in a single collection:

```
{{ collection from="blog" }}
    {{ title }}
{{ /collection }}
```

You can also use the shorthand syntax for this:

```
{{ collection:blog }}
    {{ title }}
{{ /collection:blog }}
```

If you'd like to fetch entries from multiple collections, you can only do that in the standard syntax, like so:

```
{{ collection from="blog|events" }}
    {{ title }}
{{ /collection }}
```

## Grouping entries by date {#group_by_date}

You can visually group repeating date-based entries.

When using this parameter, the templating structure you need to use will be a little different from a regular loop.

### Example

Let's assume that the entries in the `blog` collection are date-based.

```
{{ collection:blog group_by_date="M Y" as="entries" }}
    {{ date_groups }}
        <h3>{{ date_group }}</h3>
        <ul>
            {{ entries }}
                <li>{{ title }}</li>
            {{ /entries }}
        </ul>
    {{ /date_groups }}
{{ /collection:blog }}
```

The code above will output something like this:

```
<h3>May 2015</h3>
<ul>
  <li>A post from May</li>
  <li>Another from May</li>
</ul>
<h3>June 2015</h3>
<ul>
  <li>A post from June</li>
</ul>
```

The `{{ date_group }}` variable will be the date formatted by whatever you specifed in the `group_by_date` parameter.

The `{{ entries }}{{ /entries }}` tag pair will allow you to iterate over the entries in that date group. The name of this variable is specified by the `as` parameter. For example, if you used `as="posts"`, you'd use a `{{ posts }}{{ /posts }}` tag pair.

### Grouping by a custom date field {#group_by_date-custom-field}

If you'd like to group by an arbitrary date field, you can specify the field name as the second value of the parameter.

```
{{ collection:blog group_by_date="M Y|purchase_date" sort="purchase_date" }}
```

Here we are grouping on the `purchase_date` field. Note that you should also sort by that field, as the default sorting
on date-based entries would still be the entry date.

## Filtering {#filtering}

There are a number of ways to filter your collection. There's the conditions syntax for filtering by fields, taxonomy filter for using terms, and the custom filter class if you need extra control.

### Conditions syntax {#conditions}

Want to get entries where the title has the words "awesome" and "thing", and "joe" is the author? You can write it how you'd say it:

```
{{ collection:blog
   title:contains="awesome"
   title:contains="thing"
   author:is="joe"
}}
```

There are a bunch of conditions available to you, like `:is`, `:isnt`, `:contains`, `:starts_with`, and `:is_before`. There are many more than that. In fact, there's a whole page dedicated to [conditions - check them out][conditions].

### Taxonomies {#taxonomies}

Filtering by a taxonomy term (or terms) is done using the `taxonomy` parameter, similar to the conditions syntax mentioned above.

To show entries with the `harry-potter` term within the `tags` taxonomy, you could do this:

```
{{ collection:blog taxonomy:tags="harry-potter" }}
```

There are a number of different ways to use this parameter. They are explained in depth in the
[Taxonomies Guide](/taxonomies#collections)

### Custom filters {#custom-filters}

Doing something complicated? You can reference a [custom filter][custom_filters] which can do the heavy lifting from outside of the template.

For example, want to filter drink entries by whether or not its one of the user's favorites?

```
{{ collection:drinks filter="users_favorite" }}
```

This'll load a custom filter file and do its thing from within there. Statamic makes the collection available to you, and you can manipulate it however you like. For example:

``` language-php
class UsersFavoriteFilter extends Filter
{
    public function filter()
    {
        $faves = User::getCurrent()->get('favorite_drinks');

        return $this->collection->filter(function($entry) use ($faves) {
            return in_array($entry->get('title'), $faves);
        });
    }
}
```

[Read more about custom filters][custom_filters].

## Pagination {#pagination}

To enable pagination mode, add the `paginate="true"` parameter, along with the `limit` parameter to specify the number of entries in each page.

```
{{ collection:blog limit="10" paginate="true" as="posts" }}

    {{ if no_results }}
        <p>Aww, there are no results.</p>
    {{ /if }}

    {{ posts }}
        <article>
            {{ title }}
        </article>
    {{ /posts }}

    {{ paginate }}
        <a href="{{ prev_page }}">⬅ Previous</a>

        {{ current_page }} of {{ total_pages }} pages
        (There are {{ total_items }} posts)

        <a href="{{ next_page }}">Next ➡</a>
    {{ /paginate }}

{{ /collection:blog }}
```

In pagination mode, your entries will be scoped (in the example, we're scoping them into the `posts` tag pair). Use that tag pair to loop over the entries in that page.

The `paginate` variable will become available to you. This is an array containing data about the paginated set.

| Variable | Description |
|----------|-------------|
| `next_page` |	The URL to the next paginated page.
| `prev_page` |	The URL to the previous paginated page.
| `total_items` |	The total number of entries.
| `total_pages` |	The number of paginated pages.
| `current_page` |	The current paginated page. (ie. the x in the ?page=x param)
| `auto_links` |	Outputs a Twitter Bootstrap ready list of links.
| `links` |	Contains data for you to construct a custom list of links.
| `links:all` |	An array of all the pages. You can loop over this and output {{ url }} and {{ page }}.
| `links:segments` |	An array of data for you to create a segmented list of links.

<br>

### Pagination Examples

The `auto_links` tag is designed to be your friend. It'll save you more than a few keystrokes, and even more headaches.
It'll output a Twitter Bootstrap-ready list of links for you. With a large number of pages, it will create segments
so that you don't end up with hundreds of numbers. You will see something like this:

![](/assets/examples/pagination-auto-links.png)

It's clever enough to work out a comfortable range of numbers to display, and it'll also throw in the prev/next arrow for good measure. Nice, right?

Maybe the Bootstrap markup isn't for you. You want something more custom. You're a maverick. That's cool. You'll want to check out the `links:all` or `links:segments` arrays. These give you all the data you need to recreate your own set of links. The `links:all` array is simply _all_ the pages with `url` and `page` variables. The `links:segments` will contain the segments like we mentioned earlier. You'll be able to access `first`, `slider`, and `last`, which are the 3 segments.

Here's the `auto_links` output, recreated using the other tags, for you mavericks out there:

```
{{ paginate }}
    <ul class="pagination">
        {{ if prev_page }}
            <li><a href="{{ prev_page }}">«</a></li>
        {{ else }}
            <li class="disabled"><span>«</span></li>
        {{ /if }}

        {{ links:segments }}

            {{ first }}
                {{ if page == current_page }}
                    <li class="active"><span>{{ page }}</span></li>
                {{ else }}
                    <li><a href="{{ url }}">{{ page }}</a></li>
                {{ /if }}
            {{ /first }}

            {{ if slider }}
                <li class="disabled"><span>...</span></li>
            {{ /if }}

            {{ slider }}
                {{ if page == current_page }}
                    <li class="active"><span>{{ page }}</span></li>
                {{ else }}
                    <li><a href="{{ url }}">{{ page }}</a></li>
                {{ /if }}
            {{ /slider }}

            {{ if slider || (!slider && last) }}
                <li class="disabled"><span>...</span></li>
            {{ /if }}

            {{ last }}
                {{ if page == current_page }}
                    <li class="active"><span>{{ page }}</span></li>
                {{ else }}
                    <li><a href="{{ url }}">{{ page }}</a></li>
                {{ /if }}
            {{ /last }}

        {{ /links:segments }}

        {{ if next_page }}
            <li><a href="{{ next_page }}">»</a></li>
        {{ else }}
            <li class="disabled"><span>»</span></li>
        {{ /if }}
    </ul>
{{ /paginate }}
```

## Aliasing {#alias}

Often times you'd like to have some extra markup around your list of entries, but only if there are results. Like a `<ul>` element, for example. You can do this by _aliasing_ the results into a new variable tag pair. This actually creates a copy of your data as a new variable. It goes like this:

```
{{ collection:blog as="posts" }}
  <ul>
  {{ posts }}
    <li><a href="{{ url }}">{{ title }}</a></li>
  {{ /posts }}
  </ul>
{{ /collection:blog }}
```

## Scoping {#scope}

Sometimes not all of your entries have the same set of variables. And sometimes the page that you're on (while listing entries in a Collection, for example) may have those very same variables on the page-level scope. Statamic assumes you'd like to fallback to the parent scope's data to plug any holes. This logic has pros and cons, and you can [read more about scoping and the Cascade here](/knowledge-base/cascade).

You can assign a _scope_ prefix to your entries so you can be sure to get the data you want. Define your scope and then prefix all of your variables with it.

```{.language-yaml}
# Page data
featured_image: /img/totes-adorbs-kitteh.jpg
```

```
{{ collection:blog scope="post" }}
  <div class="block">
    <img src="{{ post:featured_image }}">
  </div>
{{ /collection:blog }}
```

You can also add your scope down into your [alias](#alias) loop. Yep, we thought of that too.

```
{{ collection:blog as="posts" }}
  {{ posts scope="post" }}
    <div class="block">
      <img src="{{ post:featured_image }}">
    </div>
  {{ /posts }}
{{ /collection:blog }}
```

Combining both an Alias and a Scope on a Collection Tag doesn't make a whole lot of sense. You shouldn't do that.

[conditions]: /conditions
[custom_filters]: /addons/classes/filters


text:
package com.xjt.crazypic.views.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;

import com.xjt.crazypic.animations.AnimationTime;
import com.xjt.crazypic.views.opengl.GLESCanvas;
import com.xjt.crazypic.views.opengl.ResourceTexture;
import com.xjt.crazypic.R;

// This is copied from android.widget.EdgeEffect with some small modifications:
// (1) Copy the images (overscroll_{edge|glow}.png) to local resources.
// (2) Use "GLESCanvas" instead of "Canvas" for draw()'s parameter.
// (3) Use a private Drawable class (which inherits from ResourceTexture)
//     instead of android.graphics.drawable.Drawable to hold the images.
//     The private Drawable class is used to translate original Canvas calls to
//     corresponding GLESCanvas calls.

/**
 * This class performs the graphical effect used at the edges of scrollable widgets
 * when the user scrolls beyond the content bounds in 2D space.
 *
 *
EdgeEffect is stateful. Custom widgets using EdgeEffect should create an
 * instance for each edge that should show the effect, feed it input data using
 * the methods {@link #onAbsorb(int)}, {@link #onPull(float)}, and {@link #onRelease()},
 * and draw the effect using {@link #draw(Canvas)} in the widget's overridden
 * {@link android.view.View#draw(Canvas)} method. If {@link #isFinished()} returns
 * false after drawing, the edge effect's animation is not yet complete and the widget
 * should schedule another drawing pass to continue the animation.

 *
 *
When drawing, widgets should draw their main content and child views first,
 * usually by invoking super.draw(canvas) from an overridden draw
 * method. (This will invoke onDraw and dispatch drawing to child views as needed.)
 * The edge effect may then be drawn on top of the view's content using the
 * {@link #draw(Canvas)} method.

 */
public class ViewEdgeEffect {
    @SuppressWarnings("unused")
    private static final String TAG = "EdgeEffect";

    // Time it will take the effect to fully recede in ms
    private static final int RECEDE_TIME = 1000;

    // Time it will take before a pulled glow begins receding in ms
    private static final int PULL_TIME = 167;

    // Time it will take in ms for a pulled glow to decay to partial strength before release
    private static final int PULL_DECAY_TIME = 1000;

    private static final float MAX_ALPHA = 0.8f;
    private static final float HELD_EDGE_ALPHA = 0.7f;
    private static final float HELD_EDGE_SCALE_Y = 0.5f;
    private static final float HELD_GLOW_ALPHA = 0.5f;
    private static final float HELD_GLOW_SCALE_Y = 0.5f;

    private static final float MAX_GLOW_HEIGHT = 4.f;

    private static final float PULL_GLOW_BEGIN = 1.f;
    private static final float PULL_EDGE_BEGIN = 0.6f;

    // Minimum velocity that will be absorbed
    private static final int MIN_VELOCITY = 100;

    private static final float EPSILON = 0.001f;

    private final Drawable mEdge;
    private final Drawable mGlow;
    private int mWidth;
    private int mHeight;
    private final int MIN_WIDTH = 300;
    private final int mMinWidth;

    private float mEdgeAlpha;
    private float mEdgeScaleY;
    private float mGlowAlpha;
    private float mGlowScaleY;

    private float mEdgeAlphaStart;
    private float mEdgeAlphaFinish;
    private float mEdgeScaleYStart;
    private float mEdgeScaleYFinish;
    private float mGlowAlphaStart;
    private float mGlowAlphaFinish;
    private float mGlowScaleYStart;
    private float mGlowScaleYFinish;

    private long mStartTime;
    private float mDuration;

    private final Interpolator mInterpolator;

    private static final int STATE_IDLE = 0;
    private static final int STATE_PULL = 1;
    private static final int STATE_ABSORB = 2;
    private static final int STATE_RECEDE = 3;
    private static final int STATE_PULL_DECAY = 4;

    // How much dragging should effect the height of the edge image.
    // Number determined by user testing.
    private static final int PULL_DISTANCE_EDGE_FACTOR = 7;

    // How much dragging should effect the height of the glow image.
    // Number determined by user testing.
    private static final int PULL_DISTANCE_GLOW_FACTOR = 7;
    private static final float PULL_DISTANCE_ALPHA_GLOW_FACTOR = 1.1f;

    private static final int VELOCITY_EDGE_FACTOR = 8;
    private static final int VELOCITY_GLOW_FACTOR = 16;

    private int mState = STATE_IDLE;

    private float mPullDistance;

    /**
     * Construct a new EdgeEffect with a theme appropriate for the provided context.
     * @param context Context used to provide theming and resource information for the EdgeEffect
     */
    public ViewEdgeEffect(Context context, Drawable edge, Drawable glow) {
        mEdge = edge;
        mGlow = glow;

        mMinWidth = (int) (context.getResources().getDisplayMetrics().density * MIN_WIDTH + 0.5f);
        mInterpolator = new DecelerateInterpolator();
    }

    /**
     * Set the size of this edge effect in pixels.
     *
     * @param width Effect width in pixels
     * @param height Effect height in pixels
     */
    public void setSize(int width, int height) {
        mWidth = width;
        mHeight = height;
    }

    /**
     * Reports if this EdgeEffect's animation is finished. If this method returns false
     * after a call to {@link #draw(Canvas)} the host widget should schedule another
     * drawing pass to continue the animation.
     *
     * @return true if animation is finished, false if drawing should continue on the next frame.
     */
    public boolean isFinished() {
        return mState == STATE_IDLE;
    }

    /**
     * Immediately finish the current animation.
     * After this call {@link #isFinished()} will return true.
     */
    public void finish() {
        mState = STATE_IDLE;
    }

    /**
     * A view should call this when content is pulled away from an edge by the user.
     * This will update the state of the current visual effect and its associated animation.
     * The host view should always {@link android.view.View#invalidate()} after this
     * and draw the results accordingly.
     *
     * @param deltaDistance Change in distance since the last call. Values may be 0 (no change) to
     *                      1.f (full length of the view) or negative values to express change
     *                      back toward the edge reached to initiate the effect.
     */
    public void onPull(float deltaDistance) {
        final long now = AnimationTime.get();
        if (mState == STATE_PULL_DECAY && now - mStartTime < mDuration) {
            return;
        }
        if (mState != STATE_PULL) {
            mGlowScaleY = PULL_GLOW_BEGIN;
        }
        mState = STATE_PULL;

        mStartTime = now;
        mDuration = PULL_TIME;

        mPullDistance += deltaDistance;
        float distance = Math.abs(mPullDistance);

        mEdgeAlpha = mEdgeAlphaStart = Math.max(PULL_EDGE_BEGIN, Math.min(distance, MAX_ALPHA));
        mEdgeScaleY = mEdgeScaleYStart = Math.max(
                HELD_EDGE_SCALE_Y, Math.min(distance * PULL_DISTANCE_EDGE_FACTOR, 1.f));

        mGlowAlpha = mGlowAlphaStart = Math.min(MAX_ALPHA,
                mGlowAlpha +
                (Math.abs(deltaDistance) * PULL_DISTANCE_ALPHA_GLOW_FACTOR));

        float glowChange = Math.abs(deltaDistance);
        if (deltaDistance > 0 && mPullDistance < 0) {
            glowChange = -glowChange;
        }
        if (mPullDistance == 0) {
            mGlowScaleY = 0;
        }

        // Do not allow glow to get larger than MAX_GLOW_HEIGHT.
        mGlowScaleY = mGlowScaleYStart = Math.min(MAX_GLOW_HEIGHT, Math.max(
                0, mGlowScaleY + glowChange * PULL_DISTANCE_GLOW_FACTOR));

        mEdgeAlphaFinish = mEdgeAlpha;
        mEdgeScaleYFinish = mEdgeScaleY;
        mGlowAlphaFinish = mGlowAlpha;
        mGlowScaleYFinish = mGlowScaleY;
    }

    /**
     * Call when the object is released after being pulled.
     * This will begin the "decay" phase of the effect. After calling this method
     * the host view should {@link android.view.View#invalidate()} and thereby
     * draw the results accordingly.
     */
    public void onRelease() {
        mPullDistance = 0;

        if (mState != STATE_PULL && mState != STATE_PULL_DECAY) {
            return;
        }

        mState = STATE_RECEDE;
        mEdgeAlphaStart = mEdgeAlpha;
        mEdgeScaleYStart = mEdgeScaleY;
        mGlowAlphaStart = mGlowAlpha;
        mGlowScaleYStart = mGlowScaleY;

        mEdgeAlphaFinish = 0.f;
        mEdgeScaleYFinish = 0.f;
        mGlowAlphaFinish = 0.f;
        mGlowScaleYFinish = 0.f;

        mStartTime = AnimationTime.get();
        mDuration = RECEDE_TIME;
    }

    /**
     * Call when the effect absorbs an impact at the given velocity.
     * Used when a fling reaches the scroll boundary.
     *
     *
When using a {@link android.widget.Scroller} or {@link android.widget.OverScroller},
     * the method getCurrVelocity will provide a reasonable approximation
     * to use here.

     *
     * @param velocity Velocity at impact in pixels per second.
     */
    public void onAbsorb(int velocity) {
        mState = STATE_ABSORB;
        velocity = Math.max(MIN_VELOCITY, Math.abs(velocity));

        mStartTime = AnimationTime.get();
        mDuration = 0.1f + (velocity * 0.03f);

        // The edge should always be at least partially visible, regardless
        // of velocity.
        mEdgeAlphaStart = 0.f;
        mEdgeScaleY = mEdgeScaleYStart = 0.f;
        // The glow depends more on the velocity, and therefore starts out
        // nearly invisible.
        mGlowAlphaStart = 0.5f;
        mGlowScaleYStart = 0.f;

        // Factor the velocity by 8. Testing on device shows this works best to
        // reflect the strength of the user's scrolling.
        mEdgeAlphaFinish = Math.max(0, Math.min(velocity * VELOCITY_EDGE_FACTOR, 1));
        // Edge should never get larger than the size of its asset.
        mEdgeScaleYFinish = Math.max(
                HELD_EDGE_SCALE_Y, Math.min(velocity * VELOCITY_EDGE_FACTOR, 1.f));

        // Growth for the size of the glow should be quadratic to properly
        // respond
        // to a user's scrolling speed. The faster the scrolling speed, the more
        // intense the effect should be for both the size and the saturation.
        mGlowScaleYFinish = Math.min(0.025f + (velocity * (velocity / 100) * 0.00015f), 1.75f);
        // Alpha should change for the glow as well as size.
        mGlowAlphaFinish = Math.max(
                mGlowAlphaStart, Math.min(velocity * VELOCITY_GLOW_FACTOR * .00001f, MAX_ALPHA));
    }

    /**
     * Draw into the provided canvas. Assumes that the canvas has been rotated
     * accordingly and the size has been set. The effect will be drawn the full
     * width of X=0 to X=width, beginning from Y=0 and extending to some factor <
     * 1.f of height.
     *
     * @param canvas Canvas to draw into
     * @return true if drawing should continue beyond this frame to continue the
     *         animation
     */
    public boolean draw(GLESCanvas canvas) {
        update();

        final int edgeHeight = mEdge.getIntrinsicHeight();
        final int edgeWidth = mEdge.getIntrinsicWidth();
        final int glowHeight = mGlow.getIntrinsicHeight();
        final int glowWidth = mGlow.getIntrinsicWidth();

        mGlow.setAlpha((int) (Math.max(0, Math.min(mGlowAlpha, 1)) * 255));

        int glowBottom = (int) Math.min(
                glowHeight * mGlowScaleY * glowHeight/ glowWidth * 0.6f,
                glowHeight * MAX_GLOW_HEIGHT);
        if (mWidth < mMinWidth) {
            // Center the glow and clip it.
            int glowLeft = (mWidth - mMinWidth)/2;
            mGlow.setBounds(glowLeft, 0, mWidth - glowLeft, glowBottom);
        } else {
            // Stretch the glow to fit.
            mGlow.setBounds(0, 0, mWidth, glowBottom);
        }

        mGlow.draw(canvas);

        mEdge.setAlpha((int) (Math.max(0, Math.min(mEdgeAlpha, 1)) * 255));

        int edgeBottom = (int) (edgeHeight * mEdgeScaleY);
        if (mWidth < mMinWidth) {
            // Center the edge and clip it.
            int edgeLeft = (mWidth - mMinWidth)/2;
            mEdge.setBounds(edgeLeft, 0, mWidth - edgeLeft, edgeBottom);
        } else {
            // Stretch the edge to fit.
            mEdge.setBounds(0, 0, mWidth, edgeBottom);
        }
        mEdge.draw(canvas);

        return mState != STATE_IDLE;
    }

    private void update() {
        final long time = AnimationTime.get();
        final float t = Math.min((time - mStartTime) / mDuration, 1.f);

        final float interp = mInterpolator.getInterpolation(t);

        mEdgeAlpha = mEdgeAlphaStart + (mEdgeAlphaFinish - mEdgeAlphaStart) * interp;
        mEdgeScaleY = mEdgeScaleYStart + (mEdgeScaleYFinish - mEdgeScaleYStart) * interp;
        mGlowAlpha = mGlowAlphaStart + (mGlowAlphaFinish - mGlowAlphaStart) * interp;
        mGlowScaleY = mGlowScaleYStart + (mGlowScaleYFinish - mGlowScaleYStart) * interp;

        if (t >= 1.f - EPSILON) {
            switch (mState) {
                case STATE_ABSORB:
                    mState = STATE_RECEDE;
                    mStartTime = AnimationTime.get();
                    mDuration = RECEDE_TIME;

                    mEdgeAlphaStart = mEdgeAlpha;
                    mEdgeScaleYStart = mEdgeScaleY;
                    mGlowAlphaStart = mGlowAlpha;
                    mGlowScaleYStart = mGlowScaleY;

                    // After absorb, the glow and edge should fade to nothing.
                    mEdgeAlphaFinish = 0.f;
                    mEdgeScaleYFinish = 0.f;
                    mGlowAlphaFinish = 0.f;
                    mGlowScaleYFinish = 0.f;
                    break;
                case STATE_PULL:
                    mState = STATE_PULL_DECAY;
                    mStartTime = AnimationTime.get();
                    mDuration = PULL_DECAY_TIME;

                    mEdgeAlphaStart = mEdgeAlpha;
                    mEdgeScaleYStart = mEdgeScaleY;
                    mGlowAlphaStart = mGlowAlpha;
                    mGlowScaleYStart = mGlowScaleY;

                    // After pull, the glow and edge should fade to nothing.
                    mEdgeAlphaFinish = 0.f;
                    mEdgeScaleYFinish = 0.f;
                    mGlowAlphaFinish = 0.f;
                    mGlowScaleYFinish = 0.f;
                    break;
                case STATE_PULL_DECAY:
                    // When receding, we want edge to decrease more slowly
                    // than the glow.
                    float factor = mGlowScaleYFinish != 0 ? 1
                            / (mGlowScaleYFinish * mGlowScaleYFinish)
                            : Float.MAX_VALUE;
                    mEdgeScaleY = mEdgeScaleYStart +
                        (mEdgeScaleYFinish - mEdgeScaleYStart) *
                            interp * factor;
                    mState = STATE_RECEDE;
                    break;
                case STATE_RECEDE:
                    mState = STATE_IDLE;
                    break;
            }
        }
    }

    public static class Drawable extends ResourceTexture {
        private Rect mBounds = new Rect();
        private int mAlpha = 255;

        public Drawable(Context context, int resId) {
            super(context, resId);
        }

        public int getIntrinsicWidth() {
            return getWidth();
        }

        public int getIntrinsicHeight() {
            return getHeight();
        }

        public void setBounds(int left, int top, int right, int bottom) {
            mBounds.set(left, top, right, bottom);
        }

        public void setAlpha(int alpha) {
            mAlpha = alpha;
        }

        public void draw(GLESCanvas canvas) {
            canvas.save(GLESCanvas.SAVE_FLAG_ALPHA);
            canvas.multiplyAlpha(mAlpha / 255.0f);
            Rect b = mBounds;
            draw(canvas, b.left, b.top, b.width(), b.height());
            canvas.restore();
        }
    }
}


text:
---
layout: documentation.pug
title: Upgrade guides
---

## Upgrade to version 3

We are preparing to integrate the Helper directly inside InstantSearch, and for this are making some breaking changes. If you are happy using the current version of the Helper, there's no pressing need for you to upgrade to the next version. If you want to migrate to the next version of the Helper, breaking changes are in the following places:

### Lodash

We have fully migrated away from lodash in v3. This means that there are some cases which used to accept incorrect shapes (objects where it should be arrays) will throw errors now.

### URL sync

Synchronizing to the URL is no longer a responsibility of the Helper, but instead now it's a responsibility of the routing functionality of InstantSearch. This means the following methods no longer exist:

- `algoliasearch-helper/url`
- `algoliasearchHelper.url`
- `getStateAsQueryString`
- `getConfigurationFromQueryString`
- `getForeignConfigurationInQueryString`
- `setStateFromQueryString`

### Events

The event payload now always is an object, instead of multiple arguments:

```js
helper.on(
  "search",
  ({ state: SearchParameters, results: SearchResults }) => {/**/}
);
helper.on(
  "change",
  ({
    state: SearchParameters,
    results: SearchResults,
    isPageReset: boolean
  }) => {/**/}
);
helper.on(
  "searchForFacetValues",
  ({ state: SearchParameters, facet: string, query: string }) => {/**/}
);
helper.on(
  "searchOnce",
  ({ state: SearchParameters }) => {/**/}
);
helper.on(
  "result",
  ({ results: SearchResults, state: SearchParameters }) => {/**/}
);
helper.on(
  "error",
  ({ error: Error }) => {/**/}
);
helper.on(
  "searchQueueEmpty",
  () => {/**/}
);
```

### Default values

SearchParameters no longer contains a default value for the parameters, from the previous `undefined`, `""` or `0`, we now have no more values on the object by default, this means an empty SearchParameters now looks like this:

```json
{
  "facets": [],
  "disjunctiveFacets": [],
  "hierarchicalFacets": [],
  "facetsRefinements": {},
  "facetsExcludes": {},
  "disjunctiveFacetsRefinements": {},
  "numericRefinements": {},
  "tagRefinements": [],
  "hierarchicalFacetsRefinements": {}
}
```

### Errors on getters

There were multiple places in SearchParameters or SearchResults which would throw an error when e.g. a refinement is requested which isn't set up via facets. This behavior was confusing, and especially unhelpful in InstantSearch where we have situations where we try to fetch before the results are in. We chose for that reason to migrate those cases to the default response:

- `SearchResults.getFacetValues` -> undefined
- `SearchResults.getFacetStats` -> undefined
- `SearchParameters.getConjunctiveRefinements` -> []
- `SearchParameters.getDisjunctiveRefinements` -> []
- `SearchParameters.getExcludeRefinements` -> []
- `SearchParameters.getHierarchicalFacetBreadcrumb` -> []
- `SearchParameters.isFacetRefined` -> false
- `SearchParameters.isExcludeRefined` -> false
- `SearchParameters.isDisjunctiveFacetRefined` -> false
- `SearchParameters.isHierarchicalFacetRefined` -> false

### Removed methods

- `getQueryParameter` & `helper.state.getQueryParameter`

```
// With getQueryParameter
helper.getQueryParameter('hitsPerPage');

// Without getQueryParameter
helper.state.hitsPerPage;
```

- `helper.state.filter`

You need to filter the returned object yourself using e.g. `Object.fromEntries(Object.entries(helper.state).filter(/**/))`

- `helper.state.mutateMe`

- `helper.getState` -> `helper.state`

- `helper.isRefined` -> `helper.hasRefinements`


text:
$(document).ready(function() {
	$('#tabs-upper, #tabs-lower').tabs();
});


text:
var React = require('react');
var Article = require('grommet/components/Article');
var Calendar = require('grommet/components/Calendar');

var CalendarDoc = React.createClass({

  _onChange: function (value) {
    this.setState({value: value});
  },

  getInitialState: function () {
    return {value: (new Date()).toISOString().slice(0, 10)};
  },

  render: function() {
    var inline =
      "<Calendar onChange={...} />";
    return (

Calendar

An input field for a date.

{inline}

Options

id            {"{string}"}

The id attribute of the input.

name          {"{string}"}

The name attribute of the input.

onChange      {"function ({string}) {...}"}

Function that will be called when the user types some text into
              the input or selects a date from the drop down.

value         {"{string}"}

What text to put in the input.

Examples

            <Calendar id="item1" name="item-1"
              onChange={this._onChange} value={this.state.value} />

{"<Calendar value={...} onChange={...} />"}

    );
  }
});

module.exports = CalendarDoc;


text:
import { atom } from 'jotai';

import { defaultAcknowledgement } from './defaults';

import { Acknowledgement } from '.';

const acknowledgementAtom = atom<Acknowledgement>(defaultAcknowledgement);

export default acknowledgementAtom;


text:
declare module "es6-request" {
    import http = require("http");
    import stream = require("stream");

    interface CustomOptions {
        bodyAsBuffer?: boolean;
        returnBody?: boolean;
    }

    interface Options extends http.ClientRequestArgs {
        custom?: CustomOptions;
    }

    type BodyType = string | Buffer;
    type PerformReturn = [BodyType, http.IncomingMessage];

    class ES6Request extends stream.Duplex {
        req: http.ClientRequest;

        headers(obj: http.OutgoingHttpHeaders): this;
        header(key: string, value: number | string | string[] | undefined): this;
        authBasic(username: string, password: string): this;
        authBearer(bearer: string): this;
        options(obj: Options): this;
        option(key: string, value: any): this;
        query(key: string, value: string): this;
        query(params: object): this;
        start(): this;
        then(onSuccess?: (data: PerformReturn) => any, onFailure?: (err: Error) => any): Promise<any>;
        catch(onFailure?: (err: Error) => any): Promise<any>;
        destroy(error?: Error): this;
        perform(): Promise<PerformReturn>;
        perform<T extends BodyType>(): Promise<[T, http.IncomingMessage]>;
        on(event: "error", listener: (err: Error) => void): this;
        on(event: "data", listener: (chunk: Buffer) => void): this;
        on(event: "progress", listener: (progress: number, current: number, total: number) => void): this;
        on(event: "end", listener: () => void): this;
        on(event: "close", listener: () => void): this;
        on(event: string | symbol, listener: (...args: any[]) => void): this;
        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
        send(body: string | Buffer, encoding?: string, callback?: Function): Promise<PerformReturn>;
        sendForm(form: object): Promise<PerformReturn>;
        sendMultipart(form: object | null, files: object | null, filesFieldNameFormat?: string, encoding?: string): Promise<PerformReturn>;
        sendJSON(data?: any): Promise<PerformReturn>;
    }

    interface CustomError extends Error {
        code: string;
    }

    interface ES6RequestExport {
        put(url: string, options?: Options): ES6Request;
        post(url: string, options?: Options): ES6Request;
        patch(url: string, options?: Options): ES6Request;
        delete(url: string, options?: Options): ES6Request;
        get(url: string, options?: Options): ES6Request;
        head(url: string, options?: Options): ES6Request;
        options(url: string, options?: Options): ES6Request;
        Errors: {
            InvalidProtocolError: CustomError;
            InvalidMethodError: CustomError;
            WriteOnReadOnlyMethodError: CustomError;
        };
    }

    var out: ES6RequestExport;
    export = out;
}


text:
package org.nmdp.hmlfhirconverter.dao;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.nmdp.hmlfhirconvertermodels.domain.Haploid;

public interface HaploidRepository extends MongoRepository<Haploid, String> {
    Page<Haploid> findAll(Pageable pageable);
}


text:
<bill session="110" type="h" number="1377" updated="2009-01-08T19:43:37-05:00">
	<status><introduced date="1173243600" datetime="2007-03-07"/></status>

	<introduced date="1173243600" datetime="2007-03-07"/>
	<titles>
		<title type="short" as="introduced">Teachers of English Language Learners Act</title>
		<title type="official" as="introduced">To amend the Internal Revenue Code of 1986 to provide a credit against tax for an individual teaching in a school with a significant number of limited English proficient students and to provide a deduction for expenses paid or incurred by a teacher for courses required for certification in teaching English as a second language.</title>
	</titles>
	<sponsor id="400657"/>
	<cosponsors>
		<cosponsor id="400263" joined="2007-03-07"/>
		<cosponsor id="400336" joined="2007-03-07"/>
		<cosponsor id="400443" joined="2007-03-07"/>
		<cosponsor id="412214" joined="2007-04-17"/>
		<cosponsor id="400356" joined="2007-04-17"/>
		<cosponsor id="400001" joined="2007-04-17"/>
		<cosponsor id="400093" joined="2007-04-26"/>
		<cosponsor id="400283" joined="2007-04-17"/>
		<cosponsor id="400310" joined="2007-03-07"/>
	</cosponsors>
	<actions>
		<action date="1173243600" datetime="2007-03-07"><text>Referred to the House Committee on Ways and Means.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	3/7/2007--Introduced.
Teachers of English Language Learners Act - Amends the Internal Revenue Code to: (1) allow a tax credit for full-time teachers in limited English proficient schools; and (2) a tax deduction for tuition and fees for courses required for certification to teach English to elementary or secondary school students who are limited English proficient, as defined by the Elementary and Secondary Education Act of 1965.

</bill>


text:
package org.apache.camel.component.kubernetes.processor;

import org.apache.camel.ExchangePattern;
import org.apache.camel.component.kubernetes.KubernetesConfiguration;
import org.apache.camel.impl.remote.DefaultServiceCallProcessor;
import org.apache.camel.spi.ServiceCallServer;
import org.apache.camel.spi.ServiceCallServerListStrategy;

public class KubernetesServiceCallProcessor extends DefaultServiceCallProcessor<ServiceCallServer> {
    public KubernetesServiceCallProcessor(String name, String scheme, String uri, ExchangePattern exchangePattern, KubernetesConfiguration conf) {
        super(name, scheme, uri, exchangePattern);
    }

    @Override
    public void setServerListStrategy(ServiceCallServerListStrategy<ServiceCallServer> serverListStrategy) {
        if (!(serverListStrategy instanceof KubernetesServiceCallServerListStrategy)) {
            throw new IllegalArgumentException("ServerListStrategy is not an instance of KubernetesServiceCallServerListStrategy");
        }

        super.setServerListStrategy(serverListStrategy);
    }

    @Override
    protected void doStart() throws Exception {
        ServiceCallServerListStrategy<ServiceCallServer> strategy = getServerListStrategy();
        if (strategy != null && strategy instanceof KubernetesServiceCallServerListStrategies.DNS) {
            setServiceCallExpression(new KubernetesDnsServiceCallExpression(
                getName(),
                getScheme(),
                getContextPath(),
                getUri()
            ));
        }

        super.doStart();
    }
}


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class EntrustSetupTables extends Migration {

    /**
     * Run the migrations.
     *
     * @return  void
     */
    public function up()
    {
        // Creates the roles table
        Schema::create('roles', function($table)
        {
            $table->increments('id')->unsigned();
            $table->string('name')->unique();
            $table->timestamps();
        });

        // Creates the assigned_roles (Many-to-Many relation) table
        Schema::create('assigned_roles', function($table)
        {
            $table->increments('id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles');
        });

        // Creates the permissions table
        Schema::create('permissions', function($table)
        {
            $table->increments('id')->unsigned();
            $table->string('name')->unique();
            $table->string('display_name');
            $table->timestamps();
        });

        // Creates the permission_role (Many-to-Many relation) table
        Schema::create('permission_role', function($table)
        {
            $table->increments('id')->unsigned();
            $table->integer('permission_id')->unsigned();
            $table->integer('role_id')->unsigned();
            $table->foreign('permission_id')->references('id')->on('permissions'); // assumes a users table
            $table->foreign('role_id')->references('id')->on('roles');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return  void
     */
    public function down()
    {
        Schema::table('assigned_roles', function(Blueprint $table) {
            $table->dropForeign('assigned_roles_user_id_foreign');
            $table->dropForeign('assigned_roles_role_id_foreign');
        });

        Schema::table('permission_role', function(Blueprint $table) {
            $table->dropForeign('permission_role_permission_id_foreign');
            $table->dropForeign('permission_role_role_id_foreign');
        });

        Schema::drop('assigned_roles');
        Schema::drop('permission_role');
        Schema::drop('roles');
        Schema::drop('permissions');
    }

}


text:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<body>

<?php //echo $about[0]->content;?>
</body>
</html>


text:
<?php

ini_set('display_errors', '1');

include "cUrl.php";

function getPlusOne($package) {
    $main_url = "https://apis.google.com/u/0/se/3/_/+1/fastbutton?usegapi=1&annotation=inline&recommendations=false&size=medium&source=google%3Amarket&hl=en&origin=https%3A%2F%2Fplay.google.com&url=https%3A%2F%2Fmarket.android.com%2Fdetails%3Fid%3D".$package."&gsrc=3p&ic=1";

    $html =  file_get_contents($main_url);

    $count = cUrl::getBetweenString($html, '+', ' ');

    return $count;
}

function getPlayStoreHTML($package) {
    $url = "https://play.google.com/store/apps/details?id=$package&hl=en";

    $html =  file_get_contents($url);

    return $html;
}

function getReviewCount($package, $html) {

    $count = cUrl::getBetweenString($html, 'stars-count"> (', ')');

    $count = str_replace(',', '', $count);

    return $count;
}

function getDescription($package, $html) {
    $description = cUrl::getBetweenString($html, '
', 'getTimestamp();
    $now = new MongoDate($ts);

    $host = "mongodb://admin:1ePwQJx4KNaR@127.6.119.3:27017/";

    $m = new MongoClient($host);
    $db = $m->underwater;
    $collection = $db->checkpoints;

    $cursor = $collection->find(array("package" => $package, "description" => array('$ne' => null)))->sort(array('date' => -1) );
    $last_row = $cursor->getNext();
    $desc_md5_last = md5($last_row['description']);
    $desc_md5_curr = md5($description);
    if($desc_md5_curr == $desc_md5_last) $description = null;

    $document = array( "data_version" => "v1", "package" => $package, "date" => $now, "reviews" => $reviews, "gplus" => $plus, "description" => $description );
    $collection->insert($document);
}

function read_targets() {
    $link = mysqli_connect('127.6.119.2', 'adminmW9DPtq', '42T3X5F_Zxc-', 'underwater');

    $targets = array();

    // Performing SQL query
    $query = "SELECT * FROM `targets`";
    $result = mysqli_query($link, $query);

    while($row = $result->fetch_array()) {
        $targets[] = $row['package'];
    }

    return $targets;
}

$targets = read_targets();

foreach($targets as $target) {
    $package = $target;

    $html = getPlayStoreHTML($package);

    $plus_one_count = getPlusOne($package);
    $review_count = getReviewCount($package, $html);
    $description = getDescription($package, $html);

    save_data_point_mongo($package, $review_count, $plus_one_count, $description);
}

echo "done";
?>


text:
#import <UIKit/UIKit.h>
#import <JavaScriptCore/JavaScriptCore.h>

#import "CobaltAlert.h"
#import "CobaltToast.h"
#import "CobaltBarButtonItem.h"
#import "BackBarButtonItem.h"

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark JAVASCRIPT KEYS

////////////////////////////////////////////////////////////////////////////////////////////////

// GENERAL
#define kJSAction                           @"action"
#define kJSCallback                         @"callback"
#define kJSData                             @"data"
#define kJSName                             @"name"
#define kJSPage                             @"page"
#define kJSTexts                            @"texts"
#define kJSType                             @"type"
#define KJSVersion                          @"version"
#define kJSValue                            @"value"
#define kJSValues                           @"values"
#define kJSResult                           @"result"

// CALLBACK
#define JSTypeCallBack                      @"callback"

// COBALT IS READY
#define JSTypeCobaltIsReady                 @"cobaltIsReady"

// EVENT
#define JSTypeEvent                         @"event"
#define kJSEvent                            @"event"

// LOG
#define JSTypeLog                           @"log"

// NAVIGATION
#define JSTypeNavigation                    @"navigation"
#define JSActionNavigationPush              @"push"
#define JSActionNavigationPop               @"pop"
#define JSActionNavigationModal             @"modal"
#define JSActionNavigationDismiss           @"dismiss"
#define kJSActionNavigationReplace          @"replace"
#define kJSNavigationController             @"controller"
#define kJSBars                             @"bars"
#define JSEventCallbackOnBackButtonPressed  @"onBackButtonPressed"

#define kJSAnimated                         @"animated"
#define kJSClearHistory                     @"clearHistory"

//LIFE CYCLE
#define JSEventOnAppStarted                 @"onAppStarted"
#define JSEventOnAppForeground              @"onAppForeground"
#define JSEventOnAppBackground              @"onAppBackground"
#define JSEventOnPageShown                  @"onPageShown"

// PULL TO REFRESH
#define JSEventPullToRefresh                @"pullToRefresh"
#define JSCallbackPullToRefreshDidRefresh   @"pullToRefreshDidRefresh"

// INFINITE SCROLL
#define JSEventInfiniteScroll               @"infiniteScroll"
#define JSCallbackInfiniteScrollDidRefresh  @"infiniteScrollDidRefresh"

// UI
#define JSTypeUI                            @"ui"
#define kJSControl                          @"control"

#define kJSTypeImage                        @"image"
#define JSActionPressed                     @"actionPressed"

// PULL TO REFRESH
#define JSControlPullToRefresh              @"pullToRefresh"
#define JSActionSetTexts                    @"setTexts"
#define kJSTextsPullToRefresh               @"pullToRefresh"
#define kJSTextsRefreshing                  @"refreshing"

// ALERT
#define JSControlAlert                      @"alert"
#define kJSAlertTitle                       @"title"
#define kJSAlertMessage                     @"message"
#define kJSAlertButtons                     @"buttons"
#define kJSAlertButtonIndex                 @"index"

// BARS
#define FLEXIBLE_SPACE_TAG                  1
#define JSControlBars                       @"bars"
#define JSActionSetBarsVisible              @"setBarsVisible"
#define JSActionSetBarContent               @"setBarContent"
#define JSActionSetActionVisible            @"setActionVisible"
#define JSActionSetActionEnabled            @"setActionEnabled"
#define JSActionSetActionBadge              @"setActionBadge"
#define JSActionSetActionContent            @"setActionContent"
#define JSActionSetBars                     @"setBars"
#define kJSBars                             @"bars"
#define kJSContent                          @"content"
#define kJSName                             @"name"
#define kJSVisible                          @"visible"
#define kJSEnabled                          @"enabled"
#define kJSBadge                            @"badge"

// TOAST
#define JSControlToast                      @"toast"

// WEB LAYER
#define JSTypeWebLayer                      @"webLayer"
#define JSActionWebLayerShow                @"show"
#define JSActionWebLayerDismiss             @"dismiss"
#define JSActionWebLayerBringToFront        @"bringToFront"
#define JSActionWebLayerSendToBack          @"sendToBack"
#define kJSWebLayerFadeDuration             @"fadeDuration"
#define JSEventWebLayerOnDismiss            @"onWebLayerDismissed"
#define JSEventWebLayerOnLoading            @"onWebLayerLoading"
#define JSEventWebLayerOnLoaded             @"onWebLayerLoaded"
#define JSEventWebLayerOnLoadFailed         @"onWebLayerLoadFailed"
#define kJSIsWebLayer                       @"isWebLayer"

//INTENT
#define kJSTypeIntent                        @"intent"
#define kJSActionOpenExternalUrl             @"openExternalUrl"
#define kJSUrl                               @"url"

// HTML
#define defaultHtmlPage                     @"index.html"

//PLUGIN
#define kJSTypePlugin                       @"plugin"
#define kJSPluginName                       @"name"

//NOTIFS
#define kOnAppStarted                       @"onAppStarted"
#define kOnAppForegroundNotification        @"onAppForegroundNotification"
#define kOnAppBackgroundNotification        @"onAppBackgroundNotification"

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark PROTOCOL

////////////////////////////////////////////////////////////////////////////////////////////////

@protocol CobaltDelegate <NSObject>

@optional
- (void)onCobaltIsReady;

@required
- (BOOL)onUnhandledMessage:(NSDictionary *)message;
- (BOOL)onUnhandledEvent:(NSString *)event withData:(NSDictionary *)data andCallback:(NSString *)callback;
- (BOOL)onUnhandledCallback:(NSString *)callback withData:(NSDictionary *)data;

@end

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark INTERFACE

////////////////////////////////////////////////////////////////////////////////////////////////

enum {
    WEB_VIEW = 0,
    WEB_LAYER = 1
};
typedef NSInteger WebViewType;

/*!
 @class			CobaltViewController
 @abstract		Base class for a webView controller that allows javascript/native dialogs
 */
@interface CobaltViewController : UIViewController <UIScrollViewDelegate, UIWebViewDelegate, CobaltAlertDelegate, CobaltToastDelegate, CobaltBarButtonItemDelegate, BackBarButtonItemDelegate>
{
    // Javascript queues
    NSOperationQueue * toJavaScriptOperationQueue;
    NSOperationQueue * fromJavaScriptOperationQueue;

    // Bar button items
    NSMutableArray *topLeftBarButtonItems;
    NSMutableArray *topRightBarButtonItems;
    NSMutableArray *bottomBarButtonItems;

@private

    id<CobaltDelegate> _delegate;
    float _lastWebviewContentOffset;
	BOOL _isLoadingMore;
    BOOL _isRefreshing;

    NSAttributedString * _ptrRefreshText;
    NSAttributedString * _ptrRefreshingText;
}

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark PROPERTIES

////////////////////////////////////////////////////////////////////////////////////////////////

/*!
 @property		webView
 @abstract		the webView displaying content
 */
@property (strong, nonatomic) IBOutlet UIWebView * webView;

/*!
 @property		pageName
 @abstract		the name of the HTML file with the content to display in the webview
 @discussion    the file must be located at ressourcePath
 */
@property (strong, nonatomic) NSString * pageName;

/*!
 @property             navigationData
 @abstract             the data to pass to the webview in onPageShown event on navigation
 */
@property (strong, nonatomic) NSDictionary *navigationData;

@property (strong, nonatomic) UIWebView * webLayer;

/*!
 @property             refreshControl
 @abstract             a refresh control shown for Pull-to-refresh feature
 */
@property (strong, nonatomic) UIRefreshControl *refreshControl;

/*!
 @property		background
 @abstract		background color of the WebView
 */
@property (strong, nonatomic) UIColor *background;

/*!
 @property		scrollsToTop
 @abstract		allows or not the scrollsToTop functionality
 */
@property BOOL scrollsToTop;

/*!
 @property		isPullToRefreshEnabled
 @abstract		allows or not the pullToRefresh functionality
 */
@property BOOL isPullToRefreshEnabled;

/*!
 @property		isInfiniteScrollEnabled
 @abstract		allows or not the infinite scroll functionality
 */
@property BOOL isInfiniteScrollEnabled;

/*!
 @property		infiniteScrollOffset
 @abstract		offset to trigger infinite scroll
 */
@property int infiniteScrollOffset;

/*!
 @property		barsConfiguration
 @abstract		bars configuration as defined in cobalt.conf or sent by Web on navigation
 */
@property NSMutableDictionary *barsConfiguration;

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark COBALT METHODS

////////////////////////////////////////////////////////////////////////////////////////////////

/*!
 @method		- (void)initWithPage:(nonnull NSString *)page andController:(nullable NSString *)controller
 @abstract		this method sets the configuration of the native controller. If the controller is instantiated from a storyboard, override the initWithCoder: method and call it in instead of instantiate it programmatically
 */
- (void)initWithPage:(nonnull NSString *)page
       andController:(nullable NSString *)controller;

/*!
 @method		- (void)setDelegate:(id<CobaltDelegate>)delegate
 @abstract		this method sets the delegate which responds to CobaltDelegate protocol
 */
- (void)setDelegate:(id<CobaltDelegate>)delegate;

/*!
 @method		-(void) customView
 @abstract		a method to custom the webView
 @discussion    must be subclassed in subclasses
 */
- (void)customWebView;

/*!
 @method		- (void)loadPage:(NSString *)page inWebView:(UIWebView *)mWebView
 @abstract		this method loads the page in ressourcePath in the Web view.
 @param         mWebView : Web view to load the page into
 @param         page: the page file
 */
- (void)loadPage:(NSString *)page inWebView:(UIWebView *)mWebView;

/*!
 @method		- (void) sendMessage:(NSDictionary *) message;
 @abstract		this method sends an message who was an Object format in an NSDictionary
 @param         messageId : the messageId given by a former JS call. It's all events aren't send with sendCallback and sendEvent.
 @discussion    This method should NOT be overridden in subclasses.
 */
- (void) sendMessage:(NSDictionary *) message;

- (void) sendMessageToWebLayer:(NSDictionary *) message;

/*!
 @method		-(void) sendCallback:(NSString *)callbackId withData:(NSObject *)data
 @abstract		this methods sends a callback with the givent callbackId and the object as parameter of the methods which is called in JS
 @param         callbackId : the callbackID given by a former JS call, so that JS calls the appropriate method
 @param         object : the object to send to the JS method which corresponds to the callbackId given
 @discussion    This method should NOT be overridden in subclasses.
 */
- (void)sendCallback:(NSString *)callback withData:(NSObject *)data;

/*!
 @method		- (void)sendEvent:(NSString *)event withData:(NSObject *)data andCallback:(NSString *)callback
 @abstract		this method sends an event with a data object and an optional callback
 @param         event: event fired
 @param         data: data object to send to JS
 @param         callback: the callback JS should calls when message is treated
 @discussion    This method should NOT be overridden in subclasses.
 */
- (void)sendEvent:(NSString *)event withData:(NSObject *)data andCallback:(NSString *)callback;

- (void)sendCallbackToWebLayer:(NSString *)callback withData:(NSObject *)data;

- (void)sendEventToWebLayer:(NSString *)event withData:(NSObject *)data andCallback:(NSString *)callback;

/*!
 @method        - (BOOL)handleDictionarySentByJavaScript:(NSDictionary *)message
 @abstract      Catches the message sent by the WebView as JSON used to fire native methods (allows interactions from the WebView to the native)
 @param         message: the JSON sent by the WebView
 @result        Returns YES if the message has been catched by the native, NO otherwise.
 @discussion    This method SHOULD NOT be overridden in subclasses.
 */
- (BOOL)handleDictionarySentByJavaScript:(NSDictionary *)message;

/*!
 @method		- (void)sendACK
 @abstract		Sends an ACK event as soon as a JS message is received
 @discussion    This is the default acquitment way. More complex acquitment methods may be implemented but on iOS, every call received by JS should send at least this acquitment.
 */
- (void)sendACK;

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark LIFECYCLE

////////////////////////////////////////////////////////////////////////////////////////////////

- (void)onAppStarted:(NSNotification *)notification;
- (void)onAppBackground:(NSNotification *)notification;
- (void)onAppForeground:(NSNotification *)notification;

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark BARS

////////////////////////////////////////////////////////////////////////////////////////////////

- (void)configureBars;
- (void)resetBars;
- (void)setBarButtonItems;
- (CobaltBarButtonItem *)barButtonItemForAction:(NSDictionary *)action;

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark PULL-TO-REFRESH METHODS

////////////////////////////////////////////////////////////////////////////////////////////////

/*!
 @method		- (void)refresh
 @abstract		Tells the webview to be refresh its content.
 */
- (void)refresh;

/*!
 @method		- (void)refreshWebView
 @abstract		Sends event to refresh Web view content.
 */
- (void)refreshWebView;

/*!
 @method		- (void)customizeRefreshControlWithAttributedText:(NSAttributedString *)attributedText andTintColor: (UIColor *)tintColor
 @abstract		customize native pull to refresh control
 */
- (void)customizeRefreshControlWithAttributedRefreshText:(NSAttributedString *)attributedRefreshText andAttributedRefreshText:(NSAttributedString *)attributedRefreshingText andTintColor: (UIColor *)tintColor;

////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark INFINITE SCROLL METHOS

////////////////////////////////////////////////////////////////////////////////////////////////

/*!
 @method		- (void)loadMoreItems
 @abstract		Tells the webview to be load more datas
 */
- (void)loadMoreItems;

/*!
 @method		-(void) loadMoreContentInWebview
 @abstract		Starts loading more content in webview
 */
- (void)loadMoreContentInWebview;

@end


text:
import numpy as np

from scipy.integrate import dblquad
from scipy.integrate import quad

from scipy.stats import uniform

from cgpm.cgpm import CGpm
from cgpm.network.importance import ImportanceNetwork
from cgpm.uncorrelated.directed import DirectedXyGpm
from cgpm.uncorrelated.uniformx import UniformX
from cgpm.utils import general as gu

class SinY(CGpm):
    def __init__(self, outputs=None, inputs=None, noise=None, rng=None):
        if rng is None:
            rng = gu.gen_rng(1)
        if outputs is None:
            outputs = [0]
        if inputs is None:
            inputs = [1]
        if noise is None:
            noise = .1
        self.rng = rng
        self.outputs = outputs
        self.inputs = inputs
        self.noise = noise
        self.uniform = uniform(scale=self.noise)

    @gu.simulate_many
    def simulate(self, rowid, targets, constraints=None, inputs=None, N=None):
        assert targets == self.outputs
        assert inputs.keys() == self.inputs
        assert not constraints
        x = inputs[self.inputs[0]]
        noise = self.rng.uniform(high=self.noise)
        if np.cos(x) < 0:
            y = np.cos(x) + noise
        else:
            y = np.cos(x) - noise
        return {self.outputs[0]: y}

    def logpdf(self, rowid, targets, constraints=None, inputs=None):
        assert targets.keys() == self.outputs
        assert inputs.keys() == self.inputs
        assert not constraints
        x = inputs[self.inputs[0]]
        y = targets[self.outputs[0]]
        if np.cos(x) < 0:
            return self.uniform.logpdf(y-np.cos(x))
        else:
            return self.uniform.logpdf(np.cos(x)-y)

class Sin(DirectedXyGpm):
    """Y = cos(X) + Noise."""

    def __init__(self, outputs=None, inputs=None, noise=None, rng=None):
        DirectedXyGpm.__init__(
            self, outputs=outputs, inputs=inputs, noise=noise, rng=rng)
        self.x = UniformX(
            outputs=[self.outputs[0]], low=-1.5*np.pi, high=1.5*np.pi)
        self.y = SinY(
            outputs=[self.outputs[1]],
            inputs=[self.outputs[0]],
            noise=noise)
        self.network = ImportanceNetwork([self.x, self.y], rng=self.rng)

    # All further methods are here for historical reasons and are not invoked.
    # Should override simuate and logpdf from the importance network in
    # DirectedXyGpm to activate them.

    def logpdf_xy(self, x, y):
        if not self.D[0] <= x <= self.D[1]:
            return -float('inf')
        if np.cos(x) < 0 and not np.cos(x) <= y <= np.cos(x) + self.noise:
            return -float('inf')
        if np.cos(x) > 0 and not np.cos(x) - self.noise <= y <= np.cos(x):
            return -float('inf')
        return -np.log(self.D[1]-self.D[0]) - np.log(self.noise)

    def logpdf_x(self, x):
        if not self.D[0] <= x <= self.D[1]:
            return -float('inf')
        return -np.log(self.D[1]-self.D[0])

    def logpdf_y(self, y):
        if 0 <= y:
            length, overflow = self._valid_x(y)
            length += 2*overflow
        else:
            length, overflow = self._valid_x(-y)
            length = 2*length + overflow
        length *= 2
        return np.log(length) - np.log(self.noise) - np.log(self.D[1]-self.D[0])

    def logpdf_x_given_y(self, x, y):
        raise NotImplementedError

    def logpdf_y_given_x(self, y, x):
        raise NotImplementedError

    def mutual_information(self):
        def mi_integrand(x, y):
            return np.exp(self.logpdf_xy(x,y)) * \
                (self.logpdf_xy(x,y) - self.logpdf_x(x) - self.logpdf_y(y))
        return dblquad(
            lambda y, x: mi_integrand(x,y), self.D[0], self.D[1],
            self._lower_y, self._upper_y)

    def _valid_x(self, y):
        """Compute valid regions of x for y \in [0, 1], with overflow."""
        assert 0<=y<=1
        x_max = np.arccos(y)
        if y+self.noise < 1:
            x_min = np.arccos(y+self.noise)
        else:
            x_min = 0
        # compute overflow
        overflow = 0
        if y < self.noise:
            overflow = np.arccos(y-self.noise) - np.pi / 2
        return x_max - x_min, overflow

    def _lower_y(self, x):
        if np.cos(x) < 0:
            return np.cos(x)
        else:
            return np.cos(x) - self.noise

    def _upper_y(self, x):
        if np.cos(x) < 0:
            return np.cos(x) + self.noise
        else:
            return np.cos(x)

    def _sanity_test(self):
        # Marginal of x integrates to one.
        print quad(lambda x: np.exp(self.logpdf_x(x)), self.D[0], self.D[1])

        # Marginal of y integrates to one.
        print quad(lambda y: np.exp(self.logpdf_y(y)), -1 ,1)

        # Joint of x,y integrates to one; quadrature will fail for small noise.
        print dblquad(
            lambda y,x: np.exp(self.logpdf_xy(x,y)), self.D[0], self.D[1],
            lambda x: -1, lambda x: 1)


text:
Test of the RNA prescribed motion feature

- BAR turbine
- advanced geometry inputs for aerodyn driver
- Prescribed yaw, rotor, and pitch motion (fairly unphysical motions)
- No induction


text:
DISABLED_DRAW_TEST_F(CGContextFill, ConcentricCirclesWinding, WhiteBackgroundTest<>) {
    CGContextRef context = GetDrawingContext();
    CGRect bounds = GetDrawingBounds();

    CGPoint center = _CGRectGetCenter(bounds);

    CGMutablePathRef concentricCirclesPath = CGPathCreateMutable();

    CGPathAddEllipseInRect(concentricCirclesPath, nullptr, _CGRectCenteredOnPoint({ 50, 50 }, center));
    CGPathAddEllipseInRect(concentricCirclesPath, nullptr, _CGRectCenteredOnPoint({ 100, 100 }, center));
    CGPathAddEllipseInRect(concentricCirclesPath, nullptr, _CGRectCenteredOnPoint({ 150, 150 }, center));
    CGPathAddEllipseInRect(concentricCirclesPath, nullptr, _CGRectCenteredOnPoint({ 200, 200 }, center));

    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 0.5);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);

    CGContextAddPath(context, concentricCirclesPath);
    CGContextDrawPath(context, kCGPathFillStroke);

    CGPathRelease(concentricCirclesPath);
}

DISABLED_DRAW_TEST_F(CGContextFill, ConcentricCirclesEvenOdd, WhiteBackgroundTest<>) {
    CGContextRef context = GetDrawingContext();
    CGRect bounds = GetDrawingBounds();

    CGPoint center = _CGRectGetCenter(bounds);

    CGMutablePathRef concentricCirclesPath = CGPathCreateMutable();

    CGPathAddEllipseInRect(concentricCirclesPath, nullptr, _CGRectCenteredOnPoint({ 50, 50 }, center));
    CGPathAddEllipseInRect(concentricCirclesPath, nullptr, _CGRectCenteredOnPoint({ 100, 100 }, center));
    CGPathAddEllipseInRect(concentricCirclesPath, nullptr, _CGRectCenteredOnPoint({ 150, 150 }, center));
    CGPathAddEllipseInRect(concentricCirclesPath, nullptr, _CGRectCenteredOnPoint({ 200, 200 }, center));

    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 0.5);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);

    CGContextAddPath(context, concentricCirclesPath);
    CGContextDrawPath(context, kCGPathEOFillStroke);

    CGPathRelease(concentricCirclesPath);
}

DISABLED_DRAW_TEST_F(CGContextFill, ConcentricRectsWinding, WhiteBackgroundTest<>) {
    CGContextRef context = GetDrawingContext();
    CGRect bounds = GetDrawingBounds();

    CGPoint center = _CGRectGetCenter(bounds);

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathAddRect(path, nullptr, _CGRectCenteredOnPoint({ 50, 50 }, center));
    CGPathAddRect(path, nullptr, _CGRectCenteredOnPoint({ 100, 100 }, center));
    CGPathAddRect(path, nullptr, _CGRectCenteredOnPoint({ 150, 150 }, center));
    CGPathAddRect(path, nullptr, _CGRectCenteredOnPoint({ 200, 200 }, center));

    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 0.5);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);

    CGContextAddPath(context, path);
    CGContextDrawPath(context, kCGPathFillStroke);

    CGPathRelease(path);
}

DISABLED_DRAW_TEST_F(CGContextFill, ConcentricRectsEvenOdd, WhiteBackgroundTest<>) {
    CGContextRef context = GetDrawingContext();
    CGRect bounds = GetDrawingBounds();

    CGPoint center = _CGRectGetCenter(bounds);

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathAddRect(path, nullptr, _CGRectCenteredOnPoint({ 50, 50 }, center));
    CGPathAddRect(path, nullptr, _CGRectCenteredOnPoint({ 100, 100 }, center));
    CGPathAddRect(path, nullptr, _CGRectCenteredOnPoint({ 150, 150 }, center));
    CGPathAddRect(path, nullptr, _CGRectCenteredOnPoint({ 200, 200 }, center));

    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 0.5);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);

    CGContextAddPath(context, path);
    CGContextDrawPath(context, kCGPathEOFillStroke);

    CGPathRelease(path);
}

class CGContextArcFill : public WhiteBackgroundTest<>, public ::testing::WithParamInterface<::testing::tuple<CGPoint, int>> {
    CFStringRef CreateOutputFilename() {
        CGPoint sweep = ::testing::get<0>(GetParam());
        int direction = ::testing::get<1>(GetParam());
        return CFStringCreateWithFormat(nullptr,
                                        nullptr,
                                        CFSTR("TestImage.CGContextFill.Arc.sweep(%0.0f--%0.0f).direction.%d.png"),
                                        sweep.x,
                                        sweep.y,
                                        direction);
    }
};

DRAW_TEST_P(CGContextArcFill, FillArc) {
    CGContextRef context = GetDrawingContext();
    CGPoint sweep = ::testing::get<0>(GetParam());
    int direction = ::testing::get<1>(GetParam());
    CGContextAddArc(context, 50, 50, 50, sweep.x, sweep.y, direction);
    CGContextFillPath(context);
}

static CGPoint sweep[] = { CGPointMake(0, M_PI),
                           CGPointMake(2 * M_PI, 0),
                           CGPointMake(0.3 * M_PI, 0.6 * M_PI),
                           CGPointMake(0, 1.9 * M_PI) };
static int directions[] = { 0, 1 };

INSTANTIATE_TEST_CASE_P(CGContextFill, CGContextArcFill, ::testing::Combine(::testing::ValuesIn(sweep), ::testing::ValuesIn(directions)));


text:
Tillåt icke auktoriserad routing

<tt>allow_untrusted_routing</tt>

Denna parameter anger om Postfix kommer att skicka e-post med avsändarbestämd
routing (user[@%!]remote[@%!]site) från icke betrodda klienter till destinationer
som välsignats med parametern <tt>relay_domains</tt>.

Standardinställningen är att icke betrodda klienter inte får ange routing.
Detta spärrar ett stort relähål, där en backup-MX-dator kan luras att vidarebefordra
e-post till en primär MX-dator som sedan sprider spam-post över världen.


text:
/**
 *
 */
package weibo4j.examples.user;

import java.io.UnsupportedEncodingException;

import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;

/**
 * @author sina
 *
 */
public class GetUserInfo {

	/**
	 * 根据用户ID获取用户资料(授权用户)
	 * @param args
	 * @throws UnsupportedEncodingException
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		try {
			String screen_name="李开复";
			Weibo weibo = new Weibo();
			weibo.setToken(args[0],args[1]);
			User user = weibo.showUser(screen_name);
			System.out.println(user.toString());
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}
}