text:
package adullact.publicrowdfunding.model.server.request;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import adullact.publicrowdfunding.model.local.ressource.Account;
import adullact.publicrowdfunding.model.server.entities.ServerRegistrationResponse;
import adullact.publicrowdfunding.model.server.errorHandler.RegistrationErrorHandler;
import adullact.publicrowdfunding.model.server.event.RegistrationEvent;

/**
 * @author Ferrand and Nelaupe
 */
public class RegistrationRequest extends Request<RegistrationRequest, RegistrationEvent, RegistrationErrorHandler> {
    private String m_username;
    private String m_password;
    private String m_pseudo;

    public RegistrationRequest(String username, String password, String pseudo, RegistrationEvent registrationEvent) {
        super(registrationEvent, new RegistrationErrorHandler());

        this.m_username = username;
        this.m_password = password;
        this.m_pseudo = pseudo;
    }

    @Override
    public void execute() {
        service().register(m_username, m_password, m_pseudo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ServerRegistrationResponse>() {
                    @Override
                    public void call(ServerRegistrationResponse response) {
                        if(response.accountOK == 0 || response.userOK == 0) {
                            errorHandler().manageCallback(response);
                            return;
                        }

                        done();
                        new Account(m_username, m_password, m_pseudo).setOwn();
                        event().onRegister();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        errorHandler().manageCallback();
                    }
                });
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace CK\BasicCmsBundle\DataFixtures\PHPCR;

use CK\BasicCmsBundle\Document\Page;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ODM\PHPCR\DocumentManager;

class LoadPageData implements FixtureInterface
{
    public function load(ObjectManager $dm)
    {
        if (!$dm instanceof DocumentManager) {
            $class = get_class($dm);
            throw new \RuntimeException(
                "Fixture requires a PHPCR ODM DocumentManager instance, instance of '$class' given."
            );
        }

        $parent = $dm->find(null, '/cms/pages');

        $rootPage = new Page();
        $rootPage->setTitle('main');
        $rootPage->setParentDocument($parent);
        $dm->persist($rootPage);

        $page = new Page();
        $page->setTitle('Home');
        $page->setParentDocument($rootPage);
        $page->setContent("Welcome to the homepage of this really basic CMS.");
        $dm->persist($page);

        $aboutPage = new Page();
        $aboutPage->setTitle('About');
        $aboutPage->setParentDocument($rootPage);
        $aboutPage->setContent("Some lorem about ipsum.");
        $dm->persist($aboutPage);

        $dm->flush();
    }
}


text:
import asyncio
import io
import os.path
from concurrent.futures import ProcessPoolExecutor
from urllib.parse import urlparse

import aiofiles

try:
    import PIL.Image
except ImportError:
    PIL = None

try:
    from . import api, peony
except (SystemError, ImportError):
    import api
    from __init__ import peony, utils

client = peony.PeonyClient(**api.keys)

def convert(img, formats):
    """
        Convert the image to all the formats specified
    Parameters
    ----------
    img : PIL.Image.Image
        The image to convert
    formats : list
        List of all the formats to use
    Returns
    -------
    io.BytesIO
        A file object containing the converted image
    """
    media = None
    min_size = 0

    for kwargs in formats:
        f = io.BytesIO()
        if img.mode == "RGBA" and kwargs["format"] != "PNG":
            # convert to RGB if picture is too large as a png
            # this implies that the png format is the first in `formats`
            if min_size < 5 * 1024**2:
                continue
            else:
                img.convert("RGB")

        img.save(f, **kwargs)
        size = f.tell()

        if media is None or size < min_size:
            if media is not None:
                media.close()

            media = f
            min_size = size
        else:
            f.close()

    return media

def optimize_media(file_, max_size, formats):
    """
        Optimize an image
    Resize the picture to the ``max_size``, defaulting to the large
    photo size of Twitter in :meth:`PeonyClient.upload_media` when
    used with the ``optimize_media`` argument.
    Parameters
    ----------
    file_ : file object
        the file object of an image
    max_size : :obj:`tuple` or :obj:`list` of :obj:`int`
        a tuple in the format (width, height) which is maximum size of
        the picture returned by this function
    formats : :obj`list` or :obj:`tuple` of :obj:`dict`
        a list of all the formats to convert the picture to
    Returns
    -------
    file
        The smallest file created in this function
    """
    if not PIL:
        msg = "Pillow must be installed to optimize a media\n$ pip3 install Pillow"
        raise RuntimeError(msg)

    img = PIL.Image.open(file_)

    # resize the picture (defaults to the 'large' photo size of Twitter
    # in peony.PeonyClient.upload_media)
    ratio = max(hw / max_hw for hw, max_hw in zip(img.size, max_size))

    if ratio > 1:
        size = tuple(int(hw // ratio) for hw in img.size)
        img = img.resize(size, PIL.Image.ANTIALIAS)

    media = convert(img, formats)

    # do not close a file opened by the user
    # only close if a filename was given
    if not hasattr(file_, "read"):
        img.close()

    return media

async def process_media(media, path):
    data = await media.read()
    mime_type = await utils.get_type(data, path)
    if not mime_type.startswith("image"):
        return media

    # formats to try when converting the picture
    formats = [dict(format="PNG"), dict(format="JPEG", quality=90, optimize=True)]

    return await client.loop.run_in_executor(
        ProcessPoolExecutor(), optimize_media, io.BytesIO(data), (2048, 2048), formats
    )

async def send_tweet_with_media():
    # read the tweet's status
    status = input("status: ")

    path = ""
    while not path and not os.path.exists(path):
        path = input("file to upload:\n")

    # read the most common input formats
    path = urlparse(path).path.strip(" \"'")

    async with aiofiles.open(path, "rb") as media:
        # optimize pictures if PIL is available
        if PIL:
            media = await process_media(media, path)

        uploaded = await client.upload_media(media, chunk_size=2**18, chunked=True)
        media_id = uploaded.media_id
        await client.api.statuses.update.post(status=status, media_ids=media_id)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(send_tweet_with_media())


text:
/******************************************************************************/
/*                                                                            */
/*    ODYSSEUS/EduCOSMOS Educational-Purpose Object Storage System            */
/*                                                                            */
/*    Developed by Professor Kyu-Young Whang et al.                           */
/*                                                                            */
/*    Database and Multimedia Laboratory                                      */
/*                                                                            */
/*    Computer Science Department and                                         */
/*    Advanced Information Technology Research Center (AITrc)                 */
/*    Korea Advanced Institute of Science and Technology (KAIST)              */
/*                                                                            */
/*    e-mail: kywhang@cs.kaist.ac.kr                                          */
/*    phone: +82-42-350-7722                                                  */
/*    fax: +82-42-350-8380                                                    */
/*                                                                            */
/*    Copyright (c) 1995-2013 by Kyu-Young Whang                              */
/*                                                                            */
/*    All rights reserved. No part of this software may be reproduced,        */
/*    stored in a retrieval system, or transmitted, in any form or by any     */
/*    means, electronic, mechanical, photocopying, recording, or otherwise,   */
/*    without prior written permission of the copyright owner.                */
/*                                                                            */
/******************************************************************************/
/*
 * Module: EduBtM_TestModule.c
 *
 * Description :
 *  Main routine of EduBtM Test Module
 *
 */

#include <stdlib.h>
#include "EduBtM_common.h"
#include "EduBtM_Internal.h"
#include "EduBtM_TestModule.h"

Four main()
{

	Four	e;									/* for errors */
	Four 	i;									/* loop index */
	Four	handle;								/* system handle */
	Four	numDevices = 0;						/* # of devices which consists formated volume */
	char 	*devNames[MAX_DEVICES_IN_VOLUME];	/* device name */
	char 	*title;								/* volume title */
	Four 	volId;								/* volume identifier */
	Two 	extSize;							/* size of an extent */
	Four 	numPagesInDevices[MAX_DEVICES_IN_VOLUME];/* # of pages in the each devices */
	Four 	segmentSize;						/* size of a segment */
	XactID 	xactId;								/* transaction identifier */

	/*
	 *   Initialize the storage system
	 */
	/* Initialize miniCOSMOS */
	e = LRDS_Init();
	if (e < eNOERROR){
		printf("LRDS_Init failed!!!\n");
		exit(1);
	}

	/* Allocate handle */
	e = LRDS_AllocHandle(&handle);
	if (e < eNOERROR) {
		printf("LRDS_AllocHandle failed!!!\n");
		LRDS_Final();
		exit(1);
	}

	/* Initialize the variable for LRDS_FormatDataVolume */
	numDevices = 1;
	devNames[0] = "testsolution.vol";
	title = "test";
	volId = 1000;
	extSize = 16;
	numPagesInDevices[0] = 5000;
	segmentSize = 16;

	/*
	 *  Format volume
	 */
    e = LRDS_FormatDataVolume(numDevices, devNames, title, volId, extSize, numPagesInDevices, segmentSize);
	if (e < eNOERROR) {
		printf("LRDS_FormatDataVolume failed!!!\n");
		LRDS_FreeHandle(handle);
		LRDS_Final();
		exit(1);
	}

	/*  Mount volume */
	e = LRDS_Mount(numDevices, devNames, &volId);
	if (e < eNOERROR){
		printf("LRDS_Mount failed!!!\n");
		LRDS_FreeHandle(handle);
		LRDS_Final();
		exit(1);
	}

	/* Begin Transaction */
	e = LRDS_BeginTransaction(&xactId, X_RR_RR);
	if (e < eNOERROR){
		LRDS_Dismount(volId);
		LRDS_FreeHandle(handle);
		LRDS_Final();
		exit(1);
	}

	/* Test miniBtM */
	e = EduBtM_Test(volId, handle);
	if (e < eNOERROR){
		printf("EduBtM_Test failed!!!\n%d\n", e);
		LRDS_AbortTransaction(&xactId);
		LRDS_Dismount(volId);
		LRDS_FreeHandle(handle);
		LRDS_Final();
		exit(1);
	}

	/* Commit Transaction */
	e = LRDS_CommitTransaction(&xactId);
	if (e < eNOERROR){
		printf("LRDS_CommitTransaction failed!!!\n");
		LRDS_Dismount(volId);
		LRDS_FreeHandle(handle);
		LRDS_Final();
		exit(1);
	}

	/* Dismount volume */
	e= LRDS_Dismount(volId);
	if (e < eNOERROR){
		printf("LRDS_Dismount failed!!!\n");
		LRDS_FreeHandle(handle);
		LRDS_Final();
		exit(1);
	}

	/* Free Handle */
	e = LRDS_FreeHandle(handle);
	if (e < eNOERROR) {
		printf("LRDS_FreeHandle failed!!!\n");
		LRDS_Final();
		exit(1);
	}

	/* Finalize miniCOSMOS */
	e = LRDS_Final();
	if (e < eNOERROR) {
		printf("LRDS_Final failed!!!\n");
		exit(1);
	}

	return 0;
}


text:
package org.springframework.scripting.support;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import junit.framework.TestCase;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;

import static org.mockito.BDDMockito.*;

/**
 * @author Rick Evans
 * @author Juergen Hoeller
 */
public class ResourceScriptSourceTests extends TestCase {

	public void testDoesNotPropagateFatalExceptionOnResourceThatCannotBeResolvedToAFile() throws Exception {
		Resource resource = mock(Resource.class);
		given(resource.lastModified()).willThrow(new IOException());

		ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
		long lastModified = scriptSource.retrieveLastModifiedTime();
		assertEquals(0, lastModified);
	}

	public void testBeginsInModifiedState() throws Exception {
		Resource resource = mock(Resource.class);
		ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
		assertTrue(scriptSource.isModified());
	}

	public void testLastModifiedWorksWithResourceThatDoesNotSupportFileBasedReading() throws Exception {
		Resource resource = mock(Resource.class);
		// underlying File is asked for so that the last modified time can be checked...
		// And then mock the file changing; i.e. the File says it has been modified
		given(resource.lastModified()).willReturn(100L, 100L, 200L);
		// does not support File-based reading; delegates to InputStream-style reading...
		//resource.getFile();
		//mock.setThrowable(new FileNotFoundException());
		given(resource.getInputStream()).willReturn(new ByteArrayInputStream(new byte[0]));

		ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
		assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified());
		scriptSource.getScriptAsString();
		assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified());
		// Must now report back as having been modified
		assertTrue("ResourceScriptSource must report back as being modified if the underlying File resource is reporting a changed lastModified time.", scriptSource.isModified());
	}

	public void testLastModifiedWorksWithResourceThatDoesNotSupportFileBasedAccessAtAll() throws Exception {
		Resource resource = new ByteArrayResource(new byte[0]);
		ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
		assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified());
		scriptSource.getScriptAsString();
		assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified());
		// Must now continue to report back as not having been modified 'cos the Resource does not support access as a File (and so the lastModified date cannot be determined).
		assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified());
	}

}


