text:
package org.apache.cassandra.cql3.validation.operations;

import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.cql3.CQLTester;
import org.apache.cassandra.dht.ByteOrderedPartitioner;
import org.apache.cassandra.exceptions.InvalidRequestException;

public class SelectLimitTest extends CQLTester
{
    @BeforeClass
    public static void setUp()
    {
        DatabaseDescriptor.setPartitionerUnsafe(ByteOrderedPartitioner.instance);
    }

    /**
     * Test limit across a partition range, requires byte ordered partitioner,
     * migrated from cql_tests.py:TestCQL.limit_range_test()
     */
    @Test
    public void testPartitionRange() throws Throwable
    {
        createTable("CREATE TABLE %s (userid int, url text, time bigint, PRIMARY KEY (userid, url)) WITH COMPACT STORAGE");

        for (int i = 0; i < 100; i++)
            for (String tld : new String[] { "com", "org", "net" })
                execute("INSERT INTO %s (userid, url, time) VALUES (?, ?, ?)", i, String.format("http://foo.%s", tld), 42L);

        assertRows(execute("SELECT * FROM %s WHERE token(userid) >= token(2) LIMIT 1"),
                   row(2, "http://foo.com", 42L));

        assertRows(execute("SELECT * FROM %s WHERE token(userid) > token(2) LIMIT 1"),
                   row(3, "http://foo.com", 42L));
    }

    /**
     * Test limit across a column range,
     * migrated from cql_tests.py:TestCQL.limit_multiget_test()
     */
    @Test
    public void testColumnRange() throws Throwable
    {
        createTable("CREATE TABLE %s (userid int, url text, time bigint, PRIMARY KEY (userid, url)) WITH COMPACT STORAGE");

        for (int i = 0; i < 100; i++)
            for (String tld : new String[] { "com", "org", "net" })
                execute("INSERT INTO %s (userid, url, time) VALUES (?, ?, ?)", i, String.format("http://foo.%s", tld), 42L);

        // Check that we do limit the output to 1 *and* that we respect query
        // order of keys (even though 48 is after 2)
        assertRows(execute("SELECT * FROM %s WHERE userid IN (48, 2) LIMIT 1"),
                   row(2, "http://foo.com", 42L));

    }

    /**
     * Test limit queries on a sparse table,
     * migrated from cql_tests.py:TestCQL.limit_sparse_test()
     */
    @Test
    public void testSparseTable() throws Throwable
    {
        createTable("CREATE TABLE %s (userid int, url text, day int, month text, year int, PRIMARY KEY (userid, url))");

        for (int i = 0; i < 100; i++)
            for (String tld : new String[] { "com", "org", "net" })
                execute("INSERT INTO %s (userid, url, day, month, year) VALUES (?, ?, 1, 'jan', 2012)", i, String.format("http://foo.%s", tld));

        assertRowCount(execute("SELECT * FROM %s LIMIT 4"), 4);

    }

    /**
     * Check for #7052 bug,
     * migrated from cql_tests.py:TestCQL.limit_compact_table()
     */
    @Test
    public void testLimitInCompactTable() throws Throwable
    {
        createTable("CREATE TABLE %s (k int, v int, PRIMARY KEY (k, v) ) WITH COMPACT STORAGE ");

        for (int i = 0; i < 4; i++)
            for (int j = 0; j < 4; j++)
                execute("INSERT INTO %s(k, v) VALUES (?, ?)", i, j);

        assertRows(execute("SELECT v FROM %s WHERE k=0 AND v > 0 AND v <= 4 LIMIT 2"),
                   row(1),
                   row(2));
        assertRows(execute("SELECT v FROM %s WHERE k=0 AND v > -1 AND v <= 4 LIMIT 2"),
                   row(0),
                   row(1));
        assertRows(execute("SELECT * FROM %s WHERE k IN (0, 1, 2) AND v > 0 AND v <= 4 LIMIT 2"),
                   row(0, 1),
                   row(0, 2));
        assertRows(execute("SELECT * FROM %s WHERE k IN (0, 1, 2) AND v > -1 AND v <= 4 LIMIT 2"),
                   row(0, 0),
                   row(0, 1));
        assertRows(execute("SELECT * FROM %s WHERE k IN (0, 1, 2) AND v > 0 AND v <= 4 LIMIT 6"),
                   row(0, 1),
                   row(0, 2),
                   row(0, 3),
                   row(1, 1),
                   row(1, 2),
                   row(1, 3));
        assertRows(execute("SELECT * FROM %s WHERE v > 1 AND v <= 3 LIMIT 6 ALLOW FILTERING"),
                   row(0, 2),
                   row(0, 3),
                   row(1, 2),
                   row(1, 3),
                   row(2, 2),
                   row(2, 3));
    }

    @Test
    public void testPerPartitionLimit() throws Throwable
    {
        perPartitionLimitTest(false);
    }

    @Test
    public void testPerPartitionLimitWithCompactStorage() throws Throwable
    {
        perPartitionLimitTest(true);
    }

    private void perPartitionLimitTest(boolean withCompactStorage) throws Throwable
    {
        String query = "CREATE TABLE %s (a int, b int, c int, PRIMARY KEY (a, b))";

        if (withCompactStorage)
            createTable(query + " WITH COMPACT STORAGE");
        else
            createTable(query);

        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                execute("INSERT INTO %s (a, b, c) VALUES (?, ?, ?)", i, j, j);
            }
        }

        assertInvalidMessage("LIMIT must be strictly positive",
                             "SELECT * FROM %s PER PARTITION LIMIT ?", 0);
        assertInvalidMessage("LIMIT must be strictly positive",
                             "SELECT * FROM %s PER PARTITION LIMIT ?", -1);

        assertRowsIgnoringOrder(execute("SELECT * FROM %s PER PARTITION LIMIT ?", 2),
                                row(0, 0, 0),
                                row(0, 1, 1),
                                row(1, 0, 0),
                                row(1, 1, 1),
                                row(2, 0, 0),
                                row(2, 1, 1),
                                row(3, 0, 0),
                                row(3, 1, 1),
                                row(4, 0, 0),
                                row(4, 1, 1));

        // Combined Per Partition and "global" limit
        assertRowCount(execute("SELECT * FROM %s PER PARTITION LIMIT ? LIMIT ?", 2, 6),
                       6);

        // odd amount of results
        assertRowCount(execute("SELECT * FROM %s PER PARTITION LIMIT ? LIMIT ?", 2, 5),
                       5);

        // IN query
        assertRows(execute("SELECT * FROM %s WHERE a IN (2,3) PER PARTITION LIMIT ?", 2),
                   row(2, 0, 0),
                   row(2, 1, 1),
                   row(3, 0, 0),
                   row(3, 1, 1));

        assertRows(execute("SELECT * FROM %s WHERE a IN (2,3) PER PARTITION LIMIT ? LIMIT 3", 2),
                   row(2, 0, 0),
                   row(2, 1, 1),
                   row(3, 0, 0));

        assertRows(execute("SELECT * FROM %s WHERE a IN (1,2,3) PER PARTITION LIMIT ? LIMIT 3", 2),
                   row(1, 0, 0),
                   row(1, 1, 1),
                   row(2, 0, 0));

        // with restricted partition key
        assertRows(execute("SELECT * FROM %s WHERE a = ? PER PARTITION LIMIT ?", 2, 3),
                   row(2, 0, 0),
                   row(2, 1, 1),
                   row(2, 2, 2));

        // with ordering
        assertRows(execute("SELECT * FROM %s WHERE a IN (3, 2) ORDER BY b DESC PER PARTITION LIMIT ?", 2),
                   row(2, 4, 4),
                   row(3, 4, 4),
                   row(2, 3, 3),
                   row(3, 3, 3));

        assertRows(execute("SELECT * FROM %s WHERE a IN (3, 2) ORDER BY b DESC PER PARTITION LIMIT ? LIMIT ?", 3, 4),
                   row(2, 4, 4),
                   row(3, 4, 4),
                   row(2, 3, 3),
                   row(3, 3, 3));

        assertRows(execute("SELECT * FROM %s WHERE a = ? ORDER BY b DESC PER PARTITION LIMIT ?", 2, 3),
                   row(2, 4, 4),
                   row(2, 3, 3),
                   row(2, 2, 2));

        // with filtering
        assertRows(execute("SELECT * FROM %s WHERE a = ? AND b > ? PER PARTITION LIMIT ? ALLOW FILTERING", 2, 0, 2),
                   row(2, 1, 1),
                   row(2, 2, 2));

        assertRows(execute("SELECT * FROM %s WHERE a = ? AND b > ? ORDER BY b DESC PER PARTITION LIMIT ? ALLOW FILTERING", 2, 2, 2),
                   row(2, 4, 4),
                   row(2, 3, 3));

        assertInvalidMessage("PER PARTITION LIMIT is not allowed with SELECT DISTINCT queries",
                             "SELECT DISTINCT a FROM %s PER PARTITION LIMIT ?", 3);
        assertInvalidMessage("PER PARTITION LIMIT is not allowed with SELECT DISTINCT queries",
                             "SELECT DISTINCT a FROM %s PER PARTITION LIMIT ? LIMIT ?", 3, 4);
        assertInvalidMessage("PER PARTITION LIMIT is not allowed with aggregate queries.",
                             "SELECT COUNT(*) FROM %s PER PARTITION LIMIT ?", 3);
    }
}


text:
try:
    raise OSError("blah")
except* ExceptionGroup as e:
    pass

try:
    async with trio.open_nursery() as nursery:
        # Make two concurrent calls to child()
        nursery.start_soon(child)
        nursery.start_soon(child)
except* ValueError:
    pass

try:
    try:
        raise ValueError(42)
    except:
        try:
            raise TypeError(int)
        except* Exception:
            pass
        1 / 0
except Exception as e:
    exc = e

try:
    try:
        raise FalsyEG("eg", [TypeError(1), ValueError(2)])
    except* TypeError as e:
        tes = e
        raise
    except* ValueError as e:
        ves = e
        pass
except Exception as e:
    exc = e

try:
    try:
        raise orig
    except* (TypeError, ValueError) as e:
        raise SyntaxError(3) from e
except BaseException as e:
    exc = e

try:
    try:
        raise orig
    except* OSError as e:
        raise TypeError(3) from e
