text:
package org.jfree.chart.block.junit;

import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.jfree.chart.block.AbstractBlock;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.block.EmptyBlock;
import org.jfree.ui.RectangleInsets;

/**
 * Tests for the {@link AbstractBlock} class.
 */
public class AbstractBlockTests extends TestCase {

    /**
     * Returns the tests as a test suite.
     *
     * @return The test suite.
     */
    public static Test suite() {
        return new TestSuite(AbstractBlockTests.class);
    }

    /**
     * Constructs a new set of tests.
     *
     * @param name  the name of the tests.
     */
    public AbstractBlockTests(String name) {
        super(name);
    }

    /**
     * Confirm that the equals() method can distinguish all the required fields.
     */
    public void testEquals() {
        EmptyBlock b1 = new EmptyBlock(1.0, 2.0);
        EmptyBlock b2 = new EmptyBlock(1.0, 2.0);
        assertTrue(b1.equals(b2));
        assertTrue(b2.equals(b2));

        b1.setID("Test");
        assertFalse(b1.equals(b2));
        b2.setID("Test");
        assertTrue(b1.equals(b2));

        b1.setMargin(new RectangleInsets(1.0, 2.0, 3.0, 4.0));
        assertFalse(b1.equals(b2));
        b2.setMargin(new RectangleInsets(1.0, 2.0, 3.0, 4.0));
        assertTrue(b1.equals(b2));

        b1.setFrame(new BlockBorder(Color.red));
        assertFalse(b1.equals(b2));
        b2.setFrame(new BlockBorder(Color.red));
        assertTrue(b1.equals(b2));

        b1.setPadding(new RectangleInsets(2.0, 4.0, 6.0, 8.0));
        assertFalse(b1.equals(b2));
        b2.setPadding(new RectangleInsets(2.0, 4.0, 6.0, 8.0));
        assertTrue(b1.equals(b2));

        b1.setWidth(1.23);
        assertFalse(b1.equals(b2));
        b2.setWidth(1.23);
        assertTrue(b1.equals(b2));

        b1.setHeight(4.56);
        assertFalse(b1.equals(b2));
        b2.setHeight(4.56);
        assertTrue(b1.equals(b2));

        b1.setBounds(new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0));
        assertFalse(b1.equals(b2));
        b2.setBounds(new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0));
        assertTrue(b1.equals(b2));

        b1 = new EmptyBlock(1.1, 2.0);
        assertFalse(b1.equals(b2));
        b2 = new EmptyBlock(1.1, 2.0);
        assertTrue(b1.equals(b2));

        b1 = new EmptyBlock(1.1, 2.2);
        assertFalse(b1.equals(b2));
        b2 = new EmptyBlock(1.1, 2.2);
        assertTrue(b1.equals(b2));
    }

    /**
     * Confirm that cloning works.
     */
    public void testCloning() {
        EmptyBlock b1 = new EmptyBlock(1.0, 2.0);
        Rectangle2D bounds1 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0);
        b1.setBounds(bounds1);
        EmptyBlock b2 = null;

        try {
            b2 = (EmptyBlock) b1.clone();
        }
        catch (CloneNotSupportedException e) {
            fail(e.toString());
        }
        assertTrue(b1 != b2);
        assertTrue(b1.getClass() == b2.getClass());
        assertTrue(b1.equals(b2));

        bounds1.setFrame(2.0, 4.0, 6.0, 8.0);
        assertFalse(b1.equals(b2));
        b2.setBounds(new Rectangle2D.Double(2.0, 4.0, 6.0, 8.0));
        assertTrue(b1.equals(b2));
    }

    /**
     * Serialize an instance, restore it, and check for equality.
     */
    public void testSerialization() {
        EmptyBlock b1 = new EmptyBlock(1.0, 2.0);
        EmptyBlock b2 = null;
        try {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(buffer);
            out.writeObject(b1);
            out.close();

            ObjectInput in = new ObjectInputStream(
                    new ByteArrayInputStream(buffer.toByteArray()));
            b2 = (EmptyBlock) in.readObject();
            in.close();
        }
        catch (Exception e) {
            fail(e.toString());
        }
        assertEquals(b1, b2);
    }

}


text:
class ProposalMailer < ApplicationMailer
  def comment_notification(proposal, comment)
    @proposal = proposal
    @comment = comment

    bcc = @proposal.speakers.map do |speaker|
      speaker.email if speaker.person != @comment.person
    end

    if bcc.any?
      mail_markdown(bcc: bcc,
           from: @proposal.event.contact_email,
          subject: "You've received a comment on your proposal '#{@proposal.title}'")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 *    @file
 *          Provides an implementation of the PlatformManager object
 *          for the PSoC6 platform.
 */

#pragma once

#include <platform/internal/GenericPlatformManagerImpl_FreeRTOS.h>

namespace chip {
namespace DeviceLayer {

/**
 * Concrete implementation of the PlatformManager singleton object for the PSoC6 platform.
 */
class PlatformManagerImpl final : public PlatformManager, public Internal::GenericPlatformManagerImpl_FreeRTOS<PlatformManagerImpl>
{
    // Allow the PlatformManager interface class to delegate method calls to
    // the implementation methods provided by this class.
    friend PlatformManager;

    // Allow the generic implementation base class to call helper methods on
    // this class.
#ifndef DOXYGEN_SHOULD_SKIP_THIS
    friend Internal::GenericPlatformManagerImpl_FreeRTOS<PlatformManagerImpl>;
#endif

public:
    // ===== Platform-specific members that may be accessed directly by the application.

    CHIP_ERROR InitLwIPCoreLock(void);
    System::Clock::Timestamp GetStartTime() { return mStartTime; }

private:
    // ===== Methods that implement the PlatformManager abstract interface.

    CHIP_ERROR _InitChipStack(void);
    void _Shutdown();

    // ===== Members for internal use by the following friends.

    friend PlatformManager & PlatformMgr(void);
    friend PlatformManagerImpl & PlatformMgrImpl(void);

    System::Clock::Timestamp mStartTime = System::Clock::kZero;

    static PlatformManagerImpl sInstance;
};

/**
 * Returns the public interface of the PlatformManager singleton object.
 *
 * Chip applications should use this to access features of the PlatformManager object
 * that are common to all platforms.
 */
inline PlatformManager & PlatformMgr(void)
{
    return PlatformManagerImpl::sInstance;
}

/**
 * Returns the platform-specific implementation of the PlatformManager singleton object.
 *
 * Chip applications can use this to gain access to features of the PlatformManager
 * that are specific to the PSoC6 platform.
 */
inline PlatformManagerImpl & PlatformMgrImpl(void)
{
    return PlatformManagerImpl::sInstance;
}

} // namespace DeviceLayer
} // namespace chip


text:
package org.apache.phoenix.schema;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.expression.LiteralExpression;
import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
import org.apache.phoenix.schema.types.PChar;
import org.apache.phoenix.schema.types.PDataType;
import org.junit.Test;

public class PCharPadTest {

    public void test(String value, PDataType dataType, int length, SortOrder sortOrder, byte[] result) throws SQLException {
        LiteralExpression expr = LiteralExpression.newConstant(value, dataType, sortOrder);
        ImmutableBytesPtr ptr = new ImmutableBytesPtr(expr.getBytes());
        dataType.pad(ptr, length, sortOrder);
        String resultValue = (String) dataType.toObject(ptr, dataType, sortOrder);
        assertTrue(Arrays.equals(result, ptr.get()));
        assertEquals(value, resultValue);
    }

    @Test
    public void testCharPaddingAsc1() throws SQLException {
        PDataType dataType = PChar.INSTANCE;
        String str = "hellow";
        byte[] result = new byte[]{104, 101, 108, 108, 111, 119, 32, 32, 32, 32};
        test(str, dataType, 10, SortOrder.ASC, result);
    }

    @Test
    public void testCharPaddingAsc2() throws SQLException {
        PDataType dataType = PChar.INSTANCE;
        String str = "phoenix";
        byte[] result = new byte[]{112, 104, 111, 101, 110, 105, 120, 32, 32, 32, 32, 32, 32, 32};
        test(str, dataType, 14, SortOrder.ASC, result);
    }

    @Test
    public void testCharPaddingAsc3() throws SQLException {
        PDataType dataType = PChar.INSTANCE;
        String str = "phoenix";
        byte[] result = new byte[]{112, 104, 111, 101, 110, 105, 120};
        test(str, dataType, 7, SortOrder.ASC, result);
    }

    @Test
    public void testCharPaddingAsc4() throws SQLException {
        PDataType dataType = PChar.INSTANCE;
        String str = "hello world";
        byte[] result = new byte[]{104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 32, 32, 32, 32, 32};
        test(str, dataType, 16, SortOrder.ASC, result);
    }

    @Test
    public void testCharPaddingDesc1() throws SQLException {
        PDataType dataType = PChar.INSTANCE;
        String str = "hellow";
        byte[] result = new byte[]{-105, -102, -109, -109, -112, -120, -33, -33, -33, -33};
        test(str, dataType, 10, SortOrder.DESC, result);
    }

    @Test
    public void testCharPaddingDesc2() throws SQLException {
        PDataType dataType = PChar.INSTANCE;
        String str = "phoenix";
        byte[] result = new byte[]{-113, -105, -112, -102, -111, -106, -121, -33, -33, -33, -33, -33, -33, -33, -33};
        test(str, dataType, 15, SortOrder.DESC, result);
    }