text:
require "test_helper"

# Single integration test.
class AbbrevSearchTest < ActionDispatch::IntegrationTest
  # Make the Capybara DSL available in all integration tests
  include Capybara::DSL

  test "it" do
    Capybara.default_driver = :selenium
    visit_home_page
    standard_page_assertions
    select "Author", from: "query-on"
    select "with abbrev", from: "query-field"
    fill_in "search-field", with: "haeck"
    click_button "Search"
    big_sleep
    search_result_must_include_content("Haeckel")
  end
end


text:
#include "pch.h"
#include "MainPage.xaml.h"

using namespace PrivateFonts;

using namespace Concurrency;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

MainPage::MainPage()
{
    StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
    task<StorageFolder^> getFolderTask = create_task(localFolder->GetFolderAsync("Fonts"));
    getFolderTask.then([this] (task<StorageFolder^> thisTask)
    {
        bool folderExists = false;

        try
        {
            StorageFolder^ fontsFolder = thisTask.get();
            folderExists = true;
        }
        catch (Exception^)
        {
        }

        if (folderExists)
        {
            InitializeComponent();
        }
        else
        {
            StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
            task<StorageFolder^> createFolderTask = create_task(localFolder->CreateFolderAsync("Fonts"));
            createFolderTask.then([this](StorageFolder^ fontsFolder)
            {
                std::array<task<void>, 8> tasks =
                {
                    create_task(TransferFontFile(fontsFolder, "Kooten.ttf")),
                    create_task(TransferFontFile(fontsFolder, "Linds.ttf")),
                    create_task(TransferFontFile(fontsFolder, "Miramo.ttf")),
                    create_task(TransferFontFile(fontsFolder, "Miramob.ttf")),
                    create_task(TransferFontFile(fontsFolder, "Peric.ttf")),
                    create_task(TransferFontFile(fontsFolder, "Pericl.ttf")),
                    create_task(TransferFontFile(fontsFolder, "Pesca.ttf")),
                    create_task(TransferFontFile(fontsFolder, "Pescab.ttf"))
                };
                when_all(begin(tasks), end(tasks)).then([this] ()
                {
                    InitializeComponent();
                });
            });
        }
    });
}