except ExceptionGroup as e:
    exc = e

redpajama_set_name: RedPajamaGithub


text:
@implementation ASPOSEOCR

static NSArray *validLanguages;
static NSArray *validFormats;

__attribute__((constructor))
static void initialize_ValidValues() {
    validLanguages = @[@"English", @"french", @"russian", @"spanish"];
    validFormats = @[@"bmp", @"tif"];
}

+ (ASPOSEOCRResponse *) extractOCRorHOCRTextFromImages:(NSString *) fileName language:(NSString *) language useDefaultDictionaries:(BOOL) useDefaultDictionaries
{
    NSParameterAssert(fileName);
    NSParameterAssert([[validFormats valueForKey:@"lowercaseString"] containsObject:
                       [(NSString *)[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] lowercaseString]]);
    NSParameterAssert([[validLanguages valueForKey:@"lowercaseString"] containsObject:[language lowercaseString]]);
    NSParameterAssert([ASPOSEProduct baseProductUri]);

    //build URL
    NSString *strURL = [NSString stringWithFormat:@"%@%@/recognize?language=%@&useDefaultDictionaries=%d", OCR_URI,
                        [fileName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], language, useDefaultDictionaries];
    //sign URL
    NSString *signedURL = [ASPOSEUtils sign:strURL];

    NSData *responseData = [ASPOSEUtils processCommand:signedURL httpMethod:@"GET"];

    //Parsing JSON
    if(responseData) {
        NSError *error;
        ASPOSEOCRResponse *ocrResponse = [[ASPOSEOCRResponse alloc] initWithData:responseData error:&error];
        if(!error && [ocrResponse.code isEqualToString:@"200"] && [ocrResponse.status isEqualToString:@"OK"]) {
            return ocrResponse;
        }
    }

    return nil;
}

+ (ASPOSEOCRResponse *) extractOCRorHOCRTextFromASpecificBlock:(NSString *) fileName language:(NSString *) language rectX:(int) rectX rectY:(int) rectY rectWidth:(int) rectWidth rectHeight:(int) rectHeight useDefaultDictionaries:(BOOL) useDefaultDictionaries
{
    NSParameterAssert(fileName);
    NSParameterAssert([[validFormats valueForKey:@"lowercaseString"]
                       containsObject:[(NSString *)[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] lowercaseString]]);
    NSParameterAssert([[validLanguages valueForKey:@"lowercaseString"] containsObject:[language lowercaseString]]);
    NSParameterAssert([ASPOSEProduct baseProductUri]);

    //build URL
    NSString *strURL = [NSString stringWithFormat:@"%@%@/recognize?language=%@&rectX=%d&rectY=%d&rectWidth=%d&rectHeight=%d&useDefaultDictionaries=%d", OCR_URI, [fileName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], language, rectX, rectY, rectWidth, rectHeight, useDefaultDictionaries];
    //sign URL
    NSString *signedURL = [ASPOSEUtils sign:strURL];

    NSData *responseData = [ASPOSEUtils processCommand:signedURL httpMethod:@"GET"];

    //Parsing JSON
    if(responseData) {
        NSError *error;
        ASPOSEOCRResponse *ocrResponse = [[ASPOSEOCRResponse alloc] initWithData:responseData error:&error];
        if(!error && [ocrResponse.code isEqualToString:@"200"] && [ocrResponse.status isEqualToString:@"OK"]) {
            return ocrResponse;
        }
    }

    return nil;
}

+ (ASPOSEOCRResponse *) extractImageTextFromlocalFile:(NSData *) fileData language:(NSString *) language useDefaultDictionaries:(BOOL)useDefaultDictionaries
{
    NSParameterAssert(fileData);
    NSParameterAssert([[validLanguages valueForKey:@"lowercaseString"] containsObject:[language lowercaseString]]);
    NSParameterAssert([ASPOSEProduct baseProductUri]);

    //build URL
    NSString *strURL = [NSString stringWithFormat:@"%@recognize?language=%@&useDefaultDictionaries=%d", OCR_URI, language, useDefaultDictionaries];
    //sign URL
    NSString *signedURL = [ASPOSEUtils sign:strURL];

    NSData *responseData = [ASPOSEUtils processCommand:signedURL httpMethod:@"POST" andData:fileData];

    //Parsing JSON
    if(responseData) {
        NSError *error;
        ASPOSEOCRResponse *ocrResponse = [[ASPOSEOCRResponse alloc] initWithData:responseData error:&error];
        if(!error && [ocrResponse.code isEqualToString:@"200"] && [ocrResponse.status isEqualToString:@"OK"]) {
            return ocrResponse;
        }
    }

    return nil;
}

@end


text:
class ApplicationController < ActionController::API

  def cadenero_user
    current_user
  end
  helper_method :cadenero_user

end


text:
<?php

    namespace Debesha\DoctrineProfileExtraBundle\DataCollector;

    use Debesha\DoctrineProfileExtraBundle\ORM\HydrationLogger;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpKernel\DataCollector\DataCollector;

    class HydrationDataCollector extends DataCollector
    {

        /**
         * @var HydrationLogger
         */
        private $hydrationLogger = array ();

        public function __construct(HydrationLogger $logger)
        {

            $this->hydrationLogger = $logger;
        }

        public function collect(Request $request, Response $response, \Exception $exception = null)
        {

            $this->data['hydrations'] = $this->hydrationLogger->hydrations;
        }

        public function getHydrations()
        {
            return $this->data['hydrations'];
        }

        public function getHydrationsCount()
        {
            return count($this->data['hydrations']);
        }

        public function getTime()
        {
            $time = 0;
            foreach ($this->data['hydrations'] as $hydration) {
                if (isset($hydration['executionMS'])) {
                    $time += $hydration['executionMS'];
                }
            }

            return $time;
        }

        /**
         * {@inheritdoc}
         */
        public function getName()
        {
            return 'hydrations';
        }
    }


text:
package org.killbill.billing.invoice.dao;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Nullable;
import javax.inject.Inject;

import org.joda.time.LocalDate;
import org.killbill.billing.ErrorCode;
import org.killbill.billing.ObjectType;
import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.invoice.api.InvoiceApiException;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.tag.TagInternalApi;
import org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory;
import org.killbill.billing.util.tag.ControlTagType;
import org.killbill.billing.util.tag.Tag;

import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;

public class InvoiceDaoHelper {

    private final TagInternalApi tagInternalApi;

    @Inject
    public InvoiceDaoHelper(final TagInternalApi tagInternalApi) {
        this.tagInternalApi = tagInternalApi;
    }

    /**
     * Find amounts to adjust for individual items, if not specified.
     * The user gives us a list of items to adjust associated with a given amount (how much to refund per invoice item).
     * In case of full adjustments, the amount can be null: in this case, we retrieve the original amount for the invoice
     * item.
     *
     * @param invoiceId                     original invoice id
     * @param entitySqlDaoWrapperFactory    the EntitySqlDaoWrapperFactory from the current transaction
     * @param invoiceItemIdsWithNullAmounts the original mapping between invoice item ids and amount to refund (contains null)
     * @param context                       the tenant callcontext
     * @return the final mapping between invoice item ids and amount to refund
     * @throws org.killbill.billing.invoice.api.InvoiceApiException
     */
    public Map<UUID, BigDecimal> computeItemAdjustments(final String invoiceId,
                                                        final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
                                                        final Map<UUID, BigDecimal> invoiceItemIdsWithNullAmounts,
                                                        final InternalTenantContext context) throws InvoiceApiException {
        // Populate the missing amounts for individual items, if needed
        final Map<UUID, BigDecimal> outputItemIdsWithAmounts = new HashMap<UUID, BigDecimal>();
        if (invoiceItemIdsWithNullAmounts.size() == 0) {
            return outputItemIdsWithAmounts;
        }

        // Retrieve invoice before the Refund
        final InvoiceModelDao invoice = entitySqlDaoWrapperFactory.become(InvoiceSqlDao.class).getById(invoiceId, context);
        if (invoice != null) {
            populateChildren(invoice, entitySqlDaoWrapperFactory, context);
        } else {
            throw new IllegalStateException("Invoice shouldn't be null for id " + invoiceId);
        }

        //
        // If we have an item amount, we 'd like to use it, but we need to check first that it is lesser or equal than maximum allowed
        //If, not we compute maximum value we can adjust per item
        for (final UUID invoiceItemId : invoiceItemIdsWithNullAmounts.keySet()) {
            final List<InvoiceItemModelDao> adjustedOrRepairedItems = entitySqlDaoWrapperFactory.become(InvoiceItemSqlDao.class).getAdjustedOrRepairedInvoiceItemsByLinkedId(invoiceItemId.toString(), context);
            computeItemAdjustmentsForTargetInvoiceItem(getInvoiceItemForId(invoice, invoiceItemId), adjustedOrRepairedItems, invoiceItemIdsWithNullAmounts, outputItemIdsWithAmounts);
        }
        return outputItemIdsWithAmounts;
    }

    private static void computeItemAdjustmentsForTargetInvoiceItem(final InvoiceItemModelDao targetInvoiceItem, final List<InvoiceItemModelDao> adjustedOrRepairedItems, final Map<UUID, BigDecimal> inputAdjInvoiceItem, final Map<UUID, BigDecimal> outputAdjInvoiceItem) throws InvoiceApiException {
        final BigDecimal originalItemAmount = targetInvoiceItem.getAmount();
        final BigDecimal maxAdjLeftAmount = computeItemAdjustmentAmount(originalItemAmount, adjustedOrRepairedItems);

        final BigDecimal proposedItemAmount = inputAdjInvoiceItem.get(targetInvoiceItem.getId());
        if (proposedItemAmount != null && proposedItemAmount.compareTo(maxAdjLeftAmount) > 0) {
            throw new InvoiceApiException(ErrorCode.INVOICE_ITEM_ADJUSTMENT_AMOUNT_INVALID, proposedItemAmount, maxAdjLeftAmount);
        }

        final BigDecimal itemAmountToAdjust = Objects.firstNonNull(proposedItemAmount, maxAdjLeftAmount);
        if (itemAmountToAdjust.compareTo(BigDecimal.ZERO) > 0) {
            outputAdjInvoiceItem.put(targetInvoiceItem.getId(), itemAmountToAdjust);
        }
    }