    @Test
    public void testCharPaddingDesc3() throws SQLException {
        PDataType dataType = PChar.INSTANCE;
        String str = "phoenix";
        byte[] result = new byte[]{-113, -105, -112, -102, -111, -106, -121};
        test(str, dataType, 7, SortOrder.DESC, result);
    }

    @Test
    public void testCharPaddingDesc4() throws SQLException {
        PDataType dataType = PChar.INSTANCE;
        String str = "hello world";
        byte[] result = new byte[]{-105, -102, -109, -109, -112, -33, -120, -112, -115, -109, -101, -33, -33, -33, -33, -33};
        test(str, dataType, 16, SortOrder.DESC, result);
    }

    @Test
    public void testRelativeByteArrayOrder() throws SQLException {
        String[] inputs = {"foo", "foo!", "fooA", "foo~"};
        PDataType dataType = PChar.INSTANCE;
        Arrays.sort(inputs);
        List<byte[]> ascOrderedInputs = new ArrayList<>(inputs.length);
        SortOrder sortOrder = SortOrder.ASC;
        for (String input : inputs) {
            LiteralExpression expr = LiteralExpression.newConstant(input, dataType, sortOrder);
            ImmutableBytesPtr ptr = new ImmutableBytesPtr(expr.getBytes());
            dataType.pad(ptr, 8, sortOrder);
            ascOrderedInputs.add(ptr.copyBytes());
        }
        Collections.sort(ascOrderedInputs, Bytes.BYTES_COMPARATOR);
        for (int i = 0; i < inputs.length; i++) {
            byte[] bytes = ascOrderedInputs.get(i);
            String resultValue = (String) dataType.toObject(bytes, 0, bytes.length, dataType, sortOrder);
            assertEquals(inputs[i], resultValue);
        }

        List<byte[]> descOrderedInputs = new ArrayList<>(inputs.length);
        sortOrder = SortOrder.DESC;
        for (String input : inputs) {
            LiteralExpression expr = LiteralExpression.newConstant(input, dataType, sortOrder);
            ImmutableBytesPtr ptr = new ImmutableBytesPtr(expr.getBytes());
            dataType.pad(ptr, 8, sortOrder);
            descOrderedInputs.add(ptr.copyBytes());
        }
        Collections.sort(descOrderedInputs, Bytes.BYTES_COMPARATOR);
        for (int i = 0; i < inputs.length; i++) {
            byte[] bytes = descOrderedInputs.get(i);
            String resultValue = (String) dataType.toObject(bytes, 0, bytes.length, dataType, sortOrder);
            assertEquals(inputs[inputs.length - 1 - i], resultValue);
        }
    }
}


text:
var enums = require('streamhub-sdk/enums');
var EventEmitter = require('event-emitter');
var find = require('mout/array/find');
var get = require('mout/object/get');
var inherits = require('inherits');
var util = require('streamhub-sdk/util');

function SortedCollection() {
    EventEmitter.apply(this, arguments);

    /**
     * Container for all content that comes in.
     * @type {Array.<Content>}
     */
    this.contents = [];

    /**
     * Whether the collection is media only.
     * @type {boolean}
     * @private
     */
    this._mediaOnly = false;

    /**
     * Sort order for the contents within this collection.
     * @type {string}
     * @private
     */
    this._order = getSortOrder(enums.SORT_ORDER.CREATED_AT_DESC);
}
inherits(SortedCollection, EventEmitter);

/**
 * Get the sort order value without `-` because this is always sorted in
 * descending order.
 * @param {string} order
 * @return {string}
 */
function getSortOrder(order) {
    return order.match(/-?(.*)/)[1];
}

/**
 * Determines if the content is media only. The trick here is that only the
 * first attachment is being checked. This is because the first attachment is
 * the only one that is displayed on the main view of the apps and it determines
 * how the modal view will look. If it's not a photo or video, the carousel
 * won't show up and it'll look like there is no media.
 * @param {Array.<object>} attachments
 * @return {boolean}
 */
function isMediaOnly(attachments) {
    return attachments.length && ['audio', 'photo', 'video'].indexOf(attachments[0].type) > -1;
}

/**
 * Add the content to the list by createdAt order.
 * @param {Content} content Content to add.
 */
SortedCollection.prototype.add = function (content) {
    if (find(this.contents, {id: content.id})) {
        return;
    }
    if (this._mediaOnly && !isMediaOnly(content.attachments)) {
        return;
    }
    util.binaryInsert({
        array: this.contents,
        prop: 'meta.content.' + this._order,
        value: content
    });
    this.emit('added', content);
};

/**
 * Sets whether the sorted collection is media only or not.
 * @param {boolean} value
 */
SortedCollection.prototype.setMediaOnly = function (value) {
    this._mediaOnly = !!value;
};

/**
 * Update the sort order for the sorted collection. Re-sorts the content and
 * updates the order so that any new content is in the correct order.
 * @param {string} order New order.
 */
SortedCollection.prototype.setSortOrder = function (order) {
    if (!order || getSortOrder(order) === this._order) {
        return;
    }
    this._order = order = getSortOrder(order);
    this.contents.sort(function (a, b) {
        var orderA = get(a, 'meta.content.' + order);
        var orderB = get(b, 'meta.content.' + order);
        return -1 * (orderA - orderB);
    });
};

module.exports = SortedCollection;


text:
package thaumicenergistics.client.render;

import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

/**
 * Implemented by Block/Item/Tile that needs to initialise a custom model
 *
 * @author BrockWS
 */
public interface IThEModel {

    /**
     * Called during {@link net.minecraftforge.client.event.ModelRegistryEvent ModelRegistryEvent}
     */
    @SideOnly(Side.CLIENT)
    void initModel();
}


text:
import { Component, Output, EventEmitter } from '@angular/core';

interface Person {
    fname: string;
    lname: string;
}

@Component({
    selector: 'cl-form',
    templateUrl: 'app/complist/form/form.component.html'
})
export class FormComponent implements Person {
    fname: string;
    lname: string;

    @Output()
    valueChange = new EventEmitter<Person>();

    alertUp(f: string, l: string) {
        this.valueChange.emit({fname: f, lname: l});
    }

}


text:
<!-- Filling out this template is required. -->

### What is the purpose of this pull request?
<!-- EX: Fix X an issue, create X new command, etc. -->

### What changes did you make?
<!-- EX: Fix bug when using X command, rewrote X module to make it better, etc. -->
<!-- Write Here -->

### Check List

