text:
package net.openhft.chronicle.network;

import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.io.ClosedIllegalStateException;
import net.openhft.chronicle.network.connection.ClientConnectionMonitor;
import net.openhft.chronicle.network.connection.FatalFailureMonitor;
import net.openhft.chronicle.network.connection.SocketAddressSupplier;
import net.openhft.chronicle.network.tcp.ChronicleSocket;
import net.openhft.chronicle.network.tcp.ChronicleSocketChannel;
import net.openhft.chronicle.network.tcp.ChronicleSocketChannelFactory;
import net.openhft.chronicle.wire.Marshallable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

import static net.openhft.chronicle.core.io.Closeable.closeQuietly;

public interface ConnectionStrategy extends Marshallable, java.io.Closeable {

    default ClientConnectionMonitor clientConnectionMonitor() {
        return new VanillaClientConnectionMonitor();
    }

    @Nullable
    static ChronicleSocketChannel socketChannel(@NotNull InetSocketAddress socketAddress, int tcpBufferSize, int socketConnectionTimeoutMs) throws IOException {

        final ChronicleSocketChannel result = ChronicleSocketChannelFactory.wrap();
        @Nullable Selector selector = null;
        boolean failed = true;
        try {
            result.configureBlocking(false);
            ChronicleSocket socket = result.socket();
            if (!TcpEventHandler.DISABLE_TCP_NODELAY) socket.setTcpNoDelay(true);
            socket.setReceiveBufferSize(tcpBufferSize);
            socket.setSendBufferSize(tcpBufferSize);
            socket.setSoTimeout(0);
            socket.setSoLinger(false, 0);
            result.connect(socketAddress);

            selector = Selector.open();
            result.register(selector, SelectionKey.OP_CONNECT);

            int select = selector.select(socketConnectionTimeoutMs);
            if (select == 0) {
                if (Jvm.isDebugEnabled(ConnectionStrategy.class))
                    Jvm.debug().on(ConnectionStrategy.class, "Timed out attempting to connect to " + socketAddress);
                return null;
            } else {
                try {
                    if (!result.finishConnect())
                        return null;

                } catch (IOException e) {
                    if (Jvm.isDebugEnabled(ConnectionStrategy.class))
                        Jvm.debug().on(ConnectionStrategy.class, "Failed to connect to " + socketAddress + " " + e);
                    return null;
                }
            }

            failed = false;
            return result;

        } catch (Exception e) {
            return null;
        } finally {
            closeQuietly(selector);
            if (failed)
                closeQuietly(result);
        }
    }

    /**
     * Connects and returns a new SocketChannel.
     *
     * @param name                  the name of the connection, only used for logging
     * @param socketAddressSupplier to use for address
     * @param didLogIn              was the last attempt successful, was a login established
     * @param fatalFailureMonitor   this is invoked on failures
     * @return the SocketChannel
     * @throws InterruptedException if the channel is interrupted.
     */
    ChronicleSocketChannel connect(@NotNull String name,
                                   @NotNull SocketAddressSupplier socketAddressSupplier,
                                   boolean didLogIn,
                                   @NotNull FatalFailureMonitor fatalFailureMonitor) throws InterruptedException;

    @Nullable
    default ChronicleSocketChannel openSocketChannel(@NotNull InetSocketAddress socketAddress,
                                                     int tcpBufferSize,
                                                     long timeoutMs) throws IOException, InterruptedException {

        return openSocketChannel(socketAddress,
                tcpBufferSize,
                timeoutMs,
                1);
    }

    /**
     * the reason for this method is that unlike the selector it uses tick time
     */
    @Nullable
    default ChronicleSocketChannel openSocketChannel(@NotNull InetSocketAddress socketAddress,
                                                     int tcpBufferSize,
                                                     long timeoutMs,
                                                     int socketConnectionTimeoutMs) throws IOException, InterruptedException {
        assert timeoutMs > 0;
        long start = System.currentTimeMillis();
        ChronicleSocketChannel sc = socketChannel(socketAddress, tcpBufferSize, socketConnectionTimeoutMs);
        if (sc != null)
            return sc;

        for (; ; ) {
            throwExceptionIfClosed();
            if (Thread.currentThread().isInterrupted())
                throw new InterruptedException();
            long startMs = System.currentTimeMillis();
            if (start + timeoutMs < startMs) {
                Jvm.warn().on(ConnectionStrategy.class, "Timed out attempting to connect to " + socketAddress);
                return null;
            }
            sc = socketChannel(socketAddress, tcpBufferSize, socketConnectionTimeoutMs);
            if (sc != null)
                return sc;
            Thread.yield();
            // If nothing is listening, socketChannel returns pretty much immediately so we support a pause here
            pauseBeforeReconnect(startMs);
        }
    }

    default void pauseBeforeReconnect(long startMs) {
        long pauseMillis = (startMs + pauseMillisBeforeReconnect()) - System.currentTimeMillis();
        if (Jvm.isDebugEnabled(this.getClass()))
            Jvm.debug().on(this.getClass(), "Waiting for reconnect " + pauseMillis + " ms");
        LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(pauseMillis));
    }

    /**
     * allows control of a backoff strategy
     *
     * @return how long in milliseconds to pause before attempting a reconnect
     */
    default long pauseMillisBeforeReconnect() {
        return 500;
    }

    @Override
    default void close() {
    }

    default boolean isClosed() {
        return false;
    }

    default ConnectionStrategy open() {
        return this;
    }

    default void throwExceptionIfClosed() throws IllegalStateException {
        if (this.isClosed()) {
            throw new ClosedIllegalStateException("Closed");
        }
    }

    default long minPauseSec() {
        return Jvm.getInteger("connectionStrategy.pause.min.secs", 5);
    }

    default long maxPauseSec() {
        return Jvm.getInteger("connectionStrategy.pause.max.secs", 5);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<tc:testcase xmlns:tc="http://restsql.org/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://restsql.org/schema ../ServiceTestCaseDefinition.xsd ">
	<step name="execute">
		<request method="GET" uri="res/SingleTable?_limit=10&_offset=0" />
		<response>
			<header name="Cache-Control" value="no-cache, no-transform" />
			<body>
<![CDATA[
<readResponse>
	<actor id="1" first_name="PENELOPE" surname="GUINESS" />
	<actor id="2" first_name="NICK" surname="WAHLBERG" />
	<actor id="3" first_name="ED" surname="CHASE" />
	<actor id="4" first_name="JENNIFER" surname="DAVIS" />
	<actor id="5" first_name="JOHNNY" surname="LOLLOBRIGIDA" />
	<actor id="6" first_name="BETTE" surname="NICHOLSON" />
	<actor id="7" first_name="GRACE" surname="MOSTEL" />
	<actor id="8" first_name="MATTHEW" surname="JOHANSSON" />
	<actor id="9" first_name="JOE" surname="SWANK" />
	<actor id="10" first_name="CHRISTIAN" surname="GABLE" />
</readResponse>
]]>
			</body>
		</response>
	</step>
</tc:testcase>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PenjualanHewanTernak.Model;

namespace PenjualanHewanTernak.Controller.Customer
{
    class CommandInsertCustomer : Command
    {
        #region Declaration

        #endregion

        #region Constructor
        public CommandInsertCustomer()
        {

        }
        #endregion

        #region Method
        public override object Execute()
        {
            CustomerItem item = new CustomerItem(true);
            return item;
        }
        #endregion
    }
}


text:
import { Middleware, Action, AnyAction } from "redux";

export interface ThunkDispatch<S, E, A extends Action> {
  <T extends A>(action: T): T;
  <R>(asyncAction: ThunkAction<R, S, E, A>): R;
}

export type ThunkAction<R, S, E, A extends Action> = (
  dispatch: ThunkDispatch<S, E, A>,
  getState: () => S,
  extraArgument: E
) => R;

export type ThunkMiddleware<S = {}, A extends Action = AnyAction, E = undefined> = Middleware<ThunkDispatch<S, E, A>, S, ThunkDispatch<S, E, A>>;

declare const thunk: ThunkMiddleware & {
  withExtraArgument<E>(extraArgument: E): ThunkMiddleware<{}, AnyAction, E>
}

export default thunk;


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:activiti="http://activiti.org/bpmn"
  targetNamespace="org.camunda.bpm.engine.test.bpmn.deployment">

  <process id="abcdefghijklmnopqrstuvwxyz12345678901234567891234567890123456789">

    <startEvent id="start" />

    <sequenceFlow id="flow1" sourceRef="start" targetRef="end" />

    <endEvent id="end" />

  </process>

</definitions>


text:
/*
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE', which is part of this source code package.
 * Tuan PM <tuanpm at live dot com>
 */

#ifndef _MQTT_CLIENT_H_
#define _MQTT_CLIENT_H_

#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "esp_err.h"

#include "mqtt_config.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct esp_mqtt_client* esp_mqtt_client_handle_t;

/**
 * @brief MQTT event types.
 *
 * User event handler receives context data in `esp_mqtt_event_t` structure with
 *  - `user_context` - user data from `esp_mqtt_client_config_t`
 *  - `client` - mqtt client handle
 *  - various other data depending on event type
 *
 */
typedef enum {
    MQTT_EVENT_ERROR = 0,
    MQTT_EVENT_CONNECTED,          /*!< connected event, additional context: session_present flag */
    MQTT_EVENT_DISCONNECTED,       /*!< disconnected event */
    MQTT_EVENT_SUBSCRIBED,         /*!< subscribed event, additional context: msg_id */
    MQTT_EVENT_UNSUBSCRIBED,       /*!< unsubscribed event */
    MQTT_EVENT_PUBLISHED,          /*!< published event, additional context:  msg_id */
    MQTT_EVENT_DATA,               /*!< data event, additional context:
                                        - msg_id               message id
                                        - topic                pointer to the received topic
                                        - topic_len            length of the topic
                                        - data                 pointer to the received data
                                        - data_len             length of the data for this event
                                        - current_data_offset  offset of the current data for this event
                                        - total_data_len       total length of the data received
                                         */
    MQTT_EVENT_BEFORE_CONNECT,     /*!< The event occurs before connecting */
} esp_mqtt_event_id_t;

typedef enum {
    MQTT_TRANSPORT_UNKNOWN = 0x0,
    MQTT_TRANSPORT_OVER_TCP,      /*!< MQTT over TCP, using scheme: ``mqtt`` */
    MQTT_TRANSPORT_OVER_SSL,      /*!< MQTT over SSL, using scheme: ``mqtts`` */
    MQTT_TRANSPORT_OVER_WS,       /*!< MQTT over Websocket, using scheme:: ``ws`` */
    MQTT_TRANSPORT_OVER_WSS       /*!< MQTT over Websocket Secure, using scheme: ``wss`` */
} esp_mqtt_transport_t;

/**
 * MQTT event configuration structure
 */
typedef struct {
    esp_mqtt_event_id_t event_id;       /*!< MQTT event type */
    esp_mqtt_client_handle_t client;    /*!< MQTT client handle for this event */
    void *user_context;                 /*!< User context passed from MQTT client config */
    char *data;                         /*!< Data asociated with this event */
    int data_len;                       /*!< Lenght of the data for this event */
    int total_data_len;                 /*!< Total length of the data (longer data are supplied with multiple events) */
    int current_data_offset;            /*!< Actual offset for the data asociated with this event */
    char *topic;                        /*!< Topic asociated with this event */
    int topic_len;                      /*!< Length of the topic for this event asociated with this event */
    int msg_id;                         /*!< MQTT messaged id of message */
    int session_present;                /*!< MQTT session_present flag for connection event */
} esp_mqtt_event_t;

typedef esp_mqtt_event_t* esp_mqtt_event_handle_t;

typedef esp_err_t (* mqtt_event_callback_t)(esp_mqtt_event_handle_t event);

/**
 * MQTT client configuration structure
 */
typedef struct {
    mqtt_event_callback_t event_handle;     /*!< handle for MQTT events */
    const char *host;                       /*!< MQTT server domain (ipv4 as string) */
    const char *uri;                        /*!< Complete MQTT broker URI */
    uint32_t port;                          /*!< MQTT server port */
    const char *client_id;                  /*!< default client id is ``ESP32_%CHIPID%`` where %CHIPID% are last 3 bytes of MAC address in hex format */
    const char *username;                   /*!< MQTT username */
    const char *password;                   /*!< MQTT password */
    const char *lwt_topic;                  /*!< LWT (Last Will and Testament) message topic (NULL by default) */
    const char *lwt_msg;                    /*!< LWT message (NULL by default) */
    int lwt_qos;                            /*!< LWT message qos */
    int lwt_retain;                         /*!< LWT retained message flag */
    int lwt_msg_len;                        /*!< LWT message length */
    int disable_clean_session;              /*!< mqtt clean session, default clean_session is true */
    int keepalive;                          /*!< mqtt keepalive, default is 120 seconds */
    bool disable_auto_reconnect;            /*!< this mqtt client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to disable */
    void *user_context;                     /*!< pass user context to this option, then can receive that context in ``event->user_context`` */
    int task_prio;                          /*!< MQTT task priority, default is 5, can be changed in ``make menuconfig`` */
    int task_stack;                         /*!< MQTT task stack size, default is 6144 bytes, can be changed in ``make menuconfig`` */
    int buffer_size;                        /*!< size of MQTT send/receive buffer, default is 1024 */
    const char *cert_pem;                   /*!< Pointer to certificate data in PEM format for server verify (with SSL), default is NULL, not required to verify the server */
    const char *client_cert_pem;            /*!< Pointer to certificate data in PEM format for SSL mutual authentication, default is NULL, not required if mutual authentication is not needed. If it is not NULL, also `client_key_pem` has to be provided. */
    const char *client_key_pem;             /*!< Pointer to private key data in PEM format for SSL mutual authentication, default is NULL, not required if mutual authentication is not needed. If it is not NULL, also `client_cert_pem` has to be provided. */
    esp_mqtt_transport_t transport;         /*!< overrides URI transport */
    int refresh_connection_after_ms;        /*!< Refresh connection after this value (in milliseconds) */
} esp_mqtt_client_config_t;

esp_mqtt_client_handle_t esp_mqtt_client_init(const esp_mqtt_client_config_t *config);
esp_err_t esp_mqtt_client_set_uri(esp_mqtt_client_handle_t client, const char *uri);
esp_err_t esp_mqtt_client_start(esp_mqtt_client_handle_t client);
esp_err_t esp_mqtt_client_reconnect(esp_mqtt_client_handle_t client);
esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client);
esp_err_t esp_mqtt_client_subscribe(esp_mqtt_client_handle_t client, const char *topic, int qos);
esp_err_t esp_mqtt_client_unsubscribe(esp_mqtt_client_handle_t client, const char *topic);
int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain);
esp_err_t esp_mqtt_client_destroy(esp_mqtt_client_handle_t client);
esp_err_t esp_mqtt_set_config(esp_mqtt_client_handle_t client, const esp_mqtt_client_config_t *config);

