text:
namespace AgileObjects.AgileMapper.UnitTests.Orms.Ef5.Infrastructure
{
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Threading.Tasks;
    using Orms.Infrastructure;

    public class Ef5DbSetWrapper<TEntity> : DbSetWrapperBase<TEntity>
        where TEntity : class
    {
        private readonly DbSet<TEntity> _dbSet;

        public Ef5DbSetWrapper(DbContext context)
            : base(context.Set<TEntity>())
        {
            _dbSet = context.Set<TEntity>();
        }

        public override void Include<TProperty>(Expression<Func<TEntity, TProperty>> navigationPropertyPath)
            => _dbSet.Include(navigationPropertyPath);

        public override Task Add(TEntity itemToAdd)
        {
            _dbSet.Add(itemToAdd);

            return Task.CompletedTask;
        }

        public override Task AddRange(TEntity[] itemsToAdd)
        {
            foreach (var entity in itemsToAdd)
            {
                _dbSet.Add(entity);
            }

            return Task.CompletedTask;
        }

        public override void Clear()
        {
            foreach (var entity in _dbSet.ToArray())
            {
                _dbSet.Remove(entity);
            }
        }
    }
}


text:
function View() {

};

View.prototype.updateDisplay = function(player) {
  player.$sprite.css('top', player.y);
  player.$sprite.css('left', player.x);
}