- [ ] package.json follows [Semantic Versioning](https://semver.org)
- [ ] Follows [Code Style](https://standardjs.com)


text:
package com.github.edgar615.gateway.metric;

import com.github.edgar615.gateway.core.dispatch.Filter;
import com.github.edgar615.gateway.core.dispatch.FilterFactory;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;

/**
 * Created by Edgar on 2017/11/10.
 *
 * @author Edgar  Date 2017/11/10
 */
public class MetricFilterFactory implements FilterFactory {
    @Override
    public String name() {
        return MetricFilter.class.getSimpleName();
    }

    @Override
    public Filter create(Vertx vertx, JsonObject config) {
        return new MetricFilter(vertx, config);
    }
}


text:
"""REST Utils."""

import typing as t
import abc

from muffin import Request

TCOLLECTION = t.TypeVar('TCOLLECTION')

class Mutate(abc.ABC):
    """Mutate collections."""

    def __init__(self, name: str, *, field=None, **meta):
        """Initialize a name."""
        self.name = name
        self.field = name if field is None else field
        self.meta = meta

    def __str__(self):
        return self.name

    def __repr__(self):
        return f"<{self.__class__.__name__} '{self.name}'>"

    @abc.abstractmethod
    async def apply(self, collection: TCOLLECTION, **options) -> TCOLLECTION:
        """Apply the mutation."""
        raise NotImplementedError

class Mutator(abc.ABC):
    """Mutate collections."""

    MUTATE_CLASS: t.Type[Mutate]

    def __init__(self, handler, params: t.Sequence):
        """Initialize the mutations."""
        from .handler import RESTHandler

        self.handler = t.cast(RESTHandler, handler)
        self.mutations = {}
        for param in params:
            obj, meta = param if isinstance(param, tuple) else (param, {})
            mut = self.convert(obj, **meta)
            if mut:
                self.mutations[mut.name] = mut

    def __iter__(self):
        """Iterate through self filters."""
        return iter(self.mutations)

    def __str__(self) -> str:
        """Describe the filters."""
        return ','.join(self.mutations)

    def __repr__(self):
        return f"<{self.__class__.__name__} '{self}'>"

    def __bool__(self):
        return bool(self.mutations)

    def convert(self, obj, **meta) -> Mutate:
        """Convert params to mutations."""
        if isinstance(obj, self.MUTATE_CLASS):
            return obj

        return self.MUTATE_CLASS(obj, **meta)

    @abc.abstractmethod
    async def apply(self, request: Request, collection: TCOLLECTION, **options) -> TCOLLECTION:
        """Mutate a collection."""
        raise NotImplementedError


text:
layout: blank
title: "Ken's Signature"
---

| Ken Howard | Simplicated Web Designs | 503.512.9323

1230 SW First Avenue, Suite 200

Portland, Oregon 97204-3200

WHAT I DO | PROJECTS | LEARN | NEWSLETTER


text:
/* this header file comes from libowfat, http://www.fefe.de/libowfat/ */
#ifndef FMT_H
#define FMT_H

/* for size_t: */
#include <stddef.h>
/* for uint32_t */
#include <stdint.h>
/* for time_t: */
#include <sys/types.h>
/* for byte_copy */
#include "byte.h"

#ifdef __cplusplus
extern "C" {
#endif

#define FMT_LONG  41 /* enough space to hold -2^127 in decimal, plus \0 */
#define FMT_ULONG 40 /* enough space to hold 2^128 - 1 in decimal, plus \0 */
#define FMT_8LONG 44 /* enough space to hold 2^128 - 1 in octal, plus \0 */
#define FMT_XLONG 33 /* enough space to hold 2^128 - 1 in hexadecimal, plus \0 */
#define FMT_LEN ((char *) 0) /* convenient abbreviation */

/* This file declares routines for formatting strings and numbers in
 * various forms or encodings, either binary or text based.
 *
 * The first argument is always the destination buffer, the second
 * argument is always the value to be formatted/encoded. The return
 * value is always the number of bytes written in the output buffer.
 *
 * If you don't know how large the output will be, call the function
 * first with NULL as destination buffer and use the length it returns
 * to allocate the destination buffer.
 *
 * Note that none of these routines append a 0 terminator.  If you need
 * 0 termination, call the functions like this:

     buf[fmt_ulong(buf,number)]=0;

 */

/* convert signed src integer -23 to ASCII '-','2','3', return number of
 * bytes of value in output format (3 in this example).
 * If dest is not NULL, write result to dest */
size_t fmt_long(char *dest,signed long src);

/* convert unsigned src integer 23 to ASCII '2','3', return number of
 * bytes of value in output format (2 in this example).
 * If dest is not NULL, write result to dest */
size_t fmt_ulong(char *dest,unsigned long src);

/* convert unsigned src integer 0x23 to ASCII '2','3', return number of
 * bytes of value in output format (2 in this example).
 * If dest is not NULL, write result to dest */
size_t fmt_xlong(char *dest,unsigned long src);

/* convert unsigned src integer 023 to ASCII '2','3', return number of
 * bytes of value in output format (2 in this example).
 * If dest is not NULL, write result to dest */
size_t fmt_8long(char *dest,unsigned long src);

/* like fmt_long but for long long */
size_t fmt_longlong(char *dest,signed long long src);

/* like fmt_ulong but for unsigned long long */
size_t fmt_ulonglong(char *dest,unsigned long long src);

/* like fmt_xlong but for unsigned long long */
size_t fmt_xlonglong(char *dest,unsigned long long src);

#define fmt_uint(dest,src) fmt_ulong(dest,src)
#define fmt_int(dest,src) fmt_long(dest,src)
#define fmt_xint(dest,src) fmt_xlong(dest,src)
#define fmt_8int(dest,src) fmt_8long(dest,src)

/* Like fmt_ulong, but prepend '0' while length is smaller than padto.
 * Does not truncate! */
/* fmt_ulong0(buf,23,4) -> '0','0','2','3' return 4 */
/* fmt_ulong0(buf,234,2) -> '2','3','4', return 3 */
size_t fmt_ulong0(char *,unsigned long src,size_t padto);

#define fmt_uint0(buf,src,padto) fmt_ulong0(buf,src,padto)

/* convert src double 1.7 to ASCII '1','.','7', return length.
 * If dest is not NULL, write result to dest */
size_t fmt_double(char *dest, double d,int max,int prec);

/* if src is negative, write '-' and return 1.
 * if src is positive, write '+' and return 1.
 * otherwise return 0 */
size_t fmt_plusminus(char *dest,int src);

/* if src is negative, write '-' and return 1.
 * otherwise return 0. */
size_t fmt_minus(char *dest,int src);

/* copy str to dest until \0 byte, return number of copied bytes. */
/* fmt_str(NULL,str) == strlen(str) */
/* fmt_str(buf,str) == strcpy(buf,str), return strlen(str) */
/* strcat(strcpy(buf,"foo"),"bar") can be written as
 *   i=fmt_str(buf,"foo");
 *   i+=fmt_str(buf+i,"bar");
 *   buf[i]=0;
 * This is more efficient because strcat needs to scan the string to
 * find the end and append.
 */
size_t fmt_str(char *dest,const char *src);

/* copy str to dest until \0 byte or limit bytes copied.
 * return number of copied bytes. */
size_t fmt_strn(char *dest,const char *src,size_t limit);

/* copy n bytes from src to dest, return n */
static inline size_t fmt_copybytes(char* dest,const char* src,size_t n) {
  byte_copy(dest,n,src);
  return n;
}

/* "foo" -> "  foo"
 * write padlen-srclen spaces, if that is >= 0.  Then copy srclen
 * characters from src.  Truncate only if total length is larger than
 * maxlen.  Return number of characters written. */
size_t fmt_pad(char* dest,const char* src,size_t srclen,size_t padlen,size_t maxlen);

/* "foo" -> "foo  "
 * append padlen-srclen spaces after dest, if that is >= 0.  Truncate
 * only if total length is larger than maxlen.  Return number of
 * characters written. */
size_t fmt_fill(char* dest,size_t srclen,size_t padlen,size_t maxlen);

/* 1 -> "1", 4900 -> "4.9k", 2300000 -> "2.3M" */
size_t fmt_human(char* dest,unsigned long long l);

/* 1 -> "1", 4900 -> "4.8k", 2300000 -> "2.2M" */
size_t fmt_humank(char* dest,unsigned long long l);

/* "Sun, 06 Nov 1994 08:49:37 GMT" */
size_t fmt_httpdate(char* dest,time_t t);

#define FMT_UTF8 5
#define FMT_ASN1LENGTH 17 /* enough space to hold 2^128-1 */
#define FMT_ASN1TAG 19 /* enough space to hold 2^128-1 */
/* some variable length encodings for integers */
size_t fmt_utf8(char* dest,uint32_t n);	/* can store 0-0x7fffffff */
size_t fmt_asn1derlength(char* dest,unsigned long long l);	/* 0-0x7f: 1 byte, above that 1+bytes_needed bytes */
size_t fmt_asn1dertag(char* dest,unsigned long long l);	/* 1 byte for each 7 bits; upper bit = more bytes coming */

/* Marshaling helper functions.
 * Escape one character, no matter if it needs escaping or not.
 * The functions will reject characters that cannot be represented but
 * not characters that the standard says should never occur.  The idea
 * is to make these functions useful for creating bad encoding for
 * penetration testing.
 * Depending on the escaping method, the input character (uint32_t, a
 * unicode codepoint) may be limited to 0x7f, 0xff or 0x10ffff. */

/* XML escaping: '&' -> '&', '<' -> '<', 'ö' -> 'ö' */
size_t fmt_escapecharxml(char* dest,uint32_t ch);
/* HTML escaping is the same as XML escaping. */
size_t fmt_escapecharhtml(char* dest,uint32_t ch);

/* JSON escaping: '\' -> '\\', '"' -> '\"', 'ö' -> '\u00f6' */
size_t fmt_escapecharjson(char* dest,uint32_t ch);

/* MIME quoted-printable escaping: 'ö' -> '=f6', characters > 0xff not supported */
size_t fmt_escapecharquotedprintable(char* dest,uint32_t ch);

/* MIME quoted-printable escaping with UTF-8: 'ö' -> '=c3=b6', characters > 0x7fffffff not supported */
size_t fmt_escapecharquotedprintableutf8(char* dest,uint32_t ch);

/* C escaping: '\' -> '\\', newline -> '\n', 0xc2 -> '\302' */
size_t fmt_escapecharc(char* dest,uint32_t ch);

/* internal functions, may be independently useful */
char fmt_tohex(char c);

#define fmt_strm(b,...) fmt_strm_internal(b,__VA_ARGS__,(char*)0)
size_t fmt_strm_internal(char* dest,...);

#ifndef MAX_ALLOCA
#define MAX_ALLOCA 100000
#endif
#define fmt_strm_alloca(a,...) ({ size_t len=fmt_strm((char*)0,a,__VA_ARGS__)+1; char* c=(len<MAX_ALLOCA?alloca(len):0); if (c) c[fmt_strm(c,a,__VA_ARGS__)]=0; c;})

#ifdef __cplusplus
}
#endif

#endif


text:
#pragma once

#include <algorithm>
#include <esp_heap_caps.h>
#include "smooth/core/logging/log.h"

namespace smooth::core::util
{
    template<typename T, size_t Size>
    class DmaFixedBuffer
    {
        public:
            constexpr size_t size()
            {
                return sizeof(T) * Size;
            }

            // Constructor
            DmaFixedBuffer(const uint32_t malloc_cap_type)
            {
                buff = static_cast<T*>(heap_caps_malloc(Size, malloc_cap_type));
            }

            // Destructor
            virtual ~DmaFixedBuffer()
            {
                heap_caps_free(buff);
            }

            /// \return Returns pointer to first element in buffer
            T* data()
            {
                return buff;
            }

            const T& operator[](size_t index) const
            {
                // Prevent going outside buffer
                return buff[std::max(0u, std::min(size() - 1, index))];
            }

            T& operator[](size_t index)
            {
                // Prevent going outside buffer
                return buff[std::max(static_cast<size_t>(0), std::min(size() - 1, index))];
            }

        protected:
            T* buff;
    };
}


text:
require 'data_mapper'
require 'json'
require 'date'
require 'grape'

require_relative '../models/expenses.rb'
require_relative '../api/api.rb'


text:
void three_arguments(int x, int y, int z);

void calls() {
	int three = 3;
	three_arguments(1, 2, three); // GOOD
	three_arguments(1, 2, &three); // BAD
}


text:
#include <linux/module.h>
#include <linux/spi/spi.h>
#include <linux/regmap.h>
#include <sound/soc.h>
#include "cs4271.h"

static int cs4271_spi_probe(struct spi_device *spi)
{
	struct regmap_config config;

	config = cs4271_regmap_config;
	config.reg_bits = 16;
	config.val_bits = 8;
	config.read_flag_mask = 0x21;
	config.write_flag_mask = 0x20;

	return cs4271_probe(&spi->dev, devm_regmap_init_spi(spi, &config));
}

static int cs4271_spi_remove(struct spi_device *spi)
{
	snd_soc_unregister_codec(&spi->dev);
	return 0;
}

static struct spi_driver cs4271_spi_driver = {
	.driver = {
		.name	= "cs4271",
		.owner	= THIS_MODULE,
		.of_match_table = of_match_ptr(cs4271_dt_ids),
	},
	.probe		= cs4271_spi_probe,
	.remove		= cs4271_spi_remove,
};
module_spi_driver(cs4271_spi_driver);

MODULE_DESCRIPTION("ASoC CS4271 SPI Driver");
MODULE_AUTHOR("Alexander Sverdlin <subaparts@yandex.ru>");
MODULE_LICENSE("GPL");


text:
<?php

function loader($class)
{
    $file = $class.'.php';
    if (file_exists($file)) {
        require $file;
    }
}
spl_autoload_register('loader');


text:
__author__ = 'Sergio Sicari'
__email__  = "sergiosicari@gmail.com"

from evernote.api.client import EvernoteClient
import evernote.edam.type.ttypes as Types
import evernote.edam.notestore.NoteStore as NoteStore
import evernote.edam.userstore.UserStore as UserStore

class EverCode:

     def __init__(self, Settings):
          self._settings = Settings
          self._token = self._settings.developer_token

     def setClient(self):
          self._client = EvernoteClient(token=self._token, sandbox=self._settings.sandbox)
          self._userStore = self._client.get_user_store()
          self._user = self._userStore.getUser()
          self._noteStore = self._client.get_note_store()
          self._notebooks = self._noteStore.listNotebooks()
     '''
     def login(self):
          self._client = EvernoteClient(
               consumer_key = self._settings.consumer_key,
               consumer_secret = self._settings.consumer_secret,
               sandbox=self._settings.sandbox
          )
          request_token = self._client.get_request_token('YOUR CALLBACK URL')
          self._client.get_authorize_url(request_token)
          access_token = self._client.get_access_token(
               request_token['oauth_token'],
               request_token['oauth_token_secret'],
               request_token.GET.get('oauth_verifier', '')
          )
          self._token = access_token
     '''

     def makeNote(self, noteTitle, noteBody, parentNotebook=None):

          result = noteBody.replace('class="highlight"', '')

          nBody =  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
          nBody += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
          nBody += "<en-note>%s</en-note>" % result

          ## Create note object
          ourNote = Types.Note()
          ourNote.title = noteTitle
          ourNote.content = nBody

          ## parentNotebook is optional; if omitted, default notebook is used
          if parentNotebook and hasattr(parentNotebook, 'guid'):
               ourNote.notebookGuid = parentNotebook.guid

          ## Attempt to create note in Evernote account
          try:
               note = self._noteStore.createNote(self._token, ourNote)
          except Errors.EDAMUserException, edue:
               ## Something was wrong with the note data
               ## See EDAMErrorCode enumeration for error code explanation
               ## http://dev.evernote.com/documentation/reference/Errors.html#Enum_EDAMErrorCode
               print "EDAMUserException:", edue
               return None
          except Errors.EDAMNotFoundException, ednfe:
               ## Parent Notebook GUID doesn't correspond to an actual notebook
               print "EDAMNotFoundException: Invalid parent notebook GUID"
               return None
               ## Return created note object
          return note


text:
package com.amazonaws.services.supportapp.model;

import javax.annotation.Generated;

/**
 * <p>
 * We can't process your request right now because of a server issue. Try again later.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InternalServerException extends com.amazonaws.services.supportapp.model.AWSSupportAppException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InternalServerException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InternalServerException(String message) {
        super(message);
    }

}


text:
/*jshint node:true */

"use strict";

var _ = require("underscore"),

    // Dump Array or Dataview
    dumpCollection = function (collection, n) {
        var dump = [],
            i = 0,
            l = _.isArray(collection) ? collection.length : collection.byteLength,
            getCollectionValue = _.isArray(collection) ?
                function (i) { return collection[i]; } :
                function (i) { return collection.getUint8(i); };

        if ((n || (n = 3)) >= l / 2) { n = l + 1; }

        while (true) {
            if (i === l) { break; }

            dump.push(getCollectionValue(i++));

            if (i === n) {
                dump.push("...");
                i = l - n;
            }
        }

        return l + ":[" + dump.join(", ") + "]";
    };

module.exports = {

    // Expect actual to be a DataView with given elements. `expected` can be a DataView or Array
    asDataViewToEqual: function (expected) {
        var getExpectedValue = _.isArray(expected) ?
                function (i) { return expected[i]; } :
                function (i) { return expected.getUint8(i);
            },
            getExpectedLength = _.isArray(expected) ?
                function () { return expected.length; } :
                function () { return expected.byteLength;
            },
            buildFailMessage = function (expected, actual, index) {
                return "Expected " + dumpCollection(actual) + " to be a DataView with elements " +
                    dumpCollection(expected) + ". (Expected " + getExpectedValue(index) +
                    " at index " + index + ", got " + actual.getUint8(index) + ")";
            },
            i;

        if (this.actual.byteLength !== getExpectedLength()) {
            this.message = function () {
                return "Expected " + dumpCollection(this.actual) + " to be a DataView of length " +
                    getExpectedLength();
            };
            return false;
        }

        for (i = 0; i < this.actual.byteLength; ++i) {
            if (this.actual.getUint8(i) !== getExpectedValue(i)) {
                this.message = buildFailMessage(expected, this.actual, i);
                return false;
            }
        }

        return true;
    }
};


text:
import unittest

import mock
import pytest
from addons.base.tests.models import (OAuthAddonNodeSettingsTestSuiteMixin,
                                      OAuthAddonUserSettingTestSuiteMixin)
from addons.dropbox.models import NodeSettings
from addons.dropbox.tests import factories

pytestmark = pytest.mark.django_db

class TestDropboxNodeSettings(OAuthAddonNodeSettingsTestSuiteMixin, unittest.TestCase):
    full_name = 'dropbox'
    short_name = 'dropbox'

    ExternalAccountFactory = factories.DropboxAccountFactory
    NodeSettingsClass = NodeSettings
    NodeSettingsFactory = factories.DropboxNodeSettingsFactory
    UserSettingsFactory = factories.DropboxUserSettingsFactory

    def _node_settings_class_kwargs(self, node, user_settings):
        return {
            'user_settings': self.user_settings,
            'folder': '1234567890',
            'owner': self.node
        }

    def test_folder_defaults_to_none(self):
        node_settings = NodeSettings(
            owner=factories.ProjectFactory(),
            user_settings=self.user_settings
        )
        node_settings.save()
        assert node_settings.folder is None

    @mock.patch(
        'addons.dropbox.models.UserSettings.revoke_remote_oauth_access',
        mock.PropertyMock()
    )
    def test_complete_has_auth_not_verified(self):
        super(TestDropboxNodeSettings, self).test_complete_has_auth_not_verified()

class TestDropboxUserSettings(OAuthAddonUserSettingTestSuiteMixin, unittest.TestCase):
    full_name = 'dropbox'
    short_name = 'dropbox'

    ExternalAccountFactory = factories.DropboxAccountFactory


text:
module Pacto
  class Consumer
    class FaradayDriver
      # Sends a Pacto::PactoRequest
      def execute(req)
        conn = Faraday.new(url: req.uri.to_s) do |faraday|
          faraday.response :logger if Pacto.configuration.logger.level == :debug
          faraday.adapter Faraday.default_adapter
        end

        response = conn.send(req.method) do |faraday_request|
          # faraday_request.url = req.uri
          faraday_request.headers = req.headers
          faraday_request.body = req.body
        end

        faraday_to_pacto_response response
      end

      private

      # This belongs in an adapter
      def faraday_to_pacto_response(faraday_response)
        data = {
          status: faraday_response.status,
          headers: faraday_response.headers,
          body: faraday_response.body
        }
        Pacto::PactoResponse.new(data)
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<test-data xmlns="http://pmd.sourceforge.net/rule-tests"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://pmd.sourceforge.net/rule-tests https://pmd.sourceforge.io/rule-tests_1_0_0.xsd">

	<code-fragment id="pojo-not-override-tostring">
		<![CDATA[
	public class FooDO {
		private String tom;

		// BAD, not Override toString()

		private static class NestedDTO {
			private String tom;
			private boolean isBar;

			@Override
			public String tostring() {		// BAD
				return tom;
			}
		}

		private static class InnerClass {
			// OK
		}
	}
		]]>
	</code-fragment>
	<test-code>
		<description>POJO not override toString()</description>
		<expected-problems>2</expected-problems>
		<expected-linenumbers>1,6</expected-linenumbers>
		<code-ref id="pojo-not-override-tostring" />
	</test-code>

	<!-- ====================================================================== -->

	<code-fragment id="pojo-override-tostring">
		<![CDATA[
	public class FooDO {
		private String tom;

		@Override
		public String toString() {
			return tom;
		}

		private static class NestedDTO {
			private String tom;
			private boolean isBar;

			@Override
			public String toString() {
				return super.toString();
			}
		}

		private static class InnerClass {
			// OK
		}
	}
		]]>
	</code-fragment>
	<test-code>
		<description>POJO already override toString()</description>
		<expected-problems>0</expected-problems>
		<code-ref id="pojo-override-tostring" />
	</test-code>

	<!-- ====================================================================== -->

	<code-fragment id="lombok-pojo">
		<![CDATA[
	import lombok.Data;

	@Data
	public class FooDO {
		private String tom;
	}
		]]>
	</code-fragment>
	<test-code>
		<description>lombok generated source not need override toString()</description>
		<expected-problems>0</expected-problems>
		<code-ref id="lombok-pojo" />
	</test-code>

	<!-- ====================================================================== -->

	<code-fragment id="lombok-pojo-2">
		<![CDATA[
	@lombok.Data
	public class FooDO {
		private String tom;
	}
		]]>
	</code-fragment>
	<test-code>
		<description>lombok generated source not need override toString()</description>
		<expected-problems>0</expected-problems>
		<code-ref id="lombok-pojo-2" />
	</test-code>

	<!-- ====================================================================== -->

	<code-fragment id="lombok-pojo-3">
		<![CDATA[
	import lombok.*;
	@Data
	public class FooDO {
		private String tom;
	}
		]]>
	</code-fragment>
	<test-code>
		<description>import lombok.*</description>
		<expected-problems>0</expected-problems>
		<code-ref id="lombok-pojo-3" />
	</test-code>

	<!-- ====================================================================== -->

	<code-fragment id="lombok-pojo-4">
		<![CDATA[
	import lombok.*;
	@ToString(callSuper = true)
	public class FooDO {
		private String tom;
	}
		]]>
	</code-fragment>
	<test-code>
		<description>use lombok.@ToString annotation</description>
		<expected-problems>0</expected-problems>
		<code-ref id="lombok-pojo-4" />
	</test-code>

    <!-- ====================================================================== -->

    <code-fragment id="interface-with-pojo-surfix">
        <![CDATA[
	public interface FooDO {
	}
		]]>
    </code-fragment>
    <test-code>
        <description>interface with POJO surfix</description>
        <expected-problems>0</expected-problems>
        <code-ref id="interface-with-pojo-surfix" />
    </test-code>

</test-data>


text:
require 'bcrypt'

module DealRedemptions
  class User < ActiveRecord::Base
    before_save :encrypt_password
    before_save :log_last_login
    after_save :send_confirmation_email

    attr_accessor :password

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :first_name, :last_name, :email, presence: true
    validates :email, uniqueness: true, format: { with: VALID_EMAIL_REGEX }
    validates :password, length: { minimum: 6 }, presence: true, confirmation: true

    def self.authenticate(email, password)
      user = find_by_email(email)
      if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
        user
      else
        nil
      end
    end

    def encrypt_password
      if password.present?
        self.password_salt = BCrypt::Engine.generate_salt
        self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
      end
    end

    def log_last_login
      self.last_login = Time.now
    end

    def send_confirmation_email
      DealRedemptions::AdminUserMailer.new_confirmation(self).deliver
    end
  end
end


text:
package org.strongback;

import java.util.function.Supplier;

import org.strongback.annotation.ThreadSafe;
import org.strongback.command.Command;
import org.strongback.components.Switch;

/**
 * A class that allows other components to react to the state of switches. For example, the reactor can be used to submit a
 * command whenever a Gamepad's left trigger button is pressed and submit a different command when the same trigger is released:
 *
 *

 *   Gamepad gamepad = ...
 *   reactor.onTriggered(gamepad.getRightTrigger(),()->Strongback.submit(new FireRepeatedlyCommand()));
 *   reactor.onUnTriggered(gamepad.getRightTrigger(),()->Strongback.submit(new StopFireCommand()));
 *

 *

 * The reactor is threadsafe, meaning functions can be registered even while the reactor is forwarding state and state
 * transitions to the already-registered functions.
 *

 * It is not currently possible to remove a function once it has been registered.
 */
@ThreadSafe
public interface SwitchReactor {

    /**
     * Submit a {@link Command} the moment when the specified {@link Switch} is triggered.
     *
     * @param swtch the {@link Switch}
     * @param commandSupplier the supplier of the command to submit; may not be null but may return a null command
     */
    default public void onTriggeredSubmit(Switch swtch, Supplier<Command> commandSupplier) {
        onTriggered(swtch,()->Strongback.submit(commandSupplier.get()));
    }

    /**
     * Submit a {@link Command} the moment when the specified {@link Switch} is untriggered.
     *
     * @param swtch the {@link Switch}
     * @param commandSupplier the supplier of the command to submit; may not be null but may return a null command
     */
    default public void onUntriggeredSubmit(Switch swtch, Supplier<Command> commandSupplier) {
        onUntriggered(swtch,()->Strongback.submit(commandSupplier.get()));
    }

    /**
     * Register a {@link Runnable} function that is to be called the moment when the specified {@link Switch} is triggered.
     *
     * @param swtch the {@link Switch}
     * @param function the function to execute when the switch is triggered
     */
    public void onTriggered(Switch swtch, Runnable function);

    /**
     * Register a {@link Runnable} function that is to be called the moment when the specified {@link Switch} is untriggered.
     *
     * @param swtch the {@link Switch}
     * @param function the function to execute when the switch is untriggered
     */
    public void onUntriggered(Switch swtch, Runnable function);

    /**
     * Register a {@link Runnable} function to be called repeatedly whenever the specified {@link Switch} is in the triggered
     * state.
     *
     * @param swtch the {@link Switch}
     * @param function the function to execute while the switch remains triggered
     */
    public void whileTriggered(Switch swtch, Runnable function);

    /**
     * Register a {@link Runnable} function to be called repeatedly whenever the specified {@link Switch} is not in the
     * triggered state.
     *
     * @param swtch the {@link Switch}
     * @param function the function to execute while the switch remains untriggered
     */
    public void whileUntriggered(Switch swtch, Runnable function);
}


text:
title: XapianIndexer::deleteDocument — Core Library
package: lib
packageTitle: Core Library
layout: default
className: XapianIndexer
type: method
---

# XapianIndexer::deleteDocument

## Synopsis

public function XapianIndexer::deleteDocument($identifier)

## Parameters

      Name
      Direction
      Type
      Description

      $identifier


text:
package com.infosec.gesturelock;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.View;
import android.widget.ImageView;

public class LockSuccessScreen extends Activity {
	private boolean isTaco = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_unlock_success);

	}

	@Override
	public void onBackPressed() {
        NavUtils.navigateUpFromSameTask(this);
        this.finish();

	    super.onBackPressed();
	}
	public void returnToLock(View view) {
		Intent lockIntent = new Intent(this, StartTestActivity.class);
		this.startActivity(lockIntent);

		this.finish();
	}

	public void goHome(View view) {
        NavUtils.navigateUpFromSameTask(this);
        this.finish();
	}

	public void tacocatRelease(View view){
		ImageView lockView = (ImageView) findViewById(R.id.imageDisplayView);
		if(!isTaco){
			lockView.setImageResource(R.drawable.tacocat);
			isTaco = true;
		}else{
			lockView.setImageResource(R.drawable.welldone);
			isTaco = false;
		}
	}
}