task<void> MainPage::TransferFontFile(StorageFolder^ fontsFolder, String^ filename)
{
    // Copy from application content to IBuffer
    String^ uri = "ms-appx:///Fonts/" + filename;
    task<IBuffer^> readBufferTask = create_task(PathIO::ReadBufferAsync(uri));
    return readBufferTask.then([fontsFolder, filename] (IBuffer^ buffer)
    {
        // Copy from IBuffer to local storage
        task<StorageFile^> createFileTask = create_task(fontsFolder->CreateFileAsync(filename));
        return createFileTask.then([buffer] (StorageFile^ fontFile)
        {
            task<void> writeBufferTask = create_task(FileIO::WriteBufferAsync(fontFile, buffer));
            return writeBufferTask.then([] () { });
        });
    });
}


text:
"""
28. Many-to-many relationships between the same two tables

In this example, a ``Person`` can have many friends, who are also ``Person``
objects. Friendship is a symmetrical relationship - if I am your friend, you
are my friend. Here, ``friends`` is an example of a symmetrical
``ManyToManyField``.

A ``Person`` can also have many idols - but while I may idolize you, you may
not think the same of me. Here, ``idols`` is an example of a non-symmetrical
``ManyToManyField``. Only recursive ``ManyToManyField`` fields may be
non-symmetrical, and they are symmetrical by default.

This test validates that the many-to-many table is created using a mangled name
if there is a name clash, and tests that symmetry is preserved where
appropriate.
"""

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=20)
    friends = models.ManyToManyField('self')
    idols = models.ManyToManyField('self', symmetrical=False, related_name='stalkers')

    def __unicode__(self):
        return self.name