View.prototype.updateGif = function(player, action) {
  if (player[action + "ing"]) {
    switch (player.facing) {
      case "right":
        player.$sprite.css('background-image', player.sprite[action + "Right"]);
        break;
      case "left":
        player.$sprite.css('background-image', player.sprite[action + "Left"]);
        break;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.b3log.solo.service;

import javax.inject.Inject;
import org.b3log.latke.Keys;
import org.b3log.latke.repository.Transaction;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.Strings;
import org.b3log.solo.model.Option;
import org.b3log.solo.repository.OptionRepository;
import org.json.JSONObject;

/**
 * Option management service.
 *
 * @author Liang Ding
 * @version 1.0.0.0, Apr 16, 2013
 * @since 0.6.0
 */
@Service
public class OptionMgmtService {

    /**
     * Option repository.
     */
    @Inject
    private OptionRepository optionRepository;

    /**
     * Adds or updates the specified option.
     *
     * @param option the specified option
     * @return option id
     * @throws ServiceException
     */
    public String addOrUpdateOption(final JSONObject option) throws ServiceException {
        final Transaction transaction = optionRepository.beginTransaction();

        try {
            String id = option.optString(Keys.OBJECT_ID);

            if (Strings.isEmptyOrNull(id)) {
                id = optionRepository.add(option);
            } else {
                final JSONObject old = optionRepository.get(id);

                if (null == old) { // The id is specified by caller
                    id = optionRepository.add(option);
                } else {
                    old.put(Option.OPTION_CATEGORY, option.optString(Option.OPTION_CATEGORY));
                    old.put(Option.OPTION_VALUE, option.optString(Option.OPTION_VALUE));

                    optionRepository.update(id, old);
                }
            }

            transaction.commit();

            return id;
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }

            throw new ServiceException(e);
        }
    }

    /**
     * Removes the option specified by the given option id.
     *
     * @param optionId the given option id
     * @throws ServiceException service exception
     */
    public void removeOption(final String optionId) throws ServiceException {
        final Transaction transaction = optionRepository.beginTransaction();

        try {
            optionRepository.remove(optionId);

            transaction.commit();
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }

            throw new ServiceException(e);
        }
    }

    /**
     * Sets the option repository with the specified option repository.
     *
     * @param optionRepository the specified option repository
     */
    public void setOptionRepository(final OptionRepository optionRepository) {
        this.optionRepository = optionRepository;
    }
}


text:
package com.morenware.tvcrawler.crawling

import akka.actor.{ActorSystem, Props}
import com.morenware.tvcrawler.actors.{HtmlGet, PageRetriever}
import com.morenware.tvcrawler.config.CrawlerConfig
import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory

/**
  * Created by david on 05/05/2016.
  */
object CrawlerManager extends CrawlerUtils {

  val log = Logger(LoggerFactory.getLogger("crawlers"))

  def startCrawler(config: CrawlerConfig) = {

    log.info(s"Starting crawler for ${config.name}")
    log.info("Initializing actor system")

    val system = ActorSystem("CrawlingSystem")
    val pageRetriever = system.actorOf(Props[PageRetriever], name = "pageRetriever")

    config.sections.foreach { section =>

      log.info(s"Starting to crawl section: ${section.name}")

      //TODO: Generate this in the actor
      val sectionBaseLink = getInitialSectionLink(config.baseUrl, section.sectionLink,
        section.listModeParameter + section.orderByDateParameter)

      log.debug("Sending message to retriever actor...")
      pageRetriever ! HtmlGet(sectionBaseLink, section.name)

      log.debug("===>> Back from retriever call (should be non block) <<====")

      //TODO: create relevant actors
      // send to HtmlRetriever Actor: sectionBaseLink (aware of CrawlerUtils Trait)
    }
  }
}


text:
package org.terasology.events;

import org.terasology.entitySystem.AbstractEvent;

/**
 *  @author Small-Jeeper
 */
public class DeleteItemEvent extends AbstractEvent {
    private float percent;

    public DeleteItemEvent() {
        this(0);
    }

    public DeleteItemEvent(float percent) {
        this.percent = percent;
    }

    public float getPercent(){
        return percent;
    }
}


text:
package com.emitrom.lienzo.client.core.image;

import com.emitrom.lienzo.client.core.shape.Picture;
import com.emitrom.lienzo.client.core.types.ImageData;
import com.google.gwt.canvas.dom.client.CanvasPixelArray;
import com.google.gwt.core.client.JavaScriptObject;

/**
 * An Image Filter than can be used to set the brightness levels for each of the RGB channels of the {@link Picture}
 */
public class ChannelBrightnessImageDataFilter extends AbstractBaseImageDataFilter<ChannelBrightnessImageDataFilter>
{
    private double m_r_brightness;

    private double m_g_brightness;

    private double m_b_brightness;

    public ChannelBrightnessImageDataFilter(double r_brightness, double g_brightness, double b_brightness)
    {
        setRBrightness(r_brightness);

        setGBrightness(g_brightness);

        setBBrightness(b_brightness);
    }

    /**
     * Sets the RED brightness value
     *
     * @param brightness
     * @return {@link ChannelBrightnessImageDataFilter}
     */
    public ChannelBrightnessImageDataFilter setRBrightness(double brightness)
    {
        m_r_brightness = checkBrightnessValue(brightness);

        return this;
    }

    /**
     * Sets the GREEN brightness value.
     *
     * @param brightness
     * @return {@link ChannelBrightnessImageDataFilter}
     */
    public ChannelBrightnessImageDataFilter setGBrightness(double brightness)
    {
        m_g_brightness = checkBrightnessValue(brightness);

        return this;
    }

    /**
     * Sets the BLUE brightness value.
     *
     * @param brightness
     * @return {@link ChannelBrightnessImageDataFilter}
     */
    public ChannelBrightnessImageDataFilter setBBrightness(double brightness)
    {
        m_b_brightness = checkBrightnessValue(brightness);

        return this;
    }

    @Override
    public ImageData filter(ImageData source, boolean copy)
    {
        if (null == source)
        {
            return null;
        }
        final int length = getLength(source);

        if (copy)
        {
            source = source.copy();
        }
        final CanvasPixelArray data = source.getData();

        if (null == data)
        {
            return source;
        }
        if (isNative())
        {
            filter0(data, length, m_r_brightness, m_g_brightness, m_b_brightness);
        }
        else
        {
            for (int i = 0; i < length; i += PIXEL_SZ)
            {
                int r = (int) Math.max(Math.min((data.get(i + R_OFFSET) + (m_r_brightness * 255) + 0.5), 255), 0);

                int g = (int) Math.max(Math.min((data.get(i + G_OFFSET) + (m_g_brightness * 255) + 0.5), 255), 0);

                int b = (int) Math.max(Math.min((data.get(i + B_OFFSET) + (m_b_brightness * 255) + 0.5), 255), 0);

                data.set(i + R_OFFSET, r);

                data.set(i + G_OFFSET, g);

                data.set(i + B_OFFSET, b);
            }
        }
        return source;
    }

    private final double checkBrightnessValue(double brightness)
    {
        if (brightness < -1)
        {
            brightness = -1;
        }
        if (brightness > 1)
        {
            brightness = 1;
        }
        return brightness;
    }

    private final native void filter0(JavaScriptObject pixa, int length, double r, double g, double b)
    /*-{
		var data = pixa;

		function calculate(v, brightness) {
			return Math.max(Math.min((v + (brightness * 255) + 0.5), 255), 0) | 0;
		}
		for (var i = 0; i < length; i += 4) {

			data[i + 0] = calculate(data[i + 0], r);

			data[i + 1] = calculate(data[i + 1], g);

			data[i + 2] = calculate(data[i + 2], b);
		}
    }-*/;
}


text:
package org.diirt.vtype;

/**
 * Scalar integer with alarm, timestamp, display and control information.
 * Auto-unboxing makes the extra method for the primitive type
 * unnecessary.
 *
 * @author carcassi
 */
public interface VInt extends VNumber, VType {
    /**
     * {@inheritDoc }
     */
    @Override
    Integer getValue();
}


text:
package org.springframework.security.jwt.crypto.sign;

import org.junit.Test;
import org.springframework.security.jwt.codec.Codecs;

import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.security.Signature;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;

/**
 * Tests for {@link EllipticCurveVerifier}.
 *
 * @author Joe Grandja
 */
public class EllipticCurveVerifierTests {
	private final static String P256_CURVE = "P-256";
	private final static String P384_CURVE = "P-384";
	private final static String P521_CURVE = "P-521";
	private final static String SHA256_ECDSA_ALG = "SHA256withECDSA";
	private final static String SHA384_ECDSA_ALG = "SHA384withECDSA";
	private final static String SHA512_ECDSA_ALG = "SHA512withECDSA";

	static {
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
	}

	@Test(expected = IllegalArgumentException.class)
	public void constructorWhenUnsupportedCurveThenThrowIllegalArgumentException() {
		new EllipticCurveVerifier(BigInteger.ONE, BigInteger.ONE, "unsupported-curve", SHA256_ECDSA_ALG);
	}

	@Test
	public void verifyWhenP256CurveAndSignatureMatchesThenVerificationPasses() throws Exception {
		this.verifyWhenSignatureMatchesThenVerificationPasses(P256_CURVE, SHA256_ECDSA_ALG);
	}

	@Test(expected = InvalidSignatureException.class)
	public void verifyWhenP256CurveAndSignatureDoesNotMatchThenThrowInvalidSignatureException() throws Exception {
		this.verifyWhenSignatureDoesNotMatchThenThrowInvalidSignatureException(P256_CURVE, SHA256_ECDSA_ALG);
	}

	@Test
	public void verifyWhenP384CurveAndSignatureMatchesThenVerificationPasses() throws Exception {
		this.verifyWhenSignatureMatchesThenVerificationPasses(P384_CURVE, SHA384_ECDSA_ALG);
	}

	@Test(expected = InvalidSignatureException.class)
	public void verifyWhenP384CurveAndSignatureDoesNotMatchThenThrowInvalidSignatureException() throws Exception {
		this.verifyWhenSignatureDoesNotMatchThenThrowInvalidSignatureException(P384_CURVE, SHA384_ECDSA_ALG);
	}

	@Test
	public void verifyWhenP521CurveAndSignatureMatchesThenVerificationPasses() throws Exception {
		this.verifyWhenSignatureMatchesThenVerificationPasses(P521_CURVE, SHA512_ECDSA_ALG);
	}

	@Test(expected = InvalidSignatureException.class)
	public void verifyWhenP521CurveAndSignatureDoesNotMatchThenThrowInvalidSignatureException() throws Exception {
		this.verifyWhenSignatureDoesNotMatchThenThrowInvalidSignatureException(P521_CURVE, SHA512_ECDSA_ALG);
	}

	@Test(expected = InvalidSignatureException.class)
	public void verifyWhenSignatureAlgorithmNotSameAsVerificationAlgorithmThenThrowInvalidSignatureException() throws Exception {
		KeyPair keyPair = this.generateKeyPair(P256_CURVE);
		ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
		ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();

		byte[] data = "Some data".getBytes();

		byte[] jwsSignature = Codecs.b64UrlEncode(this.generateJwsSignature(data, SHA256_ECDSA_ALG, privateKey));

		EllipticCurveVerifier verifier = new EllipticCurveVerifier(
				publicKey.getW().getAffineX(),
				publicKey.getW().getAffineY(),
				P256_CURVE,
				SHA512_ECDSA_ALG);
		verifier.verify(data, Codecs.b64UrlDecode(jwsSignature));
	}

	private void verifyWhenSignatureMatchesThenVerificationPasses(String curve, String algorithm) throws Exception {
		KeyPair keyPair = this.generateKeyPair(curve);
		ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
		ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();

		byte[] data = "Some data".getBytes();

		byte[] jwsSignature = Codecs.b64UrlEncode(this.generateJwsSignature(data, algorithm, privateKey));

		EllipticCurveVerifier verifier = new EllipticCurveVerifier(
				publicKey.getW().getAffineX(),
				publicKey.getW().getAffineY(),
				curve,
				algorithm);
		verifier.verify(data, Codecs.b64UrlDecode(jwsSignature));
	}

	private void verifyWhenSignatureDoesNotMatchThenThrowInvalidSignatureException(String curve, String algorithm) throws Exception {
		KeyPair keyPair = this.generateKeyPair(curve);
		ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
		ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();

		byte[] data = "Some data".getBytes();

		byte[] jwsSignature = Codecs.b64UrlEncode(this.generateJwsSignature(data, algorithm, privateKey));

		EllipticCurveVerifier verifier = new EllipticCurveVerifier(
				publicKey.getW().getAffineX(),
				publicKey.getW().getAffineY(),
				curve,
				algorithm);
		verifier.verify("Data not matching signature".getBytes(), Codecs.b64UrlDecode(jwsSignature));
	}

	private KeyPair generateKeyPair(String curve) throws Exception {
		ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec(curve);
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA");
		keyPairGenerator.initialize(ecGenParameterSpec);
		return keyPairGenerator.generateKeyPair();
	}

	private byte[] generateJwsSignature(byte[] data, String algorithm, ECPrivateKey privateKey) throws Exception {
		Signature signature = Signature.getInstance(algorithm);
		signature.initSign(privateKey);
		signature.update(data);
		byte[] jcaSignature = signature.sign();// DER-encoded signature, according to JCA spec (sequence of two integers - R + S)
		int jwsSignatureLength = -1;
		if (SHA256_ECDSA_ALG.equals(algorithm)) {
			jwsSignatureLength = 64;
		} else if (SHA384_ECDSA_ALG.equals(algorithm)) {
			jwsSignatureLength = 96;
		} else if (SHA512_ECDSA_ALG.equals(algorithm)) {
			jwsSignatureLength = 132;
		}
		return EllipticCurveSignatureHelper.transcodeSignatureToJWS(jcaSignature, jwsSignatureLength);
	}
}


text:
#include "gm.h"
#include "SkBitmap.h"
#include "SkRandom.h"
#include "SkShader.h"
#include "SkXfermode.h"

namespace skiagm {

/**
 * Renders overlapping shapes with colorburn against a checkerboard.
 */
class DstReadShuffle : public GM {
public:
    DstReadShuffle() {
       this->setBGColor(SkColorSetARGB(0xff, 0xff, 0, 0xff));
    }

protected:
    enum ShapeType {
        kCircle_ShapeType,
        kRoundRect_ShapeType,
        kRect_ShapeType,
        kConvexPath_ShapeType,
        kConcavePath_ShapeType,
        kText_ShapeType,
        kNumShapeTypes
    };

    SkString onShortName() SK_OVERRIDE {
        return SkString("dstreadshuffle");
    }

    SkISize onISize() SK_OVERRIDE {
        return SkISize::Make(kWidth, kHeight);
    }

    void drawShape(SkCanvas* canvas,
                   SkPaint* paint,
                   ShapeType type) {
        static const SkRect kRect = SkRect::MakeXYWH(SkIntToScalar(-50), SkIntToScalar(-50),
                                                     SkIntToScalar(75), SkIntToScalar(105));
        switch (type) {
            case kCircle_ShapeType:
                canvas->drawCircle(0, 0, 50, *paint);
                break;
            case kRoundRect_ShapeType:
                canvas->drawRoundRect(kRect, SkIntToScalar(10), SkIntToScalar(20), *paint);
                break;
            case kRect_ShapeType:
                canvas->drawRect(kRect, *paint);
                break;
            case kConvexPath_ShapeType:
                if (fConvexPath.isEmpty()) {
                    SkPoint points[4];
                    kRect.toQuad(points);
                    fConvexPath.moveTo(points[0]);
                    fConvexPath.quadTo(points[1], points[2]);
                    fConvexPath.quadTo(points[3], points[0]);
                    SkASSERT(fConvexPath.isConvex());
                }
                canvas->drawPath(fConvexPath, *paint);
                break;
            case kConcavePath_ShapeType:
                if (fConcavePath.isEmpty()) {
                    SkPoint points[5] = {{0, SkIntToScalar(-50)} };
                    SkMatrix rot;
                    rot.setRotate(SkIntToScalar(360) / 5);
                    for (int i = 1; i < 5; ++i) {
                        rot.mapPoints(points + i, points + i - 1, 1);
                    }
                    fConcavePath.moveTo(points[0]);
                    for (int i = 0; i < 5; ++i) {
                        fConcavePath.lineTo(points[(2 * i) % 5]);
                    }
                    fConcavePath.setFillType(SkPath::kEvenOdd_FillType);
                    SkASSERT(!fConcavePath.isConvex());
                }
                canvas->drawPath(fConcavePath, *paint);
                break;
            case kText_ShapeType: {
                const char* text = "Hello!";
                paint->setTextSize(30);
                canvas->drawText(text, strlen(text), 0, 0, *paint);
            }
            default:
                break;
        }
    }

    static SkColor GetColor(SkRandom* random, int i) {
        SkColor color;
        switch (i) {
            case 0:
                color = SK_ColorTRANSPARENT;
                break;
            case 1:
                color = SkColorSetARGB(0xff,
                                       random->nextULessThan(256),
                                       random->nextULessThan(256),
                                       random->nextULessThan(256));
                break;
            default:
                uint8_t alpha = random->nextULessThan(256);
                color = SkColorSetARGB(alpha,
                                       random->nextRangeU(0, alpha),
                                       random->nextRangeU(0, alpha),
                                       random->nextRangeU(0, alpha));
                break;
        }
        return color;
    }

    static void SetStyle(SkPaint* p, int style, int width) {
        switch (style) {
            case 0:
                p->setStyle(SkPaint::kStroke_Style);
                p->setStrokeWidth((SkScalar)width);
                break;
            case 1:
                p->setStyle(SkPaint::kStrokeAndFill_Style);
                p->setStrokeWidth((SkScalar)width);
                break;
            default:
                p->setStyle(SkPaint::kFill_Style);
                break;
        }
    }

    void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkRandom random;
        SkScalar y = 100;
        for (int i = 0; i < kNumShapeTypes; i++) {
            ShapeType shapeType = static_cast<ShapeType>(i);
            SkScalar x = 25;
            for (int style = 0; style < 3; style++) {
                for (int width = 0; width <= 1; width++) {
                    for (int alpha = 0; alpha <= 2; alpha++) {
                        for (int r = 0; r <= 5; r++) {
                            SkColor color = GetColor(&random, alpha);

                            SkPaint p;
                            p.setAntiAlias(true);
                            p.setColor(color);
                            p.setXfermodeMode(r % 3 == 0 ? SkXfermode::kHardLight_Mode :
                                                           SkXfermode::kSrcOver_Mode);
                            SetStyle(&p, style, width);
                            canvas->save();
                            canvas->translate(x, y);
                            canvas->rotate((SkScalar)(r < 3 ? 10 : 0));
                            this->drawShape(canvas, &p, shapeType);
                            canvas->restore();
                            x += 8;
                        }
                    }
                }
            }
            y += 50;
        }
    }

private:
    enum {
        kNumShapes = 100,
    };
    SkAutoTUnref<SkShader> fBG;
    SkPath                 fConcavePath;
    SkPath                 fConvexPath;
    static const int kWidth = 900;
    static const int kHeight = 400;
    typedef GM INHERITED;
};

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

static GM* MyFactory(void*) { return new DstReadShuffle; }
static GMRegistry reg(MyFactory);

}