#ifdef __cplusplus
}
#endif //__cplusplus

#endif


text:
package org.knowm.xchange.deribit.v2;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.knowm.xchange.deribit.v2.dto.DeribitException;
import org.knowm.xchange.deribit.v2.dto.DeribitResponse;
import org.knowm.xchange.deribit.v2.dto.GrantType;
import org.knowm.xchange.deribit.v2.dto.Kind;
import org.knowm.xchange.deribit.v2.dto.account.DeribitAuthentication;
import org.knowm.xchange.deribit.v2.dto.marketdata.DeribitCurrency;
import org.knowm.xchange.deribit.v2.dto.marketdata.DeribitInstrument;
import org.knowm.xchange.deribit.v2.dto.marketdata.DeribitOrderBook;
import org.knowm.xchange.deribit.v2.dto.marketdata.DeribitSummary;
import org.knowm.xchange.deribit.v2.dto.marketdata.DeribitTicker;
import org.knowm.xchange.deribit.v2.dto.marketdata.DeribitTrades;

@Path("/api/v2/public")
@Produces(MediaType.APPLICATION_JSON)
public interface Deribit {

  /**
   * @param currency required, the currency symbol
   * @param kind optional, Instrument kind, if not provided instruments of all kinds are considered
   * @param expired optional, set to true to show expired instruments instead of active ones
   * @return
   * @throws DeribitException
   * @throws IOException
   */
  @GET
  @Path("get_instruments")
  DeribitResponse<List<DeribitInstrument>> getInstruments(
      @QueryParam("currency") String currency,
      @QueryParam("kind") Kind kind,
      @QueryParam("expired") Boolean expired)
      throws DeribitException, IOException;

  /**
   * Retrieves available trading instruments. This method can be used to see which instruments are
   * available for trading, or which instruments have existed historically.
   *
   * @return
   * @throws DeribitException
   * @throws IOException
   */
  @GET
  @Path("get_currencies")
  DeribitResponse<List<DeribitCurrency>> getCurrencies() throws DeribitException, IOException;

  /**
   * Retrieves the order book, along with other market values for a given instrument.
   *
   * @param instrumentName required, the instrument name for which to retrieve the order book, see
   *     {@link #getInstruments(String, Kind, Boolean) getInstruments} to obtain instrument names.
   * @param depth optional, the number of entries to return for bids and asks. max: 10000, default:
   *     20
   * @return
   * @throws DeribitException
   * @throws IOException
   */
  @GET
  @Path("get_order_book")
  DeribitResponse<DeribitOrderBook> getOrderBook(
      @QueryParam("instrument_name") String instrumentName, @QueryParam("depth") Integer depth)
      throws DeribitException, IOException;

  /**
   * Provides information about historical volatility for given cryptocurrency.
   *
   * @param currency required, the currency name for which to retrieve the historical volatility,the
   *     value can be BTC,ETH or USDT.
   * @return
   * @throws DeribitException
   * @throws IOException
   */
  @GET
  @Path("get_historical_volatility")
  DeribitResponse<List<List<BigDecimal>>> getHistoricalVolatility(
      @QueryParam("currency") String currency) throws DeribitException, IOException;

  /**
   * Retrieve the latest trades that have occurred for a specific instrument.
   *
   * @param instrumentName required, Instrument name
   * @param startSeq optional, The sequence number of the first trade to be returned
   * @param endSeq optional, The sequence number of the last trade to be returned
   * @param count optional, Number of requested items, default: 10
   * @param includeOld optional, Include trades older than 7 days, default: false
   * @param sorting optional, (asc, desc, default) Direction of results sorting (default value means
   *     no sorting, results will be returned in order in which they left the database)
   * @return
   * @throws DeribitException
   * @throws IOException
   */
  @GET
  @Path("get_last_trades_by_instrument")
  DeribitResponse<DeribitTrades> getLastTradesByInstrument(
      @QueryParam("instrument_name") String instrumentName,
      @QueryParam("start_seq") Integer startSeq,
      @QueryParam("end_seq") Integer endSeq,
      @QueryParam("count") Integer count,
      @QueryParam("include_old") Boolean includeOld,
      @QueryParam("sorting") String sorting)
      throws DeribitException, IOException;

  /**
   * Retrieves the summary information such as open interest, 24h volume, etc. for a specific
   * instrument.
   *
   * @param instrumentName required, Instrument name
   * @return
   * @throws DeribitException
   * @throws IOException
   */
  @GET
  @Path("get_book_summary_by_instrument")
  DeribitResponse<List<DeribitSummary>> getSummaryByInstrument(
      @QueryParam("instrument_name") String instrumentName) throws DeribitException, IOException;

  /**
   * Get ticker for an instrument.
   *
   * @param instrumentName required, Instrument name
   * @return
   * @throws DeribitException
   * @throws IOException
   */
  @GET
  @Path("ticker")
  DeribitResponse<DeribitTicker> getTicker(@QueryParam("instrument_name") String instrumentName)
      throws DeribitException, IOException;

  /**
   * Retrieve an Oauth access token, to be used for authentication of 'private' requests.
   *
   * @param grantType Method of authentication
   * @param username Required for grant type 'password'
   * @param password Required for grant type 'password'
   * @param clientId Required for grant type 'client_credentials' and 'client_signature'
   * @param clientSecret Required for grant type 'client_credentials'
   * @param refreshToken Required for grant type 'refresh_token'
   * @param timestamp Required for grant type 'client_signature', provides time when request has
   *     been generated
   * @param signature Required for grant type 'client_signature'; it's a cryptographic signature
   *     calculated over provided fields using user secret key. The signature should be calculated
   *     as an HMAC (Hash-based Message Authentication Code) with SHA256 hash algorithm
   * @param nonce Optional for grant type 'client_signature'; delivers user generated initialization
   *     vector for the server token
   * @param state Will be passed back in the response
   * @param scope Describes type of the access for assigned token, possible values: connection,
   *     session, session:name, trade:[read, read_write, none], wallet:[read, read_write, none],
   *     account:[read, read_write, none], expires:NUMBER, ip:ADDR. NOTICE: Depending on choosing an
   *     authentication method (grant type) some scopes could be narrowed by the server. e.g. when
   *     grant_type = client_credentials and scope = wallet:read_write it's modified by the server
   *     as scope = wallet:read
   * @return
   * @throws DeribitException
   * @throws IOException
   */
  @GET
  @Path("auth")
  DeribitResponse<DeribitAuthentication> auth(
      @QueryParam("grant_type") GrantType grantType,
      @QueryParam("username") String username,
      @QueryParam("password") String password,
      @QueryParam("client_id") String clientId,
      @QueryParam("client_secret") String clientSecret,
      @QueryParam("refresh_token") String refreshToken,
      @QueryParam("timestamp") String timestamp,
      @QueryParam("signature") String signature,
      @QueryParam("nonce") String nonce,
      @QueryParam("state") String state,
      @QueryParam("scope") String scope)
      throws DeribitException, IOException;
}


text:
package com.gmail.hasszhao.mininews.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;

public class OneDirectionListView extends ListView {

	private GestureDetector mGestureDetector;
	View.OnTouchListener mGestureListener;
	private boolean mAllowTouch = true;

	public OneDirectionListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mGestureDetector = new GestureDetector(context, new YScrollDetector());
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		mGestureDetector.onTouchEvent(ev);
		if (mAllowTouch)
			return super.onInterceptTouchEvent(ev);
		return false;
	}

	// Return false if we're scrolling in the x direction
	class YScrollDetector extends SimpleOnGestureListener {

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
			if (Math.abs(distanceY) > Math.abs(distanceX)) {
				mAllowTouch = true;
				return true;
			}
			mAllowTouch = false;
			return false;
		}
	}
}


text:
if (NOT _MAC_DEPENDENCY_PATHS)
set(_MAC_DEPENDENCY_PATHS)
    # As of CMake 2.8.3, Fink and MacPorts search paths are appended to the
    # default search prefix paths, but the nicer thing would be if they are
    # prepended to the default, so that is fixed here.
    if (APPLE)
        list(INSERT CMAKE_SYSTEM_PREFIX_PATH 0 /opt/local) # MacPorts
        list(INSERT CMAKE_SYSTEM_PREFIX_PATH 0 /sw)        # Fink
    endif ()
endif ()


text:
import numpy as np

# Code in str2bool and readini pulled from github.com/bsmithyman/pygeo/pygeo/fullpy.py
# Original code is licensed LGPL; I am explicitly re-licensing this under the umbrella
# of the windtunnel MIT license. –– Brendan Smithyman

def str2bool(v):
    '''
    Converts certain string values to a boolean.
    '''

    return v.lower() in ("yes", "true", "t", "1")