text:
/*
 * Legal Entity Management API
 *
 * The version of the OpenAPI document: 2
 * Contact: developer-experience@adyen.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.adyen.model.legalEntityManagement;

import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.adyen.model.legalEntityManagement.JSON;

/**
 * Attachment
 */

public class Attachment {
  public static final String SERIALIZED_NAME_CONTENT = "content";
  @SerializedName(SERIALIZED_NAME_CONTENT)
  private byte[] content;

  public static final String SERIALIZED_NAME_CONTENT_TYPE = "contentType";
  @SerializedName(SERIALIZED_NAME_CONTENT_TYPE)
  private String contentType;

  public static final String SERIALIZED_NAME_FILENAME = "filename";
  @SerializedName(SERIALIZED_NAME_FILENAME)
  private String filename;

  public static final String SERIALIZED_NAME_PAGE_NAME = "pageName";
  @SerializedName(SERIALIZED_NAME_PAGE_NAME)
  private String pageName;

  public static final String SERIALIZED_NAME_PAGE_TYPE = "pageType";
  @SerializedName(SERIALIZED_NAME_PAGE_TYPE)
  private String pageType;

  public Attachment() {
  }

  public Attachment content(byte[] content) {

    this.content = content;
    return this;
  }

   /**
   * The document in Base64-encoded string format.
   * @return content
  **/
  @javax.annotation.Nonnull
  @ApiModelProperty(required = true, value = "The document in Base64-encoded string format.")

  public byte[] getContent() {
    return content;
  }

  public void setContent(byte[] content) {
    this.content = content;
  }

  public Attachment contentType(String contentType) {

    this.contentType = contentType;
    return this;
  }