text:
set -ex

CURRENT=`pwd`

################################################################################
#
# Install GAP
#
echo -e "\nInstalling latest master GAP into $GAPROOT..."

git clone --depth=2 https://github.com/gap-system/gap.git $GAPROOT

cd $GAPROOT

if [ -f autogen.sh ]; then
  ./autogen.sh
fi

./configure
make -j4

make bootstrap-pkg-full WGET="wget -N --no-check-certificate --tries=5 --waitretry=5 --retry-connrefused"

cd pkg

rm -rf uuid-* crypting-*

# install latest version of uuid
git clone https://github.com/gap-packages/uuid

# install latest version of crypting
git clone https://github.com/gap-packages/crypting

# install latest version of JupyterKernel
git clone https://github.com/gap-packages/JupyterKernel

# install latest version of francy-monoid
git clone https://github.com/gap-packages/FrancyMonoids

# install latest version of subgroup-latice
git clone https://github.com/mcmartins/subgroup-lattice

# build some packages; default is to build 'io' and 'profiling', in order to
# generate coverage results. If you need to build additional packages (or for
# some reason need to build a custom version of io or profiling), please set
# the GAP_PKGS_TO_BUILD environment variable (e.g. in your .travis.yml), or
# directly call BuildPackages.sh from .travis.yml. For an example of the
# former, take a look at the cvec package.
for pkg in ${GAP_PKGS_TO_BUILD-io profiling ZeroMQInterface json crypting}; do
    ../bin/BuildPackages.sh --strict $pkg*