    /**
     * @param requestedPositiveAmountToAdjust amount we are adjusting for that item
     * @param adjustedOrRepairedItems        list of all adjusted or repaired linking to this item
     * @return the amount we should really adjust based on whether or not the item got repaired
     */
    private static BigDecimal computeItemAdjustmentAmount(final BigDecimal requestedPositiveAmountToAdjust, final List<InvoiceItemModelDao> adjustedOrRepairedItems) {

        BigDecimal positiveAdjustedOrRepairedAmount = BigDecimal.ZERO;

        for (final InvoiceItemModelDao cur : adjustedOrRepairedItems) {
            // Adjustment or repair items are negative so we negate to make it positive
            positiveAdjustedOrRepairedAmount = positiveAdjustedOrRepairedAmount.add(cur.getAmount().negate());
        }
        return (positiveAdjustedOrRepairedAmount.compareTo(requestedPositiveAmountToAdjust) >= 0) ? BigDecimal.ZERO : requestedPositiveAmountToAdjust.subtract(positiveAdjustedOrRepairedAmount);
    }

    private InvoiceItemModelDao getInvoiceItemForId(final InvoiceModelDao invoice, final UUID invoiceItemId) throws InvoiceApiException {
        for (final InvoiceItemModelDao invoiceItem : invoice.getInvoiceItems()) {
            if (invoiceItem.getId().equals(invoiceItemId)) {
                return invoiceItem;
            }
        }
        throw new InvoiceApiException(ErrorCode.INVOICE_ITEM_NOT_FOUND, invoiceItemId);
    }

    public BigDecimal computePositiveRefundAmount(final InvoicePaymentModelDao payment, final BigDecimal requestedRefundAmount, final Map<UUID, BigDecimal> invoiceItemIdsWithAmounts) throws InvoiceApiException {
        final BigDecimal maxRefundAmount = payment.getAmount() == null ? BigDecimal.ZERO : payment.getAmount();
        final BigDecimal requestedPositiveAmount = requestedRefundAmount == null ? maxRefundAmount : requestedRefundAmount;
        // This check is good but not enough, we need to also take into account previous refunds
        // (But that should have been checked in the payment call already)
        if (requestedPositiveAmount.compareTo(maxRefundAmount) > 0) {
            throw new InvoiceApiException(ErrorCode.REFUND_AMOUNT_TOO_HIGH, requestedPositiveAmount, maxRefundAmount);
        }

        // Verify if the requested amount matches the invoice items to adjust, if specified
        BigDecimal amountFromItems = BigDecimal.ZERO;
        for (final BigDecimal itemAmount : invoiceItemIdsWithAmounts.values()) {
            amountFromItems = amountFromItems.add(itemAmount);
        }

        // Sanity check: if some items were specified, then the sum should be equal to specified refund amount, if specified
        if (amountFromItems.compareTo(BigDecimal.ZERO) != 0 && requestedPositiveAmount.compareTo(amountFromItems) < 0) {
            throw new InvoiceApiException(ErrorCode.REFUND_AMOUNT_DONT_MATCH_ITEMS_TO_ADJUST, requestedPositiveAmount, amountFromItems);
        }
        return requestedPositiveAmount;
    }

    public List<InvoiceModelDao> getUnpaidInvoicesByAccountFromTransaction(final UUID accountId, final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final LocalDate upToDate, final InternalTenantContext context) {
        final List<InvoiceModelDao> invoices = getAllInvoicesByAccountFromTransaction(entitySqlDaoWrapperFactory, context);
        return getUnpaidInvoicesByAccountFromTransaction(invoices, upToDate);
    }

    public List<InvoiceModelDao> getUnpaidInvoicesByAccountFromTransaction(final List<InvoiceModelDao> invoices, @Nullable final LocalDate upToDate) {
        final Collection<InvoiceModelDao> unpaidInvoices = Collections2.filter(invoices, new Predicate<InvoiceModelDao>() {
            @Override
            public boolean apply(final InvoiceModelDao in) {
                return (InvoiceModelDaoHelper.getBalance(in).compareTo(BigDecimal.ZERO) >= 1) && (upToDate == null || !in.getTargetDate().isAfter(upToDate));
            }
        });
        return new ArrayList<InvoiceModelDao>(unpaidInvoices);

    }

    /**
     * Create an adjustment for a given invoice item. This just creates the object in memory, it doesn't write it to disk.
     *
     * @param invoiceId         the invoice id
     * @param invoiceItemId     the invoice item id to adjust
     * @param effectiveDate     adjustment effective date, in the account timezone
     * @param positiveAdjAmount the amount to adjust. Pass null to adjust the full amount of the original item
     * @param currency          the currency of the amount. Pass null to default to the original currency used
     * @return the adjustment item
     */
    public InvoiceItemModelDao createAdjustmentItem(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final UUID invoiceId, final UUID invoiceItemId,
                                                    final BigDecimal positiveAdjAmount, final Currency currency,
                                                    final LocalDate effectiveDate, final InternalCallContext context) throws InvoiceApiException {
        // First, retrieve the invoice item in question
        final InvoiceItemSqlDao invoiceItemSqlDao = entitySqlDaoWrapperFactory.become(InvoiceItemSqlDao.class);
        final InvoiceItemModelDao invoiceItemToBeAdjusted = invoiceItemSqlDao.getById(invoiceItemId.toString(), context);
        if (invoiceItemToBeAdjusted == null) {
            throw new InvoiceApiException(ErrorCode.INVOICE_ITEM_NOT_FOUND, invoiceItemId);
        }

        // Validate the invoice it belongs to
        if (!invoiceItemToBeAdjusted.getInvoiceId().equals(invoiceId)) {
            throw new InvoiceApiException(ErrorCode.INVOICE_INVALID_FOR_INVOICE_ITEM_ADJUSTMENT, invoiceItemId, invoiceId);
        }

        // Retrieve the amount and currency if needed
        final BigDecimal amountToAdjust = Objects.firstNonNull(positiveAdjAmount, invoiceItemToBeAdjusted.getAmount());
        // TODO - should we enforce the currency (and respect the original one) here if the amount passed was null?
        final Currency currencyForAdjustment = Objects.firstNonNull(currency, invoiceItemToBeAdjusted.getCurrency());

        // Finally, create the adjustment
        // Note! The amount is negated here!
        return new InvoiceItemModelDao(context.getCreatedDate(), InvoiceItemType.ITEM_ADJ, invoiceItemToBeAdjusted.getInvoiceId(), invoiceItemToBeAdjusted.getAccountId(),
                                       null, null, null, null, null, null, effectiveDate, effectiveDate, amountToAdjust.negate(), null, currencyForAdjustment, invoiceItemToBeAdjusted.getId());
    }

    public void populateChildren(final InvoiceModelDao invoice, final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final InternalTenantContext context) {
        getInvoiceItemsWithinTransaction(ImmutableList.<InvoiceModelDao>of(invoice), entitySqlDaoWrapperFactory, context);
        getInvoicePaymentsWithinTransaction(ImmutableList.<InvoiceModelDao>of(invoice), entitySqlDaoWrapperFactory, context);
        setInvoiceWrittenOff(invoice, context);
    }

    public void populateChildren(final Iterable<InvoiceModelDao> invoices, final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final InternalTenantContext context) {
        getInvoiceItemsWithinTransaction(invoices, entitySqlDaoWrapperFactory, context);
        getInvoicePaymentsWithinTransaction(invoices, entitySqlDaoWrapperFactory, context);
        setInvoicesWrittenOff(invoices, context);
    }

    public List<InvoiceModelDao> getAllInvoicesByAccountFromTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final InternalTenantContext context) {
        final List<InvoiceModelDao> invoices = entitySqlDaoWrapperFactory.become(InvoiceSqlDao.class).getByAccountRecordId(context);
        populateChildren(invoices, entitySqlDaoWrapperFactory, context);
        return invoices;
    }

    public BigDecimal getRemainingAmountPaidFromTransaction(final UUID invoicePaymentId, final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final InternalTenantContext context) {
        final BigDecimal amount = entitySqlDaoWrapperFactory.become(InvoicePaymentSqlDao.class).getRemainingAmountPaid(invoicePaymentId.toString(), context);
        return amount == null ? BigDecimal.ZERO : amount;
    }

    private void getInvoiceItemsWithinTransaction(final Iterable<InvoiceModelDao> invoices, final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final InternalTenantContext context) {
        final InvoiceItemSqlDao invoiceItemSqlDao = entitySqlDaoWrapperFactory.become(InvoiceItemSqlDao.class);
        final List<InvoiceItemModelDao> invoiceItemsForAccount = invoiceItemSqlDao.getByAccountRecordId(context);

        final Map<UUID, List<InvoiceItemModelDao>> invoiceItemsPerInvoiceId = new HashMap<UUID, List<InvoiceItemModelDao>>();
        for (final InvoiceItemModelDao item : invoiceItemsForAccount) {
            if (invoiceItemsPerInvoiceId.get(item.getInvoiceId()) == null) {
                invoiceItemsPerInvoiceId.put(item.getInvoiceId(), new LinkedList<InvoiceItemModelDao>());
            }
            invoiceItemsPerInvoiceId.get(item.getInvoiceId()).add(item);
        }

        for (final InvoiceModelDao invoice : invoices) {
            // Make sure to set invoice items to a non-null value
            final List<InvoiceItemModelDao> invoiceItemsForInvoice = Objects.firstNonNull(invoiceItemsPerInvoiceId.get(invoice.getId()), ImmutableList.<InvoiceItemModelDao>of());
            invoice.addInvoiceItems(invoiceItemsForInvoice);
        }
    }

    private void getInvoicePaymentsWithinTransaction(final Iterable<InvoiceModelDao> invoices, final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final InternalTenantContext context) {
        final InvoicePaymentSqlDao invoicePaymentSqlDao = entitySqlDaoWrapperFactory.become(InvoicePaymentSqlDao.class);
        final List<InvoicePaymentModelDao> invoicePaymentsForAccount = invoicePaymentSqlDao.getByAccountRecordId(context);

        final Map<UUID, List<InvoicePaymentModelDao>> invoicePaymentsPerInvoiceId = new HashMap<UUID, List<InvoicePaymentModelDao>>();
        for (final InvoicePaymentModelDao invoicePayment : invoicePaymentsForAccount) {
            if (invoicePaymentsPerInvoiceId.get(invoicePayment.getInvoiceId()) == null) {
                invoicePaymentsPerInvoiceId.put(invoicePayment.getInvoiceId(), new LinkedList<InvoicePaymentModelDao>());
            }
            invoicePaymentsPerInvoiceId.get(invoicePayment.getInvoiceId()).add(invoicePayment);
        }

        for (final InvoiceModelDao invoice : invoices) {
            // Make sure to set payments to a non-null value
            final List<InvoicePaymentModelDao> invoicePaymentsForInvoice = Objects.firstNonNull(invoicePaymentsPerInvoiceId.get(invoice.getId()), ImmutableList.<InvoicePaymentModelDao>of());
            invoice.addPayments(invoicePaymentsForInvoice);

            for (final InvoicePaymentModelDao invoicePayment : invoicePaymentsForInvoice) {
                if (invoicePayment.getCurrency() != invoicePayment.getProcessedCurrency()) {
                    // If any entry is set with a different processed currency, we use it as a processed currency.
                    invoice.setProcessedCurrency(invoicePayment.getProcessedCurrency());
                    break;
                }
            }
        }
    }

    private void setInvoicesWrittenOff(final Iterable<InvoiceModelDao> invoices, final InternalTenantContext internalTenantContext) {

        final List<Tag> tags = tagInternalApi.getTagsForAccountType(ObjectType.INVOICE, false, internalTenantContext);
        final Iterable<Tag> writtenOffTags = filterForWrittenOff(tags);
        for (final Tag cur : writtenOffTags) {
            final InvoiceModelDao foundInvoice = Iterables.tryFind(invoices, new Predicate<InvoiceModelDao>() {
                @Override
                public boolean apply(final InvoiceModelDao input) {
                    return input.getId().equals(cur.getObjectId());
                }
            }).orNull();
            if (foundInvoice != null) {
                foundInvoice.setIsWrittenOff(true);
            }
        }
    }

    private void setInvoiceWrittenOff(final InvoiceModelDao invoice, final InternalTenantContext internalTenantContext) {
        final List<Tag> tags =  tagInternalApi.getTags(invoice.getId(), ObjectType.INVOICE, internalTenantContext);
        final Iterable<Tag> writtenOffTags = filterForWrittenOff(tags);
        invoice.setIsWrittenOff(writtenOffTags.iterator().hasNext());
    }

    private Iterable<Tag> filterForWrittenOff(final List<Tag> tags) {
        return Iterables.filter(tags, new Predicate<Tag>() {
            @Override
            public boolean apply(final Tag input) {
                return  input.getTagDefinitionId().equals(ControlTagType.WRITTEN_OFF.getId());
            }
        });
    }

}