   /**
   * The file format.   Possible values: **application/pdf**, **image/jpg**, **image/jpeg**, **image/png**.
   * @return contentType
   * @deprecated
  **/
  @Deprecated
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The file format.   Possible values: **application/pdf**, **image/jpg**, **image/jpeg**, **image/png**. ")

  public String getContentType() {
    return contentType;
  }

  public void setContentType(String contentType) {
    this.contentType = contentType;
  }

  public Attachment filename(String filename) {

    this.filename = filename;
    return this;
  }

   /**
   * The name of the file including the file extension.
   * @return filename
   * @deprecated
  **/
  @Deprecated
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The name of the file including the file extension.")

  public String getFilename() {
    return filename;
  }

  public void setFilename(String filename) {
    this.filename = filename;
  }

  public Attachment pageName(String pageName) {

    this.pageName = pageName;
    return this;
  }

   /**
   * The name of the file including the file extension.
   * @return pageName
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The name of the file including the file extension.")

  public String getPageName() {
    return pageName;
  }

  public void setPageName(String pageName) {
    this.pageName = pageName;
  }

  public Attachment pageType(String pageType) {

    this.pageType = pageType;
    return this;
  }

   /**
   * Specifies which side of the ID card is uploaded.  * When `type` is **driversLicense**, set this to **front** or **back**.  * When omitted, we infer the page number based on the order of attachments.
   * @return pageType
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "Specifies which side of the ID card is uploaded.  * When `type` is **driversLicense**, set this to **front** or **back**.  * When omitted, we infer the page number based on the order of attachments.")

  public String getPageType() {
    return pageType;
  }

  public void setPageType(String pageType) {
    this.pageType = pageType;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Attachment attachment = (Attachment) o;
    return Arrays.equals(this.content, attachment.content) &&
        Objects.equals(this.contentType, attachment.contentType) &&
        Objects.equals(this.filename, attachment.filename) &&
        Objects.equals(this.pageName, attachment.pageName) &&
        Objects.equals(this.pageType, attachment.pageType);
  }

  @Override
  public int hashCode() {
    return Objects.hash(Arrays.hashCode(content), contentType, filename, pageName, pageType);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class Attachment {\n");
    sb.append("    content: ").append(toIndentedString(content)).append("\n");
    sb.append("    contentType: ").append(toIndentedString(contentType)).append("\n");
    sb.append("    filename: ").append(toIndentedString(filename)).append("\n");
    sb.append("    pageName: ").append(toIndentedString(pageName)).append("\n");
    sb.append("    pageType: ").append(toIndentedString(pageType)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

  public static HashSet<String> openapiFields;
  public static HashSet<String> openapiRequiredFields;

  static {
    // a set of all properties/fields (JSON key names)
    openapiFields = new HashSet<String>();
    openapiFields.add("content");
    openapiFields.add("contentType");
    openapiFields.add("filename");
    openapiFields.add("pageName");
    openapiFields.add("pageType");

    // a set of required properties/fields (JSON key names)
    openapiRequiredFields = new HashSet<String>();
    openapiRequiredFields.add("content");
  }

 /**
  * Validates the JSON Object and throws an exception if issues found
  *
  * @param jsonObj JSON Object
  * @throws IOException if the JSON Object is invalid with respect to Attachment
  */
  public static void validateJsonObject(JsonObject jsonObj) throws IOException {
      if (jsonObj == null) {
        if (Attachment.openapiRequiredFields.isEmpty()) {
          return;
        } else { // has required fields
          throw new IllegalArgumentException(String.format("The required field(s) %s in Attachment is not found in the empty JSON string", Attachment.openapiRequiredFields.toString()));
        }
      }

      Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
      // check to see if the JSON string contains additional fields
      for (Entry<String, JsonElement> entry : entries) {
        if (!Attachment.openapiFields.contains(entry.getKey())) {
          throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Attachment` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
        }
      }

      // check to make sure all required properties/fields are present in the JSON string
      for (String requiredField : Attachment.openapiRequiredFields) {
        if (jsonObj.get(requiredField) == null) {
          throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
        }
      }
      // validate the optional field contentType
      if (jsonObj.get("contentType") != null && !jsonObj.get("contentType").isJsonPrimitive()) {
        throw new IllegalArgumentException(String.format("Expected the field `contentType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("contentType").toString()));
      }
      // validate the optional field filename
      if (jsonObj.get("filename") != null && !jsonObj.get("filename").isJsonPrimitive()) {
        throw new IllegalArgumentException(String.format("Expected the field `filename` to be a primitive type in the JSON string but got `%s`", jsonObj.get("filename").toString()));
      }
      // validate the optional field pageName
      if (jsonObj.get("pageName") != null && !jsonObj.get("pageName").isJsonPrimitive()) {
        throw new IllegalArgumentException(String.format("Expected the field `pageName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("pageName").toString()));
      }
      // validate the optional field pageType
      if (jsonObj.get("pageType") != null && !jsonObj.get("pageType").isJsonPrimitive()) {
        throw new IllegalArgumentException(String.format("Expected the field `pageType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("pageType").toString()));
      }
  }

  public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
    @SuppressWarnings("unchecked")
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
       if (!Attachment.class.isAssignableFrom(type.getRawType())) {
         return null; // this class only serializes 'Attachment' and its subtypes
       }
       final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
       final TypeAdapter<Attachment> thisAdapter
                        = gson.getDelegateAdapter(this, TypeToken.get(Attachment.class));

       return (TypeAdapter<T>) new TypeAdapter<Attachment>() {
           @Override
           public void write(JsonWriter out, Attachment value) throws IOException {
             JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
             elementAdapter.write(out, obj);
           }

           @Override
           public Attachment read(JsonReader in) throws IOException {
             JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
             validateJsonObject(jsonObj);
             return thisAdapter.fromJsonTree(jsonObj);
           }

       }.nullSafe();
    }
  }

 /**
  * Create an instance of Attachment given an JSON string
  *
  * @param jsonString JSON string
  * @return An instance of Attachment
  * @throws IOException if the JSON string is invalid with respect to Attachment
  */
  public static Attachment fromJson(String jsonString) throws IOException {
    return JSON.getGson().fromJson(jsonString, Attachment.class);
  }

 /**
  * Convert an instance of Attachment to an JSON string
  *
  * @return JSON string
  */
  public String toJson() {
    return JSON.getGson().toJson(this);
  }
}


text:
package org.apache.storm.benchmark.lib.reducer;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;

import java.util.Set;

public class SetReducer<T> implements Reducer<Set<T>> {