done

cd $CURRENT

################################################################################
#
# Install francy on GAP
#
cp -r . $GAPROOT/pkg/francy

################################################################################
#
# Install francy-js and extensions build tools
#
cd js
npm install
npm run bootstrap
npm run build:production

cd $CURRENT


text:
name              'omnibus'
maintainer        'Chef Software, Inc.'
maintainer_email  'releng@chef.io'
license           'Apache-2.0'
description       'Prepares a machine to be an Omnibus builder.'
version           '6.0.0'

supports 'amazon'
supports 'centos'
supports 'debian'
supports 'fedora'
supports 'freebsd'
supports 'mac_os_x'
supports 'oracle'
supports 'redhat'
supports 'scientific'
supports 'solaris2'
supports 'suse'
supports 'ubuntu'
supports 'windows'

depends 'chef-sugar', '>= 3.2.0'
depends 'chef-ingredient', '>= 0.21.4'
depends 'git'
depends 'homebrew'
depends 'remote_install'
depends 'seven_zip'
depends 'wix'

gem 'pkg-config'

source_url 'https://github.com/chef-cookbooks/omnibus'
issues_url 'https://github.com/chef-cookbooks/omnibus/issues'
chef_version '>= 14'


text:
package com.icegreen.greenmail.standalone;

import com.icegreen.greenmail.configuration.PropertiesBasedGreenMailConfigurationBuilder;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.PropertiesBasedServerSetupBuilder;
import com.icegreen.greenmail.util.ServerSetup;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintStream;
import java.util.Arrays;
import java.util.Properties;