def readini (infile):
    '''
    Reads (2.5-D) omega ini file of a given filename.
    '''

    f = open(infile, 'r')
    lines = f.readlines()
    f.close()

    settingsdict = {}

    lsplit = lines[1].strip().split()
    settingsdict['comment'] = int(lsplit[0])
    settingsdict['lessfiles'] = str2bool(lsplit[1])

    lsplit = lines[3].strip().split()
    settingsdict['nx'] = int(lsplit[0])
    settingsdict['nz'] = int(lsplit[1])
    settingsdict['dx'] = float(lsplit[2])
    settingsdict['dz'] = float(lsplit[3])
    settingsdict['xorig'] = float(lsplit[4])
    settingsdict['zorig'] = float(lsplit[5])

    lsplit = lines[5].replace('\'','').strip().split()
    settingsdict['inv'] = str2bool(lsplit[0])
    settingsdict['datain'] = lsplit[1]
    settingsdict['dataout'] = lsplit[2]
    settingsdict['waveout'] = int(lsplit[3])
    settingsdict['usescratch'] = str2bool(lsplit[4])
    settingsdict['nom'] = int(lsplit[5])
    settingsdict['nsam'] = int(lsplit[6])
    settingsdict['tau'] = float(lsplit[7])
    settingsdict['nftout'] = int(lsplit[8])
    settingsdict['tau'] = float(lsplit[7])

    lsplit = lines[7].replace('\'','').strip().split()
    settingsdict['we'] = lsplit[0]
    settingsdict['param'] = int(lsplit[1])
    settingsdict['nky'] = int(lsplit[2])
    settingsdict['method'] = int(lsplit[3])
    settingsdict['vmin'] = float(lsplit[4])
    settingsdict['deltatt'] = float(lsplit[5])
    settingsdict['src'] = int(lsplit[6])
    settingsdict['wavscale'] = str2bool(lsplit[7])
    settingsdict['aniso'] = float(lsplit[8])
    settingsdict['freqbase'] = float(lsplit[9])

    lsplit = lines[9].strip().split()
    settingsdict['reduce'] = str2bool(lsplit[0])
    settingsdict['redvel'] = float(lsplit[1])
    settingsdict['tbegin'] = float(lsplit[2])
    settingsdict['fst'] = str2bool(lsplit[3])
    settingsdict['fsr'] = str2bool(lsplit[4])
    settingsdict['fsb'] = str2bool(lsplit[5])
    settingsdict['fsl'] = str2bool(lsplit[6])
    settingsdict['sponge'] = str2bool(lsplit[7])
    settingsdict['isufx'] = int(lsplit[8])

    freqs = []
    freqstart = 11
    freqend = freqstart + settingsdict['nom']/5 + 1*(not not settingsdict['nom']%5)
    [[freqs.append(float(item)) for item in line.strip().split() ] for line in lines[freqstart:freqend]]
    settingsdict['freqs'] = np.array(freqs)

    kys = []
    kystart = freqend+1
    kyend = kystart + settingsdict['nky']/5 + 1*(not not settingsdict['nky']%5)
    [[kys.append(float(item)) for item in line.strip().split() ] for line in lines[kystart:kyend]]
    settingsdict['kys'] = np.array(kys)

    lsplit = lines[kyend+1].strip().split()
    settingsdict['nslices'] = int(lsplit[0])

    slices = []
    slicestart = kyend+3
    sliceend = slicestart + settingsdict['nslices']
    for i in xrange(slicestart,sliceend):
        slices.append(lines[i].strip().split())
        slices[-1][0] = int(slices[-1][0])
        slices[-1][1] = int(slices[-1][1])
        slices[-1][2] = float(slices[-1][2])
        settingsdict['slices'] = slices

    lsplit = lines[sliceend+1].strip().split()
    settingsdict['ns'] = int(lsplit[0])
    settingsdict['isreg'] = int(lsplit[1])
    settingsdict['sspread'] = float(lsplit[2])
    settingsdict['useswt'] = str2bool(lsplit[3])

    srcs = []
    srcstart = sliceend+3
    srcend = srcstart + settingsdict['ns']
    for i in xrange(srcstart,srcend):
        srcs.append([float(item) for item in lines[i].strip().split()[1:]])
    srcs = np.array(srcs)
    settingsdict['srcs'] = srcs

    lsplit = lines[srcend+1].strip().split()
    settingsdict['nr'] = int(lsplit[0])
    settingsdict['irreg'] = int(lsplit[1])
    settingsdict['rspread'] = float(lsplit[2])
    settingsdict['userwt'] = str2bool(lsplit[3])

    recs = []
    recstart = srcend+3
    recend = recstart + settingsdict['nr']
    for i in xrange(recstart,recend):
        recs.append([float(item) for item in lines[i].strip().split()[1:]])
    recs = np.array(recs)
    settingsdict['recs'] = recs

    lsplit = lines[recend+1].strip().split()
    settingsdict['ng'] = int(lsplit[0])
    settingsdict['igreg'] = int(lsplit[1])
    settingsdict['gspread'] = float(lsplit[2])
    settingsdict['usegwt'] = str2bool(lsplit[3])

    geos = []
    geostart = recend+3
    geoend = geostart + settingsdict['ng']
    for i in xrange(geostart,geoend):
        geos.append([float(item) for item in lines[i].strip().split()[1:]])
    geos = np.array(geos)
    settingsdict['geos'] = geos

    lsplit = lines[geoend+1].strip().split()
    settingsdict['sghost'] = str2bool(lsplit[0])
    settingsdict['rghost'] = str2bool(lsplit[1])
    settingsdict['gghost'] = str2bool(lsplit[2])
    settingsdict['zgg'] = float(lsplit[3])

    lsplit = lines[geoend+3].strip().split()
    settingsdict['zero1'] = [int(item) for item in lsplit]

    lsplit = lines[geoend+4].strip().split()
    settingsdict['zero2'] = [int(item) for item in lsplit]

    return settingsdict


text:
class Api::CountriesController < Api::BaseController
  resource_controller_for_api
  actions :index, :show
end


text:
export = milliseconds;

/**
 * Parse the given `str` and return milliseconds.
 *
 * @see {@link https://mochajs.org/api/module-milliseconds.html}
 * @see {@link https://mochajs.org/api/module-milliseconds.html#~parse}
 */
declare function milliseconds(val: string): number;

/**
 * Format for `ms`.
 *
 * @see {@link https://mochajs.org/api/module-milliseconds.html}
 * @see {@link https://mochajs.org/api/module-milliseconds.html#~format}
 */
declare function milliseconds(val: number): string;


text:
package org.chance.cloud.controller;

import org.apache.log4j.Logger;
import org.chance.cloud.client.ComputeClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Administrator on 2017/2/23.
 */

@RestController
@RequestMapping("/")
public class ConsumerController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private ComputeClient computeClient;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public Integer add(){
        System.out.println("test");
        return computeClient.add(10,20);
    }
}


text:
import gulp from 'gulp';
import GulpConfig from './gulp.config.json';
import merge from 'merge-stream';

module.exports = () => {
  const assets = gulp.src(GulpConfig.PATH.COPY_ASSETS.APP)
    .pipe(gulp.dest(GulpConfig.PATH.COPY_ASSETS.DIST));

  const configFiles = gulp.src(GulpConfig.COPY_ASSETS_LIST)
  .pipe(gulp.dest(GulpConfig.PATH.DIST));

  return merge(assets, configFiles);
};


text:
package iojjj.androidbootstrap.appcompat.utils;