    private static final long serialVersionUID = -5236751818829417995L;

    @Override
    public Set<T> reduce(Set<T> v1, Set<T> v2) {
        return Sets.union(v1, v2);
    }

    @Override
    public Set<T> zero() {
        return ImmutableSet.of();
    }

    @Override
    public boolean isZero(Set<T> ts) {
        return ts.isEmpty();
    }
}


text: A robot framework debugger written in python


text:
module Slim
  # Handle logic less mode
  # This filter can be activated with the option "logic_less"
  # @api private
  class LogicLess < Filter
    # Default dictionary access order, change it with the option :dictionary_access
    DEFAULT_ACCESS_ORDER = [:symbol, :string, :method, :instance_variable].freeze

    define_options :logic_less => true,
                   :dictionary => 'self',
                   :dictionary_access => DEFAULT_ACCESS_ORDER

    def initialize(opts = {})
      super
      access = [options[:dictionary_access]].flatten.compact
      access.each do |type|
        raise ArgumentError, "Invalid dictionary access #{type.inspect}" unless DEFAULT_ACCESS_ORDER.include?(type)
      end
      raise ArgumentError, 'Option dictionary access is missing' if access.empty?
      @access = access.inspect
    end

    def call(exp)
      if options[:logic_less]
        @context = unique_name
        [:multi,
         [:code, "#{@context} = ::Slim::LogicLess::Context.new(#{options[:dictionary]}, #{@access})"],
         super]
      else
        exp
      end
    end

    # Interpret control blocks as sections or inverted sections
    def on_slim_control(name, content)
      method =
        if name =~ /\A!\s*(.*)/
          name = $1
          'inverted_section'
        else
          'section'
        end
      [:block, "#{@context}.#{method}(#{name.to_sym.inspect}) do", compile(content)]
    end

    def on_slim_output(escape, name, content)
      [:slim, :output, escape, empty_exp?(content) ? access(name) :
       "#{@context}.lambda(#{name.to_sym.inspect}) do", compile(content)]
    end

    def on_slim_attrvalue(escape, value)
      [:slim, :attrvalue, escape, access(value)]
    end

    def on_slim_splat(code)
      [:slim, :splat, access(code)]
    end

    def on_dynamic(code)
      raise Temple::FilterError, 'Embedded code is forbidden in logic less mode'
    end

    def on_code(code)
      raise Temple::FilterError, 'Embedded code is forbidden in logic less mode'
    end

    private

    def access(name)
      case name
      when 'yield'
        'yield'
      when 'self'
        "#{@context}.to_s"
      else
        "#{@context}[#{name.to_sym.inspect}]"
      end
    end
  end
end


text:
class AdditionalColumnsTestSchedule < ActiveRecord::Migration[5.1]
  def change
    add_column :test_schedules, :cancel, :boolean, :after => :complete
    add_column :test_schedules, :start_time, :datetime, :after => :cancel
    add_column :test_schedules, :end_time, :datetime, :after => :start_time
  end
end


text:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../tools'))

import files
import arrays

def main(argv):
    lines = files.read_lines(argv[0])