text:
FOUNDATION_EXPORT double CocoaBarVersionNumber;

//! Project version string for CocoaBar.
FOUNDATION_EXPORT const unsigned char CocoaBarVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <CocoaBar/PublicHeader.h>


text:
package templates

import (
	"bytes"
	"encoding/json"
	"github.com/trainmeditations/journey/conversion"
	"github.com/trainmeditations/journey/database"
	"github.com/trainmeditations/journey/date"
	"github.com/trainmeditations/journey/plugins"
	"github.com/trainmeditations/journey/structure"
	"github.com/trainmeditations/journey/structure/methods"
	"html"
	"log"
	"net/url"
	"regexp"
	"sort"
	"strconv"
	"strings"
)

// Helper fuctions
func nullFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// Check if the helper was defined in a plugin
	if plugins.LuaPool != nil {
		// Get a state map to execute and attach it to the request data
		if values.PluginVMs == nil {
			values.PluginVMs = plugins.LuaPool.Get(helper, values)
		}
		if values.PluginVMs[helper.Name] != nil {
			pluginResult, err := plugins.Execute(helper, values)
			if err != nil {
				return []byte{}
			}
			return evaluateEscape(pluginResult, helper.Unescaped)
		} else {
			// This helper is not implemented in a plugin. Get rid of the Lua VMs
			plugins.LuaPool.Put(values.PluginVMs)
			values.PluginVMs = nil
		}
	}
	log.Println("Warning: This helper is not implemented:", helper.Name)
	return []byte{}
}

func slugFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(values.Blog.NavigationItems) != 0 {
		return evaluateEscape([]byte(values.Blog.NavigationItems[values.CurrentNavigationIndex].Slug), helper.Unescaped)
	}
	return []byte{}
}

var pageInUrlRegex = regexp.MustCompile("/page/[0-9]+/$")

func currentFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(values.Blog.NavigationItems) != 0 {
		url := values.Blog.NavigationItems[values.CurrentNavigationIndex].Url
		// Since the router rewrites all urls with a trailing slash, add / to url if not already there
		if !strings.HasSuffix(url, "/") {
			url = url + "/"
		}
		currentPath := pageInUrlRegex.ReplaceAllString(values.CurrentPath, "/")
		if currentPath == url {
			return []byte{1}
		}
	}
	return []byte{}
}

func navigationFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(values.Blog.NavigationItems) == 0 {
		return []byte{}
	} else if templateHelper, ok := compiledTemplates.m["navigation"]; ok {
		return executeHelper(templateHelper, values, values.CurrentHelperContext)
	}
	return []byte{}
}

func labelFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(values.Blog.NavigationItems) != 0 {
		return evaluateEscape([]byte(values.Blog.NavigationItems[values.CurrentNavigationIndex].Label), helper.Unescaped)
	}
	return []byte{}
}

func contentForFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// If there is no array attached to the request data already, make one
	if values.ContentForHelpers == nil {
		values.ContentForHelpers = make([]structure.Helper, 0)
	}
	// Collect all contentFor helpers to use them with a block helper
	values.ContentForHelpers = append(values.ContentForHelpers, *helper)
	return []byte{}
}

func blockFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		// Loop through the collected contentFor helpers and execute the appropriate one
		for index, _ := range values.ContentForHelpers {
			if len(values.ContentForHelpers[index].Arguments) != 0 {
				if values.ContentForHelpers[index].Arguments[0].Name == helper.Arguments[0].Name {
					return executeHelper(&values.ContentForHelpers[index], values, values.CurrentHelperContext)
				}
			}
		}
	}
	return []byte{}
}

func paginationFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if templateHelper, ok := compiledTemplates.m["pagination"]; ok {
		return executeHelper(templateHelper, values, values.CurrentHelperContext)
	}
	return []byte{}
}

func paginationDotTotalFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentTemplate == 0 { // index
		return []byte(strconv.FormatInt(values.Blog.PostCount, 10))
	} else if values.CurrentTemplate == 3 { // author
		count, err := database.RetrieveNumberOfPostsByUser(values.Posts[values.CurrentPostIndex].Author.Id)
		if err != nil {
			log.Println("Couldn't get number of posts", err.Error())
			return []byte{}
		}
		return []byte(strconv.FormatInt(count, 10))
	} else if values.CurrentTemplate == 2 { // tag
		count, err := database.RetrieveNumberOfPostsByTag(values.CurrentTag.Id)
		if err != nil {
			log.Println("Couldn't get number of posts", err.Error())
			return []byte{}
		}
		return []byte(strconv.FormatInt(count, 10))
	}
	return []byte{}
}

func pluralFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		// Get the number calculated by executing the first argument
		countString := string(helper.Arguments[0].Function(helper, values))
		if countString == "" {
			log.Println("Couldn't get count in plural helper")
			return []byte{}
		}
		arguments := methods.ProcessHelperArguments(helper.Arguments)
		for key, value := range arguments {
			if countString == "0" && key == "empty" {
				output := value
				output = strings.Replace(output, "%", countString, -1)
				return []byte(output)
			} else if countString == "1" && key == "singular" {
				output := value
				output = strings.Replace(output, "%", countString, -1)
				return []byte(output)
			} else if countString != "0" && countString != "1" && key == "plural" {
				output := value
				output = strings.Replace(output, "%", countString, -1)
				return []byte(output)
			}
		}
	}
	return []byte{}
}

func prevFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentIndexPage > 1 {
		return []byte{1}
	}
	return []byte{}
}

func nextFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	var count int64
	var err error
	if values.CurrentTemplate == 0 { // index
		count = values.Blog.PostCount
	} else if values.CurrentTemplate == 2 { // tag
		count, err = database.RetrieveNumberOfPostsByTag(values.CurrentTag.Id)
		if err != nil {
			log.Println("Couldn't get number of posts for tag", err.Error())
			return []byte{}
		}
	} else if values.CurrentTemplate == 3 { // author
		count, err = database.RetrieveNumberOfPostsByUser(values.Posts[values.CurrentPostIndex].Author.Id)
		if err != nil {
			log.Println("Couldn't get number of posts for author", err.Error())
			return []byte{}
		}
	}
	maxPages := positiveCeilingInt64(float64(count) / float64(values.Blog.PostsPerPage))
	if int64(values.CurrentIndexPage) < maxPages {
		return []byte{1}
	}
	return []byte{}
}

func pageFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return []byte(strconv.Itoa(values.CurrentIndexPage))
}

func pagesFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	var count int64
	var err error
	if values.CurrentTemplate == 0 { // index
		count = values.Blog.PostCount
	} else if values.CurrentTemplate == 2 { // tag
		count, err = database.RetrieveNumberOfPostsByTag(values.CurrentTag.Id)
		if err != nil {
			log.Println("Couldn't get number of posts for tag", err.Error())
			return []byte{}
		}
	} else if values.CurrentTemplate == 3 { // author
		count, err = database.RetrieveNumberOfPostsByUser(values.Posts[values.CurrentPostIndex].Author.Id)
		if err != nil {
			log.Println("Couldn't get number of posts for author", err.Error())
			return []byte{}
		}
	}
	maxPages := positiveCeilingInt64(float64(count) / float64(values.Blog.PostsPerPage))
	// Output at least 1 (even if there are no posts in the database)
	if maxPages == 0 {
		maxPages = 1
	}
	return []byte(strconv.FormatInt(maxPages, 10))
}