import android.support.annotation.NonNull;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Reflection {

    public static class Invoker<T> {

        private final Method m;

        private Invoker(@NonNull Method m) {
            if (!m.isAccessible()) {
                m.setAccessible(true);
            }
            this.m = m;
        }

        public Method getMethod() {
            return m;
        }

        @SuppressWarnings("unchecked")
        public <R> R invokeFor(T receiver, Object... args) {
            try {
                return (R) m.invoke(receiver, args);
            } catch (IllegalAccessException e) {
                throw new Error(e);
            } catch (InvocationTargetException e) {
                throw new Error(e);
            }
        }
    }

    public static <T> Invoker<T> invoker(@NonNull String methodName, @NonNull Class<T> clazz, Class<?>... args) {
        try {
            return new Invoker<T>(clazz.getDeclaredMethod(methodName, args));
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }

    public static <T> Invoker<T> invokerWithException(@NonNull String methodName, @NonNull Class<T> clazz, Class<?>... args) throws NoSuchMethodException{
        return new Invoker<T>(clazz.getDeclaredMethod(methodName, args));
    }

    public static class Creator<T> {

        private final Constructor<T> c;

        private Creator(@NonNull Constructor<T> c) {
            if (!c.isAccessible()) {
                c.setAccessible(true);
            }
            this.c = c;
        }

        public Constructor<T> getConstructor() {
            return c;
        }

        @SuppressWarnings("unchecked")
        public T newInstanceFor(Object... args) {
            try {
                return c.newInstance(args);
            } catch (InstantiationException e) {
                throw new Error(e);
            } catch (IllegalAccessException e) {
                throw new Error(e);
            } catch (InvocationTargetException e) {
                throw new Error(e);
            }
        }
    }

    public static <T> Creator<T> creator(@NonNull Class<T> clazz, Class<?>... args) {
        try {
            return new Creator<T>(clazz.getDeclaredConstructor(args));
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
}


text:
using RedisTray.Annotations;
using RedisTray.Properties;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;

namespace RedisTray
{
    public class RedisProcess : INotifyPropertyChanged
    {
        private static readonly Regex PortReadyRegex = new Regex(
            @"the server is now ready to accept connections on port (\d+)",
            RegexOptions.Compiled | RegexOptions.IgnoreCase
        );

        private static readonly Regex RedisVersionRegex = new Regex(
            @"server started, redis version ([0-9.]+)",
            RegexOptions.Compiled | RegexOptions.IgnoreCase
        );

        private bool _isRunning;
        private int _portNumber = 6379;
        private Process _proc;
        private Version _redisVersion = new Version(0, 0);

        private static Settings Settings
        {
            get
            {
                return Settings.Default;
            }
        }

        public bool IsRunning
        {
            get { return _isRunning; }
            private set
            {
                if (value.Equals(_isRunning)) return;
                _isRunning = value;
                OnPropertyChanged();
            }
        }

        public int PortNumber
        {
            get { return _portNumber; }
            private set
            {
                if (value == _portNumber) return;
                _portNumber = value;
                OnPropertyChanged();
            }
        }

        public Version RedisVersion
        {
            get { return _redisVersion; }
            set
            {
                if (Equals(value, _redisVersion)) return;
                _redisVersion = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public event DataReceivedEventHandler ErrorDataReceived;
        public event DataReceivedEventHandler OutputDataReceived;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void Stop()
        {
            if (!IsRunning)
            {
                return;
            }

            try
            {
                using (var sock = new TcpClient())
                {
                    sock.Connect(new IPEndPoint(IPAddress.Loopback, PortNumber));
                    var s = sock.GetStream();

                    var command = Encoding.ASCII.GetBytes("SHUTDOWN\r\n");
                    s.Write(command, 0, command.Length);
                    s.Close(1000);
                }
            }
            catch (Exception)
            {
                Kill();
            }
        }

        public void Start()
        {
            if (IsRunning)
            {
                return;
            }

            var redisArgs = string.Empty;

            if (!string.IsNullOrWhiteSpace(Settings.RedisServerConfigPath) &&
                File.Exists(Settings.RedisServerConfigPath))
            {
                redisArgs = Settings.RedisServerConfigPath;
            }

            _proc = new Process
            {
                EnableRaisingEvents = true,
                StartInfo = new ProcessStartInfo
                {
                    FileName               = Settings.RedisServerPath,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    StandardOutputEncoding = Encoding.UTF8,
                    StandardErrorEncoding  = Encoding.UTF8,
                    Arguments              = redisArgs,
                }
            };

            _proc.Exited += delegate
            {
                IsRunning = false;
                Cleanup();
            };

            _proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs args)
            {
                var handler = ErrorDataReceived;
                if (handler != null)
                {
                    handler(this, args);
                }
            };

            _proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs args)
            {
                var handler = OutputDataReceived;
                if (handler != null)
                {
                    handler(this, args);
                }

                OnDataReceived(args);
            };

            try
            {
                IsRunning = _proc.Start();
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch (Exception)
            {
                return;
            }
            // ReSharper restore EmptyGeneralCatchClause

            _proc.BeginErrorReadLine();
            _proc.BeginOutputReadLine();
        }

        protected virtual void OnDataReceived(DataReceivedEventArgs args)
        {
            if (string.IsNullOrWhiteSpace(args.Data))
            {
                return;
            }

            var m = PortReadyRegex.Match(args.Data);
            if (m.Success)
            {
                PortNumber = int.Parse(m.Groups[1].Value);
            }

            m = RedisVersionRegex.Match(args.Data);

            if (m.Success)
            {
                Version parsed;
                if (Version.TryParse(m.Groups[1].Value, out parsed))
                {
                    RedisVersion = parsed;
                }
            }
        }

        public void Kill()
        {
            if (!IsRunning || _proc == null)
            {
                return;
            }

            if (_proc.HasExited)
            {
                return;
            }

            _proc.Kill();
            IsRunning = false;
            Cleanup();
        }

        private void Cleanup()
        {
            _proc.Dispose();
            _proc = null;
        }

        public void ClearEventHandlers()
        {
            ErrorDataReceived = OutputDataReceived = null;
            PropertyChanged   = null;
        }
    }
}


text:
using UnityEngine;
using System.Collections;

namespace PixelCrushers.DialogueSystem {

	/// <summary>
	/// This component indicates that the game object is usable. This component works in
	/// conjunction with the Selector component. If you leave overrideName blank but there
	/// is an OverrideActorName component on the same object, this component will use
	/// the name specified in OverrideActorName.
	/// </summary>
	[AddComponentMenu("Dialogue System/Actor/Usable")]
	public class Usable : MonoBehaviour {

		/// <summary>
		/// (Optional) Overrides the name shown by the Selector.
		/// </summary>
		public string overrideName;

		/// <summary>
		/// (Optional) Overrides the use message shown by the Selector.
		/// </summary>
		public string overrideUseMessage;

		/// <summary>
		/// The max distance at which the object can be used.
		/// </summary>
		public float maxUseDistance = 5f;

		/// <summary>
		/// Gets the name of the override, including parsing if it contains a [lua]
		/// or [var] tag.
		/// </summary>
		/// <returns>The override name.</returns>
		public string GetName() {
			if (string.IsNullOrEmpty(overrideName)) {
				return name;
			} else if (overrideName.Contains("[lua") || overrideName.Contains("[var")) {
				return FormattedText.Parse(overrideName, DialogueManager.MasterDatabase.emphasisSettings).text;
			} else {
				return overrideName;
			}
		}

		public void Start() {
			if (string.IsNullOrEmpty(overrideName)) {
				OverrideActorName overrideActorName = GetComponentInChildren<OverrideActorName>();
				if (overrideActorName != null) overrideName = overrideActorName.overrideName;
			}
		}

	}

}


text:
<?php

namespace Buntsuu\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Buntsuu\MainBundle\Entity\Notification
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Buntsuu\MainBundle\Entity\NotificationRepository")
 */
class Notification
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $title
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var datetime $datetime
     *
     * @ORM\Column(name="datetime", type="datetime")
     */
    private $datetime;

    /**
     * @ORM\ManyToOne(targetEntity="Buntsuu\MainBundle\Entity\Type")
     */
    private $type;

    /**
     * @ORM\OneToOne(targetEntity="Buntsuu\MainBundle\Entity\User")
     */
    private $user;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set datetime
     *
     * @param datetime $datetime
     */
    public function setDatetime($datetime)
    {
        $this->datetime = $datetime;
    }

    /**
     * Get datetime
     *
     * @return datetime
     */
    public function getDatetime()
    {
        return $this->datetime;
    }
}


text:
<link rel="stylesheet" href="/static/css/tomorrow-night-eighties.css" />

{{.Blog.Title}}

{{.Blog.Views}}

      {{.Catalog.Name}}
      ·
      {{dateformat .Blog.Created_at "2006-01-02 15:04:05"}}

{{str2html .Content}}


text:
import Ember from 'ember';

var Router = Ember.Router.extend({
  location: LiquidFireENV.locationType
});

Router.map(function() {

  /* Interactive Documentation */

  this.resource("helpers-documentation", { path: 'helpers'}, function(){
    this.route('liquid-outlet', function(){
      this.route('other');
    });
    this.route('liquid-with', function(){
      this.route('page', { path: '/:id' });
    });
    this.route('liquid-bind');
    this.route('liquid-if');
  });

  this.resource('transition-map', function(){
    this.route('route-constraints');
    this.route('model-constraints');
    this.route('dom-constraints');
    this.route('choosing-transitions');
  });

  this.resource('transitions', function(){
    this.route('predefined');
    this.route('defining');
    this.route('primitives', function(){
      this.route('two');
      this.route('three');
    });
  });

  this.resource("modal-documentation", { path: 'modals'}, function(){
    this.route('modal');
    this.route('component');

    // BEGIN-SNIPPET hello-modal-map
    this.modal('hello-modal', {
      withParams: ['salutation', 'person'],
      actions: {
        changeSalutation: "changeSalutation"
      }
    });
    // END-SNIPPET

  });

  this.modal('warning-popup', {
    withParams: 'warn'
  });

  /* Test Scenarios */

  this.resource('scenarios', function() {
    this.route('inline');
    this.route('inline-serial');
    this.route('empty-if');
    this.route('growable-with');
    this.route('growable-flexboxes');
    this.route('nested-outlets', function(){
      this.route('middle', function(){
        this.route('inner');
        this.route('inner2');
      });
      this.route('middle2');
    });
  });

});

export default Router;


text:
<?php

declare(strict_types=1);

namespace Yproximite\Bundle\InfluxDbPresetBundle\Connection;

class ConnectionFactory implements ConnectionFactoryInterface
{
    public function create(): ConnectionInterface
    {
        return new Connection();
    }

    public function createFromConfig(array $config): ConnectionInterface
    {
        $connection = $this->create();
        $connection
            ->setName($config['name'])
            ->setProtocol($config['protocol'])
            ->setDeferred($config['deferred'])
        ;

        return $connection;
    }
}


text:
/**
 *
 * @author wangjue / https://github.com/hanmag
 */

var NETWORK = NETWORK || {};

// define Shaders and Materials
(function () {
    var node_uniforms = {
        color: {
            value: new THREE.Color(0xffffff)
        },
        texture: {
            value: new THREE.TextureLoader().load("images/sprites/spark1.png")
        },
        texture2: {
            value: new THREE.TextureLoader().load("images/sprites/spark2.png")
        }
    };

    var particle_uniforms = {
        color: {
            value: new THREE.Color(0xffffff)
        },
        texture: {
            value: new THREE.TextureLoader().load("images/sprites/particleA.png")
        }
    };

    var shader = {
        vertexShader: [
            'attribute float size;',
            'attribute float scale;',
            'attribute vec3 customColor;',
            'attribute float importance;',
            'varying vec3 vColor;',
            'varying float opacity;',
            'varying float type;',
            'void main() {',
            'vColor = customColor;',
            'vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
            'gl_PointSize = size * scale;',
            'gl_Position = projectionMatrix * mvPosition;',
            'opacity = scale;',
            'type = importance;',
            '}'
        ].join('\n'),
        fragmentShader: [
            'uniform vec3 color;',
            'uniform sampler2D texture;',
            'uniform sampler2D texture2;',
            'varying vec3 vColor;',
            'varying float opacity;',
            'varying float type;',
            'void main() {',
            'gl_FragColor = vec4( color * vColor, opacity);',
            'if(type>0.0)',
            'gl_FragColor = gl_FragColor * texture2D( texture, gl_PointCoord );',
            'else',
            'gl_FragColor = gl_FragColor * texture2D( texture2, gl_PointCoord );',
            'if(opacity<0.2) discard;',
            '}'
        ].join('\n')
    };

    var materials = {
        "Node": new THREE.ShaderMaterial({
            uniforms: node_uniforms,
            vertexShader: shader.vertexShader,
            fragmentShader: shader.fragmentShader,
            blending: THREE.AdditiveBlending,
            depthTest: false,
            transparent: true
        }),
        "Line": new THREE.LineBasicMaterial({
            vertexColors: THREE.VertexColors,
            blending: THREE.AdditiveBlending,
            transparent: true
        }),
        "Particle": new THREE.ShaderMaterial({
            uniforms: particle_uniforms,
            vertexShader: shader.vertexShader,
            fragmentShader: shader.fragmentShader,
            blending: THREE.AdditiveBlending,
            depthTest: false,
            transparent: true
        }),
        "SpecialLine": new THREE.MeshPhongMaterial({
            color: 0xffff00,
            specular: 0x333333,
            shininess: 150,
            side: THREE.FrontSide,
            vertexColors: THREE.VertexColors,
            shading: THREE.SmoothShading
        })
    };

    NETWORK.Materials = materials;
})();


text:
package com.tle.web.oaiidentifier;

import com.tle.common.Check;
import com.tle.common.settings.standard.OAISettings;
import com.tle.core.settings.service.ConfigurationService;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.annotations.Bookmarked;
import com.tle.web.sections.annotations.EventFactory;
import com.tle.web.sections.annotations.EventHandlerMethod;
import com.tle.web.sections.equella.annotation.PlugKey;
import com.tle.web.sections.equella.layout.OneColumnLayout;
import com.tle.web.sections.equella.receipt.ReceiptService;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.sections.events.js.EventGenerator;
import com.tle.web.sections.render.GenericTemplateResult;
import com.tle.web.sections.render.Label;
import com.tle.web.sections.render.TemplateResult;
import com.tle.web.sections.standard.Button;
import com.tle.web.sections.standard.Checkbox;
import com.tle.web.sections.standard.TextField;
import com.tle.web.sections.standard.annotations.Component;
import com.tle.web.settings.menu.SettingsUtils;
import com.tle.web.template.Breadcrumbs;
import com.tle.web.template.Decorations;
import javax.inject.Inject;

/** @author larry */
public class RootOaiIdentifierSettingsSection
    extends OneColumnLayout<RootOaiIdentifierSettingsSection.OaiSettingsModel> {
  @PlugKey("oai.title")
  private static Label TITLE_LABEL;

  @Component(stateful = false)
  private TextField oaiSchemeText;

  @Component(stateful = false)
  private TextField namespaceText;

  @Component(stateful = false)
  private TextField emailText;

  @Component(stateful = false)
  private Checkbox useDownloadItemAcl;

  @PlugKey("oai.settings.save.receipt")
  private static Label SAVE_RECEIPT_LABEL;

  @Component
  @PlugKey("settings.save.button")
  private Button saveButton;

  @EventFactory private EventGenerator events;

  @Inject private OaiIdentifierSettingsPrivilegeTreeProvider securityProvider;
  @Inject private ConfigurationService configService;
  @Inject private ReceiptService receiptService;

  @Override
  public void registered(String id, SectionTree tree) {
    super.registered(id, tree);
    saveButton.setClickHandler(events.getNamedHandler("save"));
  }

  @Override
  protected TemplateResult setupTemplate(RenderEventContext info) {
    securityProvider.checkAuthorised();

    OaiSettingsModel model = getModel(info);
    if (!model.isLoaded()) {
      OAISettings oaiSettings = getOAISettings();

      oaiSchemeText.setValue(info, oaiSettings.getScheme());
      namespaceText.setValue(info, oaiSettings.getNamespaceIdentifier());
      emailText.setValue(info, oaiSettings.getEmailAddress());
      useDownloadItemAcl.setChecked(info, oaiSettings.isUseDownloadItemAcl());
      model.setLoaded(true);
    }
    return new GenericTemplateResult(
        viewFactory.createNamedResult(BODY, "oaiidentifier.ftl", this));
  }

  @Override
  protected void addBreadcrumbsAndTitle(
      SectionInfo info, Decorations decorations, Breadcrumbs crumbs) {
    decorations.setTitle(TITLE_LABEL);
    crumbs.addToStart(SettingsUtils.getBreadcrumb(info));
  }

  private OAISettings getOAISettings() {
    return configService.getProperties(new OAISettings());
  }

  @EventHandlerMethod
  public void save(SectionInfo info) {
    boolean altered = saveSystemConstants(info);
    if (altered) {
      receiptService.setReceipt(SAVE_RECEIPT_LABEL);
    }
  }

  private boolean saveSystemConstants(SectionInfo info) {
    boolean altered = false;
    OAISettings settings = getOAISettings();

    String oldOaiScheme = settings.getScheme();
    String newOaiScheme = oaiSchemeText.getValue(info);
    if (!(Check.isEmpty(oldOaiScheme) && Check.isEmpty(newOaiScheme))) {
      String old = oldOaiScheme != null ? oldOaiScheme : "";
      if (!old.equals(newOaiScheme)) {
        altered |= true;
        settings.setScheme(newOaiScheme);
      }
    }

    String oldNamespace = settings.getNamespaceIdentifier();
    String newNamespace = namespaceText.getValue(info);
    if (!(Check.isEmpty(oldNamespace) && Check.isEmpty(newNamespace))) {
      String old = oldNamespace != null ? oldNamespace : "";
      if (!old.equals(newNamespace)) {
        altered |= true;
        settings.setNamespaceIdentifier(newNamespace);
      }
    }

    String oldEmail = settings.getEmailAddress();
    String newEmail = emailText.getValue(info);
    if (!(Check.isEmpty(oldEmail) && Check.isEmpty(newEmail))) {
      String old = oldEmail != null ? oldEmail : "";
      if (!old.equals(newEmail)) {
        altered |= true;
        settings.setEmailAddress(newEmail);
      }
    }
    boolean downloadItemAcl = settings.isUseDownloadItemAcl();
    if (!useDownloadItemAcl.isChecked(info) == downloadItemAcl) {
      altered |= true;
      settings.setUseDownloadItemAcl(useDownloadItemAcl.isChecked(info));
    }

    // and finally, persist (if any alterations).
    if (altered) {
      configService.setProperties(settings);
      OaiSettingsModel model = getModel(info);
      model.setLoaded(false);
    }
    return altered;
  }

  /** @return the oaiSchemeText */
  public TextField getOaiSchemeText() {
    return oaiSchemeText;
  }

  /** @return the namespaceText */
  public TextField getNamespaceText() {
    return namespaceText;
  }

  /** @return the emailText */
  public TextField getEmailText() {
    return emailText;
  }

  public Checkbox getUseDownloadItemAcl() {
    return useDownloadItemAcl;
  }

  /** @return the saveButton */
  public Button getSaveButton() {
    return saveButton;
  }

  @Override
  public Class<OaiSettingsModel> getModelClass() {
    return OaiSettingsModel.class;
  }

  public static class OaiSettingsModel extends OneColumnLayout.OneColumnLayoutModel {
    @Bookmarked(stateful = false)
    private boolean loaded;

    public boolean isLoaded() {
      return loaded;
    }

    public void setLoaded(boolean loaded) {
      this.loaded = loaded;
    }
  }
}


text:
/*
 * Kernel support routines for Promiscuous INET functionality.
 */

#include "opt_promiscinet.h"

#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/queue.h>
#include <sys/refcount.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/sysctl.h>
#include <sys/syslog.h>
#include <sys/systm.h>
#include <vm/uma.h>

#include <net/if.h>

#include <netinet/in.h>
#include <netinet/in_pcb.h>
#include <netinet/in_promisc.h>
#include <netinet/in_var.h>
#include <netinet/tcp_syncache.h>

struct syn_filter_internal {
	struct syn_filter params;	/* must be first in struct */
	unsigned int refcount;
	SLIST_ENTRY(syn_filter_internal) next;
};

struct syn_filter_instance {
	struct syn_filter_internal *sfi;
	char ctor_arg[SYNF_ARG_MAX];
	void *instance_arg;
};

static void syn_filter_run_destructor(struct inpcb *inp);

static struct mtx syn_filter_mtx;
MTX_SYSINIT(syn_filter, &syn_filter_mtx, "syn_filter_mtx", MTX_DEF);

#define	SYN_FILTER_LOCK()		mtx_lock(&syn_filter_mtx)
#define	SYN_FILTER_UNLOCK()		mtx_unlock(&syn_filter_mtx)
#define SYN_FILTER_ASSERT_LOCKED()	mtx_assert(&syn_filter_mtx, MA_OWNED);

static SLIST_HEAD(, syn_filter_internal) syn_filter_head =
	SLIST_HEAD_INITIALIZER(syn_filter_head);

MALLOC_DEFINE(M_SYNF, "synf", "SYN filter data");

static uma_zone_t zone_label;
static int syn_filters_unloadable = 0;

SYSCTL_NODE(_net_inet, OID_AUTO, synf, CTLFLAG_RW, 0, "SYN filters");
SYSCTL_INT(_net_inet_synf, OID_AUTO, unloadable, CTLFLAG_RW, &syn_filters_unloadable, 0,
	   "Allow unload of SYN filters (not recommended)");

static void
in_promisc_init(void)
{
	zone_label = uma_zcreate("in_l2info", sizeof(struct in_l2info),
				 NULL, NULL, NULL, NULL,
				 UMA_ALIGN_PTR, 0);
}

struct in_l2info *
in_promisc_l2info_alloc(int flags)
{
	return (uma_zalloc(zone_label, flags | M_ZERO));
}

void
in_promisc_l2info_free(struct in_l2info *l2info)
{
	uma_zfree(zone_label, l2info);
}

void
in_promisc_l2info_copy(struct in_l2info *dst, const struct in_l2info *src)
{
	memcpy(dst->inl2i_local_addr, src->inl2i_local_addr,
	       IN_L2INFO_ADDR_MAX);
	memcpy(dst->inl2i_foreign_addr, src->inl2i_foreign_addr,
	       IN_L2INFO_ADDR_MAX);

	dst->inl2i_flags = src->inl2i_flags;

	in_promisc_l2tagstack_copy(&dst->inl2i_tagstack, &src->inl2i_tagstack);
}

void
in_promisc_l2tagstack_copy(struct in_l2tagstack *dst, const struct in_l2tagstack *src)
{
	memcpy(dst, src, sizeof(*dst));
}

int
in_promisc_tagcmp(const struct in_l2tagstack *l2ts1, const struct in_l2tagstack *l2ts2)
{
	uint32_t tagcnt1, tagcnt2;
	uint32_t i1, i2;

	tagcnt1 = l2ts1 ? l2ts1->inl2t_cnt : 0;
	tagcnt2 = l2ts2 ? l2ts2->inl2t_cnt : 0;

	/* Fast compare for empty tag stacks */
	if (tagcnt1 + tagcnt2 == 0)
		return (0);

	/*
	 * Compare tag stacks without considering zero-masked tags.
	 */

	i1 = 0;
	i2 = 0;
	while (1) {
		/* skip zero-masked tags */
		while (tagcnt1 && l2ts1->inl2t_masks[i1]) {
			tagcnt1--;
			i1++;
		}

		while (tagcnt2 && l2ts2->inl2t_masks[i2]) {
			tagcnt2--;
			i2++;
		}

		if (!tagcnt1 || !tagcnt2) {
			/* Ran out of tags in one or both stacks. */

			if (!tagcnt1 && !tagcnt2) {
				/*
				 * Ran out of tags in both stacks without
				 * any miscompares.
				 */
				return (0);
			}

			/*
			 * Ran out of tags in one stack and the other stack
			 * has at least one more tag with non-zero mask.
			 */
			return (1);
		}

		if ((l2ts1->inl2t_tags[i1] & l2ts1->inl2t_masks[i1]) !=
		    (l2ts2->inl2t_tags[i2] & l2ts2->inl2t_masks[i2]))
			return (1);

		tagcnt1--; i1++;
		tagcnt2--; i2++;
	}
}

int
in_promisc_socket_init(struct socket *so, int flags)
{
	so->so_l2info = in_promisc_l2info_alloc(flags);
	if (NULL == so->so_l2info)
		return (ENOMEM);

	return (0);
}

void
in_promisc_socket_destroy(struct socket *so)
{
	if (so->so_l2info != NULL) {
		in_promisc_l2info_free(so->so_l2info);
		so->so_l2info = NULL;
	}
}

void
in_promisc_socket_newconn(struct socket *head, struct socket *so)
{
	so->so_l2info->inl2i_flags = head->so_l2info->inl2i_flags & ~INL2I_TAG_ANY;

	in_promisc_l2tagstack_copy(&so->so_l2info->inl2i_tagstack,
				   &head->so_l2info->inl2i_tagstack);
}

int
in_promisc_inpcb_init(struct inpcb *inp, int flags)
{
	inp->inp_l2info = in_promisc_l2info_alloc(flags);
	if (NULL == inp->inp_l2info)
		return (ENOMEM);

	if (inp->inp_socket->so_options & SO_PROMISC)
		inp->inp_flags2 |= INP_PROMISC;

	return (0);
}

void
in_promisc_inpcb_destroy(struct inpcb *inp)
{
	INP_WLOCK_ASSERT(inp);

	if (inp->inp_l2info != NULL) {
		in_promisc_l2info_free(inp->inp_l2info);
		inp->inp_l2info = NULL;
	}

	syn_filter_run_destructor(inp);
}

static struct syn_filter_internal *
syn_filter_get_locked(const char *name)
{
	struct syn_filter_internal *p;

	SYN_FILTER_ASSERT_LOCKED();

	SLIST_FOREACH(p, &syn_filter_head, next)
		if (strcmp(p->params.synf_name, name) == 0)
			break;

	return (p);
}

static struct syn_filter_internal *
syn_filter_alloc(struct syn_filter *params)
{
	struct syn_filter_internal *sfi;

	sfi = malloc(sizeof(*sfi), M_SYNF, M_WAITOK);
	if (NULL != sfi) {
		memcpy(&sfi->params, params, sizeof(*params));
		refcount_init(&sfi->refcount, 1);
	}

	return (sfi);
}

static void
syn_filter_free(struct syn_filter_internal *sfi)
{
	free(sfi, M_SYNF);
}

static void *
syn_filter_attach(const char *name)
{
	struct syn_filter_internal *sfi;

	SYN_FILTER_LOCK();
	sfi = syn_filter_get_locked(name);
	if (sfi) {
		refcount_acquire(&sfi->refcount);
	}
	SYN_FILTER_UNLOCK();

	return (sfi);
}

static void
syn_filter_detach_locked(struct syn_filter_internal *sfi)
{
	SYN_FILTER_ASSERT_LOCKED();
	if (refcount_release(&sfi->refcount)) {
		SLIST_REMOVE(&syn_filter_head, sfi, syn_filter_internal, next);
		syn_filter_free(sfi);
	}
}

static void
syn_filter_detach(struct syn_filter_internal *sfi)
{
	SYN_FILTER_LOCK();
	syn_filter_detach_locked(sfi);
	SYN_FILTER_UNLOCK();
}

static int
syn_filter_null_callback(struct inpcb *inp, void *inst_arg,
			 struct syn_filter_cbarg *arg)
{
	return (SYNF_REJECT);
}

/*
 * Run the filter callback safely with respect to whether the filters are
 * unloadable.
 */
int
syn_filter_run_callback(struct inpcb *inp, struct syn_filter_cbarg *arg)
{
	struct syn_filter_instance *sfinst;
	struct syn_filter_internal *sfi;
	int result = SYNF_ACCEPT;

	INP_RLOCK(inp);

	sfinst = (struct syn_filter_instance *)inp->inp_synf;
	if (sfinst) {
		sfi = sfinst->sfi;
		if (syn_filters_unloadable) {
			/*
			 * N.B. This serializes execution of all SYN filter
			 * routines in the system.
			 */
			SYN_FILTER_LOCK();
			result = sfi->params.synf_callback(inp,
							   sfinst->instance_arg,
							   arg);
			SYN_FILTER_UNLOCK();
		} else {
			result = sfi->params.synf_callback(inp,
							   sfinst->instance_arg,
							   arg);
		}
	}

	INP_RUNLOCK(inp);

	return (result);
}

/*
 * Run the filter constructor safely with respect to whether the filters are
 * unloadable.
 */
static void *
syn_filter_run_constructor(struct inpcb *inp)
{
	struct syn_filter_instance *sfinst;
	struct syn_filter_internal *sfi;
	void *result = inp;  /* Default result is anything non-NULL as NULL
			      * indicates failure.
			      */

	INP_WLOCK_ASSERT(inp);

	sfinst = (struct syn_filter_instance *)inp->inp_synf;
	sfi = sfinst->sfi;
	if (syn_filters_unloadable) {
		/*
		 * N.B. This serializes execution of all SYN filter routines
		 * in the system.
		 */
		SYN_FILTER_LOCK();
		if (sfi->params.synf_create)
			result = sfi->params.synf_create(inp, sfinst->ctor_arg);
		SYN_FILTER_UNLOCK();
	} else {
		if (sfi->params.synf_create)
			result = sfi->params.synf_create(inp, sfinst->ctor_arg);
	}

	return (result);
}

/*
 * Run the filter destructor safely with respect to whether the filters are
 * unloadable.
 */
static void
syn_filter_run_destructor(struct inpcb *inp)
{
	struct syn_filter_instance *sfinst;
	struct syn_filter_internal *sfi;

	INP_WLOCK_ASSERT(inp);

	sfinst = (struct syn_filter_instance *)inp->inp_synf;
	if (sfinst) {
		sfi = sfinst->sfi;
		if (syn_filters_unloadable) {
			/*
			 * N.B. This serializes execution of all SYN filter
			 * routines in the system.
			 */
			SYN_FILTER_LOCK();
			if (sfi->params.synf_destroy)
				sfi->params.synf_destroy(inp, sfinst->instance_arg);
			syn_filter_detach_locked(sfi);
			SYN_FILTER_UNLOCK();
		} else {
			if (sfi->params.synf_destroy)
				sfi->params.synf_destroy(inp, sfinst->instance_arg);
			syn_filter_detach(sfi);
		}

		free(sfinst, M_SYNF);
		inp->inp_synf = NULL;
	}

	inp->inp_flags2 &= ~INP_SYNFILTER;
}

static int
syn_filter_add(struct syn_filter *sf)
{
	struct syn_filter_internal *p;
	int error = 0;

	SYN_FILTER_LOCK();
	SLIST_FOREACH(p, &syn_filter_head, next)
		if (strcmp(p->params.synf_name, sf->synf_name) == 0)  {
			if (p->params.synf_callback != syn_filter_null_callback) {
				SYN_FILTER_UNLOCK();
				return (EEXIST);
			} else {
				p->params.synf_callback = sf->synf_callback;
				SYN_FILTER_UNLOCK();
				return (0);
			}
		}

	if (NULL == p) {
		p = syn_filter_alloc(sf);
		if (NULL != p)
			SLIST_INSERT_HEAD(&syn_filter_head, p, next);
		else
			error = ENOMEM;
	}
	SYN_FILTER_UNLOCK();

	return (error);
}

static int
syn_filter_del(const char *name)
{
	struct syn_filter_internal *sfi;

	SYN_FILTER_LOCK();
	sfi = syn_filter_get_locked(name);
	if (sfi) {
		/*
		 * Redirect the filter callback to the null_callback to
		 * handle the case where the filter is still attached to a
		 * socket when the module is removed.
		 */
		sfi->params.synf_callback = syn_filter_null_callback;
		syn_filter_detach_locked(sfi);
	} else {
		log(LOG_WARNING, "Attempt to remove non-existent SYN filter %s", name);
	}
	SYN_FILTER_UNLOCK();

	return (0);
}

int
syn_filter_generic_mod_event(module_t mod, int event, void *data)
{
	struct syn_filter *sf = (struct syn_filter *)data;
	int error;

	switch (event) {
	case MOD_LOAD:
		error = syn_filter_add(sf);
		break;

	case MOD_UNLOAD:
		if (syn_filters_unloadable)
			error = syn_filter_del(sf->synf_name);
		else
			error = EOPNOTSUPP;

		break;

	case MOD_SHUTDOWN:
		error = 0;
		break;

	default:
		error = EOPNOTSUPP;
		break;
	}

	return (error);
}

int
syn_filter_getopt(struct socket *so, struct sockopt *sopt)
{
	struct inpcb *inp = sotoinpcb(so);
	struct syn_filter_instance *sfinst;
	struct syn_filter_internal *sfi;
	struct syn_filter_optarg *sfa_out;
	int error = 0;

	sfa_out = malloc(sizeof(*sfa_out), M_TEMP, M_WAITOK | M_ZERO);

	if ((so->so_options & SO_PROMISC) == 0) {
		error = EINVAL;
		goto out;
	}

	INP_RLOCK(inp);
	sfinst = (struct syn_filter_instance *)inp->inp_synf;
	sfi = sfinst->sfi;
	if (sfi) {
		strcpy(sfa_out->sfa_name, sfi->params.synf_name);
		strcpy(sfa_out->sfa_arg, sfinst->ctor_arg);
	} else {
		sfa_out->sfa_name[0] = '\0';
		sfa_out->sfa_arg[0] = '\0';
	}
	INP_RUNLOCK(inp);

out:
	if (0 == error)
		error = sooptcopyout(sopt, sfa_out, sizeof(*sfa_out));
	free(sfa_out, M_TEMP);
	return (error);
}

int
syn_filter_setopt(struct socket *so, struct sockopt *sopt)
{
	struct inpcb *inp = sotoinpcb(so);
	int error = 0;

	if ((so->so_options & SO_PROMISC) == 0) {
		return (EINVAL);
	}

	switch (sopt->sopt_name) {
	case IP_SYNFILTER:
	{
		struct syn_filter_optarg *sfa;
		struct syn_filter_internal *sfi;
		struct syn_filter_instance *sfinst = NULL;

		/*
		 * Handle the simple delete case first.
		 */
		if (sopt->sopt_val == NULL) {
			INP_WLOCK(inp);
			syn_filter_run_destructor(inp);
			INP_WUNLOCK(inp);

			return (0);
		}

		sfa = malloc(sizeof(*sfa), M_TEMP, M_WAITOK);
		sfinst = malloc(sizeof(*sfinst), M_SYNF, M_WAITOK);

		error = sooptcopyin(sopt, sfa, sizeof *sfa, sizeof *sfa);
		if (error) {
			free(sfa, M_TEMP);
			return (error);
		}

		sfa->sfa_name[sizeof(sfa->sfa_name)-1] = '\0';
		sfa->sfa_arg[sizeof(sfa->sfa_arg)-1] = '\0';

		INP_WLOCK(inp);

		/* Must delete the old one before installing a new one. */
		if (NULL != inp->inp_synf) {
			error = EINVAL;
			goto out;
		}

		sfi = syn_filter_attach(sfa->sfa_name);

		if (NULL == sfi) {
			error = ENOENT;
			goto out;
		}

		sfinst->sfi = sfi;
		strcpy(sfinst->ctor_arg, sfa->sfa_arg);

		inp->inp_synf = sfinst;
		sfinst->instance_arg = syn_filter_run_constructor(inp);

		if (NULL == sfinst->instance_arg) {
			syn_filter_detach(sfi);
			inp->inp_synf = NULL;
			error = EINVAL;
			goto out;
		}

		inp->inp_flags2 |= INP_SYNFILTER;
		sfinst = NULL;
	out:
		INP_WUNLOCK(inp);

		if (NULL != sfinst)
			free(sfinst, M_SYNF);

		free(sfa, M_TEMP);
		break;
	}

	case IP_SYNFILTER_RESULT:
	{
		struct syn_filter_cbarg cbarg;

		error = sooptcopyin(sopt, &cbarg, sizeof cbarg, sizeof cbarg);
		if (error) {
			return (error);
		}

		if (SYNF_REJECT == cbarg.decision) {
			m_freem(cbarg.m);
		} else if (SYNF_ACCEPT == cbarg.decision) {
			INP_WLOCK(inp);
			syncache_add(&cbarg.inc, &cbarg.to, &cbarg.th, inp, &so, cbarg.m);

			/* syncache_add performs the INP_WUNLOCK(inp) */
		} else {
			error = EINVAL;
		}

		break;
	}

	}

	return (error);
}

/*
 * The following is adapted from Austin Appleby's MurmurHash3.[h,cpp],
 * http://smhasher.googlecode.com/svn, revision 150.  In this use we do not
 * care about the fact that different results will be obtained for the same
 * input on different endian platforms, as it is used for internal hashing
 * (we only care about overall hash quality).  Also, in this use we do not
 * care about the implementation assumption that unaligned 32-bit reads are
 * OK, since it will only be applied to 32-bit aligned data.
 */

#define	FORCE_INLINE static inline __attribute__((always_inline))

static inline uint32_t rotl32 ( uint32_t x, int8_t r )
{
  return (x << r) | (x >> (32 - r));
}

#define	ROTL32(x,y)	rotl32(x,y)

//-----------------------------------------------------------------------------
// Finalization mix - force all bits of a hash block to avalanche

FORCE_INLINE uint32_t fmix32 ( uint32_t h )
{
  h ^= h >> 16;
  h *= 0x85ebca6b;
  h ^= h >> 13;
  h *= 0xc2b2ae35;
  h ^= h >> 16;

  return h;
}

//-----------------------------------------------------------------------------

/*
 * This is MurmurHash3_x86_32 with 32-bit aligned input that is a multiple
 * of 32-bits in length, so there are no unaligned accesses, nor is there
 * any need for a tail computation.  Note that all 32-bit blocks with a
 * corresponding mask of zero are ignored in the computation, including that
 * the effective block count incorporated into the hash does not include
 * them.
 */
uint32_t in_promisc_hash32 ( const uint32_t * key, const uint32_t *masks, int nblocks, uint32_t seed )
{
  uint32_t h1 = seed;

  const uint32_t c1 = 0xcc9e2d51;
  const uint32_t c2 = 0x1b873593;

  //----------
  // body

  const uint32_t * blocks = key + nblocks;
  const uint32_t * block_masks = masks + nblocks;

  for(int i = -nblocks; i; i++)
  {
    if (block_masks[i]) {
      uint32_t k1 = blocks[i] & block_masks[i];

      k1 *= c1;
      k1 = ROTL32(k1,15);
      k1 *= c2;

      h1 ^= k1;
      h1 = ROTL32(h1,13);
      h1 = h1*5+0xe6546b64;
    } else {
      nblocks--;
    }
  }

  //----------
  // finalization

  h1 ^= (nblocks << 2);

  h1 = fmix32(h1);

  return (h1);
}

//-----------------------------------------------------------------------------

SYSINIT(in_promisc, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY, in_promisc_init, NULL);


text:
require_relative 'domain'
require 'cocoapods-core'
require_relative "quality_modifiers"

# Setup DB connections
DB.entities.each do |entity|
  name = entity.plural
  define_method name do
    DB[name]
  end
end

# Loop through all Pods
pods.where(:deleted => false).each do |pod|

  # Grab all the usual metadata
  version = pod_versions.where(pod_id: pod.id, deleted: false).sort_by { |v| Pod::Version.new(v.name) }.last
  commit = commits.where(pod_version_id: version.id, deleted_file_during_import: false).first
  next unless commit
  next unless commit.specification_data

  spec = Pod::Specification.from_json commit.specification_data

  metric = cocoadocs_pod_metrics.where(cocoadocs_pod_metrics[:pod_id] => pod.id).first
  next unless metric

  github_stats = github_pod_metrics.where(github_pod_metrics[:pod_id] => pod.id).first
  next unless github_stats

  owners = owners_pods.outer_join(:owners).on(:owner_id => :id).where(:pod_id => pod.id)
  next unless owners

  cocoapods_stats = stats_metrics.where(pod_id: pod.id).first
  # Don't skip if this can't be found, it's not critical

  # Grab the QI
  qi = QualityModifiers.new.generate(spec, metric, github_stats, cocoapods_stats, owners)
  cocoadocs_pod_metrics.update(:quality_estimate => qi).where(id: metric.id).kick.to_json

  # Output to show something is happening
  if metric[:quality_estimate] != qi
    puts "\nMigrated #{pod.name} from #{metric[:quality_estimate]} to #{qi}"
  else
    print "."
  end
end


text:
% ======================================================================
%> @brief computes f_0 through zero crossing distances
%> called by ::ComputePitch
%>
%> @param x: audio signal
%> @param iBlockLength: block length in samples
%> @param iHopLength: hop length in samples
%> @param f_s: sample rate of audio data
%>
%> @retval f double zero crossing distance (in Hz)
% ======================================================================
function [f, t] = PitchTimeZeroCrossings(x, iBlockLength, iHopLength, f_s)

    % number of results
    iNumOfBlocks    = ceil (length(x)/iHopLength);

    % compute time stamps
    t               = ((0:iNumOfBlocks-1) * iHopLength + (iBlockLength/2))/f_s;

    % allocate memory
    f               = zeros(1,iNumOfBlocks);

    for (n = 1:iNumOfBlocks)
        i_start     = (n-1)*iHopLength + 1;
        i_stop      = min(length(x),i_start + iBlockLength - 1);

        i_tmp       = diff(find(x(i_start:i_stop-1).*x(i_start+1:i_stop) < 0));
        f(n)        = mean(i_tmp); % or histogram max, ...
    end

    % convert to Hz
    f                   = f_s ./ f;
end


text:
namespace gl {

GLStubApi::GLStubApi() {}

GLStubApi::~GLStubApi() = default;

GLenum GLStubApi::glCheckFramebufferStatusEXTFn(GLenum target) {
  return GL_FRAMEBUFFER_COMPLETE;
}

GLuint GLStubApi::glCreateProgramFn(void) {
  return 1;
}

GLuint GLStubApi::glCreateShaderFn(GLenum type) {
  return 2;
}

GLsync GLStubApi::glFenceSyncFn(GLenum condition, GLbitfield flags) {
  return reinterpret_cast<GLsync>(1);
}

void GLStubApi::glGenBuffersARBFn(GLsizei n, GLuint* buffers) {
  GenHelper(n, buffers);
}

void GLStubApi::glGenerateMipmapEXTFn(GLenum target) {}

void GLStubApi::glGenFencesAPPLEFn(GLsizei n, GLuint* fences) {
  GenHelper(n, fences);
}

void GLStubApi::glGenFencesNVFn(GLsizei n, GLuint* fences) {
  GenHelper(n, fences);
}

void GLStubApi::glGenFramebuffersEXTFn(GLsizei n, GLuint* framebuffers) {
  GenHelper(n, framebuffers);
}

GLuint GLStubApi::glGenPathsNVFn(GLsizei range) {
  return 1;
}

void GLStubApi::glGenQueriesFn(GLsizei n, GLuint* ids) {
  GenHelper(n, ids);
}

void GLStubApi::glGenRenderbuffersEXTFn(GLsizei n, GLuint* renderbuffers) {
  GenHelper(n, renderbuffers);
}

void GLStubApi::glGenSamplersFn(GLsizei n, GLuint* samplers) {
  GenHelper(n, samplers);
}

void GLStubApi::glGenTexturesFn(GLsizei n, GLuint* textures) {
  GenHelper(n, textures);
}

void GLStubApi::glGenTransformFeedbacksFn(GLsizei n, GLuint* ids) {
  GenHelper(n, ids);
}

void GLStubApi::glGenVertexArraysOESFn(GLsizei n, GLuint* arrays) {
  GenHelper(n, arrays);
}

void GLStubApi::glGetIntegervFn(GLenum pname, GLint* params) {
  // We need some values to be large enough to initialize ContextGroup.
  switch (pname) {
    default:
      *params = 1;
      break;
    case GL_MAX_RENDERBUFFER_SIZE:
      *params = 512;
      break;
    case GL_MAX_SAMPLES:
      *params = 4;
      break;
    case GL_MAX_COLOR_ATTACHMENTS_EXT:
      *params = 4;
      break;
    case GL_MAX_DRAW_BUFFERS_ARB:
      *params = 4;
      break;
    case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:
      *params = 4;
      break;
    case GL_MAX_UNIFORM_BUFFER_BINDINGS:
      *params = 24;
      break;
    case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
      *params = 256;
      break;
    case GL_MAX_VERTEX_ATTRIBS:
      *params = 8;
      break;
    case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
      *params = 8;
      break;
    case GL_MAX_TEXTURE_IMAGE_UNITS:
      *params = 8;
      break;
    case GL_MAX_TEXTURE_SIZE:
    case GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB:
      *params = 2048;
      break;
    case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
      *params = 2048;
      break;
    case GL_MAX_3D_TEXTURE_SIZE:
      *params = 256;
      break;
    case GL_MAX_ARRAY_TEXTURE_LAYERS:
      *params = 256;
      break;
    case GL_MAX_VARYING_VECTORS:
      *params = 8;
      break;
    case GL_MAX_VARYING_FLOATS:
      *params = 32;
      break;
    case GL_MAX_VERTEX_UNIFORM_VECTORS:
      *params = 128;
      break;
    case GL_MAX_VERTEX_UNIFORM_COMPONENTS:
      *params = 512;
      break;
    case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
      *params = 16;
      break;
    case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
      *params = 64;
      break;
    case GL_MAX_VERTEX_OUTPUT_COMPONENTS:
      *params = 64;
      break;
    case GL_MAX_FRAGMENT_INPUT_COMPONENTS:
      *params = 60;
      break;
    case GL_MAX_PROGRAM_TEXEL_OFFSET:
      *params = 7;
      break;
    case GL_MIN_PROGRAM_TEXEL_OFFSET:
      *params = -8;
      break;
    case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
      *params = 32;
      break;
    case GL_MAX_VIEWPORT_DIMS:
      *params = 1024 << 8;
      break;
    case GL_ALPHA_BITS:
      *params = 8;
      break;
    case GL_DEPTH_BITS:
      *params = 24;
      break;
    case GL_STENCIL_BITS:
      *params = 8;
      break;
    case GL_TEXTURE_BINDING_2D:
      *params = 1;
      break;
    case GL_FRAMEBUFFER_BINDING:
      *params = 1;
      break;
    case GL_IMPLEMENTATION_COLOR_READ_TYPE:
      *params = GL_UNSIGNED_BYTE;
      break;
    case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
      *params = GL_RGBA;
      break;
  }
}

void GLStubApi::glGetProgramivFn(GLuint program, GLenum pname, GLint* params) {
  switch (pname) {
    case GL_LINK_STATUS:
      *params = GL_TRUE;
      break;
    case GL_VALIDATE_STATUS:
      *params = GL_TRUE;
      break;
    default:
      break;
  }
}

void GLStubApi::glGetQueryObjecti64vFn(GLuint id,
                                       GLenum pname,
                                       GLint64* params) {
  switch (pname) {
    case GL_QUERY_RESULT_AVAILABLE:
      *params = GL_TRUE;
      break;
    default:
      break;
  }
}

void GLStubApi::glGetQueryObjectivFn(GLuint id, GLenum pname, GLint* params) {
  switch (pname) {
    case GL_QUERY_RESULT_AVAILABLE:
      *params = GL_TRUE;
      break;
    default:
      break;
  }
}

void GLStubApi::glGetQueryObjectui64vFn(GLuint id,
                                        GLenum pname,
                                        GLuint64* params) {
  switch (pname) {
    case GL_QUERY_RESULT_AVAILABLE:
      *params = GL_TRUE;
      break;
    default:
      break;
  }
}

void GLStubApi::glGetQueryObjectuivFn(GLuint id, GLenum pname, GLuint* params) {
  switch (pname) {
    case GL_QUERY_RESULT_AVAILABLE:
      *params = GL_TRUE;
      break;
    default:
      break;
  }
}

void GLStubApi::glGetShaderivFn(GLuint shader, GLenum pname, GLint* params) {
  switch (pname) {
    case GL_COMPILE_STATUS:
      *params = GL_TRUE;
      break;
    default:
      break;
  }
}

const GLubyte* GLStubApi::glGetStringFn(GLenum name) {
  switch (name) {
    case GL_RENDERER:
    default:
      return reinterpret_cast<const GLubyte*>("");
    case GL_VERSION:
      return reinterpret_cast<const GLubyte*>(version_.c_str());
    case GL_EXTENSIONS:
      return reinterpret_cast<const GLubyte*>(extensions_.c_str());
  }
}

const GLubyte* GLStubApi::glGetStringiFn(GLenum name, GLuint index) {
  return reinterpret_cast<const GLubyte*>("");
}

GLboolean GLStubApi::glIsBufferFn(GLuint buffer) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsEnabledFn(GLenum cap) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsFenceAPPLEFn(GLuint fence) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsFenceNVFn(GLuint fence) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsFramebufferEXTFn(GLuint framebuffer) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsPathNVFn(GLuint path) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsProgramFn(GLuint program) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsQueryFn(GLuint query) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsRenderbufferEXTFn(GLuint renderbuffer) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsSamplerFn(GLuint sampler) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsShaderFn(GLuint shader) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsSyncFn(GLsync sync) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsTextureFn(GLuint texture) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsTransformFeedbackFn(GLuint id) {
  return GL_TRUE;
}

GLboolean GLStubApi::glIsVertexArrayOESFn(GLuint array) {
  return GL_TRUE;
}

GLboolean GLStubApi::glTestFenceAPPLEFn(GLuint fence) {
  return GL_TRUE;
}

GLboolean GLStubApi::glTestFenceNVFn(GLuint fence) {
  return GL_TRUE;
}

GLboolean GLStubApi::glUnmapBufferFn(GLenum target) {
  return GL_TRUE;
}

}  // namespace gl


text:
package com.intellij.util;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Ref;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.Field;

/**
 * Thread unsafe field accessor.
 *
 * @param <E> the type of the field's class
 * @param <T> the type of the field
 */
public class FieldAccessor<E, T> {
  private static final Logger LOG = Logger.getInstance(FieldAccessor.class);

  private Ref<Field> myFieldRef;
  private final Class<E> myClass;
  private final String myName;
  private final Class<T> myType;

  public FieldAccessor(@NotNull Class<E> aClass, @NotNull @NonNls String name) {
    this(aClass, name, null);
  }

  public FieldAccessor(@NotNull Class<E> aClass, @NotNull @NonNls String name, @Nullable Class<T> type) {
    myClass = aClass;
    myName = name;
    myType = type;
  }

  public boolean isAvailable() {
    if (myFieldRef == null) {
      try {
        myFieldRef = new Ref<>();
        myFieldRef.set(ReflectionUtil.findAssignableField(myClass, myType, myName));
        myFieldRef.get().setAccessible(true);
      }
      catch (NoSuchFieldException e) {
        LOG.warn("Field not found: " + myClass.getName() + "." + myName);
      }
    }
    return myFieldRef.get() != null;
  }

  public T get(@Nullable E object) {
    if (!isAvailable()) return null;
    try {
      //noinspection unchecked
      return (T)myFieldRef.get().get(object);
    }
    catch (IllegalAccessException e) {
      LOG.warn("Field not accessible: " + myClass.getName() + "." + myName);
    }
    return null;
  }

  public void set(@Nullable E object, @Nullable T value) {
    if (!isAvailable()) return;
    try {
      myFieldRef.get().set(object, value);
    }
    catch (IllegalAccessException e) {
      LOG.warn("Field not accessible: " + myClass.getName() + "." + myName);
    }
  }
}


text:
<?php

/*
 *  Created on :Sep 10, 2015, 9:19:25 AM
 *  Author     :Varun Garg <varun.10@live.com>

	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
defined('BASEPATH') OR exit('No direct script access allowed');

class News extends CI_Controller {

    function index() {
        redirect(base_url() . 'News/view_all');
    }

    function secure_hard() {
        if ($this->permissions->get_level() == 0) {
            echo $this->load->view('common/header', '', TRUE);
            $message['errors'] = "Insufficient Privelleges. Please Contact Our Content Head";
            echo $this->load->view('Error_message', $message, TRUE);
            echo $this->load->view('common/footer', '', TRUE);
            die();
        }
        return 1;
    }

    function CreateOrUpdate() {
        $this->secure_hard();

        $this->load->helper(array('form', 'url'));
        $this->form_validation->set_rules('title', 'title', 'required');
        $this->form_validation->set_rules('slug', 'slug', 'required');
        $this->form_validation->set_rules('text', 'Description', 'required');

        $this->load->view('common/header');
        $this->load->library('form_validation');
        if ($this->form_validation->run() == FALSE) {
            if ($this->input->get("news_id") != NULL) {

                $query = $this->db->get_where('news', array('id' => $this->input->get('news_id')));
                if ($query->num_rows() == 0) {
                    echo "

No such News exists";
                    die();
                }
                $form_data = $query->row();
                $this->load->view('News_form', $form_data);
            } else
                $this->load->view('News_form');
        } else {
            $this->load->helper('htmlpurifier');
            $form_data = array(
                'title' => html_purify($this->input->post('title')),
                'slug' => html_purify($this->input->post('slug')),
                'text' => html_purify($this->input->post('text')),
            );
            if ($this->input->get('news_id') != "") { // update
                $this->db->update('news', $form_data, " id = '" . $this->input->get('news_id') . "'");
                $this->logger->insert('Updated news article - ' . html_purify($this->input->post('title')) . ' (' . $this->input->get('news_id') . ')');
            } else {
                $this->db->insert('news', $form_data);
                $this->logger->insert('Created news article - ' . html_purify($this->input->post('title')));
            }
            redirect(base_url() . 'News/view_all');
        }

        $this->load->view('common/footer');
    }

    function view_all() {

        $this->load->view('common/header');
        $this->load->view('View_allnews');
        $this->load->view('common/footer');
    }

    function delete() {
        $this->secure_hard();

        $title_q = $this->db->query("select title from news where id = '" . $this->input->get('news_id') . "' ");
        $title_r = $title_q->row();
        $title = $title_r->title;

        $this->db->query("delete from news where id = '" . $this->input->get('news_id') . "'");

        $this->logger->insert('Deleted news article ' . $title . ' (' . $this->input->get('news_id') . ')', TRUE);

        redirect(base_url() . 'News/view_all');
    }

}


text:
<?php
return array (
  'Available updates' => 'Mises à jour disponible',
  'Browse online' => 'Voir en ligne',
  'Installed' => 'Installé',
  'Modules extend the functionality of HumHub. Here you can install and manage modules from the HumHub Marketplace.' => 'Les modules étendent les fonctionnalités de HumHub. C\'est ici que vous pouvez installer et gérer les modules de la marketplace de HumHub.',
  'Purchases' => 'Achats',
);


text:
/**
 * SelectionText
 */

import articleFor from '../utils/article-for'
import pluralize from '../utils/pluralize'

interface Options {
  resource: string
  fetching: boolean
  item: boolean
  isPlural: boolean
}

export default function selectionText(options: Options) {
  let resource = options.resource || 'Photo'
  let fetching = options.fetching
  let isPlural = options.isPlural
  let item = options.item

  let noun = getNoun(resource, isPlural)

  if (fetching) {
    return getLoadingText(noun)
  }

  if (item) {
    return getSelectedText(noun, isPlural)
  }

  return getEmptyText(articleFor(noun), noun, isPlural)
}

function getNoun(resource: string, isPlural: boolean) {
  let noun = resource.toLowerCase()

  if (isPlural) {
    noun = pluralize(noun)
  }

  return noun
}

function getEmptyText(article: string, noun: string, isPlural: boolean) {
  let a = isPlural ? ' ' : ` ${article} `
  return `Pick${a}${noun}`
}

function getSelectedText(noun: string, isPlural: boolean) {
  let a = isPlural ? ' ' : ' a '
  return `Pick${a}different ${noun}`
}

function getLoadingText(noun: string) {
  return `Loading ${noun}`
}


text:
- Upon fetching an entry using the `entry` method, the entry can be modified in-place after dereferencing it.

- The `or_insert` [method](https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html#method.or_insert) inserts the given value in the case when the entry is vacant, and returns a mutable reference to the value in the entry.

```rust
*counter.entry(key).or_insert(0) += 1;
```

- The `or_default` [method](https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html#method.or_default) ensures a value is in the entry by inserting the default value if empty, and returns a mutable reference to the value in the entry.

```rust
*counter.entry(key).or_default() += 1;
```


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.framework;

import static org.junit.Assert.*;

import org.junit.Test;

import generic.test.AbstractGenericTest;

public class ApplicationIdentifierTest extends AbstractGenericTest {

	@Test
	public void testApplicationPropertiesIdentifier() {
		// We should be able to create an ApplicationIdentifier object from the application info
		// defined in the application properties file without an exception being thrown.
		new ApplicationIdentifier(Application.getApplicationLayout().getApplicationProperties());
	}

	@Test
	public void testApplicationVersionParsing() {
		ApplicationIdentifier id = new ApplicationIdentifier("Ghidra_9.0.1_public_05212019");
		assertEquals(id.getApplicationName(), "ghidra");
		assertEquals(id.getApplicationVersion(), new ApplicationVersion("9.0.1"));
		assertEquals(id.getApplicationReleaseName(), "PUBLIC");
		assertEquals(id.toString(), "ghidra_9.0.1_PUBLIC");

		try {
			new ApplicationIdentifier("ghidra");
			fail(
				"Should not be able to parse only a name...a version and release name are required.");
		}
		catch (IllegalArgumentException e) {
			// Getting here indicates success
		}

		try {
			new ApplicationIdentifier("ghidra_9.0.1");
			fail(
				"Should not be able to parse only a name and version...a release name is required.");
		}
		catch (IllegalArgumentException e) {
			// Getting here indicates success
		}
	}

	@Test
	public void testApplicationIdentifierEquals() {
		ApplicationIdentifier id1 = new ApplicationIdentifier("ghi dra_9.0_pub lic");
		ApplicationIdentifier id2 = new ApplicationIdentifier("Ghidra_9.0.0_PUBLIC");
		assertEquals(id1, id2);

		id1 = new ApplicationIdentifier("ghidra_9.0_public");
		id2 = new ApplicationIdentifier("Ghidra_9.0.1_PUBLIC");
		assertNotEquals(id1, id2);

		id1 = new ApplicationIdentifier("ghidra_9.0_DEV");
		id2 = new ApplicationIdentifier("ghidra_9.0_PUBLIC");
		assertNotEquals(id1, id2);
	}
}


text:
package io.vertx.ext.web.templ.extension;

import com.mitchellbosecke.pebble.extension.AbstractExtension;
import com.mitchellbosecke.pebble.extension.Function;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by jensklingsporn on 22.02.17.
 */
public class TestExtension extends AbstractExtension{

  @Override
  public Map<String, Function> getFunctions() {
    return Collections.singletonMap("createString",new CreateStringFunction());
  }

  class CreateStringFunction implements Function{

    @Override
    public Object execute(Map<String, Object> args) {
      return "TEST";
    }

    @Override
    public List<String> getArgumentNames() {
      return Collections.emptyList();
    }
  }
}


text:
/* $Id$ */

package org.apache.fop.traits;

import java.awt.Color;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

import org.apache.xmlgraphics.java2d.color.ColorWithAlternatives;
import org.apache.xmlgraphics.java2d.color.DeviceCMYKColorSpace;

import org.apache.fop.fo.Constants;
import org.apache.fop.util.ColorUtil;

/**
 * Tests the BorderProps class.
 */
public class BorderPropsTestCase {

    /**
     * Test serialization and deserialization to/from String.
     * @throws Exception if an error occurs
     */
    @Test
    public void testSerialization() throws Exception {
        Color col = new Color(1.0f, 1.0f, 0.5f, 1.0f);
        //Normalize: Avoid false alarms due to color conversion (rounding)
        col = ColorUtil.parseColorString(null, ColorUtil.colorToString(col));
        BorderProps sut = BorderProps.makeRectangular(Constants.EN_DOUBLE, 1250, col,
                BorderProps.Mode.COLLAPSE_OUTER);
        testSerialization(sut);

        float[] cmyk = new float[] {1.0f, 1.0f, 0.5f, 1.0f};
        col = DeviceCMYKColorSpace.createCMYKColor(cmyk);
        //Convert to sRGB with CMYK alternative as constructed by the cmyk() function
        float[] rgb = col.getRGBColorComponents(null);
        col = new ColorWithAlternatives(rgb[0], rgb[1], rgb[2], new Color[] {col});
        sut = BorderProps.makeRectangular(Constants.EN_INSET, 9999, col, BorderProps.Mode.SEPARATE);
        testSerialization(sut);
    }

    /**
     * Test serialization and deserialization to/from String.
     * @throws Exception if an error occurs
     */
    @Test
    public void testSerializationWithCornerRadii() throws Exception {
        Color col = new Color(1.0f, 1.0f, 0.5f, 1.0f);
        //Normalize: Avoid false alarms due to color conversion (rounding)
        col = ColorUtil.parseColorString(null, ColorUtil.colorToString(col));
        for (BorderProps.Mode mode : BorderProps.Mode.values()) {
            BorderProps sut = BorderProps.makeRectangular(Constants.EN_SOLID, 10, col, mode);
            testSerialization(sut);
            sut = new BorderProps(Constants.EN_SOLID, 10, 4, 3, col, mode);
            testSerialization(sut);
        }
    }

    private void testSerialization(BorderProps borderProp) {
        assertEquals(borderProp, BorderProps.valueOf(null, borderProp.toString()));
    }

}


text:
layout: post
title:  "Content"
date:   0006-05-01 12:23:49
categories: page-elements structural-elements
---

The content section of each page is the place where the main text, images, maps and data
is displayed. Its width is flexible, taking 100% of the screen up to 1200px. Its height
depends on the content itself.

![alt text][content]

### Responsive

When the site is accessed from a mobile device, the content just adapts to its width.

![alt text][content-mobile]

[content]: /gfw-style-guides/images/posts/structural-elements/content/07-01-content.png "content"
[content-2]: /gfw-style-guides/images/posts/structural-elements/content/07-02-content.png "content-2"
[content-mobile]: /gfw-style-guides/images/posts/structural-elements/content/07-03-content-mobile.png "content-mobile"
[learn-more]: /gfw-style-guides/page-elements/structural-elements/sidebar.html


text:
import '../css/options.scss';
import getOptions from './utils/get-options';
import defaultOptions from './utils/default-options';
import ChromePromise from 'chrome-promise';

const chromep = new ChromePromise();

const saveOptions = () => {
  const elements = document.querySelectorAll('.option-input');
  let updatedOptions = [];
  for (let i = 0; i < elements.length; i++) {
    const elem = elements[i];
    let optionValue = null;

    if (elem.type === 'select-one') {
      optionValue = elem.options[elem.selectedIndex].value;
    } else {
      optionValue = elem.value;
    }

    updatedOptions.push({
      [elem.id]: optionValue,
    });
  }

  chromep.storage.sync.set({ options: updatedOptions }).then(() => {
    // TODO: pop success message
    window.close();
  });
};

const getOptionsInit = () => {
  getOptions().then((options) => {
    if (!options.length) {
      // first time using the extension
      resetDefaults();
      return;
    }

    updateOptionsUI(options);
  });

};

const updateOptionsUI = (options) => {
  options.forEach((option) => {
    const key = Object.keys(option)[0];
    const inputElem = document.getElementById(key);

    if (inputElem) {
      inputElem.value = option[key];
    }
  });
};

const clearOptions = () => {
  chrome.storage.sync.clear(function() {
    var error = chrome.runtime.lastError;
    if (error) {
      console.error(error);
    }

    console.log('CLEAR OPTIONS')
  });
};

const resetDefaults = (e) => {
  if (e) {
    e.preventDefault();
  }

  chrome.storage.sync.set({ options: defaultOptions }, () => {
    // TODO: pop success message
    updateOptionsUI(defaultOptions);
    window.close()
  });
};

document.getElementById('save').addEventListener('click', saveOptions);

document.getElementById('reset-defaults').addEventListener('click', resetDefaults);

// development only
// document.getElementById('clear').addEventListener('click', clearOptions);

document.addEventListener('DOMContentLoaded', getOptionsInit);


text:
package org.onosproject.k8snetworking.api;

import org.onosproject.event.EventListener;

/**
 * Listener for kubernetes service event.
 */
public interface K8sServiceListener extends EventListener<K8sServiceEvent> {
}