    text  = lines[0]
    k     = int(lines[1])
    psa   = arrays.partial_suffix_array(text, k)

    print '\n'.join('%s,%s' % v for v in psa)

if __name__ == "__main__":
    main(sys.argv[1:])


text:
package org.opencds.cqf.cql.engine.elm.execution;

import org.opencds.cqf.cql.engine.exception.InvalidOperatorArgument;
import org.opencds.cqf.cql.engine.execution.Context;
import org.opencds.cqf.cql.engine.runtime.Interval;

/*
*** NOTES FOR INTERVAL ***
properly included in(left Interval<T>, right Interval<T>) Boolean

The properly included in operator for intervals returns true if the first interval is completely included in the second and
  the first interval is strictly smaller than the second.
  More precisely, if the starting point of the first interval is greater than or equal to the starting point of the second interval,
    and the ending point of the first interval is less than or equal to the ending point of the second interval,
      and they are not the same interval.
This operator uses the semantics described in the Start and End operators to determine interval boundaries.
If either argument is null, the result is null.
Note that during is a synonym for included in.

*** NOTES FOR LIST ***
properly included in(left List<T>, right list<T>) Boolean

The properly included in operator for lists returns true if every element of the first list is in the second list and the
    first list is strictly smaller than the second list.
This operator uses the notion of equivalence to determine whether or not two elements are the same.
If the left argument is null, the result is true if the right argument is not empty. Otherwise, if the right argument is null, the result is false.
Note that the order of elements does not matter for the purposes of determining inclusion.
*/

public class ProperIncludedInEvaluator extends org.cqframework.cql.elm.execution.ProperIncludedIn {

    public static Object properlyIncludedIn(Object left, Object right, String precision, Context context) {
        if (left == null && right == null) {
            return null;
        }

        try {
            if (left == null) {
                return right instanceof Interval
                        ? ProperIncludesEvaluator.intervalProperlyIncludes((Interval) right, null, precision, context)
                        : ProperIncludesEvaluator.listProperlyIncludes((Iterable<?>) right, null, context);
            }

            if (right == null) {
                return left instanceof Interval
                        ? ProperIncludesEvaluator.intervalProperlyIncludes(null, (Interval) left, precision, context)
                        : ProperIncludesEvaluator.listProperlyIncludes(null, (Iterable<?>) left, context);
            }

            return ProperIncludesEvaluator.properlyIncludes(right, left, precision,context);
        }
        catch (InvalidOperatorArgument e) {
            throw new InvalidOperatorArgument(
                    "ProperIncludedIn(Interval<T>, Interval<T>) or ProperIncludedIn(List<T>, List<T>)",
                    String.format("ProperlyIncludedIn(%s, %s)", left.getClass().getName(), right.getClass().getName())
            );
        }
    }

    @Override
    protected Object internalEvaluate(Context context) {
        Object left = getOperand().get(0).evaluate(context);
        Object right = getOperand().get(1).evaluate(context);
        String precision = getPrecision() != null ? getPrecision().value() : null;

        return properlyIncludedIn(left, right, precision, context);
    }
}


text:
    <md-button flex="80" ng-click="$ctrl.operator.addOption($ctrl.option)"
            class="md-raised md-primary"
            style="min-height: 3vh; max-height: 3vh; line-height: 0; font-size: 0.6em;">
        +{{$ctrl.option.title}}
    </md-button>

                <md-checkbox class="md-primary" flex
                             ng-model="$ctrl.option.showing"
                             ng-click="$ctrl.operator.toggleStock($ctrl.option)">
                    {{$ctrl.option.ticker}}
                </md-checkbox>

                <md-checkbox class="md-primary"
                             ng-model="$ctrl.option.showing"
                            ng-click="$ctrl.operator.toggleOption($ctrl.option)"></md-checkbox>

            <md-input-container style="padding:0; margin:0">
                Metrics
                <md-select ng-model="$ctrl.option.selections.metrics.selected" multiple
                        style="font-size: 0.7em; padding: 0; margin: 0;">
                    <md-optgroup label="Metrics">
                        <md-option ng-value="metric.title"
                                   ng-repeat="metric in $ctrl.option.indicators"
                                   ng-click="$ctrl.operator.toggleMetric($ctrl.option, metric)">
                            {{metric.title}}
                        </md-option>
                    </md-optgroup>
                </md-select>
            </md-input-container>