text:
import window as w
import functions as f
import tkinter as tk

f.import_crops(f.data)

def add_checkbox(Frame, row, label, gained_gold, long_gold=None):
    """ Given a seed and it's associated gold income, adds a checkbox to
    Frame (middle_frame). """
    if (long_gold != None):
        right_label = "{:5.2f} ({:6.2f})".format(gained_gold, long_gold)

    else:
        right_label = "{:6.2f}".format(gained_gold)

    num_letters = 35 - len(label) - len(right_label)
    label += " " * num_letters + right_label

    checkbox = tk.Checkbutton(Frame, text=label, bg='WHITE')
    checkbox.grid(row=row, sticky=tk.W)

def update_seeds():
    """ Called when the Update Seeds button is pressed. Takes the inputs given
    in the fields above the button (budget, season, date, max # seeds) and then
    fills the below frame with possible seeds and their associated gold income.
    """

    # Update status bar to reflect calculations are being made.
    w.status.config(text = "Calculating...")

    # Destroy existing choices.
    for checkbox in w.middle_frame.winfo_children():
        checkbox.destroy()

    # Get the crops that can be purchased based on input.
    paths = f.get_net_income(
        w.season_dropdown.get().lower(),
        int(w.date_entry.get()),
        int(w.budget_entry.get()),
        int(w.num_seeds_entry.get()),
        f.data)

    # Check if crop net gold incomes were successfully retrieved.
    if paths == None:
        return

    # Add a new checkbox for each crop.
    row = 1
    for path in paths:
        add_checkbox(w.middle_frame, row, *path)
        row += 1

    # Update the status bar to reflect that calculations are finished.
    w.status.config(text = "Seeds updated! (Idle)")

# Associate a function with the Update Seeds button.
w.update_seeds_button.config(command = update_seeds)

# Open GUI and program.
w.root.geometry('250x500')
w.root.mainloop()


text:
Reports a package that is exported or opened to the same Java 9 module where it's defined.
The quick-fix removes such directives from module-info.java

Example:

  module com.mycomp {
    exports com.mycomp.main to com.mycomp;
  }

After the quick-fix is applied the result looks like:

  module main {
  }

This inspection only reports if the language level of the project or module is 9 or higher.


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

<title>Overview List</title>
<meta name="date" content="2016-03-07">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Packages

com.yingkan.dictionaryAPI

com.yingkan.mydictapp


text:
@interface WJYTabBarController : UITabBarController

@end