/**
 * Enables GreenMail to run in standalone mode.
 * <p/>
 * Example: java  -Dgreenmail.smtp -Dgreenmail.users=test1:pwd1 -jar greenmail.jar
 *
 * @see PropertiesBasedServerSetupBuilder
 * @see PropertiesBasedGreenMailConfigurationBuilder
 */
public class GreenMailStandaloneRunner {
    private final Logger log = LoggerFactory.getLogger(GreenMailStandaloneRunner.class);

    /**
     * Start and configure GreenMail using given properties.
     *
     * @param properties the properties such as System.getProperties()
     */
    public void doRun(Properties properties) {
        ServerSetup[] serverSetup = new PropertiesBasedServerSetupBuilder().build(properties);

        if (serverSetup.length == 0) {
            printUsage(System.out);

        } else {
            GreenMail greenMail = new GreenMail(serverSetup);
            log.info("Starting GreenMail standalone using " + Arrays.toString(serverSetup));
            greenMail.withConfiguration(new PropertiesBasedGreenMailConfigurationBuilder().build(properties))
                    .start();
        }
    }

    private void printUsage(PrintStream out) {
        // Don't use logger
        out.println("Usage: java OPTIONS -jar greenmail.jar");
        out.println("\nOPTIONS:");
        String[][] options = {
                {"-Dgreenmail.setup.<protocol|all>", "specify mail server to start using default port and bind " +
                        "address 127.0.0.1"},
                {"Note: protocol can be one of smtp,smtps,imap,imaps,pop3 or pop3s"},
                {"-Dgreenmail.setup.test.<protocol|all>", "specify mail server to start using default port plus " +
                        "offset 3000 and bind address 127.0.0.1"},
                {"-Dgreenmail.<protocol|all>.hostname=...",
                        "specify bind address. Requires additional port parameter."},
                {"-Dgreenmail.<protocol|all>.port=...", "specify port. Requires additional hostname parameter."},
                {"-Dgreenmail.users=<logon:pwd@domain>[,...]", "specify mail users, eg foo:pwd@bar.com,foo2:pwd@bar2.com."},
                {"Note: domain must be DNS resolvable!"},
        };
        for (String[] opt : options) {
            if (opt.length == 1) {
                out.println(String.format("%1$44s %2$s", " ", opt[0]));
            } else {
                out.println(String.format("%1$-42s : %2$s", opt)); // NOSONAR
            }
        }
        out.println();
        out.println("Example: ");
        out.println(" java -Dgreenmail.setup.test.all -Dgreenmail.users=foo:pwd@bar.com -jar greenmail.jar");
        out.println("       Starts SMTP,SMTPS,IMAP,IMAPS,POP3,POP3S" +
                "with default ports plus offset 3000 on 127.0.0.1 and user foo@bar.com.");
        out.println("       Note: bar.com domain for user must be DNS resolvable!");
        out.println(" java -Dgreenmail.setup.test.smtp -Dgreenmail.setup.test.imap -jar greenmail.jar");
        out.println("       Starts SMTP on 127.0.01:3025 and IMAP on 127.0.0.1:3143");
        out.println(" java -Dgreenmail.smtp.hostname=0.0.0.0 -Dgreenmail.smtp.port=3025 " +
                "-Dgreenmail.imap.hostname=0.0.0.0 -Dgreenmail.imap.port=3143 -jar greenmail.jar");
        out.println("       Starts SMTP on 0.0.0.0:3025 and IMAP on 0.0.0.0:3143");
    }

    public static void main(String[] args) {
        // Init logging: Try standard log4j configuration mechanism before falling back to
        // provided logging configuration
        String log4jConfig = System.getProperty("log4j.configuration");
        if (null == log4jConfig) {
            DOMConfigurator.configure(GreenMailStandaloneRunner.class.getResource("/log4j.xml"));
        } else {
            if (log4jConfig.toLowerCase().endsWith(".xml")) {
                DOMConfigurator.configure(log4jConfig);
            } else {
                PropertyConfigurator.configure(log4jConfig);
            }
        }

        new GreenMailStandaloneRunner().doRun(System.getProperties());
    }
}


text:
package main

import (
	"github.com/flynn/go-docopt"
	"github.com/theupdateframework/go-tuf"
)

func init() {
	register("timestamp", cmdTimestamp, `
usage: tuf timestamp [--expires=<days>]

Update the timestamp metadata file.

Alternatively, passphrases can be set via environment variables in the
form of TUF_{{ROLE}}_PASSPHRASE

Options:
  --expires=<days>   Set the timestamp metadata file to expire <days> days from now.
`)
}

func cmdTimestamp(args *docopt.Args, repo *tuf.Repo) error {
	if arg := args.String["--expires"]; arg != "" {
		expires, err := parseExpires(arg)
		if err != nil {
			return err
		}
		return repo.TimestampWithExpires(expires)
	}
	return repo.Timestamp()
}


text:
var fs = require("fs");
var mongoose = require("mongoose");

module.exports = function (config) {
  /**
   * Connect to database
   */
  mongoose.connect(config.mongo.url, function (err) {
    if (err) {
      console.error("\x1b[31m", "Could not connect to MongoDB!");
      console.log(err);
    }
  });
  mongoose.connection.on("error", function (err) {
    console.log("Error Mongo:");
    console.log(err);
  });

  mongoose.Promise = global.Promise;

  /**
   * Load the models
   */
  var models_path = config.app.root + "/src/models";
  fs.readdirSync(models_path).forEach(function (file) {
    if (~file.indexOf("js")) {
      require(models_path + "/" + file);
    }
  });
};