 1" layout="column" flex style="padding: 0; margin: 0">
            <md-input-container flex style="padding:0; margin:0; min-width: 2vh; width: 2vh; max-width: 2vh">
                Indicators
                <md-select ng-model="$ctrl.option.selections.indicators.selected" single
                           style="font-size: 0.7em; padding: 0; margin: 0;">
                    <md-optgroup label="Indicators">
                        <md-option ng-value="indicator.title"
                                   ng-repeat="indicator in $ctrl.option.indicators"
                                   ng-click="$ctrl.operator.setIndicator($ctrl.option, indicator)">
                            {{indicator.title}}
                        </md-option>
                    </md-optgroup>
                </md-select>
            </md-input-container>

            <md-button class="md-raised md-warn"
                       style="line-height: 0; min-width: 4vh; max-width: 4vh;
                            min-height: 4vh; max-height: 4vh; padding:0; margin: 0"
                       flex="5">
                <md-icon flex class="material-icons"
                         style="font-size:1em; padding: 1px; margin: 1px; margin-left: -3px;">
                    delete
                </md-icon>
            </md-button>

                {{param.val}}

            <md-slider-container flex="50" style="overflow: hidden; margin-top: -2vh;">
                <md-slider style="max-height:1vh; min-height:1vh; height: 1vh;" flex
                           ng-model="param.val"
                           min="{{param.minVal}}"
                           max="{{param.maxVal}}"
                           ng-change="$ctrl.operator.updateOption($ctrl.option)">
                </md-slider>
            </md-slider-container>


text:
#include "jsonsl.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <errno.h>
#include "all-tests.h"

/* "actual" must have at least all the same bits set as "expected" */
static void
check_flags (int actual, int expected)
{
    int i;

    for (i = 0; i < (int)(sizeof actual); i++) {
        if (expected & (1 << i)) {
            if (!(actual & (1 << i))) {
                fprintf(stderr, "bit %d not set in special_flags\n", i);
                abort();
            }
        }
    }
}

static void
special_flags_test_pop_callback (jsonsl_t jsn,
                                 jsonsl_action_t action,
                                 struct jsonsl_state_st *state,
                                 const char *buf)
{
    jsonsl_special_t flags = (jsonsl_special_t) jsn->data;
    if (state->type == JSONSL_T_SPECIAL) {
        check_flags (state->special_flags, flags);
    }
}

int
main (int argc, char **argv)
{
    typedef struct {
       const char *value;
       jsonsl_special_t expected_special_flags;
    } special_flags_test_t;

    special_flags_test_t tests[] = {
       { "1", JSONSL_SPECIALf_UNSIGNED },
       { "1.0", JSONSL_SPECIALf_FLOAT|JSONSL_SPECIALf_UNSIGNED },
       { "0", JSONSL_SPECIALf_UNSIGNED },
       { "0.0", JSONSL_SPECIALf_FLOAT|JSONSL_SPECIALf_UNSIGNED },
       { "-0.0", JSONSL_SPECIALf_FLOAT|JSONSL_SPECIALf_SIGNED },
       { NULL }
    };

    special_flags_test_t *test;
    jsonsl_t jsn;
    char name[512];
    char formatted_json[512];
    int formatted_len;

    for (test = tests; test->value; test++) {
        snprintf (name, sizeof name, "parse \"%s\"", test->value);
        fprintf (stderr, "==== %-40s ====\n", name);
        formatted_len = snprintf (formatted_json,
                                  sizeof formatted_json,
                                  "{\"x\": %s}",
                                  test->value);

        jsn = jsonsl_new(0x2000);
        jsn->data = (void *) test->expected_special_flags;
        jsn->action_callback_POP = special_flags_test_pop_callback;
        jsonsl_enable_all_callbacks (jsn);

        jsonsl_feed (jsn, formatted_json, (size_t) formatted_len);
        jsonsl_destroy (jsn);
    }

    return 0;
}


text:
<?php

namespace App\Ship\Criterias\Eloquent;

use App\Ship\Parents\Criterias\Criteria;
use Illuminate\Support\Facades\DB;
use Prettus\Repository\Contracts\RepositoryInterface as PrettusRepositoryInterface;

/**
 * Class CountCriteria
 *
 * @author  Mahmoud Zalt  <mahmoud@zalt.me>
 */
class CountCriteria extends Criteria
{

    /**
     * @var
     */
    private $field;

    /**
     * ThisFieldCriteria constructor.
     *
     * @param $field
     */
    public function __construct($field)
    {
        $this->field = $field;
    }

    /**
     * @param                                                   $model
     * @param \Prettus\Repository\Contracts\RepositoryInterface $repository
     *
     * @return  mixed
     */
    public function apply($model, PrettusRepositoryInterface $repository)
    {
        return DB::table($model->getModel()->getTable())->select('*', DB::raw('count('.$this->field.') as total_count'))->groupBy($this->field);
    }

}