text:
{-# LANGUAGE OverloadedStrings, ConstraintKinds #-}

module Network.Salesforce.Types where

import Data.ByteString (ByteString)

import Control.Failure
import Network.HTTP.Conduit
import Control.Monad.Reader
import Control.Applicative

import Data.Conduit
import Data.Aeson

data SFToken = SFToken { issuedAt    :: ByteString,
                         instanceURL :: ByteString,
                         accessToken :: ByteString,
                         signature   :: ByteString } deriving Show

instance FromJSON SFToken where
  parseJSON (Object v) = SFToken <$> (v .: "issued_at") <*>
                         (v .: "instance_url") <*>
                         (v .: "access_token") <*>
                         (v .: "signature")
  parseJSON _ = fail "Invalid login request."

type SFContext m = MonadReader (Manager, SFToken) m

type RestIO m = (MonadBaseControl IO m, MonadResource m, Failure HttpException m)
type SFConnection m a = ReaderT (Manager, SFToken) (ResourceT m) a
type SFRunnable m = (MonadIO m, MonadBaseControl IO m, MonadUnsafeIO m, MonadThrow m)


text:
typedef NS_ENUM(NSInteger, TestRequestType) {
    LoginType = 100,

};

@interface TestRequest : STBaseRequest
@property (nonatomic,assign) TestRequestType requestType;
@end


text:
class FantasyTeam < ActiveRecord::Base
    belongs_to :fantasy_league

    def name_and_owner
        "#{name} - #{owner}"
    end

    def owner_and_team
        "#{owner} - #{name}"
    end

end


text:
<?php
/**
 * Authentication trait.
 *
 * @package ComicCMS2
 * @author Cezary Kluczyński
 * @license https://github.com/cezarykluczynski/ComicCMS2/blob/master/LICENSE.txt MIT
 */

namespace Application\Service;

use Zend\Session\Container;
use Zend\Mvc\MvcEvent;

trait Authentication
{
    /**
     * @var \User\Entity\User|null
     */
    protected $authenticatedUser;

    public function onDispatchAuthentication(MvcEvent $e)
    {
        $userContainer = new Container('user');

        if (!is_null($userContainer->authenticatedUser)) {
            $this->authenticatedUser = $userContainer->authenticatedUser;
        }
    }
}


text:
--+ holdcas on;
set  system parameters 'dont_reuse_heap_file=yes';
create table a (i int auto_increment);
insert into a (i) values(NULL);
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;
insert into a (i) select NULL from a;

create table t (i char(255), j int, k int, s string);
create index idx on t(i,j,k);

insert into t(i,j,k, s) select NULL, NULL, NULL, NULL from a;
insert into t(i,j,k, s) select NULL, i, i, i from a;
insert into t(i,j,k, s) select 1, i, i, i from a;
insert into t(i,j,k, s) select 2, i, i, i from a;
insert into t(i,j,k, s) select 3, i, i, i from a;
insert into t(i,j,k, s) select 4, i, i, i from a;
insert into t(i,j,k, s) select 5, i, i, i from a;

select /*+ recompile INDEX_SS */ i, j from t where j = '2'order by 1;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j = '2' order by i desc;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j <= '1'order by 1;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j <= '1' or j = 3 order by 1;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j <= '1' order by i;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j <= '1' or j = 3 order by i;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j < '2' order by i desc;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j < '2' or j = 3 order by i desc;

update statistics on all classes;

--Test ISS
select /*+ recompile INDEX_SS */ i, j from t where j = '2' order by 1;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j = '2' order by i desc;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j <= '1'order by 1;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j <= '1' or j = 3 order by 1;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j <= '1' order by i;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j <= '1' or j = 3 order by i;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j < '2' order by i desc;
--Test
select /*+ recompile INDEX_SS */ i, j from t where j < '2' or j = 3 order by i desc;

--Test ISS
select /*+ recompile  */ i, j from t where j is NULL and k = '3'order by i;
--Test
select /*+ recompile  */ i, j from t where j <=> NULL and k = '2' order by i;
--Test
select /*+ recompile  */ i, j from t where k = 3 order by i, j;

drop table t;

drop table a;
set  system parameters 'dont_reuse_heap_file=no';
commit;
--+ holdcas off;


text:
require File.dirname(__FILE__) + '/../test_helper'

class RsvpTest < ActiveSupport::TestCase

  fixtures :events, :users

  def test_should_be_invalid_with_invalid_attendees_count
    e = events(:future_event)
    u = users(:quentin)
    ['',0,-1,3.5].each do |c|
      assert_no_difference Rsvp, :count do
        r = e.rsvps.build(:attendees_count=>c)
        r.user = u
        r.save
        assert r.errors.on(:attendees_count)
      end
    end
  end

  def test_should_be_invalid_with_event_that_does_not_allow_rsvp
    e = events(:no_rsvp_event)
    u = users(:quentin)
    assert_no_difference Rsvp, :count do
      r = e.rsvps.build(:attendees_count=>1)
      r.user = u
      r.save
      assert r.errors.on(:base)
    end
  end

end


text:
This example showcases Next.js's [Static Generation](https://nextjs.org/docs/basic-features/pages) feature using [Kentico Kontent](https://kontent.ai) as the data source.

## Demo

[https://next-blog-kontent.vercel.app/](https://next-blog-kontent.vercel.app/)

## Deploy your own

Once you have access to [the environment variables you'll need](#step-3-set-up-environment-variables), deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/cms-kontent&project-name=cms-kontent&repository-name=cms-kontent&env=KONTENT_PROJECT_ID,KONTENT_PREVIEW_API_KEY,KONTENT_PREVIEW_SECRET&envDescription=Required%20to%20connect%20the%20app%20with%20Kontent&envLink=https://github.com/vercel/next.js/tree/canary/examples/cms-kontent%23step-3-set-up-environment-variables)

### Related examples

- [WordPress](/examples/cms-wordpress)
- [DatoCMS](/examples/cms-datocms)
- [Sanity](/examples/cms-sanity)
- [TakeShape](/examples/cms-takeshape)
- [Prismic](/examples/cms-prismic)
- [Contentful](/examples/cms-contentful)
- [Strapi](/examples/cms-strapi)
- [Agility CMS](/examples/cms-agilitycms)
- [Cosmic](/examples/cms-cosmic)
- [ButterCMS](/examples/cms-buttercms)
- [Storyblok](/examples/cms-storyblok)
- [GraphCMS](/examples/cms-graphcms)
- [Ghost](/examples/cms-ghost)
- [Blog Starter](/examples/blog-starter)

## How to use

Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:

```bash
npx create-next-app --example cms-kontent cms-kontent-app
# or
yarn create next-app --example cms-kontent cms-kontent-app
```

## Configuration

### Step 1. Create an account on Kontent

First, [create an account on Kontent.ai](https://app.kontent.ai/sign-up?utm_source=nextjs_docs_example&utm_medium=devrel&utm_campaign=extended_trial).

> The link above will provide you with the 90-days trial. Once you finish the trial, or even during the trial period, you could switch to the [**developer plan**](https://kontent.ai/developer-plan) which is **free of charge** and offers all the features you'll need to test out the example capabilities.

After signing up, [create an empty project](https://docs.kontent.ai/tutorials/set-up-kontent/projects/manage-projects#a-creating-projects).

### Step 2. Create the content models and fill them with data

The [content model](https://docs.kontent.ai/tutorials/set-up-kontent/content-modeling/what-is-content-modeling) defines the data structures of your application/websites. The structures are flexible and you can tailor them to your needs.

For this example you need to create a content model that defines an `author` and a `post` content type. **You can import these automatically or by doing it manually** to familiarize yourself with the Kontent user interface.

To import the content models with their data follow the next steps:

1. Enter [Kontent application](https://app.kontent.ai)
1. Go to "Project Settings", select API keys
1. Activate Management API
1. Copy `Project ID` and `Management API` key
1. Install [Kontent Backup Manager](https://github.com/Kentico/kontent-backup-manager-js) and import data to newly created project from kontent-backup.zip file (place appropriate values for apiKey and projectId arguments):

   ```sh
   npm i -g @kentico/kontent-backup-manager
   kbm --action=restore --apiKey=<Management API key> --projectId=<Project ID> --zipFilename=kontent-backup
   ```

   > **💡 Alternatively, you can use the [Template Manager UI](https://kentico.github.io/kontent-template-manager/import) for importing the content.**

1. Go to your Kontent project and publish all the imported items.
   > You could deactivate Management API key, it is not necessary any more.

### Step 2.1. Optionally create the content models manually

You can safely ignore this step if you already imported the content models in Step 2.

#### Create an `Author` content type

From your Kontent project, go to **Content models** and add a new `Content type`:

> you don't have to modify the element configuration unless specified

- Content type name: `Author`
- Add the following content elements
  - `Name` - **Text** element
  - `Picture` - **Asset** element - configure to allow to select `At most 1` asset and `Limit file types` only to `Adjustable images`

Save the content type and continue.

The content type should look like this:

![Content type Author](./docs/author-content-type.png)

#### Create a `Post` content type

From your Kontent project, go to **Content models** and add a new content type:

> you don't have to modify the element configuration unless specified

- Content type name: `Post`
- Add the following content elements
  - `Title` - **Text** element
  - `Date` - **Date & time** element
  - `Excerpt` - **Text** element
  - `Content` - **Rich Text** element
  - `Cover Image` - **Asset Text** element - configure to allow to select `At most 1` asset and `Limit file types` only to `Adjustable images` - `Content` - `Slug` - **URL slug** element - auto-generated from `Title` element
  - `Author` - **Linked items** element - configure to accept `Exactly 1` item of type `Author`

Save the content type and continue.

The content type should look like this:

![Content type Author](./docs/post-content-type.png)

#### Fill content models with data

Go to `Content & Assets` section in your project and click `Create new` on the `Content` tab and select `Author` content type.

- You just need **1 author item** first.
- Use dummy data for his name.
- For the image, you can download one from [Unsplash](https://unsplash.com/).

Next, create another item based on **Post** content type:

- It's recommend to create at least **2 post items**.
- Use dummy data for the text.
- For images, you can download them from [Unsplash](https://unsplash.com/).
- Pick the **author** you created earlier.

**Important:** For each item, you need to click on **Publish**. If not, the entry will be in draft workflow step.

![Published post item overview](./docs/publish-post-overview.png)

### Step 3. Set up environment variables

Copy the `.env.local.example` file in this directory to `.env.local` (which will be ignored by Git):

```bash
cp .env.local.example .env.local
```

Then set each variable on `.env.local` using the keys `Project settings` > `API keys`:

- `KONTENT_PROJECT_ID` - Should be the Project ID in `Project settings` > `API keys`.
- `KONTENT_PREVIEW_API_KEY` - One of the Preview API keys in `Project settings` > `API keys`.
- `KONTENT_PREVIEW_SECRET` - Can be any random string (but avoid spaces), like `MY_SECRET` - this is used for [Preview Mode](https://nextjs.org/docs/advanced-features/preview-mode).

### Step 4. Run Next.js in development mode

```bash
npm install
npm run dev

# or

yarn
yarn dev
```

Your blog should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/vercel/next.js/discussions).

### Step 5. Try preview mode

In your Kontent project, go to **Project Settings > Preview URLs** and set a new preview URL for the `Post` content type to:

```plain
http://localhost:3000/api/preview?secret=<KONTENT_PREVIEW_SECRET>&slug={URLslug}
```

Replace `<KONTENT_PREVIEW_SECRET>` with its respective value in `.env.local`:

![Preview URL setup](./docs/preview-URLs-setup.png)

Once saved, go to one of the posts you've created and:

- Create a new version of the post
- **Update the title**. For example, you can add `[Draft]` in front of the title.
  > Mind the title also regenerates the URL slug, if you want to change any other field that does not influence URL slug, feel free to do so.
- **Do not** publish it. By doing this, the post will be in draft workflow step.
- On the menu, you will see the **Preview** button. Click on it!

![Post preview button](./docs/post-preview-button.png).

You will now be able to see the updated title. To exit preview mode, you can click on **Click here to exit preview mode** at the top of the page.

### Step 6. Deploy on Vercel

You can deploy this app to the cloud with [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).

#### Deploy Your Local Project

To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [import to Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example).

**Important**: When you import your project on Vercel, make sure to click on **Environment Variables** and set them to match your `.env.local` file.

#### Deploy from Our Template

Alternatively, you can deploy using our template by clicking on the Deploy button below.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/cms-kontent&project-name=cms-kontent&repository-name=cms-kontent&env=KONTENT_PROJECT_ID,KONTENT_PREVIEW_API_KEY,KONTENT_PREVIEW_SECRET&envDescription=Required%20to%20connect%20the%20app%20with%20Kontent&envLink=https://github.com/vercel/next.js/tree/canary/examples/cms-kontent%23step-3-set-up-environment-variables)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/appwidget_bit_item"
    android:layout_width="fill_parent"
    android:layout_height="37dp"
    android:layout_marginBottom="1dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/widgetPoster"
        android:layout_width="@dimen/widget_poster_width"
        android:layout_height="match_parent"
        android:layout_alignBottom="@+id/textViewWidgetEpisode"
        android:layout_alignTop="@+id/widgetAirtime"
        android:layout_marginRight="5dp"
        android:src="@drawable/ic_image_missing"/>

    <TextView
        android:id="@+id/textViewWidgetShow"
        style="@style/WidgetTextView"
        android:layout_alignParentTop="true"
        android:layout_marginRight="5dp"
        android:layout_toLeftOf="@+id/widgetAirtime"
        android:layout_toRightOf="@+id/widgetPoster"
        android:text="@string/app_name"
        android:textColor="@color/white"
        android:textSize="13sp"/>

    <TextView
        android:id="@+id/textViewWidgetEpisode"
        style="@style/WidgetTextView"
        android:layout_alignLeft="@+id/textViewWidgetShow"
        android:layout_below="@+id/textViewWidgetShow"
        android:layout_marginRight="5dp"
        android:layout_toLeftOf="@+id/widgetNetwork"
        android:text="@string/no_nextepisode"
        android:textSize="12sp"/>

    <TextView
        android:id="@+id/widgetAirtime"
        style="@style/WidgetTextView"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="@string/not_available"/>

    <TextView
        android:id="@+id/widgetNetwork"
        style="@style/WidgetTextView"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/widgetAirtime"
        android:text="@string/not_available"/>

</RelativeLayout>


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v12/enums/optimization_goal_type.proto

namespace Google\Ads\GoogleAds\V12\Enums;

if (false) {
    /**
     * This class is deprecated. Use Google\Ads\GoogleAds\V12\Enums\OptimizationGoalTypeEnum\OptimizationGoalType instead.
     * @deprecated
     */
    class OptimizationGoalTypeEnum_OptimizationGoalType {}
}
class_exists(OptimizationGoalTypeEnum\OptimizationGoalType::class);
@trigger_error('Google\Ads\GoogleAds\V12\Enums\OptimizationGoalTypeEnum_OptimizationGoalType is deprecated and will be removed in the next major release. Use Google\Ads\GoogleAds\V12\Enums\OptimizationGoalTypeEnum\OptimizationGoalType instead', E_USER_DEPRECATED);


text:
#include "rt_player.h"

namespace mu {

  // Callback function for RtAudio when requesting more data for playback.
  // NOTE: see tarballs/stk-4.4.4/src/RtWvOut.cpp
  int dac_callback( void *outputBuffer,
                    void *inputBuffer,
                    unsigned int nBufferFrames,
                    double streamTime,
                    RtAudioStreamStatus status,
                    void *dataPointer ) {
    return ( (RtPlayer *) dataPointer )->RtPlayer::readBuffer( outputBuffer, nBufferFrames, streamTime );
  }

  // Callback method for RtAudio.  buffer is an array of StkFloat
  // values, interleaved (if multichannel).  frame_count is the number
  // of sample frames.
  //
  // Note that this is called in a separate thread, so care must be
  // taken in reading or writing any state here.
  //
  // Implementation note: RtAudio expects to receive samples in an
  // array of doubles.  SampleProcessor objects expect to be called with an
  // StkFrames object.  The main work in this method is to copy data
  // out of the StkFrames object into RtAudio's buffer object.
  //
  // See also:
  // ~/Projects/Mune/tarballs/stk-4.4.4/src/RtWvOut.cpp Line::36
  //
  int RtPlayer::readBuffer( void *buffer, unsigned int frame_count, double stream_time ) {
    if (source_ == NULL) { return 0; };

    // grow the stkFrames buffer as needed
    stk_frames_.resize(frame_count, channel_count_);

    // ask the source to generate samples
    source_->step(stk_frames_, tick_, is_first_);

    is_first_ = false;

    // update tick counter
    tick_ += frame_count;

    // copy the samples to RtAudio's buffer
    stk::StkFloat *src = (stk::StkFloat *)&stk_frames_[0];
    stk::StkFloat *dst = (stk::StkFloat *)buffer;
    unsigned int sample_count = frame_count * channel_count_;
    for (int i=sample_count-1; i>=0; i--) { *dst++ = *src++; }

    if ((!TickUtils::isIndefinite(source_->getEnd())) && (tick_ >= source_->getEnd())) {
      stop();
    }

    return 0;
  }

  RtPlayer::RtPlayer()
  : device_number_ (kDefaultDeviceNumber),
    is_running_ (false) {
    stk_frames_.resize(stk::RT_BUFFER_SIZE, 2);
    init();
  }

  RtPlayer::~RtPlayer() {
  }

  // Start the player if not already running.  Does not rewind
  // before starting.
  RtPlayer& RtPlayer::start() {
    if (!is_running_) {
      RtAudio::StreamParameters dac_parameters;
      if ( device_number_ == 0 ) {
        dac_parameters.deviceId = dac_.getDefaultOutputDevice();
      } else {
        dac_parameters.deviceId = device_number_ - 1;
      }
      dac_parameters.nChannels = channel_count_;

      is_first_ = true;
      dac_.openStream( &dac_parameters,
                       NULL,
                       ((sizeof(stk::StkFloat) == 8) ? RTAUDIO_FLOAT64 : RTAUDIO_FLOAT32),
                       frame_rate_,
                       &frame_size_,
                       &dac_callback,
                       (void *)this);

      dac_.startStream();
      is_running_ = true;
    }
    return *this;
  }

  // Stop the player if not already stopped. If \c immediately is
  // true, immediately stops the player, otherwise gives time for
  // already queued samples to finish.
  RtPlayer& RtPlayer::stop(bool immediately) {
    if (is_running_) {
      // dac_.isSPRunning() ?
      dac_.closeStream();
      is_running_ = false;
    }
    return *this;
  }

}


text:
using System;
using System.ComponentModel;

namespace Azure.AI.MetricsAdvisor.Models
{
    /// <summary>
    /// condition operator
    ///
    ///
    ///
    /// should be specified when combining multiple detection conditions.
    /// </summary>
    public readonly partial struct DetectionConditionsOperator : IEquatable<DetectionConditionsOperator>
    {
        private readonly string _value;

        /// <summary> Determines if two <see cref="DetectionConditionsOperator"/> values are the same. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public DetectionConditionsOperator(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string AndValue = "AND";
        private const string OrValue = "OR";
        /// <summary> Determines if two <see cref="DetectionConditionsOperator"/> values are the same. </summary>
        public static bool operator ==(DetectionConditionsOperator left, DetectionConditionsOperator right) => left.Equals(right);
        /// <summary> Determines if two <see cref="DetectionConditionsOperator"/> values are not the same. </summary>
        public static bool operator !=(DetectionConditionsOperator left, DetectionConditionsOperator right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="DetectionConditionsOperator"/>. </summary>
        public static implicit operator DetectionConditionsOperator(string value) => new DetectionConditionsOperator(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is DetectionConditionsOperator other && Equals(other);
        /// <inheritdoc />
        public bool Equals(DetectionConditionsOperator other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
@implementation HYBlockThreeView

- (void)dealloc {
    NSLog(@"%@ - execute %s",NSStringFromClass([self class]),__func__);
}

- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubviews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder  {

    self = [super initWithCoder:coder];
    if (self) {
        [self setupSubviews];
    }
    return self;
}

- (HYBlockThreeSubView *)blockThreeSubView {

    if (!_blockThreeSubView) {
        _blockThreeSubView = [HYBlockThreeSubView new];
    }
    return _blockThreeSubView;
}

- (HYBlockTitleView *)blockTitleView {

    if (!_blockTitleView) {
        _blockTitleView = [HYBlockTitleView new];
    }
    return _blockTitleView;
}

- (void)setupSubviews {

    [self addSubview:self.blockThreeSubView];
    [self addSubview:self.blockTitleView];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat blockTitleViewX = 0;
    CGFloat blockTitleViewY = 0;
    CGFloat blockTitleViewW = self.frame.size.width;
    CGFloat blockTitleViewH = 50;
    _blockTitleView.frame = CGRectMake(blockTitleViewX, blockTitleViewY, blockTitleViewW, blockTitleViewH);

    CGFloat blockThreeSubViewX = blockTitleViewX;
    CGFloat blockThreeSubViewY = blockTitleViewY + blockTitleViewH;
    CGFloat blockThreeSubViewW = blockTitleViewW;
    CGFloat blockThreeSubViewH = 220;
    _blockThreeSubView.frame = CGRectMake(blockThreeSubViewX, blockThreeSubViewY, blockThreeSubViewW, blockThreeSubViewH);

}

@end


text:
package challenger

import (
	"crypto-tonality/pb"
	"crypto/ecdsa"
	"crypto/elliptic"
	"math/big"
	"testing"
)

var testFlag = "hello"

// Copied from ecdsa.go
func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
	orderBits := c.Params().N.BitLen()
	orderBytes := (orderBits + 7) / 8
	if len(hash) > orderBytes {
		hash = hash[:orderBytes]
	}

	ret := new(big.Int).SetBytes(hash)
	excess := len(hash)*8 - orderBits
	if excess > 0 {
		ret.Rsh(ret, uint(excess))
	}
	return ret
}

func TestSignWithZeroScalarFails(t *testing.T) {
	chal, err := NewChallenger(testFlag)
	if err != nil {
		t.Errorf("NewChallenger failed: %s", err)
		return
	}

	for _, a := range []*big.Int{new(big.Int).SetInt64(0), elliptic.P256().Params().N} {
		res := chal.SignFirstMessage(&pb.SignRequest{Scalar: a.Bytes()})
		if res.Message0Sig != nil {
			t.Errorf("SignFirstMessage expected to fail, got %+v", res)
		}
	}
}

func TestSignWithOneScalarSucceeds(t *testing.T) {
	chal, err := NewChallenger(testFlag)
	if err != nil {
		t.Errorf("NewChallenger failed: %s", err)
		return
	}

	hello := chal.Hello(&pb.HelloRequest{})
	pk := &ecdsa.PublicKey{
		Curve: elliptic.P256(),
		X:     new(big.Int).SetBytes(hello.Pubkey.X),
		Y:     new(big.Int).SetBytes(hello.Pubkey.Y),
	}

	a := new(big.Int).SetInt64(1)
	res := chal.SignFirstMessage(&pb.SignRequest{Scalar: a.Bytes()})
	r := new(big.Int).SetBytes(res.Message0Sig.R)
	s := new(big.Int).SetBytes(res.Message0Sig.S)
	ok := ecdsa.Verify(pk, hashMessage(hello.Message0), r, s)
	if !ok {
		t.Errorf("ecdsa.Verify failed to verify m0 signature")
	}
}

// Section 4.2 in https://eprint.iacr.org/2015/1135
// "On the Security of the Schnorr Signature Scheme and DSA against Related-Key Attacks"
// Hiraku Morita and Jacob C.N. Schuldt and Takahiro Matsuda and Goichiro Hanaoka and Tetsu Iwata
func TestRelatedKeyAttack(t *testing.T) {
	chal, err := NewChallenger(testFlag)
	if err != nil {
		t.Errorf("NewChallenger failed: %s", err)
		return
	}

	hello := chal.Hello(&pb.HelloRequest{})
	z0 := hashToInt(hashMessage(hello.Message0), elliptic.P256())
	z1 := hashToInt(hashMessage(hello.Message1), elliptic.P256())
	n := elliptic.P256().Params().N

	// a <- z0 / z1 mod N
	a := new(big.Int)
	a.Mul(z0, new(big.Int).ModInverse(z1, n))
	a.Mod(a, n)

	// Query signing oracle.
	sig := chal.SignFirstMessage(&pb.SignRequest{Scalar: a.Bytes()})
	r := new(big.Int).SetBytes(sig.Message0Sig.R)
	s := new(big.Int).SetBytes(sig.Message0Sig.S)

	// s <- s / a mod N
	s.Mul(s, new(big.Int).ModInverse(a, n))
	s.Mod(s, n)

	// Send forged signature for m1.
	res := chal.VerifySecondMessage(&pb.VerifyRequest{
		Message1Sig: &pb.Signature{
			R: r.Bytes(),
			S: s.Bytes(),
		},
	})

	if res.Flag != testFlag {
		t.Errorf("VerifySecondMessage did not return the flag")
	}
}


text:
require 'active_record/connection_adapters/mysql_adapter'

module ActiveRecord

  module Calculations #:nodoc:
    CALCULATIONS_OPTIONS << :use_db
  end

  class Base

    def with_database(named_connection, &block)
      self.class.with_database(named_connection, &block)
    end

    class << self

      VALID_FIND_OPTIONS << :use_db

      # Establishes a connection to the database that's used by all Active Record objects.
      def mysql_proxy_connection(config) # :nodoc:
        config = config.symbolize_keys
        host     = config[:host]
        port     = config[:port]
        socket   = config[:socket]
        username = config[:username] ? config[:username].to_s : 'root'
        password = config[:password].to_s

        if config.has_key?(:database)
          database = config[:database]
        else
          raise ArgumentError, "No database specified. Missing argument: database."
        end

        # Require the MySQL driver and define Mysql::Result.all_hashes
        unless defined? Mysql
          begin
            require_library_or_gem('mysql')
          rescue LoadError
            $stderr.puts '!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.'
            raise
          end
        end
        MysqlCompat.define_all_hashes_method!

        mysql = Mysql.init
        mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslca] || config[:sslkey]

        ConnectionAdapters::MysqlProxyAdapter.new(mysql, logger, [host, username, password, database, port, socket], config)
      end

      def use_named(options)
        if connection.is_a?(ConnectionAdapters::MysqlProxyAdapter)
          connection.use_named(connection.named_connection_option(options)) do
            yield
          end
        else
          yield
        end
      end

      def with_database(named_connection)
        use_named(named_connection) do
          yield
        end
      end

      ###
      # Chain ActiveRecord::Base methods to optionally use a named connection.
      def find_every_with_named_connection(options)
        use_named(options) do
          find_every_without_named_connection(options)
        end
      end
      alias_method_chain :find_every, :named_connection

      def find_by_sql_with_named_connection(sql, *args)
        use_named(args.extract_options!) do
          find_by_sql_without_named_connection(sql)
        end
      end
      alias_method_chain :find_by_sql, :named_connection

      def count_by_sql_with_named_connection(sql, *args)
        use_named(args.extract_options!) do
          count_by_sql_without_named_connection(sql)
        end
      end
      alias_method_chain :count_by_sql, :named_connection

      def calculate_with_named_connection(operation, column_name, options ={})
        use_named(options.delete(:use_db)) do
          calculate_without_named_connection(operation, column_name, options)
        end
      end
      alias_method_chain :calculate, :named_connection

    end
  end

  module ConnectionAdapters

    # The MySQL adapter will work with both Ruby/MySQL, which is a Ruby-based MySQL adapter that comes bundled with Active Record, and with
    # the faster C-based MySQL/Ruby adapter (available both as a gem and from http://www.tmtm.org/en/mysql/ruby/).
    #
    # Options:
    #
    # * <tt>:host</tt> -- Defaults to localhost
    # * <tt>:port</tt> -- Defaults to 3306
    # * <tt>:socket</tt> -- Defaults to /tmp/mysql.sock
    # * <tt>:username</tt> -- Defaults to root
    # * <tt>:password</tt> -- Defaults to nothing
    # * <tt>:database</tt> -- The name of the database. No default, must be provided.
    # * <tt>:sslkey</tt> -- Necessary to use MySQL with an SSL connection
    # * <tt>:sslcert</tt> -- Necessary to use MySQL with an SSL connection
    # * <tt>:sslcapath</tt> -- Necessary to use MySQL with an SSL connection
    # * <tt>:sslcipher</tt> -- Necessary to use MySQL with an SSL connection
    #
    # By default, the MysqlAdapter will consider all columns of type tinyint(1)
    # as boolean. If you wish to disable this emulation (which was the default
    # behavior in versions 0.13.1 and earlier) you can add the following line
    # to your environment.rb file:
    #
    #   ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = false
    class MysqlProxyAdapter < MysqlAdapter

      ADAPTER_NAME = 'MySQLProxy'.freeze

      def initialize(connection, logger, connection_options, config)
        @named_connections = nil
        @retries = config[:retries]
        super(connection, logger, connection_options, config)
      end

      def adapter_name #:nodoc:
        ADAPTER_NAME
      end

      def use_named(connection)
        old_connection = @connection
        @connection = connection
        yield
      ensure
        @connection = old_connection
      end

      def named_connection_option(option = nil)
        # pull the :use_db option if a Hash, else option is assumed to be the connection name
        option = option.is_a?(Hash) ? option[:use_db] : option

        named_connection =  @named_connections[option.to_sym] unless option.blank?
        named_connection || @connection
      end

      def disconnect!
        @connection.close rescue nil
        @named_connections.each_value { |conn| conn.close rescue nil } if @named_connections
      end

      # DATABASE STATEMENTS ======================================

      def execute(sql, name = nil) #:nodoc:
        retries = 0
        log(sql, "#{name} against #{@connection.host_info}") do
          @connection.query(sql)
        end
      rescue Mysql::Error => ex
        if ex.message =~ /MySQL server has gone away/
          if @retries && retries < @retries
            retries += 1
            disconnect!
            connect
            retry
          else
            raise
          end
        else
          raise
        end
      rescue ActiveRecord::StatementInvalid => exception
        if exception.message.split(":").first =~ /Packets out of order/
          raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information.  If you're on Windows, use the Instant Rails installer to get the updated mysql bindings."
        else
          raise
        end
      end

      def connect
        # set up the primary connection
        setup_connection(@connection, @connection_options)
        setup_named_connections
      end

      private

        def setup_named_connections
          named_connections_config = @config[:named_connections].symbolize_keys! rescue return

          # create the named connections if they don't already exist
          initialize_named_connections unless @named_connections

          @named_connections.each do |name, conn|
            config = named_connections_config[name]
            setup_connection(conn, [config["host"], config["username"], config["password"], config["database"], config["port"], config["socket"]])
          end
        end

        # call #real_connect on the given connection with the passed in options.
        def setup_connection(conn, conn_opts)
          encoding = @config[:encoding]
          if encoding
            conn.options(Mysql::SET_CHARSET_NAME, encoding) rescue nil
          end

          if @config[:sslca] || @config[:sslkey]
            conn.ssl_set(@config[:sslkey], @config[:sslcert], @config[:sslca], @config[:sslcapath], @config[:sslcipher])
          end

          conn.real_connect(*conn_opts)

          # reconnect must be set after real_connect is called, because real_connect sets it to false internally
          conn.reconnect = !!@config[:reconnect] if conn.respond_to?(:reconnect=)

          old_conn, @connection = @connection, conn
          execute("SET NAMES '#{encoding}'") if encoding
          # By default, MySQL 'where id is null' selects the last inserted id.
          # Turn this off. http://dev.rubyonrails.org/ticket/6778
          execute("SET SQL_AUTO_IS_NULL=0")
          @connection = old_conn
        end

        def initialize_named_connections
          @config[:named_connections].each_key {|name| @named_connections ||= {}; @named_connections[name] = Mysql.init}
        end

    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>

<info><title>ActionStack</title></info>

    <para>
        Помощник ActionStack позволяет помещать в стек запросы к
        плагину
        <link linkend="zend.controller.plugins.standard.actionstack">ActionStack</link>
        фронт-контроллера, помогая эффективно создавать очереди действий,
        выполняемых в течение запроса. Этот помощник позволяет добавлять
        действия посредством установки новых объектов запросов или наборов
        действие/контроллер/модуль.
    </para>

    <note><info><title>Вызов помощника ActionStack инициализирует плагин ActionStack</title></info>

        <para>
            При вызове помощника ActionStack неявным образом
            регистрируется плагин ActionStack. Это значит, что нет
            необходимости явным образом регистрировать плагин
            ActionStack для того, чтобы использовать его
            функционал.
        </para>
    </note>

    <example xml:id="zend.controller.actionhelpers.actionstack.simple"><info><title>Добавление задачи с использованием имен действия, контроллера и модуля</title></info>

        <para>
            Зачастую наиболее простым способом будет указание действия,
            контроллера и модуля (и необязательных параметров запроса), почти
            так же, как если бы вы вызывали
            Zend_Controller_Action::_forward():
        </para>

        <programlisting language="php"><![CDATA[
class FooController extends Zend_Controller_Action
{
    public function barAction()
    {
        // Добавление двух действий в стек
        // Добавление вызова к /foo/baz/bar/baz
        // (FooController::bazAction() с переменной запроса bar == baz)
        $this->_helper->actionStack('baz',
                                    'foo',
                                    'default',
                                    array('bar' => 'baz'));

        // Добавление вызова к /bar/bat
        // (BarController::batAction())
        $this->_helper->actionStack('bat', 'bar');
    }
}
]]></programlisting>

    </example>

    <example xml:id="zend.controller.actionhelpers.actionstack.simple2"><info><title>Добавление задачи с использованием объекта запроса</title></info>

        <para>
            Иногда имеет смысл использовать объект запроса, что более
            соответствует духу ООП. Объект запроса тоже можно передавать
            помощнику ActionStack.
        </para>

        <programlisting language="php"><![CDATA[
class FooController extends Zend_Controller_Action
{
    public function barAction()
    {
        // Добавление двух действий в стек
        // Добавление вызова к /foo/baz/bar/baz
        // (FooController::bazAction() с переменной запроса bar == baz)
        $request = clone $this->getRequest();
        // Не устанавливайте контроллер и модуль;
        // используются текущие значения
        $request->setActionName('baz')
                ->setParams(array('bar' => 'baz'));
        $this->_helper->actionStack($request);

        // Add call to /bar/bat
        // (BarController::batAction())
        $request = clone $this->getRequest();
        // Не устанавливайте модуль;
        // используется текущиее значение
        $request->setActionName('bat')
                ->setControllerName('bar');
        $this->_helper->actionStack($request);
    }
}
]]></programlisting>
    </example>


text:
<?php

/**
 * Sippy::Config singleton
 */

class Config {

	private $_config_settings;
	private static $instance;

	protected function __construct() {
        $config = null;
		require(APP_DIR .'config/config.php');
		$this->_config_settings = $config;
	}

   public static function getInstance() {
     if(self::$instance == NULL) {
      self::$instance = new Config();
     }
     return self::$instance;
   }

   public function getconfig() {
   	 return $this->_config_settings;
   }

}


text:
var express = require('express');
var router = express.Router();
var cuentasMysql = require('./cuentas_mysql');

router.get('/', function (req, res) {
    var query = req.query;
    if (query.codmacta==null) {
            cuentasMysql.getCuentas( 1,function (err, result) {
            if (err) {
                return res.status(500).send(err.message);
            }
            if (result) {
                res.json(result)
            } else {
                res.status(404).send('No se han encontrado datos');
            }
        });
    }
    else
    if (query.codmacta) {
        cuentasMysql.getCuentas(1,query.codmacta, function (err, result) {
            if (err) {
                return res.status(500).send(err.message);
            }
            if (result) {
                res.json(result)
            } else {
                res.status(404).send('No se han encontrado datos');
            }
        });
    } else {
        res.status(400).send('Formato de la petición incorrecto');
    }

});

// Consulta extracto   http://localhost:9080/api/cuentas/extr?codmacta=1
//Datos de la cuenta y saldo
router.get('/extrCab', function (req, res) {
    var query = req.query;
    if (query.codmacta==null) {
        res.status(400).send('Formato de la petición incorrecto');
    }
    else
        cuentasMysql.getExtractoCabecera(1,query.codmacta, function (err, result) {
            if (err) {
                return res.status(500).send(err.message);
            }
            if (result) {
                res.json(result)
            } else {
                res.status(404).send('No se han encontrado datos');
            }
        });

});

router.get('/extr', function (req, res) {
    var query = req.query;
    if (query.codmacta==null) {
        res.status(400).send('Formato de la petición incorrecto');
    }
    else
        cuentasMysql.getExtracto(1,query.codmacta, function (err, result) {
            if (err) {
                return res.status(500).send(err.message);
            }
            if (result) {
                res.json(result)
            } else {
                res.status(404).send('No se han encontrado datos');
            }
        });

});

router.get('/ctaDetalle', function (req, res) {
    var query = req.query;
    if (query.codmacta==null) {
        res.status(400).send('Formato de la petición incorrecto');
    }
    else
        cuentasMysql.getDetalleCuenta(1,query.codmacta, function (err, result) {
            if (err) {
                return res.status(500).send(err.message);
            }
            if (result) {
                res.json(result)
            } else {
                res.status(404).send('No se han encontrado datos');
            }
        });

});

// Exports
module.exports = router;


text:
package top.nefkgame.dubbo.registry.zk;

import java.util.List;

import org.I0Itec.zkclient.util.ZkPathUtil;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

/**
 * TODO
 *
 * @author zjj
 * @version V1.0
 * @since 2017-08-28 13:44
 */
public class ZKUtils {
    public static String toString(ZooKeeper zkClient) throws KeeperException, InterruptedException {
        return toString(zkClient, "/", ZkPathUtil.PathFilter.ALL);
    }

    public static String toString(ZooKeeper zkClient, String startPath, ZkPathUtil.PathFilter pathFilter)
        throws KeeperException, InterruptedException {
        final int level = 1;
        final StringBuilder builder = new StringBuilder("+ (" + startPath + ")");
        builder.append("\n");
        addChildrenToStringBuilder(zkClient, pathFilter, level, builder, startPath);
        return builder.toString();
    }

    private static void addChildrenToStringBuilder(ZooKeeper zkClient, ZkPathUtil.PathFilter pathFilter, final int level, final StringBuilder builder, final String startPath)
        throws KeeperException, InterruptedException {
        final List<String> children = zkClient.getChildren(startPath, false);
        for (final String node : children) {
            String nestedPath;
            if (startPath.endsWith("/")) {
                nestedPath = startPath + node;
            } else {
                nestedPath = startPath + "/" + node;
            }
            if (pathFilter.showChilds(nestedPath)) {
                builder.append(getSpaces(level - 1) + "'-" + "+" + node + "\n");
                addChildrenToStringBuilder(zkClient, pathFilter, level + 1, builder, nestedPath);
            } else {
                builder.append(getSpaces(level - 1) + "'-" + "-" + node + " (contents hidden)\n");
            }
        }
    }

    private static String getSpaces(final int level) {
        String s = "";
        for (int i = 0; i < level; i++) {
            s += "  ";
        }
        return s;
    }
}


text: from . import blocks, parts  # noqa


text:
namespace fully_homomorphic_encryption {
namespace transpiler {

// Converts booleanified XLS functions into TFHE-based C++, using the gate ops
// from the TFHE library.
class TfheTranspiler : public AbstractXLSTranspiler<TfheTranspiler> {
 public:
  static absl::StatusOr<std::string> TranslateHeader(
      const xls::Function* function,
      const xlscc_metadata::MetadataOutput& metadata,
      absl::string_view header_path,
      const absl::string_view
          encryption_specific_transpiled_structs_header_path,
      bool skip_scheme_data_deps, const std::vector<std::string>& unwrap);

  static absl::StatusOr<std::string> FunctionSignature(
      const xls::Function* function,
      const xlscc_metadata::MetadataOutput& metadata);

  static std::string CopyNodeToOutput(absl::string_view output_arg, int offset,
                                      const xls::Node* node);
  static std::string CopyParamToNode(const xls::Node* node,
                                     const xls::Node* param, int offset);
  static std::string InitializeNode(const xls::Node* node);

  static absl::StatusOr<std::string> Execute(const xls::Node* node);

  static absl::StatusOr<std::string> Prelude(
      const xls::Function* function,
      const xlscc_metadata::MetadataOutput& metadata);

  static absl::StatusOr<std::string> Conclusion();
};

}  // namespace transpiler
}  // namespace fully_homomorphic_encryption

#endif  // FULLY_HOMOMORPHIC_ENCRYPTION_TRANSPILER_TFHE_TRANSPILER_H_


text:
package com.cvnhan.androidcr.mvp.model.remote;

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

/**
 * Created by NhanCao on 13-Sep-15.
 */
public class MRRadioRes {
    @SerializedName("radioList")
    public ArrayList<MRRadio> radioList;
    @SerializedName("status")
    public int status;
}


text:
module.exports = function (config) {
  return {

    // Base path that will be used to resolve all patterns
    basePath: '%BASE_PATH%',

    // Project type
    project: '%PROJECT%',

    // Instanciate server
    server: %SERVER%,

    // Server main folder
    serverPath: '%SERVERPATH%',

    // Twig compilation
    twig: %TWIG%,

    // Twig to compile
    twigsource: [%TWIGSRC%
    ],

    // Content type
    // possible values: yml || json || no
    content: '%CONTENT%',

    // Content path
    contentPath: '%CONTENTPATH%',

    // Twig compilation dist folder
    twigdist: '%TWIGDIST%',

    // Validate HTML templates
    html: %HTML%,

    // HTML folder(s)
    htmlPath: [%HTMLPATH%
    ],

    // JS compilation
    js: %JS%,

    // JS sources
    jssource: [%JSSRC%
    ],

    // JS dist folder
    jsdist: '%JSDIST%',

    // JS main sources (to be lint)
    jsApplication: [%JSAPP%
    ],

    // Optimize images
    images: %IMAGES%,

    // Images to optimize
    imagessource: [%IMAGESSRC%
    ],

    // images dist folder
    imagesdist: '%IMAGESDIST%',

    // preprocess matching files before serving them to the browser
    csspreprocessors: '%CSSPREPROCESSORS%',

    // preprocess matching files sources
    csspreprocessorssource: [%CSSPREPROCESSORSSRC%
    ],

    // preprocess dist folder
    csspreprocessorsdist: '%CSSPREPROCESSORSDIST%',

    // enable / disable colors in the output (logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO
  };
};


text:
<?php

namespace HelloFresh\Engine\Serializer\Type;

use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonSerializationVisitor;

class LocalizedDateTimeHandler implements SubscribingHandlerInterface
{
    public static function getSubscribingMethods()
    {
        return array(
            array(
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'format' => 'json',
                'type' => 'LocalizedDateTime',
                'method' => 'serializeLocalizedDateTimeToJson',
            ),
        );
    }

    public function serializeLocalizedDateTimeToJson(
        JsonSerializationVisitor $visitor,
        \DateTime $date,
        array $type,
        Context $context
    ) {
        $df = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);

        return $df->format($date);
    }
}