text:
package com.example.android.camera2basic;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v13.app.FragmentCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Camera2BasicFragment extends Fragment
        implements View.OnClickListener, FragmentCompat.OnRequestPermissionsResultCallback {

    /**
     * Conversion from screen rotation to JPEG orientation.
     */
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    private static final int REQUEST_CAMERA_PERMISSION = 1;
    private static final String FRAGMENT_DIALOG = "dialog";

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    /**
     * Tag for the {@link Log}.
     */
    private static final String TAG = "Camera2BasicFragment";

    /**
     * Camera state: Showing camera preview.
     */
    private static final int STATE_PREVIEW = 0;

    /**
     * Camera state: Waiting for the focus to be locked.
     */
    private static final int STATE_WAITING_LOCK = 1;

    /**
     * Camera state: Waiting for the exposure to be precapture state.
     */
    private static final int STATE_WAITING_PRECAPTURE = 2;

    /**
     * Camera state: Waiting for the exposure state to be something other than precapture.
     */
    private static final int STATE_WAITING_NON_PRECAPTURE = 3;

    /**
     * Camera state: Picture was taken.
     */
    private static final int STATE_PICTURE_TAKEN = 4;

    /**
     * Max preview width that is guaranteed by Camera2 API
     */
    private static final int MAX_PREVIEW_WIDTH = 1920;

    /**
     * Max preview height that is guaranteed by Camera2 API
     */
    private static final int MAX_PREVIEW_HEIGHT = 1080;

    /**
     * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a
     * {@link TextureView}.
     */
    private final TextureView.SurfaceTextureListener mSurfaceTextureListener
            = new TextureView.SurfaceTextureListener() {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
            openCamera(width, height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
            configureTransform(width, height);
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture texture) {
        }

    };

    /**
     * ID of the current {@link CameraDevice}.
     */
    private String mCameraId;

    /**
     * An {@link AutoFitTextureView} for camera preview.
     */
    private AutoFitTextureView mTextureView;

    /**
     * A {@link CameraCaptureSession } for camera preview.
     */
    private CameraCaptureSession mCaptureSession;

    /**
     * A reference to the opened {@link CameraDevice}.
     */
    private CameraDevice mCameraDevice;

    /**
     * The {@link android.util.Size} of camera preview.
     */
    private Size mPreviewSize;

    /**
     * {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state.
     */
    private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            // This method is called when the camera is opened.  We start camera preview here.
            mCameraOpenCloseLock.release();
            mCameraDevice = cameraDevice;
            createCameraPreviewSession();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int error) {
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
            Activity activity = getActivity();
            if (null != activity) {
                activity.finish();
            }
        }

    };

    /**
     * An additional thread for running tasks that shouldn't block the UI.
     */
    private HandlerThread mBackgroundThread;

    /**
     * A {@link Handler} for running tasks in the background.
     */
    private Handler mBackgroundHandler;

    /**
     * An {@link ImageReader} that handles still image capture.
     */
    private ImageReader mImageReader;

    /**
     * This is the output file for our picture.
     */
    private File mFile;

    /**
     * This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
     * still image is ready to be saved.
     */
    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {
            mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile));
        }

    };

    /**
     * {@link CaptureRequest.Builder} for the camera preview
     */
    private CaptureRequest.Builder mPreviewRequestBuilder;

    /**
     * {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
     */
    private CaptureRequest mPreviewRequest;

    /**
     * The current state of camera state for taking pictures.
     *
     * @see #mCaptureCallback
     */
    private int mState = STATE_PREVIEW;

    /**
     * A {@link Semaphore} to prevent the app from exiting before closing the camera.
     */
    private Semaphore mCameraOpenCloseLock = new Semaphore(1);

    /**
     * Whether the current camera device supports Flash or not.
     */
    private boolean mFlashSupported;

    /**
     * Orientation of the camera sensor
     */
    private int mSensorOrientation;

    /**
     * A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture.
     */
    private CameraCaptureSession.CaptureCallback mCaptureCallback
            = new CameraCaptureSession.CaptureCallback() {

        private void process(CaptureResult result) {
            switch (mState) {
                case STATE_PREVIEW: {
                    // We have nothing to do when the camera preview is working normally.
                    break;
                }
                case STATE_WAITING_LOCK: {
                    Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
                    if (afState == null) {
                        captureStillPicture();
                    } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
                        // CONTROL_AE_STATE can be null on some devices
                        Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                        if (aeState == null ||
                                aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                            mState = STATE_PICTURE_TAKEN;
                            captureStillPicture();
                        } else {
                            runPrecaptureSequence();
                        }
                    }
                    break;
                }
                case STATE_WAITING_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null ||
                            aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
                            aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
                        mState = STATE_WAITING_NON_PRECAPTURE;
                    }
                    break;
                }
                case STATE_WAITING_NON_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
            }
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                                        @NonNull CaptureRequest request,
                                        @NonNull CaptureResult partialResult) {
            process(partialResult);
        }

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                       @NonNull CaptureRequest request,
                                       @NonNull TotalCaptureResult result) {
            process(result);
        }

    };

    /**
     * Shows a {@link Toast} on the UI thread.
     *
     * @param text The message to show
     */
    private void showToast(final String text) {
        final Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
     * is at least as large as the respective texture view size, and that is at most as large as the
     * respective max size, and whose aspect ratio matches with the specified value. If such size
     * doesn't exist, choose the largest one that is at most as large as the respective max size,
     * and whose aspect ratio matches with the specified value.
     *
     * @param choices           The list of sizes that the camera supports for the intended output
     *                          class
     * @param textureViewWidth  The width of the texture view relative to sensor coordinate
     * @param textureViewHeight The height of the texture view relative to sensor coordinate
     * @param maxWidth          The maximum width that can be chosen
     * @param maxHeight         The maximum height that can be chosen
     * @param aspectRatio       The aspect ratio
     * @return The optimal {@code Size}, or an arbitrary one if none were big enough
     */
    private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
            int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {

        // Collect the supported resolutions that are at least as big as the preview Surface
        List<Size> bigEnough = new ArrayList<>();
        // Collect the supported resolutions that are smaller than the preview Surface
        List<Size> notBigEnough = new ArrayList<>();
        int w = aspectRatio.getWidth();
        int h = aspectRatio.getHeight();
        for (Size option : choices) {
            if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
                    option.getHeight() == option.getWidth() * h / w) {
                if (option.getWidth() >= textureViewWidth &&
                    option.getHeight() >= textureViewHeight) {
                    bigEnough.add(option);
                } else {
                    notBigEnough.add(option);
                }
            }
        }

        // Pick the smallest of those big enough. If there is no one big enough, pick the
        // largest of those not big enough.
        if (bigEnough.size() > 0) {
            return Collections.min(bigEnough, new CompareSizesByArea());
        } else if (notBigEnough.size() > 0) {
            return Collections.max(notBigEnough, new CompareSizesByArea());
        } else {
            Log.e(TAG, "Couldn't find any suitable preview size");
            return choices[0];
        }
    }

    public static Camera2BasicFragment newInstance() {
        return new Camera2BasicFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_camera2_basic, container, false);
    }

    @Override
    public void onViewCreated(final View view, Bundle savedInstanceState) {
        mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
    }

    @Override
    public void onResume() {
        super.onResume();
        startBackgroundThread();

        // When the screen is turned off and turned back on, the SurfaceTexture is already
        // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
        // a camera and start preview from here (otherwise, we wait until the surface is ready in
        // the SurfaceTextureListener).
        if (mTextureView.isAvailable()) {
            openCamera(mTextureView.getWidth(), mTextureView.getHeight());
        } else {
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
        }
    }

    @Override
    public void onPause() {
        closeCamera();
        stopBackgroundThread();
        super.onPause();
    }

    private void requestCameraPermission() {
        if (FragmentCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            new ConfirmationDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
        } else {
            FragmentCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                ErrorDialog.newInstance(getString(R.string.request_permission))
                        .show(getChildFragmentManager(), FRAGMENT_DIALOG);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * Sets up member variables related to camera.
     *
     * @param width  The width of available size for camera preview
     * @param height The height of available size for camera preview
     */
    private void setUpCameraOutputs(int width, int height) {
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics
                        = manager.getCameraCharacteristics(cameraId);

                // We don't use a front facing camera in this sample.
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                    continue;
                }

                StreamConfigurationMap map = characteristics.get(
                        CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                if (map == null) {
                    continue;
                }

                // For still image captures, we use the largest available size.
                Size largest = Collections.max(
                        Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                        new CompareSizesByArea());
                mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
                        ImageFormat.JPEG, /*maxImages*/2);
                mImageReader.setOnImageAvailableListener(
                        mOnImageAvailableListener, mBackgroundHandler);

                // Find out if we need to swap dimension to get the preview size relative to sensor
                // coordinate.
                int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
                //noinspection ConstantConditions
                mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                boolean swappedDimensions = false;
                switch (displayRotation) {
                    case Surface.ROTATION_0:
                    case Surface.ROTATION_180:
                        if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                            swappedDimensions = true;
                        }
                        break;
                    case Surface.ROTATION_90:
                    case Surface.ROTATION_270:
                        if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                            swappedDimensions = true;
                        }
                        break;
                    default:
                        Log.e(TAG, "Display rotation is invalid: " + displayRotation);
                }

                Point displaySize = new Point();
                activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
                int rotatedPreviewWidth = width;
                int rotatedPreviewHeight = height;
                int maxPreviewWidth = displaySize.x;
                int maxPreviewHeight = displaySize.y;

                if (swappedDimensions) {
                    rotatedPreviewWidth = height;
                    rotatedPreviewHeight = width;
                    maxPreviewWidth = displaySize.y;
                    maxPreviewHeight = displaySize.x;
                }

                if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                    maxPreviewWidth = MAX_PREVIEW_WIDTH;
                }

                if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                    maxPreviewHeight = MAX_PREVIEW_HEIGHT;
                }

                // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
                // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
                // garbage capture data.
                mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                        rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                        maxPreviewHeight, largest);

                // We fit the aspect ratio of TextureView to the size of preview we picked.
                int orientation = getResources().getConfiguration().orientation;
                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getWidth(), mPreviewSize.getHeight());
                } else {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getHeight(), mPreviewSize.getWidth());
                }

                // Check if the flash is supported.
                Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                mFlashSupported = available == null ? false : available;

                mCameraId = cameraId;
                return;
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            // Currently an NPE is thrown when the Camera2API is used but not supported on the
            // device this code runs.
            ErrorDialog.newInstance(getString(R.string.camera_error))
                    .show(getChildFragmentManager(), FRAGMENT_DIALOG);
        }
    }

    /**
     * Opens the camera specified by {@link Camera2BasicFragment#mCameraId}.
     */
    private void openCamera(int width, int height) {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestCameraPermission();
            return;
        }
        setUpCameraOutputs(width, height);
        configureTransform(width, height);
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening.");
            }
            manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
        }
    }

    /**
     * Closes the current {@link CameraDevice}.
     */
    private void closeCamera() {
        try {
            mCameraOpenCloseLock.acquire();
            if (null != mCaptureSession) {
                mCaptureSession.close();
                mCaptureSession = null;
            }
            if (null != mCameraDevice) {
                mCameraDevice.close();
                mCameraDevice = null;
            }
            if (null != mImageReader) {
                mImageReader.close();
                mImageReader = null;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
        } finally {
            mCameraOpenCloseLock.release();
        }
    }

    /**
     * Starts a background thread and its {@link Handler}.
     */
    private void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }

    /**
     * Stops the background thread and its {@link Handler}.
     */
    private void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * Creates a new {@link CameraCaptureSession} for camera preview.
     */
    private void createCameraPreviewSession() {
        try {
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;

            // We configure the size of default buffer to be the size of camera preview we want.
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

            // This is the output Surface we need to start preview.
            Surface surface = new Surface(texture);

            // We set up a CaptureRequest.Builder with the output Surface.
            mPreviewRequestBuilder
                    = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewRequestBuilder.addTarget(surface);

            // Here, we create a CameraCaptureSession for camera preview.
            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            // The camera is already closed
                            if (null == mCameraDevice) {
                                return;
                            }

                            // When the session is ready, we start displaying the preview.
                            mCaptureSession = cameraCaptureSession;
                            try {
                                // Auto focus should be continuous for camera preview.
                                mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                                // Flash is automatically enabled when necessary.
                                setAutoFlash(mPreviewRequestBuilder);

                                // Finally, we start displaying the camera preview.
                                mPreviewRequest = mPreviewRequestBuilder.build();
                                mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                        mCaptureCallback, mBackgroundHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(
                                @NonNull CameraCaptureSession cameraCaptureSession) {
                            showToast("Failed");
                        }
                    }, null
            );
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
     * This method should be called after the camera preview size is determined in
     * setUpCameraOutputs and also the size of `mTextureView` is fixed.
     *
     * @param viewWidth  The width of `mTextureView`
     * @param viewHeight The height of `mTextureView`
     */
    private void configureTransform(int viewWidth, int viewHeight) {
        Activity activity = getActivity();
        if (null == mTextureView || null == mPreviewSize || null == activity) {
            return;
        }
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            matrix.postRotate(180, centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }

    /**
     * Initiate a still image capture.
     */
    private void takePicture() {
        lockFocus();
    }

    /**
     * Lock the focus as the first step for a still image capture.
     */
    private void lockFocus() {
        try {
            // This is how to tell the camera to lock focus.
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_START);
            // Tell #mCaptureCallback to wait for the lock.
            mState = STATE_WAITING_LOCK;
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * Run the precapture sequence for capturing a still image. This method should be called when
     * we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
     */
    private void runPrecaptureSequence() {
        try {
            // This is how to tell the camera to trigger.
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
                    CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
            // Tell #mCaptureCallback to wait for the precapture sequence to be set.
            mState = STATE_WAITING_PRECAPTURE;
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * Capture a still picture. This method should be called when we get a response in
     * {@link #mCaptureCallback} from both {@link #lockFocus()}.
     */
    private void captureStillPicture() {
        try {
            final Activity activity = getActivity();
            if (null == activity || null == mCameraDevice) {
                return;
            }
            // This is the CaptureRequest.Builder that we use to take a picture.
            final CaptureRequest.Builder captureBuilder =
                    mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(mImageReader.getSurface());

            // Use the same AE and AF modes as the preview.
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            setAutoFlash(captureBuilder);

            // Orientation
            int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));

            CameraCaptureSession.CaptureCallback CaptureCallback
                    = new CameraCaptureSession.CaptureCallback() {

                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                               @NonNull CaptureRequest request,
                                               @NonNull TotalCaptureResult result) {
                    showToast("Saved: " + mFile);
                    Log.d(TAG, mFile.toString());
                    unlockFocus();
                }
            };

            mCaptureSession.stopRepeating();
            mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * Retrieves the JPEG orientation from the specified screen rotation.
     *
     * @param rotation The screen rotation.
     * @return The JPEG orientation (one of 0, 90, 270, and 360)
     */
    private int getOrientation(int rotation) {
        // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
        // We have to take that into account and rotate JPEG properly.
        // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
        // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
        return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
    }

    /**
     * Unlock the focus. This method should be called when still image capture sequence is
     * finished.
     */
    private void unlockFocus() {
        try {
            // Reset the auto-focus trigger
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
            setAutoFlash(mPreviewRequestBuilder);
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
            // After this, the camera will go back to the normal state of preview.
            mState = STATE_PREVIEW;
            mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.picture: {
                takePicture();
                break;
            }
            case R.id.info: {
                Activity activity = getActivity();
                if (null != activity) {
                    new AlertDialog.Builder(activity)
                            .setMessage(R.string.intro_message)
                            .setPositiveButton(android.R.string.ok, null)
                            .show();
                }
                break;
            }
        }
    }

    private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        if (mFlashSupported) {
            requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                    CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
        }
    }

    /**
     * Saves a JPEG {@link Image} into the specified {@link File}.
     */
    private static class ImageSaver implements Runnable {

        /**
         * The JPEG image
         */
        private final Image mImage;
        /**
         * The file we save the image into.
         */
        private final File mFile;

        public ImageSaver(Image image, File file) {
            mImage = image;
            mFile = file;
        }

        @Override
        public void run() {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(mFile);
                output.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    /**
     * Compares two {@code Size}s based on their areas.
     */
    static class CompareSizesByArea implements Comparator<Size> {

        @Override
        public int compare(Size lhs, Size rhs) {
            // We cast here to ensure the multiplications won't overflow
            return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                    (long) rhs.getWidth() * rhs.getHeight());
        }

    }

    /**
     * Shows an error message dialog.
     */
    public static class ErrorDialog extends DialogFragment {

        private static final String ARG_MESSAGE = "message";

        public static ErrorDialog newInstance(String message) {
            ErrorDialog dialog = new ErrorDialog();
            Bundle args = new Bundle();
            args.putString(ARG_MESSAGE, message);
            dialog.setArguments(args);
            return dialog;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Activity activity = getActivity();
            return new AlertDialog.Builder(activity)
                    .setMessage(getArguments().getString(ARG_MESSAGE))
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            activity.finish();
                        }
                    })
                    .create();
        }

    }

    /**
     * Shows OK/Cancel confirmation dialog about camera permission.
     */
    public static class ConfirmationDialog extends DialogFragment {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Fragment parent = getParentFragment();
            return new AlertDialog.Builder(getActivity())
                    .setMessage(R.string.request_permission)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            FragmentCompat.requestPermissions(parent,
                                    new String[]{Manifest.permission.CAMERA},
                                    REQUEST_CAMERA_PERMISSION);
                        }
                    })
                    .setNegativeButton(android.R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Activity activity = parent.getActivity();
                                    if (activity != null) {
                                        activity.finish();
                                    }
                                }
                            })
                    .create();
        }
    }

}