func page_urlFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		if helper.Arguments[0].Name == "prev" || helper.Arguments[0].Name == "pagination.prev" {
			if values.CurrentIndexPage > 1 {
				var buffer bytes.Buffer
				if values.CurrentIndexPage == 2 {
					if values.CurrentTemplate == 3 { // author
						buffer.WriteString("/author/")
						//TODO: Error handling if there is no Posts[values.CurrentPostIndex]
						buffer.WriteString(values.Posts[values.CurrentPostIndex].Author.Slug)
					} else if values.CurrentTemplate == 2 { // tag
						buffer.WriteString("/tag/")
						//TODO: Error handling if there is no Posts[values.CurrentPostIndex]
						buffer.WriteString(values.CurrentTag.Slug)
					}
					buffer.WriteString("/")
				} else {
					if values.CurrentTemplate == 3 { // author
						buffer.WriteString("/author/")
						//TODO: Error handling if there is no Posts[values.CurrentPostIndex]
						buffer.WriteString(values.Posts[values.CurrentPostIndex].Author.Slug)
					} else if values.CurrentTemplate == 2 { // tag
						buffer.WriteString("/tag/")
						//TODO: Error handling if there is no Posts[values.CurrentPostIndex]
						buffer.WriteString(values.CurrentTag.Slug)
					}
					page := values.CurrentIndexPage - 1
					if page > 1 {
						buffer.WriteString("/page/")
						buffer.WriteString(strconv.Itoa(page))
					}
					buffer.WriteString("/")
				}
				return buffer.Bytes()
			}
		} else if helper.Arguments[0].Name == "next" || helper.Arguments[0].Name == "pagination.next" {
			var count int64
			var err error
			if values.CurrentTemplate == 0 { // index
				count = values.Blog.PostCount
			} else if values.CurrentTemplate == 2 { // tag
				count, err = database.RetrieveNumberOfPostsByTag(values.CurrentTag.Id)
				if err != nil {
					log.Println("Couldn't get number of posts for tag", err.Error())
					return []byte{}
				}
			} else if values.CurrentTemplate == 3 { // author
				count, err = database.RetrieveNumberOfPostsByUser(values.Posts[values.CurrentPostIndex].Author.Id)
				if err != nil {
					log.Println("Couldn't get number of posts for author", err.Error())
					return []byte{}
				}
			}
			maxPages := positiveCeilingInt64(float64(count) / float64(values.Blog.PostsPerPage))
			if int64(values.CurrentIndexPage) < maxPages {
				var buffer bytes.Buffer
				if values.CurrentTemplate == 3 { // author
					buffer.WriteString("/author/")
					// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
					buffer.WriteString(values.Posts[values.CurrentPostIndex].Author.Slug)
				} else if values.CurrentTemplate == 2 { // tag
					buffer.WriteString("/tag/")
					// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
					buffer.WriteString(values.CurrentTag.Slug)
				}
				page := values.CurrentIndexPage + 1
				if page > 1 {
					buffer.WriteString("/page/")
					buffer.WriteString(strconv.Itoa(page))
				}
				buffer.WriteString("/")
				return buffer.Bytes()
			}
		}
	}
	return []byte{}
}

func extendFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		return []byte(helper.Arguments[0].Name)
	}
	return []byte{}
}

func featuredFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.Posts[values.CurrentPostIndex].IsFeatured {
		return []byte{1}
	}
	return []byte{}
}

func publishedFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.Posts[values.CurrentPostIndex].IsPublished {
		return []byte{1}
	}
	return []byte{}
}

func body_classFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentTemplate == 1 { // post
		// TODO: is there anything else that needs to be output here?
		var buffer bytes.Buffer
		buffer.WriteString("post-template")
		// If page
		if values.Posts[values.CurrentPostIndex].IsPage {
			buffer.WriteString(" page-template page")
		}
		for _, tag := range values.Posts[values.CurrentPostIndex].Tags {
			buffer.WriteString(" tag-")
			buffer.WriteString(tag.Slug)
		}
		return buffer.Bytes()
	} else if values.CurrentTemplate == 0 { // index
		if values.CurrentIndexPage == 1 {
			return []byte("home-template")
		} else {
			return []byte("paged archive-template")
		}
	} else if values.CurrentTemplate == 3 { // author
		var buffer bytes.Buffer
		buffer.WriteString("author-template author-")
		// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
		buffer.WriteString(values.Posts[values.CurrentPostIndex].Author.Slug)
		if values.CurrentIndexPage > 1 {
			buffer.WriteString(" paged archive-template")
		}
		return buffer.Bytes()
	} else if values.CurrentTemplate == 2 { // tag
		var buffer bytes.Buffer
		buffer.WriteString("tag-template tag-")
		buffer.WriteString(values.CurrentTag.Slug)
		if values.CurrentIndexPage > 1 {
			buffer.WriteString(" paged archive-template")
		}
		return buffer.Bytes()
	}
	// TODO: Delete this. Probably not needed.
	return []byte("post-template")
}

func ghost_headFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// SEO stuff:
	currentUrl := string(evaluateEscape(values.Blog.Url, helper.Unescaped)) + values.CurrentPath
	// Output canonical url
	var buffer bytes.Buffer
	buffer.WriteString("<link rel=\"canonical\" href=\"")
	buffer.WriteString(currentUrl)
	buffer.WriteString("\">\n")
	// Output structured data
	// values.CurrentPostIndex = 0 // current
	structuredData := map[string]string{
		"og:site_name": string(evaluateEscape(values.Blog.Title, helper.Unescaped)),
		"og:type": "website",
		"og:title": string(meta_titleFunc(helper, values)),
		"og:description": string(meta_descriptionFunc(helper, values)),
		"og:url": currentUrl,
		"og:image": string(imageFunc(helper, values)),
		"twitter:card": "summary", // summary or summary_large_image
		"twitter:title": string(meta_titleFunc(helper, values)),
		"twitter:description": string(meta_descriptionFunc(helper, values)),
		"twitter:url": currentUrl,
		"twitter:image:src": string(imageFunc(helper, values)),
	}
	schema := map[string]string{
		"@context": "http://schema.org",
		"@type": "Website",
		"publisher": string(evaluateEscape(values.Blog.Title, helper.Unescaped)),
		"headline": string(meta_titleFunc(helper, values)),
		"url": currentUrl,
		"image": string(imageFunc(helper, values)),
		// "keywords": ,
		"description": string(meta_descriptionFunc(helper, values)),
	};
	if values.CurrentTemplate == 1 { // post
		publicationDate := values.Posts[values.CurrentPostIndex].Date.Format("2006-01-02T15:04:05Z")
		structuredData["og:type"] = "article"
		structuredData["article:published_time"] = values.Posts[values.CurrentPostIndex].Date.Format("2006-01-02T15:04:05Z")
		// structuredData["article:modified_time"]
		// structuredData["article:tag"]
		schema["@type"] = "Article"
		schema["datePublished"] = publicationDate
		// schema["dateModified"]
	} else if values.CurrentTemplate == 2 { // tag
		schema["@type"] = "Series"
	} else if values.CurrentTemplate == 3 { // author
		structuredData["og:type"] = "profile"
		schema["@type"] = "Person"
	}
	structuredDataKeys := make([]string, len(structuredData))
	i := 0
	for key, _ := range structuredData {
		structuredDataKeys[i] = key
		i++
	}
	sort.Strings(structuredDataKeys)
	for _, key := range structuredDataKeys {
		buffer.WriteString("<meta property=\"")
		buffer.WriteString(key)
		buffer.WriteString("\" content=\"")
		buffer.WriteString(structuredData[key])
		buffer.WriteString("\">\n")
	}
	buffer.WriteString("\n")
	return buffer.Bytes()
}

func ghost_footFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: customized code injection
	return []byte{}
}

func meta_titleFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentTemplate == 1 { // post or page
		return evaluateEscape(values.Posts[values.CurrentPostIndex].Title, helper.Unescaped)
	} else if values.CurrentTemplate == 3 { // author
		var buffer bytes.Buffer
		// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
		buffer.Write(values.Posts[values.CurrentPostIndex].Author.Name)
		buffer.WriteString(" - ")
		buffer.Write(values.Blog.Title)
		return evaluateEscape(buffer.Bytes(), helper.Unescaped)
	} else if values.CurrentTemplate == 2 { // tag
		var buffer bytes.Buffer
		// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
		buffer.Write(values.CurrentTag.Name)
		buffer.WriteString(" - ")
		buffer.Write(values.Blog.Title)
		return evaluateEscape(buffer.Bytes(), helper.Unescaped)
	}
	// index
	return evaluateEscape(values.Blog.Title, helper.Unescaped)
}

func meta_descriptionFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Finish this
	if values.CurrentTemplate == 1 || values.CurrentHelperContext == 1 { // post
		return evaluateEscape(values.Posts[values.CurrentPostIndex].MetaDescription, helper.Unescaped)
	} else {
		return evaluateEscape(values.Blog.Description, helper.Unescaped)
	}
	// Nothing on post yet
	return []byte{}
}

func bodyFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return helper.Block
}

func insertFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		if templateHelper, ok := compiledTemplates.m[helper.Arguments[0].Name]; ok {
			return executeHelper(templateHelper, values, values.CurrentHelperContext)
		}
	}
	return []byte{}
}

func encodeFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		return []byte(url.QueryEscape(string(helper.Arguments[0].Function(&helper.Arguments[0], values))))
	}
	return []byte{}
}

func authorFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// Check if helper is block helper
	if len(helper.Block) != 0 {
		return executeHelper(helper, values, 3) // context = author
	}
	// Else return author name (as link)
	arguments := methods.ProcessHelperArguments(helper.Arguments)
	for key, value := range arguments {
		// If link is set to false, just return the name
		if key == "autolink" && value == "false" {
			return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Name, helper.Unescaped)
		}
	}
	var buffer bytes.Buffer
	buffer.WriteString("")
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	buffer.Write(evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Name, helper.Unescaped))
	buffer.WriteString("")
	return buffer.Bytes()
}

func authorDotNameFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Name, helper.Unescaped)
}

func bioFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Bio, helper.Unescaped)
}

func emailFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Email, helper.Unescaped)
}

func websiteFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Website, helper.Unescaped)
}

func imageFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentHelperContext == 1 { // post
		// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
		return evaluateEscape(values.Posts[values.CurrentPostIndex].Image, helper.Unescaped)
	} else if values.CurrentHelperContext == 3 { // author
		// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
		return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Image, helper.Unescaped)
	}
	return []byte{}
}

func authorDotImageFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Image, helper.Unescaped)
}

func coverFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Cover, helper.Unescaped)
}

func locationFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Location, helper.Unescaped)
}

func twitterFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Twitter, helper.Unescaped)
}

func facebookFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Facebook, helper.Unescaped)
}

func postFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	values.CurrentPostIndex = 0 // the current post
	return executeHelper(helper, values, 1) // context = post
}

func prevPostFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.Posts[1].Id == 0 {
		return []byte{}
	}
	values.CurrentPostIndex = 1 // the previous post
	var buffer bytes.Buffer
	buffer.Write(executeHelper(helper, values, 1)) // context = post
	values.CurrentPostIndex = 0 // the current post
	return buffer.Bytes()
}

func nextPostFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.Posts[2].Id == 0 {
		return []byte{}
	}
	values.CurrentPostIndex = 2 // the next post
	var buffer bytes.Buffer
	buffer.Write(executeHelper(helper, values, 1)) // context = post
	values.CurrentPostIndex = 0 // the current post
	return buffer.Bytes()
}

func postsFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(values.Posts) > 0 {
		return []byte{1}
	}
	return []byte{}
}

func tagsFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(values.Posts[values.CurrentPostIndex].Tags) > 0 {
		separator := ", "
		suffix := ""
		prefix := ""
		makeLink := true
		if len(helper.Arguments) != 0 {
			arguments := methods.ProcessHelperArguments(helper.Arguments)
			for key, value := range arguments {
				if key == "separator" {
					separator = value
				} else if key == "suffix" {
					suffix = value
				} else if key == "prefix" {
					prefix = value
				} else if key == "autolink" {
					if value == "false" {
						makeLink = false
					}
				}
			}
		}
		var buffer bytes.Buffer
		if prefix != "" {
			buffer.WriteString(prefix)
			buffer.WriteString(" ")
		}
		for index, tag := range values.Posts[values.CurrentPostIndex].Tags {
			if index != 0 {
				buffer.WriteString(separator)
			}
			if makeLink {
				buffer.WriteString("")
			}
			buffer.Write(evaluateEscape(tag.Name, helper.Unescaped))
			if makeLink {
				buffer.WriteString("")
			}
		}
		if suffix != "" {
			buffer.WriteString(" ")
			buffer.WriteString(suffix)
		}
		return buffer.Bytes()
	}
	return []byte{}
}

func post_classFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	var buffer bytes.Buffer
	buffer.WriteString("post")
	if values.Posts[values.CurrentPostIndex].IsFeatured {
		buffer.WriteString(" featured")
	}
	if values.Posts[values.CurrentPostIndex].IsPage {
		buffer.WriteString(" page")
	}
	for _, tag := range values.Posts[values.CurrentPostIndex].Tags {
		buffer.WriteString(" tag-")
		buffer.WriteString(tag.Slug)
	}
	return evaluateEscape(buffer.Bytes(), helper.Unescaped)
}

func urlFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	var buffer bytes.Buffer
	if len(helper.Arguments) != 0 {
		arguments := methods.ProcessHelperArguments(helper.Arguments)
		for key, value := range arguments {
			if key == "absolute" {
				if value == "true" {
					// Only write the blog url if navigation url does not begin with http/https
					if values.CurrentHelperContext == 4 && (!strings.HasPrefix(values.Blog.NavigationItems[values.CurrentNavigationIndex].Url, "http://") && !strings.HasPrefix(values.Blog.NavigationItems[values.CurrentNavigationIndex].Url, "https://")) { // navigation
						buffer.Write(values.Blog.Url)
					} else if values.CurrentHelperContext != 4 {
						buffer.Write(values.Blog.Url)
					}
				}
			}
		}
	}
	if values.CurrentHelperContext == 1 { // post
		buffer.WriteString("/")
		buffer.WriteString(values.Posts[values.CurrentPostIndex].Slug)
		buffer.WriteString("/")
		return evaluateEscape(buffer.Bytes(), helper.Unescaped)
	} else if values.CurrentHelperContext == 3 { // author
		buffer.WriteString("/author/")
		// TODO: Error handling if there is no Posts[values.CurrentPostIndex]
		buffer.WriteString(values.Posts[values.CurrentPostIndex].Author.Slug)
		buffer.WriteString("/")
		return evaluateEscape(buffer.Bytes(), helper.Unescaped)
	} else if values.CurrentHelperContext == 4 { // navigation
		buffer.WriteString(values.Blog.NavigationItems[values.CurrentNavigationIndex].Url)
		return evaluateEscape(buffer.Bytes(), helper.Unescaped)
	}
	return []byte{}
}

func titleFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Title, helper.Unescaped)
}

func contentFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// TODO: is content always unescaped? seems like it...
	return values.Posts[values.CurrentPostIndex].Html
}

func excerptFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentHelperContext == 1 { // post
		if len(helper.Arguments) != 0 {
			arguments := methods.ProcessHelperArguments(helper.Arguments)
			for key, value := range arguments {
				if key == "words" {
					number, err := strconv.Atoi(value)
					if err == nil {
						excerpt := conversion.StripTagsFromHtml(values.Posts[values.CurrentPostIndex].Html)
						words := bytes.Fields(excerpt)
						if len(words) < number {
							return excerpt
						}
						return bytes.Join(words[:number], []byte(" "))
					}
				} else if key == "characters" {
					number, err := strconv.Atoi(value)
					if err == nil {
						// Use runes for UTF-8 support
						runes := []rune(string(conversion.StripTagsFromHtml(values.Posts[values.CurrentPostIndex].Html)))
						if len(runes) < number {
							return []byte(string(runes))
						}
						return []byte(string(runes[:number]))
					}
				}
			}
		}
		// Default to 50 words excerpt
		excerpt := conversion.StripTagsFromHtml(values.Posts[values.CurrentPostIndex].Html)
		words := bytes.Fields(excerpt)
		if len(words) < 50 {
			return excerpt
		}
		return bytes.Join(words[:50], []byte(" "))
	}
	return []byte{}
}

func dateFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	showPublicationDate := false
	timeFormat := "MMM Do, YYYY" // Default time format
	// If in scope of a post, change default to published date
	if values.CurrentHelperContext == 1 { // post
		showPublicationDate = true
	}
	// Get the date
	if len(helper.Arguments) != 0 {
		arguments := methods.ProcessHelperArguments(helper.Arguments)
		for key, value := range arguments {
			if key == "published_at" {
				showPublicationDate = true
			} else if key == "timeago" {
				if value == "true" {
					// Compute time ago
					return evaluateEscape(date.GenerateTimeAgo(values.Posts[values.CurrentPostIndex].Date), helper.Unescaped)
				}
			} else if key == "format" {
				timeFormat = value
			}
		}
	}
	if showPublicationDate {
		return evaluateEscape(date.FormatDate(timeFormat, values.Posts[values.CurrentPostIndex].Date), helper.Unescaped)
	}
	currentDate := date.GetCurrentTime()
	return evaluateEscape(date.FormatDate(timeFormat, &currentDate), helper.Unescaped)
}

func atFirstFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentHelperContext == 1 { // post
		if values.CurrentPostIndex == 0 {
			return []byte{1}
		}
		return []byte{}
	}
	if values.CurrentHelperContext == 2 { // tag
		if values.CurrentTagIndex == 0 {
			return []byte{1}
		}
		return []byte{}
	}
	return []byte{}
}

func atLastFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentHelperContext == 1 { // post
		if values.CurrentPostIndex == (len(values.Posts) - 1) {
			return []byte{1}
		}
		return []byte{}
	}
	if values.CurrentHelperContext == 2 { // tag
		if values.CurrentTagIndex == (len(values.Posts[values.CurrentPostIndex].Tags) - 1) {
			return []byte{1}
		}
		return []byte{}
	}
	return []byte{}
}

func atEvenFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentHelperContext == 1 { // post
		// First post (index 0) needs to be odd
		if values.CurrentPostIndex%2 == 1 {
			return []byte{1}
		}
		return []byte{}
	}
	if values.CurrentHelperContext == 2 { // tag
		// First tag (index 0) needs to be odd
		if values.CurrentTagIndex%2 == 1 {
			return []byte{1}
		}
		return []byte{}
	}
	return []byte{}
}

func atOddFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentHelperContext == 1 { // post
		// First post (index 0) needs to be odd
		if values.CurrentPostIndex%2 == 0 {
			return []byte{1}
		}
		return []byte{}
	}
	if values.CurrentHelperContext == 2 { // tag
		// First tag (index 0) needs to be odd
		if values.CurrentTagIndex%2 == 0 {
			return []byte{1}
		}
		return []byte{}
	}
	return []byte{}
}

func nameFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	// If tag (commented out the code for generating a link. Ghost doesn't seem to do that either).
	if values.CurrentHelperContext == 2 { // tag
		//var buffer bytes.Buffer
		//buffer.WriteString("")
		//buffer.Write(evaluateEscape([]byte(values.Posts[values.CurrentPostIndex].Tags[values.CurrentTagIndex].Name), helper.Unescaped))
		//buffer.WriteString("")
		//return buffer.Bytes()
		return evaluateEscape(values.Posts[values.CurrentPostIndex].Tags[values.CurrentTagIndex].Name, helper.Unescaped)
	}
	// If author (commented out the code for generating a link. Ghost doesn't seem to do that).
	//var buffer bytes.Buffer
	//buffer.WriteString("")
	//buffer.Write(evaluateEscape([]byte(values.Author.Name), helper.Unescaped))
	//buffer.WriteString("")
	//return buffer.Bytes()
	//TODO: Error handling if there is no Posts[values.CurrentPostIndex]
	return evaluateEscape(values.Posts[values.CurrentPostIndex].Author.Name, helper.Unescaped)
}

func tagDotNameFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(values.CurrentTag.Name) != 0 {
		return evaluateEscape(values.CurrentTag.Name, helper.Unescaped)
	} else {
		return evaluateEscape(values.Posts[values.CurrentPostIndex].Tags[values.CurrentTagIndex].Name, helper.Unescaped)
	}
}

func tagDotSlugFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if values.CurrentTag.Slug != "" {
		return evaluateEscape([]byte(values.CurrentTag.Slug), helper.Unescaped)
	} else {
		return evaluateEscape([]byte(values.Posts[values.CurrentPostIndex].Tags[values.CurrentTagIndex].Slug), helper.Unescaped)
	}
}

func idFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return []byte(strconv.FormatInt(values.Posts[values.CurrentPostIndex].Id, 10))
}

func assetFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		var buffer bytes.Buffer
		buffer.Write(values.Blog.AssetPath)
		buffer.WriteString(helper.Arguments[0].Name)
		return buffer.Bytes()
	}
	return []byte{}
}

func foreachFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		switch helper.Arguments[0].Name {
		case "posts":
			var buffer bytes.Buffer
			for index, _ := range values.Posts {
				//if values.Posts[index].Id != 0 { // If post is not empty (Commented out for now. This was only neccessary in previous versions, when the array length was always the postsPerPage length)
				values.CurrentPostIndex = index
				buffer.Write(executeHelper(helper, values, 1)) // context = post
				//}
			}
			return buffer.Bytes()
		case "tags":
			var buffer bytes.Buffer
			for index, _ := range values.Posts[values.CurrentPostIndex].Tags {
				//if values.Posts[values.CurrentPostIndex].Tags[index].Id != 0 { // If tag is not empty (Commented out for now. Not neccessary.)
				values.CurrentTagIndex = index
				buffer.Write(executeHelper(helper, values, 2)) // context = tag
				//}
			}
			return buffer.Bytes()
		case "navigation":
			var buffer bytes.Buffer
			for index, _ := range values.Blog.NavigationItems {
				values.CurrentNavigationIndex = index
				buffer.Write(executeHelper(helper, values, 4)) // context = navigation
			}
			return buffer.Bytes()
		default:
			return []byte{}
		}
	}
	return []byte{}
}

func ifFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		if len(helper.Arguments[0].Function(&helper.Arguments[0], values)) != 0 {
			// If the evaluation is true, execute the if helper
			return executeHelper(helper, values, values.CurrentHelperContext)
		} else {
			// Else execute the else helper which is always at the last index of the if helper Arguments
			if helper.Arguments[len(helper.Arguments)-1].Name == "else" {
				if len(helper.Arguments[len(helper.Arguments)-1].Children) != 0 {
				}
				return executeHelper(&helper.Arguments[len(helper.Arguments)-1], values, values.CurrentHelperContext)
			}
		}
	}
	return []byte{}
}

func unlessFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	if len(helper.Arguments) != 0 {
		if len(helper.Arguments[0].Function(&helper.Arguments[0], values)) == 0 {
			// If the evaluation is false, execute the unless helper
			return executeHelper(helper, values, values.CurrentHelperContext)
		}
	}
	return []byte{}
}

func atBlogDotTitleFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return evaluateEscape(values.Blog.Title, helper.Unescaped)
}

func atBlogDotUrlFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	var buffer bytes.Buffer
	buffer.Write(values.Blog.Url)
	buffer.WriteString("/")
	return evaluateEscape(buffer.Bytes(), helper.Unescaped)
}

func atBlogDotLogoFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return evaluateEscape(values.Blog.Logo, helper.Unescaped)
}

func atBlogDotCoverFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return evaluateEscape(values.Blog.Cover, helper.Unescaped)
}

func atBlogDotDescriptionFunc(helper *structure.Helper, values *structure.RequestData) []byte {
	return evaluateEscape(values.Blog.Description, helper.Unescaped)
}

func evaluateEscape(value []byte, unescaped bool) []byte {
	if unescaped {
		return value
	}
	return []byte(html.EscapeString(string(value)))
}

func positiveCeilingInt64(input float64) int64 {
	output := int64(input)
	if (input - float64(output)) > 0 {
		output++
	}
	return output
}


text:
@interface BGAImageView : UIView
@property (nonatomic, strong) UIImage *image;
@end


text:
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
use yii\bootstrap\Modal;
use yii\helpers\URL;

$title = '';
if($IdArea == 3)
switch($IdSubProceso){
    case 6:
        $title = "Control de Fallas Robert Sinto y FDNX F-PC-7.0-31/05";
        break;
    case 2:
        $title = "Reporte de producción en las corazoneras  F-PC-7.0-02/6";
        break;
    case 10:
        $title = "Material vaciado F-PC-7.0-05/6";
        break;
    case 3:
        $title = "Rebabeo y ensamble almas ( Bronce ) F-PC-7.0-51/1";
        break;
}

if($IdArea == 2){
    switch($IdSubProceso){
        case 2:
            $title = "Reporte de producción Almas ( ACEROS )";
            break;

        case 4:
            $title = "Pintado Almas ( ACEROS ) ";
            break;
    }
}

$this->title = $title;

//$minFecha = date('H')< 6 ? date('Y-m-d',strtotime('-1 day',strtotime(date()))) : date('Y-m-d');
?>

<?=$title?>

<div class="container-fluid" ng-controller="Produccion" ng-init="
    Fecha = '<?=strtotime(date('G:i:s')) < strtotime('06:00') ? date('Y-m-d', strtotime('-1 day',strtotime(date('Y-m-d')))) : date('Y-m-d');?>';
    IdTurno = 1;
    countProducciones(<?=$IdSubProceso?>,<?=$IdArea?>);
    IdSubProceso = <?=$IdSubProceso?>;
    IdArea = <?=$IdArea?>;
    loadProgramacion(true);
    <?=$IdEmpleado == null ? "" : "produccion.IdEmpleado = $IdEmpleado;"?>
    loadCentros();
    <?php if($IdSubProceso != 12):?>
    loadMaquinas();
    <?php else:?>
    loadCentros();
    <?php endif?>
    loadFallas();
    loadDefectos();
    loadMaterial();
    loadTurnos();
    <?php if($IdSubProceso == 12 || $IdSubProceso == 16):?>
        loadEmpleados('2-6');
    <?php endif?>
    <?php if($IdSubProceso == 16):?>
        loadEmpleados('2-6');
    <?php endif?>
   <?php if( ($IdSubProceso == 2 || $IdSubProceso == 3)  && $IdArea == 3 ):?>
        loadEmpleados('2-1');
    <?php endif?>
	<?php if( ($IdSubProceso == 2 || $IdSubProceso == 4)  && $IdArea == 2 ):?>
        loadEmpleados('1-1');
    <?php endif?>
    <?php if($IdSubProceso == 6 || $IdSubProceso == 10):?>
        loadEmpleados(['2-1,2-2,2-5']);
    <?php endif?>
    <?php if($IdSubProceso == 10):?>
        loadAleaciones();
    <?php endif?>