text:
@interface FRPPhotoViewController ()
//Private assignment
@property (nonatomic, assign) NSInteger photoIndex;
@property (nonatomic, strong) FRPPhotoModel *photoModel;

//Private properties
@property (nonatomic, weak) UIImageView * imageView;

@end

@implementation FRPPhotoViewController

- (instancetype)initWithPhotoModel:(FRPPhotoModel *)photoModel index:(NSInteger)photoIndex{
    self = [self init];
    if (!self) return nil;

    self.photoModel = photoModel;
    self.photoIndex = photoIndex;

    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];

    //Configure self's view
    self.view.backgroundColor = [UIColor blackColor];

    //Configure subViews
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];

    RAC(imageView, image) = [RACObserve(self.photoModel, fullsizedData) map:^id (id value){
        [SVProgressHUD dismiss];
        return [UIImage imageWithData:value];
    }];

    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:imageView];
    self.imageView = imageView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [SVProgressHUD show];

    //Fetch data
    [[FRPPhotoImporter fetchPhotoDetails:self.photoModel]
     subscribeError:^(NSError *error){
         [SVProgressHUD showErrorWithStatus:@"Error"];
     }];
}

@end


text:
module LLT
  class PppBuilder < DeclinableBuilder
    builds_like_an :adjective
    builds_with :modus, :tempus, :genus, :prefix

    has_modus  t.participium
    has_tempus t.perfectum
    has_genus  t.passivum
  end
end


text:
/* More information about these options at jshint.com/docs/options */

/* globals apprtc, Constants */
/* exported RemoteWebSocket */

'use strict';

// This class is used as a proxy for the WebSocket owned by background.js.
// This proxy class sends commands and receives events via a Port object
// opened to communicate with background.js in a Chrome App.
// The WebSocket object must be owned by background.js so the call can be
// properly terminated when the app window is closed.
var RemoteWebSocket = function(wssUrl, wssPostUrl) {
  this.wssUrl_ = wssUrl;
  apprtc.windowPort.addMessageListener(this.handleMessage_.bind(this));
  this.sendMessage_({
    action: Constants.WS_ACTION,
    wsAction: Constants.WS_CREATE_ACTION,
    wssUrl: wssUrl,
    wssPostUrl: wssPostUrl
  });
  this.readyState = WebSocket.CONNECTING;
};

RemoteWebSocket.prototype.sendMessage_ = function(message) {
  apprtc.windowPort.sendMessage(message);
};

RemoteWebSocket.prototype.send = function(data) {
  if (this.readyState !== WebSocket.OPEN) {
    throw 'Web socket is not in OPEN state: ' + this.readyState;
  }
  this.sendMessage_({
    action: Constants.WS_ACTION,
    wsAction: Constants.WS_SEND_ACTION,
    data: data
  });
};

RemoteWebSocket.prototype.close = function() {
  if (this.readyState === WebSocket.CLOSING ||
      this.readyState === WebSocket.CLOSED) {
    return;
  }
  this.readyState = WebSocket.CLOSING;
  this.sendMessage_({
    action: Constants.WS_ACTION,
    wsAction: Constants.WS_CLOSE_ACTION
  });
};

RemoteWebSocket.prototype.handleMessage_ = function(message) {
  if (message.action === Constants.WS_ACTION &&
        message.wsAction === Constants.EVENT_ACTION) {
    if (message.wsEvent === Constants.WS_EVENT_ONOPEN) {
      this.readyState = WebSocket.OPEN;
      if (this.onopen) {
        this.onopen();
      }
    } else if (message.wsEvent === Constants.WS_EVENT_ONCLOSE) {
      this.readyState = WebSocket.CLOSED;
      if (this.onclose) {
        this.onclose(message.data);
      }
    } else if (message.wsEvent === Constants.WS_EVENT_ONERROR) {
      if (this.onerror) {
        this.onerror(message.data);
      }
    } else if (message.wsEvent === Constants.WS_EVENT_ONMESSAGE) {
      if (this.onmessage) {
        this.onmessage(message.data);
      }
    } else if (message.wsEvent === Constants.WS_EVENT_SENDERROR) {
      if (this.onsenderror) {
        this.onsenderror(message.data);
      }
      trace('ERROR: web socket send failed: ' + message.data);
    }
  }
};