">

            <form class="form-horizontal" name="editableForm" onaftersave="saveProduccion()">

                            Fecha:
                            <input ng-show="!mostrar" class="form-control input-sm" type="date" ng-change="produccion.Fecha = Fecha;loadProgramacion();" max="<?=strtotime(date('G:i:s')) < strtotime('06:00') ? date('Y-m-d', strtotime('-1 day',strtotime(date('Y-m-d')))) : date('Y-m-d');?>" ng-model="Fecha" format-date/>
                            <input ng-show="mostrar" disabled="" class="form-control input-sm" value="{{produccion.Fecha}}"/>

                    <?php if($IdSubProceso == 3 || $IdSubProceso == 19 || $IdSubProceso == 12):?>

                            Proceso:
                            <select ng-show="!mostrar" id="aleacion" aria-describedby="Maquinas" class="form-control input-sm" ng-change="produccion.IdCentroTrabajo = IdCentroTrabajo;loadMaquinas();loadProgramacion();" ng-model="IdCentroTrabajo" required>
                                <option ng-selected="produccion.IdCentroTrabajo == centro.IdCentroTrabajo" value="{{centro.IdCentroTrabajo}}" ng-repeat="centro in centros">{{centro.Descripcion}}</option>
                            </select>
                            <input ng-show="mostrar" disabled="" class="form-control input-sm" value="{{produccion.idCentroTrabajo.Descripcion}}"/>

                    <?php endif;?>
                    <?php if($IdSubProceso != 16 && $IdSubProceso != 3):?>

                            <?php if($IdSubProceso == 10):?>Horno:<?php else:?>Maquina:<?php endif;?>
                            <select ng-show="!mostrar" id="aleacion" aria-describedby="Maquinas" class="form-control input-sm" ng-change="selectMaquina();loadProgramacion();" ng-model="IdMaquina" required>
                                <option ng-selected="IdMaquina == maquina.IdMaquina" value="{{maquina.IdMaquina}}" ng-repeat="maquina in maquinas">{{maquina.ClaveMaquina}} - {{maquina.Maquina}}</option>
                            </select>
                            <input ng-show="mostrar" disabled="" class="form-control input-sm" value="{{produccion.idMaquina.Identificador}} - {{produccion.idMaquina.Descripcion}}"/>

                    <?php endif;?>
                    <?php if($IdSubProceso == 12 || $IdSubProceso == 6 || $IdSubProceso == 2 || $IdSubProceso == 16 || $IdSubProceso == 3 ||  $IdSubProceso == 4):?>

                            Empleado:
                            <select ng-show="!mostrar" aria-describedby="Empleados" class="form-control input-sm" ng-model="IdEmpleado" required>
                                <option ng-selected="produccion.IdEmpleado == e.IdEmpleado" ng-repeat="e in empleados" ng-value="{{e.IdEmpleado}}">{{e.NombreCompleto}}</option>
                            </select>
                            <input ng-show="mostrar" disabled="" class="form-control input-sm" value="{{produccion.idEmpleado.ApellidoPaterno}} {{produccion.idEmpleado.ApellidoMaterno}} {{produccion.idEmpleado.Nombre}}"/>

                    <?php endif;?>

                            Turno:
                            <select ng-show="!mostrar" aria-describedby="Turnos" class="form-control input-sm" ng-change="produccion.IdTurno = IdTurno;loadProgramacion();" ng-model="IdTurno" required>
                                <option ng-selected="IdTurno == t.IdTurno" ng-repeat="t in turnos" ng-value="{{t.IdTurno}}">{{t.Descripcion}}</option>
                            </select>
                            <input ng-show="mostrar" disabled="" class="form-control input-sm" value="{{produccion.idTurno.Descripcion}}"/>

                <?php if($IdSubProceso == 10):?>

                            Aleacion:
                            <select ng-show="!mostrar" id="aleacion" aria-describedby="Aleaciones"  class="form-control" ng-model="IdAleacion" required>
                                <option ng-selected="produccion.lances.IdAleacion == a.IdAleacion" ng-repeat="a in aleaciones" ng-value="{{a.IdAleacion}}">{{a.Identificador}}</option>
                            </select>
                            <input ng-show="mostrar" disabled="" class="form-control input-sm" value="{{produccion.lances.idAleacion.Identificador}}"/>

                            Cons Horno:
                            <input ng-show="mostrar" class="form-control input-sm" ng-model="produccion.lances.HornoConsecutivo" ng-value="{{produccion.lances.HornoConsecutivo}}"/>
                            <input ng-show="!mostrar" disabled="" class="form-control input-sm" value="{{produccion.lances.HornoConsecutivo}}"/>

                            Colada:
                            <input ng-show="mostrar" class="form-control" ng-model="produccion.lances.Colada" ng-value="{{produccion.lances.Colada}}"/>
                            <input ng-show="!mostrar" disabled="" class="form-control input-sm" value="{{produccion.lances.Colada}}"/>

                            Lance:
                            <input ng-show="mostrar" class="form-control" ng-model="produccion.lances.Lance" ng-value="{{produccion.lances.Lance}}"/>
                            <input ng-show="!mostrar" disabled="" class="form-control input-sm" value="{{produccion.lances.Lance}}"/>

                <?php endif;?>

                            Observaciones:
                            <textarea aria-describedby="Observaciones" class="form-control input-sm" ng-model="produccion.Observaciones">{{produccion.Observaciones}}</textarea>

                        <button class="btn btn-primary" ng-click="addProduccion();mostrar=false" ng-show="mostrar">Nuevo Registro</button>
                        <button class="btn btn-primary" ng-click="findProduccion();mostrar=true" ng-show="!mostrar">Generar</button>
                        <button class="btn btn-success" ng-click="loadProduccion();mostrar=true" ng-show="!mostrar">Cancelar</button>
                        <button class="btn btn-success" ng-click="updateProduccion();getChanges();saveChanges();" ng-show="mostrar">Guardar</button>
                        <button class="btn btn-danger" ng-click="deleteProducciones();" ng-show="mostrar">Eliminar</button>
                        <button class="btn" ng-click="produccion.IdProduccionEstatus=2;saveProduccion();" ng-show="mostrar">Cerrar Captura</button>
                        <?php if($IdSubProceso == 10):?>
                        <button ng-click="buscar2();" class="btn btn-info">Mantenimiento de Hornos</button>
                        <?php endif;?>
                        <button title="Buscar" class="btn" ng-click="buscar();" >Buscar</button>

                        <button title="Primer Registro" class="btn btn-default btn-sg" ng-click="First();" ng-disabled="!mostrar"></button>
                        <button title="Registro Anterior" class="btn btn-default btn-sg" ng-click="Prev();" ng-disabled="!mostrar"></button>
                        Registro: {{index+1}} de {{producciones.length}}
                        <button title="Siguiente Registro" class="btn btn-default btn-sg" ng-click="Next();" ng-disabled="!mostrar"></button>
                        <button title="Ultimo Registro" class="btn btn-default btn-sg" ng-click="Last();" ng-disabled="!mostrar"></button>
                        Semana: {{produccion.Semana}}

            </form>

            <alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>

    <?php if($IdSubProceso == 2):?>

            <?= $this->render('programacionAlmas',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

            <?= $this->render('FormProduccionAlmasDetalle',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

            <?= $this->render('FormProduccionAlmasRechazo',[
                'subProceso'=>$IdSubProceso,
                'titulo' => 'Rechazo Almas',
            ]);?>

            <?= $this->render('FormTiemposMuerto',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

        <?php if($IdArea == 3): ?>

            <?= $this->render('FormTemperaturas',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

        <?php endif;?>

    <?php endif?>
    <?php if($IdSubProceso == 3|| $IdSubProceso == 4):?>

            <?= $this->render('programacionAlmas',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

                    <?= $this->render('FormProduccionAlmasDetalle',[
                        'IdSubProceso'=>$IdSubProceso,
                    ]);?>

                    <?= $this->render('FormProduccionAlmasRechazo',[
                        'IdSubProceso'=>$IdSubProceso,
                        'titulo' => 'Rechazo Almas',
                    ]);?>

                <?= $this->render('FormTiemposMuerto',[
                    'IdSubProceso'=>$IdSubProceso,
                ]);?>

    <?php endif?>
    <?php if($IdSubProceso == 6):?>

            <?= $this->render('programacion',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

                    <?= $this->render('FormProduccionDetalle',[
                        'IdSubProceso'=>$IdSubProceso,
                    ]);?>

                    <?= $this->render('FormProduccionRechazo',[
                        'IdSubProceso'=>$IdSubProceso,
                        'titulo' => 'Rechazo Moldeo',
                    ]);?>

                    <?= $this->render('FormTiemposMuerto',[
                            'subProceso'=>$IdSubProceso,
                        ]);?>

    <?php endif?>
    <?php if($IdSubProceso == 10):?>

            <?= $this->render('programacion',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

            <?= $this->render('FormProduccionDetalle',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>
            <?= $this->render('FormTemperaturas',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

            <?= $this->render('FormProduccionMaterial',[
                'subProceso'=>$IdSubProceso,
            ]);?>

    <?php endif?>
    <?php if($IdSubProceso == 12):?>

            <?= $this->render('programacion',[
                'IdSubProceso'=>$IdSubProceso,
            ]);?>

                    <?= $this->render('FormProduccionDetalle',[
                        'IdSubProceso'=>$IdSubProceso,
                    ]);?>

                    <?= $this->render('FormProduccionRechazo',[
                        'IdSubProceso'=>$IdSubProceso,
                        'titulo' => 'Rechazo Moldeo',
                    ]);?>

                    <?= $this->render('FormTiemposMuerto',[
                            'subProceso'=>$IdSubProceso,
                        ]);?>

    <?php endif?>
    <modal title="Buscar Produccion" visible="showModal">

                    Semana

<input class="form-control" ng-model="filtro.Semana">

                    Fecha

<input class="form-control" ng-model="filtro.Fecha">

                    Turno

<input class="form-control" ng-model="filtro.Turno">

                    Lance

<input class="form-control" ng-model="filtro.Lance">

                    Empleado

<input class="form-control" ng-model="filtro.Empleado">

                    Maquina

<input class="form-control" ng-model="filtro.Maquina">

                    Producto

<input class="form-control" ng-model="filtro.Producto">

                    Buenas
                    Rechazadas

                    <button class="btn" ng-click="show(busqueda.index);">Ver</button>
                    {{busqueda.Semana}}
                    {{busqueda.Fecha | date:'dd-MMM-yyyy'}}
                    {{busqueda.Turno}}
                    {{busqueda.Lance}}
                    {{busqueda.Empleado}}
                    {{busqueda.Maquina}}
                    {{busqueda.Producto}}
                    {{busqueda.Hechas}}
                    {{busqueda.Rechazadas}}

    </modal>
    <modal title="Registro de mantenimiento de hornos" visible="showModal2">
        <?= $this->render('MantenimientoHornos',[
            'IdSubProceso'=>$IdSubProceso,
        ]);?>
    </modal>


text:
{% extends "base.html" %}

{% block title %}Password Reset Complete{% endblock %}

{% block content %}

Password Reset Complete

Your password has been set. You may go ahead and log in now.

Login

{% endblock %}


text:
<?php

/**
 * This file is part of the Nextras community extensions of Nette Framework
 *
 * @license    New BSD License
 * @link       https://github.com/nextras/migrations
 */

namespace Nextras\Migrations\Printers;

use Nextras\Migrations\Entities\File;
use Nextras\Migrations\Exception;
use Nextras\Migrations\IPrinter;

class TextPrinter implements IPrinter
{

	public function printIntro($mode)
	{
		// Suppress output
	}

	public function printToExecute(array $toExecute)
	{
		if ($toExecute) {
			$count = count($toExecute);
			$this->output($count . ' migration' . ($count > 1 ? 's' : '') . ' need' . ($count > 1 ? '' : 's') . ' to be executed.');
		} else {
			$this->output('No migration needs to be executed.');
		}
	}

	public function printExecute(File $file, $count, $time)
	{
		// Suppress output
	}

	public function printDone()
	{
		$this->output('OK');
	}

	public function printError(Exception $e)
	{
		$this->output('ERROR: ' . $e->getMessage());
		throw $e;
	}

	public function printSource($code)
	{
		$this->output($code);
	}

	protected function output($s)
	{
		echo "$s\n";
	}

}


text:
from functools import wraps
from flask import g, request, redirect, url_for, flash
from flask.ext.babel import gettext as _

def login_required(func):
    """ Decorator allow to access route only logged in user. Usage:

        @project.route('/test', methods=['GET'])
        @login_required
        def test():
            return "You are logged in"

    """
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if g.user is None:
            flash(_('Login required'))
            return redirect(url_for('gitauth.login', next=request.url))
        return func(*args, **kwargs)
    return decorated_function

def cached(obj):
    cache = obj.cache = {}

    @wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwargs)
        return cache[args]
    return memoizer


text:
Мои библиотеки

<select class="selectpicker hor-margin input-large"
	ng-model="library.id" ng-options="library.Name for library in libraries"
	ng-change="viewLibrary(library, '{{library.id}}')">
	<option value="">--Выберите библиотеку--</option>
	</select>
	<button type="button" ui-sref="newLibrary" class="btn btn-success hor-margin">

					Добавить библиотеку
				</button>

			Id
			Название
			Автор

            {{book.Id}}
			{{book.Name}}
			{{book.Author}}

                <button type="button" ui-sref="editBook({id:book.Id})" class="btn btn-warning hor-margin">

				</button>

                 <button type="button" ui-sref="deleteBook({id:book.Id})" class="btn btn-danger hor-margin">

				</button>

				<button type="button" ui-sref="books({libId: 1})" class="btn btn-success text-center">

					Добавить книгу в библиотеку
				</button>


text:
package com.facebook.buck.model;

import com.google.common.collect.ImmutableSortedSet;
import org.immutables.value.Value;

/** A constructor arg of rules which have default flavors. */
public interface HasDefaultFlavors {
  /**
   * @return If present, the default flavors with which to build this target if none are provided on
   *     the command line.
   */
  @Value.NaturalOrder
  ImmutableSortedSet<Flavor> getDefaultFlavors();
}