text:
<?php

return array(
    'router' => array(
        'routes' => array(
            'thongtinlienhe' => array(
                'type' => 'segment',
                'options' => array(
                    'route'    => '/thongtinlienhe[/:action][/:id]',
                	'constrains'=> array (
                				'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                				'id'=> '[0-9]+',
                				) ,
                    'defaults' => array(
                        'controller' => 'Thongtinlienhe\Controller\Thongtinlienhe',
                        'action'     => 'index',
                    ),
                ),
            ),
            // The following is a route to simplify getting started creating
            // new controllers and actions without needing to create a new
            // module. Simply drop new controllers in, and you can access them
            // using the path /application/:controller/:action
        ),
    ),

    'controllers' => array(
        'invokables' => array(
            'Thongtinlienhe\Controller\Thongtinlienhe' => 'Thongtinlienhe\Controller\ThongtinlienheController'
        ),
    ),
    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',

        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),

    // Placeholder for console routes
    'console' => array(
        'router' => array(
            'routes' => array(
            ),
        ),
    ),

);

redpajama_set_name: RedPajamaGithub


text:
/**
 * Conversion functions between IDL attributes and content attributes.
 * @see https://html.spec.whatwg.org/multipage/infrastructure.html#reflecting-content-attributes-in-idl-attributes
 */

/*
 * For simplicity we assume that there are five data types:
 * - Number
 * - String
 * - Boolean
 * - Array (containing data of types shown above)
 * - Object (everything else)
 *
 * Object type cannot be converted.
 *
 * IDL attribute is a Javascript entity, backed by content attribute.
 * Content attribute is a plain-old javascript string.
 */

const stringIdentity = x => `${x}`

const jsonParse = x => JSON.parse(x)
const jsonStringify = x => JSON.stringify(x)

const arrayParse = (x, elemParse) => x.split(',').map(e => elemParse(e.trim()))
const arrayStringify = (x, elemStringify) => x.map(elemStringify).join(',')

const booleanParse = x => x !== null
const booleanStringify = () => ''

const normalizeType = type => {
  if (Array.isArray(type)) {
    return type.map(normalizeType)
  } else {
    switch (type) {
      case Array:
      case 'Array':
      case 'array': return Array
      case Number:
      case 'Number':
      case 'number': return Number
      case Boolean:
      case 'Boolean':
      case 'boolean': return Boolean
      case String:
      case 'String':
      case 'string': return String
    }
    throw new Error(`Unsupported type ${type}.`)
  }
}

export function getConvertToAttribute (type) {
  const ntype = normalizeType(type)
  if (Array.isArray(ntype) && ntype[0] === Array) {
    return x => arrayStringify(x, getConvertToAttribute(ntype[1]))
  } else {
    switch (ntype) {
      case Number: return jsonStringify
      case Boolean: return booleanStringify
      case String: return stringIdentity
    }
    throw new Error(`No converter found for ${ntype} type.`)
  }
}

export function getConvertFromAttribute (type) {
  const ntype = normalizeType(type)
  if (Array.isArray(ntype) && ntype[0] === Array) {
    return x => arrayParse(x, getConvertFromAttribute(ntype[1]))
  } else {
    switch (ntype) {
      case Number: return jsonParse
      case Boolean: return booleanParse
      case String: return stringIdentity
    }
    throw new Error(`No converter found for ${ntype} type.`)
  }
}

export function getDefaultValue (type) {
  const ntype = normalizeType(type)
  if (Array.isArray(ntype) && ntype[0] === Array) {
    return []
  } else {
    switch (ntype) {
      case Number: return 0
      case Boolean: return false
      case String: return ''
    }
    throw new Error(`No default value found for ${ntype} type.`)
  }
}


text:
<?php
namespace OuzoMigrations\Task;

use OuzoMigrations\OuzoMigrationsException;
use OuzoMigrations\Util\Naming;

define('RUCKUSING_TASK_DIR', RUCKUSING_BASE . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'Task');

class Manager
{
    /**
     * @var \OuzoMigrations\Adapter\AdapterBase
     */
    private $_adapter;

    private $_tasks = array();

    public function __construct($adapter)
    {
        $this->setAdapter($adapter);
    }

    public function setAdapter($adapter)
    {
        if (!($adapter instanceof \OuzoMigrations\Adapter\AdapterBase)) {
            throw new OuzoMigrationsException('Adapter must be implement Base!', OuzoMigrationsException::INVALID_ADAPTER);
        }
        $this->_adapter = $adapter;

        return $this;
    }

    public function get_adapter()
    {
        return $this->_adapter;
    }

    /**
     * @param $key
     * @return mixed
     * @throws \OuzoMigrations\OuzoMigrationsException
     * @return TaskInterface
     */
    public function get_task($key)
    {
        if (!$this->has_task($key)) {
            throw new OuzoMigrationsException("Task '$key' is not registered.", OuzoMigrationsException::INVALID_ARGUMENT);
        }
        return $this->_tasks[$key];
    }

    public function has_task($key)
    {
        if (empty($this->_tasks)) {
            $this->load_all_tasks(RUCKUSING_TASK_DIR);
        }
        if (array_key_exists($key, $this->_tasks)) {
            return true;
        }
        return false;
    }

    public function register_task($key, $obj)
    {
        if (array_key_exists($key, $this->_tasks)) {
            throw new OuzoMigrationsException(sprintf("Task key '%s' is already defined!", $key), OuzoMigrationsException::INVALID_ARGUMENT);
        }
        if (!($obj instanceof TaskInterface)) {
            throw new OuzoMigrationsException(sprintf('Task (' . $key . ') does not implement Ruckusing_Task_Interface', $key), OuzoMigrationsException::INVALID_ARGUMENT);
        }
        $this->_tasks[$key] = $obj;
        return true;
    }

    private function load_all_tasks($task_dir)
    {
        if (!is_dir($task_dir)) {
            throw new OuzoMigrationsException(sprintf("Task dir: %s does not exist", $task_dir), OuzoMigrationsException::INVALID_ARGUMENT);
        }
        $namespaces = scandir($task_dir);
        foreach ($namespaces as $namespace) {
            if ($namespace == '.' || $namespace == '..'
                || !is_dir($task_dir . DIRECTORY_SEPARATOR . $namespace)
            ) {
                continue;
            }
            $files = scandir($task_dir . DIRECTORY_SEPARATOR . $namespace);
            $regex = '/^(\w+)\.php$/';
            foreach ($files as $file) {
                //skip over invalid files
                if ($file == '.' || $file == ".." || !preg_match($regex, $file)) {
                    continue;
                }
                require_once $task_dir . DIRECTORY_SEPARATOR . $namespace . DIRECTORY_SEPARATOR . $file;
                $className = Naming::classFromFileToName($task_dir . DIRECTORY_SEPARATOR . $namespace . DIRECTORY_SEPARATOR . $file);
                $task_name = Naming::task_from_class_name($className);

                $this->register_task($task_name, new $className($this->get_adapter()));
            }
        }
    }

    public function execute($framework, $task_name, $options)
    {
        $task = $this->get_task($task_name);
        $task->set_framework($framework);
        return $task->execute($options);
    }

    public function help($task_name)
    {
        $task = $this->get_task($task_name);
        return $task->help();
    }
}


text:
Machine learning tools for automatic classification of Somali text.  This was part of a project for Africa's Voices Foundation, in partnership with UNICEF, which aimed to understand Somali citizens' opinions on a range of healthcare issues.

For more information on the system produced by Africa's Voices:
* [Introducing CODA: A tool for data analysis](https://www.africasvoices.org/ideas/newsblog/introducing-our-latest-analysis-tool-coda/)

For reports from the Somali project:
* [Report for UNICEF Somalia on beliefs and practices concerning HIV/AIDS](https://issuu.com/africasvoices/docs/unicef-somalia_hiv_aids_report_marc)
* [Africa's Voices report for the malaria team, UNICEF Somalia](https://issuu.com/africasvoices/docs/final-_africa_s_voices_report_for_u)
* [Gender and Child Protection Report for UNICEF Somalia](https://issuu.com/africasvoices/docs/gender_and_child_protection_report_)


text:
class Cms::Agents::Tasks::Line::MessagesController < ApplicationController
  include Cms::Line::TaskFilter

  def deliver
    if @message.nil?
      @task.log "message not found!"
      head :ok
      return
    end

    now = Time.zone.now
    begin
      pull_private_files(@message)
      deliver_message(@message)
    rescue => e
      @task.log("#{e.class} (#{e.message}):\n  #{e.backtrace.join("\n  ")}")
    ensure
      @message.complete_delivery(now)
    end
    head :ok
  end

  def test_deliver
    if @message.nil? || @test_members.blank?
      @task.log "message or test members not found!"
      head :ok
      return
    end

    now = Time.zone.now
    begin
      pull_private_files(@message)
      deliver_test_message(@message, @test_members)
    rescue => e
      @task.log("#{e.class} (#{e.message}):\n  #{e.backtrace.join("\n  ")}")
    ensure
      @message.complete_test_delivery(now)
    end
    head :ok
  end

  def reserve_deliver
    now = Time.zone.now
    messages = Cms::Line::Message.site(@site).where(deliver_state: "ready")
    plans = Cms::Line::DeliverPlan.site(@site).in(message_id: messages.pluck(:id)).where(
      :state => "ready",
      :deliver_date.ne => nil,
      :deliver_date.lte => now
    ).to_a
    messages = plans.map { |plan| plan.message  }.uniq { |message| message.id }

    messages.each do |message|
      begin
        pull_private_files(message)
        message.publish
        deliver_message(message)
      rescue => e
        @task.log("#{e.class} (#{e.message}):\n  #{e.backtrace.join("\n  ")}")
      ensure
        message.complete_delivery(now)
      end
    end
    head :ok
  end

  def pull_private_files(message)
    return unless SS::Lgwan.enabled?
    message.templates.each { |template| SS::Lgwan.pull_private_files(template) }
  end
end


text:
require 'tapp/printer'
require 'ap'

module Tapp::Printer
  class AwesomePrint < Base
    def print(*args)
      ap *args
    end
  end
end


text:
Raw Data from MQTT Queue

{{rawMessageData}}


text:
package com.st.BlueSTSDK.Features;

import com.st.BlueSTSDK.Feature;
import com.st.BlueSTSDK.Node;
import com.st.BlueSTSDK.Utils.NumberConversion;

/**
 * Feature that contains the data comes form a luminosity sensor.
 * <p>
 * Node: since the sensor is the same, it is possible that you can not have data from a
 * proximity sensor and from a luminosity sensor at the same time
 * </p>
 *
 * @author STMicroelectronics - Central Labs.
 * @version 1.0
 */
public class FeatureLuminosity extends Feature {

    public static final String FEATURE_NAME = "Luminosity";
    public static final String FEATURE_UNIT = "Lux";
    public static final String FEATURE_DATA_NAME = "Luminosity";
    public static final short DATA_MAX = 1000;
    public static final short DATA_MIN = 0;

    /**
     * build a Feature of type FeatureLuminosity
     *
     * @param n node that will send the data to this feature
     */
    public FeatureLuminosity(Node n) {
        super(FEATURE_NAME, n,
                new Field[]{
                        new Field(FEATURE_DATA_NAME, FEATURE_UNIT, Field.Type.UInt16, DATA_MAX,
                                DATA_MIN),
                });
    }//FeatureLuminosity

    /**
     * extract the luminosity value from the feature raw data
     *
     * @param s feature raw data
     * @return luminosity value or -1 if the data array is not valid
     */
    public static int getLuminosity(Sample s) {
        if(s!=null)
            if(s.data!=null)
                if(s.data.length>0)
                    if (s.data[0] != null)
                        return s.data[0].intValue();
        //else
        return -1; // the luminosity is always positive
    }

    /**
     * extract the luminosity value from the node raw data, it reads an uint16
     *
     * @param data       array where read the Field data
     * @param dataOffset offset where start to read the data
     * @return number of read byte (2) and data extracted (the luminosity information)
     * @throws IllegalArgumentException if the data array has not enough data
     */
    @Override
    protected ExtractResult extractData(long timestamp,byte[] data, int dataOffset) {
        if (data.length - dataOffset < 2)
            throw new IllegalArgumentException("There are no 2 bytes available to read");
        Sample temp = new Sample(timestamp,new Number[]{
                NumberConversion.LittleEndian.bytesToUInt16(data, dataOffset)
        },getFieldsDesc());
        return new ExtractResult(temp,2);
    }//update

}


text:
package org.nightcode.common.service;

import org.nightcode.common.base.Throwables;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Unit test for {@link AbstractMessageService}.
 */
public class AbstractMessageServiceTest {

  @Test public void submit() throws Exception {
    final AtomicBoolean value = new AtomicBoolean(false);
    final AtomicInteger counter = new AtomicInteger(0);
    MessageService<Boolean> service = new AbstractMessageService<Boolean>("MessageServiceTest") {
      @Override protected void doStart() {
        started();
      }

      @Override protected void doStop() {
        stopped();
      }

      @Override protected void process(Boolean message) throws Exception {
        value.set(message);
        counter.incrementAndGet();
      }
    };
    service.start().get();
    boolean actual = service.submit(Boolean.TRUE);
    assertEquals(true, actual);
    assertEquals(true, value.get());
    assertEquals(1, counter.get());
    service.stop().get();
  }

  @Test public void submitFailed() throws Exception {
    final AtomicInteger counter = new AtomicInteger(0);
    MessageService<Boolean> service = new AbstractMessageService<Boolean>("MessageServiceTest") {
      @Override protected void doStart() {
        started();
      }

      @Override protected void doStop() {
        stopped();
      }

      @Override protected void process(Boolean message) throws Exception {
        counter.incrementAndGet();
        throw new Exception("This service always throws exception when calling process() method.");
      }
    };
    service.start().get();
    boolean actual = service.submit(Boolean.TRUE);
    assertEquals(false, actual);
    assertEquals(1, counter.get());
    service.stop().get();
  }

  @Test public void submitFailedPropagate() throws Exception {
    final AtomicInteger counter = new AtomicInteger(0);
    MessageService<Boolean> service
        = new AbstractMessageService<Boolean>("MessageServiceTest", true) {
      @Override protected void doStart() {
        started();
      }

      @Override protected void doStop() {
        stopped();
      }

      @Override protected void process(Boolean message) throws Exception {
        counter.incrementAndGet();
        throw new Exception("This service always throws exception when calling process() method.");
      }
    };
    service.start().get();
    try {
      service.submit(Boolean.TRUE);
      Assert.fail();
    } catch(Exception ex) {
      Assert.assertEquals("This service always throws exception when calling process() method."
          , Throwables.getRootCause(ex).getMessage());
    }
    assertEquals(1, counter.get());
    service.stop().get();
  }
}


text:
package com.filreas.gosthlm.database.queries;

import com.filreas.gosthlm.database.helpers.ITransportationOfChoiceDbHelper;
import com.filreas.gosthlm.database.model.TransportationOfChoice;

public class TransportationOfChoiceQuery implements IQuery<TransportationOfChoice> {

    private final ITransportationOfChoiceDbHelper helper;

    public TransportationOfChoiceQuery(ITransportationOfChoiceDbHelper helper) {
        this.helper = helper;
    }

    @Override
    public TransportationOfChoice get() {
        TransportationOfChoice result = helper.read();
        if (result == null) {
            result = new TransportationOfChoice();
            helper.create(result);
        }

        return result;
    }
}


text:
name: 'Feature Request'
about: 'Suggest new features and changes'
labels: enhancement
---

<!--- Provide a general summary of the feature request in the Title above -->

## Feature Suggestion

<!--- Tell us how we could improve your experience -->

## Possible Implementation

<!--- Not obligatory, but ideas as to the implementation of the addition or change -->

## Context

<!--- What are you trying to accomplish? -->
<!--- helps us come up with a solution that is most useful in the real world -->


text:
from flask_statics.helpers import get_resources, priority

def test_priority():
    values = ['CSSHAKE', 'BOOTSTRAP', 'ANGULAR', 'JQUERY']
    values.sort(key=priority)
    assert ['JQUERY', 'BOOTSTRAP', 'ANGULAR', 'CSSHAKE'] == values

def test_get_resources(all_files_both):
    all_resources = get_resources()
    all_resources_minified = get_resources(minify=True)
    assert all_resources.keys() == all_resources_minified.keys()
    assert all_resources.values() != all_resources_minified.values()

    all_files, all_files_minified = all_files_both
    assert all('.min.' not in f for f in all_files)
    assert any('.min.' in f for f in all_files_minified)


text:
<?php

namespace Valerian\Html;

interface EmptyElementInterface extends HtmlInterface
{
    /**
     * @return $this
     */
    function attribute($name, $value);

    /**
     * @return string
     */
    function getElementName();

}


text:
<?php
namespace app\console\controllers;

use yii\helpers\Console;
use yii\console\Controller;
use Yii;

/**
 * Creates base rbac authorization data for our application.
 * -----------------------------------------------------------------------------
 * Creates 6 roles:
 *
 * - theCreator : you, developer of this site (super admin)
 * - admin      : your direct clients, administrators of this site
 * - editor     : editor of this site
 * - support    : support staff
 * - premium    : premium member of this site
 * - member     : user of this site who has registered his account and can log in
 *
 * Creates 7 permissions:
 *
 * - usePremiumContent  : allows premium members to use premium content
 * - createArticle      : allows editor+ roles to create articles
 * - updateOwnArticle   : allows editor+ roles to update own articles
 * - updateArticle      : allows admin+ roles to update all articles
 * - deleteArticle      : allows admin+ roles to delete articles
 * - adminArticle       : allows admin+ roles to manage articles
 * - manageUsers        : allows admin+ roles to manage users (CRUD plus role assignment)
 *
 * Creates 1 rule:
 *
 * - AuthorRule : allows editor+ roles to update their own content
 */
class RbacController extends Controller
{
    /**
     * Initializes the RBAC authorization data.
     */
    public function actionInit()
    {
        $auth = Yii::$app->authManager;

        //---------- RULES ----------//

        // add the rule
        $rule = new \app\rbac\rules\AuthorRule;
        $auth->add($rule);

        //---------- PERMISSIONS ----------//

        // add "useSettings" Permissions
        $useSettings = $auth->createPermission('useSettings');
        $useSettings->description = 'Allow user to modify system settings';
        $auth->add($useSettings);

        $appAdmin = $auth->createRole('admin');
        $auth->add($appAdmin);
        $auth->addchild($appAdmin, $useSettings);

        $auth->assign($appAdmin, 1);

        if ($auth)
        {
            $this->stdout("\nRbac authorization data are installed successfully.\n", Console::FG_GREEN);
        }
    }
}


text:
from django.test import SimpleTestCase
# from django.utils.encoding import force_text
# from django.core.validators import EMPTY_VALUES

from rest_framework.serializers import ValidationError
from rest_framework.serializers import CharField

class DRFTestCase(SimpleTestCase):
    """
    Test case created to override the assertFieldOutput, to
        verify if test with valid and invalid data it was a success.
    """

    def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
                          field_kwargs=None, empty_value=''):
        """
        Asserts that a form field behaves correctly with various inputs.
        Args:
            fieldclass: the class of the field to be tested.
            valid: a dictionary mapping valid inputs to their expected
                    clean values.
            invalid: a dictionary mapping invalid inputs to one or more
                    raised error messages.
            field_args: the args passed to instantiate the field
            field_kwargs: the kwargs passed to instantiate the field
            empty_value: the expected run_validation output for inputs in empty_values
        """
        if field_args is None:
            field_args = []
        if field_kwargs is None:
            field_kwargs = {}
        required = fieldclass(*field_args, **field_kwargs)
        optional = fieldclass(*field_args,
                              **dict(field_kwargs, required=False, allow_blank=True))
        # test valid inputs
        for input, output in valid.items():
            self.assertEqual(required.run_validation(input), output)
            self.assertEqual(optional.run_validation(input), output)
        # test invalid inputs
        for input, errors in invalid.items():
            with self.assertRaises(ValidationError) as context_manager:
                required.run_validation(input)
            self.assertEqual(context_manager.exception.detail, errors)

        # TODO: Fix optional to serializer fields
        #     with self.assertRaises(ValidationError) as context_manager:
        #         optional.run_validation(input)

        #     self.assertEqual(context_manager.exception.detail, errors)
        # test required inputs
        # error_required = [force_text(required.error_messages['required'])]
        # for e in EMPTY_VALUES:
        #     with self.assertRaises(ValidationError) as context_manager:
        #         required.run_validation(e)
        #     self.assertEqual(context_manager.exception.detail,
        #                      error_required)
        #     self.assertEqual(optional.run_validation(e), empty_value)
        # test that max_length and min_length are always accepted
        if issubclass(fieldclass, CharField):
            field_kwargs.update({'min_length': 2, 'max_length': 20})
            self.assertIsInstance(fieldclass(*field_args, **field_kwargs),
                                  fieldclass)


text:
using APIService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace APIService.Services
{
    public class BooksService : IBooksService
    {
        private List<Book> _books = new List<Book>();
        public BooksService()
        {
            InitBooks();
        }

        private void InitBooks()
        {
            _books.AddRange(Enumerable.Range(0, 30).Select(x => new Book { BookId = x, Title = $"title {x}", Publisher = "sample pub" }));
        }

        public IEnumerable<Book> GetBooks() => _books;

        public Book GetBook(int id) => _books.SingleOrDefault(b => b.BookId == id);

        public Book AddBook(Book book)
        {
            book.BookId = _books.Max(b => b.BookId) + 1;
            _books.Add(book);
            return book;
        }
    }
}


text:
package org.openfact.connections.jpa;

import org.hibernate.jpa.AvailableSettings;
import org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform;
import org.jboss.logging.Logger;
import org.openfact.Config;
import org.openfact.ServerStartupError;
import org.openfact.connections.jpa.updater.JpaUpdaterProvider;
import org.openfact.connections.jpa.util.JpaUtils;
import org.openfact.models.OpenfactSession;
import org.openfact.models.OpenfactSessionFactory;
import org.openfact.models.OpenfactSessionTask;
import org.openfact.models.dblock.DBLockManager;
import org.openfact.models.dblock.DBLockProvider;
import org.openfact.models.utils.OpenfactModelUtils;
import org.openfact.provider.ServerInfoAwareProviderFactory;
import org.openfact.timer.TimerProvider;
import org.openfact.transaction.JtaTransactionManagerLookup;

import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.SynchronizationType;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Stian Thorgersen
 */
public class DefaultJpaConnectionProviderFactory implements JpaConnectionProviderFactory, ServerInfoAwareProviderFactory {

    private static final Logger logger = Logger.getLogger(DefaultJpaConnectionProviderFactory.class);

    enum MigrationStrategy {
        UPDATE, VALIDATE, MANUAL
    }

    private volatile EntityManagerFactory emf;

    private Config.Scope config;

    private Map<String, String> operationalInfo;

    private boolean jtaEnabled;
    private JtaTransactionManagerLookup jtaLookup;

    private OpenfactSessionFactory factory;

    @Override
    public JpaConnectionProvider create(OpenfactSession session) {
        logger.trace("Create JpaConnectionProvider");
        lazyInit(session);

        EntityManager em = null;
        if (!jtaEnabled) {
            logger.trace("enlisting EntityManager in JpaOpenfactTransaction");
            em = emf.createEntityManager();
        } else {

            em = emf.createEntityManager(SynchronizationType.SYNCHRONIZED);
        }
        em = PersistenceExceptionConverter.create(em);
        if (!jtaEnabled) session.getTransactionManager().enlist(new JpaOpenfactTransaction(em));
        return new DefaultJpaConnectionProvider(em);
    }

    @Override
    public void close() {
        if (emf != null) {
            emf.close();
        }
    }

    @Override
    public String getId() {
        return "default";
    }

    @Override
    public void init(Config.Scope config) {
        this.config = config;
    }

    @Override
    public void postInit(OpenfactSessionFactory factory) {
        this.factory = factory;
        checkJtaEnabled(factory);

    }

    protected void checkJtaEnabled(OpenfactSessionFactory factory) {
        jtaLookup = (JtaTransactionManagerLookup) factory.getProviderFactory(JtaTransactionManagerLookup.class);
        if (jtaLookup != null) {
            if (jtaLookup.getTransactionManager() != null) {
                jtaEnabled = true;
            }
        }
    }

    private void lazyInit(OpenfactSession session) {
        if (emf == null) {
            synchronized (this) {
                if (emf == null) {
                    OpenfactModelUtils.suspendJtaTransaction(session.getOpenfactSessionFactory(), () -> {
                        logger.debug("Initializing JPA connections");

                        Map<String, Object> properties = new HashMap<String, Object>();

                        String unitName = "openfact-default";

                        String dataSource = config.get("dataSource");
                        if (dataSource != null) {
                            if (config.getBoolean("jta", jtaEnabled)) {
                                properties.put(AvailableSettings.JTA_DATASOURCE, dataSource);
                            } else {
                                properties.put(AvailableSettings.NON_JTA_DATASOURCE, dataSource);
                            }
                        } else {
                            properties.put(AvailableSettings.JDBC_URL, config.get("url"));
                            properties.put(AvailableSettings.JDBC_DRIVER, config.get("driver"));

                            String user = config.get("user");
                            if (user != null) {
                                properties.put(AvailableSettings.JDBC_USER, user);
                            }
                            String password = config.get("password");
                            if (password != null) {
                                properties.put(AvailableSettings.JDBC_PASSWORD, password);
                            }
                        }

                        String schema = getSchema();
                        if (schema != null) {
                            properties.put(JpaUtils.HIBERNATE_DEFAULT_SCHEMA, schema);
                        }

                        MigrationStrategy migrationStrategy = getMigrationStrategy();
                        boolean initializeEmpty = config.getBoolean("initializeEmpty", true);
                        File databaseUpdateFile = getDatabaseUpdateFile();

                        properties.put("hibernate.show_sql", config.getBoolean("showSql", false));
                        properties.put("hibernate.format_sql", config.getBoolean("formatSql", true));

                        Connection connection = getConnection();
                        try {
                            prepareOperationalInfo(connection);

                            String driverDialect = detectDialect(connection);
                            if (driverDialect != null) {
                                properties.put("hibernate.dialect", driverDialect);
                            }

                            migration(migrationStrategy, initializeEmpty, schema, databaseUpdateFile, connection, session);

                            int globalStatsInterval = config.getInt("globalStatsInterval", -1);
                            if (globalStatsInterval != -1) {
                                properties.put("hibernate.generate_statistics", true);
                            }

                            logger.trace("Creating EntityManagerFactory");
                            logger.tracev("***** create EMF jtaEnabled {0} ", jtaEnabled);
                            if (jtaEnabled) {
                                properties.put(org.hibernate.cfg.AvailableSettings.JTA_PLATFORM, new AbstractJtaPlatform() {
                                    @Override
                                    protected TransactionManager locateTransactionManager() {
                                        return jtaLookup.getTransactionManager();
                                    }

                                    @Override
                                    protected UserTransaction locateUserTransaction() {
                                        return null;
                                    }
                                });
                            }
                            emf = JpaUtils.createEntityManagerFactory(session, unitName, properties, getClass().getClassLoader(), jtaEnabled);
                            logger.trace("EntityManagerFactory created");

                            if (globalStatsInterval != -1) {
                                startGlobalStats(session, globalStatsInterval);
                            }
                        } finally {
                            // Close after creating EntityManagerFactory to prevent in-mem databases from closing
                            if (connection != null) {
                                try {
                                    connection.close();
                                } catch (SQLException e) {
                                    logger.warn("Can't close connection", e);
                                }
                            }
                        }
                    });
                }
            }
        }
    }

    private File getDatabaseUpdateFile() {
        String databaseUpdateFile = config.get("migrationExport", "openfact-database-update.sql");
        return new File(databaseUpdateFile);
    }

    protected void prepareOperationalInfo(Connection connection) {
        try {
            operationalInfo = new LinkedHashMap<>();
            DatabaseMetaData md = connection.getMetaData();
            operationalInfo.put("databaseUrl", md.getURL());
            operationalInfo.put("databaseUser", md.getUserName());
            operationalInfo.put("databaseProduct", md.getDatabaseProductName() + " " + md.getDatabaseProductVersion());
            operationalInfo.put("databaseDriver", md.getDriverName() + " " + md.getDriverVersion());

            logger.debugf("Database info: %s", operationalInfo.toString());
        } catch (SQLException e) {
            logger.warn("Unable to prepare operational info due database exception: " + e.getMessage());
        }
    }

    protected String detectDialect(Connection connection) {
        String driverDialect = config.get("driverDialect");
        if (driverDialect != null && driverDialect.length() > 0) {
            return driverDialect;
        } else {
            try {
                String dbProductName = connection.getMetaData().getDatabaseProductName();
                String dbProductVersion = connection.getMetaData().getDatabaseProductVersion();

                // For MSSQL2014, we may need to fix the autodetected dialect by hibernate
                if (dbProductName.equals("Microsoft SQL Server")) {
                    String topVersionStr = dbProductVersion.split("\\.")[0];
                    boolean shouldSet2012Dialect = true;
                    try {
                        int topVersion = Integer.parseInt(topVersionStr);
                        if (topVersion < 12) {
                            shouldSet2012Dialect = false;
                        }
                    } catch (NumberFormatException nfe) {
                    }
                    if (shouldSet2012Dialect) {
                        String sql2012Dialect = "org.hibernate.dialect.SQLServer2012Dialect";
                        logger.debugf("Manually override hibernate dialect to %s", sql2012Dialect);
                        return sql2012Dialect;
                    }
                }
            } catch (SQLException e) {
                logger.warnf("Unable to detect hibernate dialect due database exception : %s", e.getMessage());
            }

            return null;
        }
    }

    protected void startGlobalStats(OpenfactSession session, int globalStatsIntervalSecs) {
        logger.debugf("Started Hibernate statistics with the interval %s seconds", globalStatsIntervalSecs);
        TimerProvider timer = session.getProvider(TimerProvider.class);
        timer.scheduleTask(new HibernateStatsReporter(emf), globalStatsIntervalSecs * 1000, "ReportHibernateGlobalStats");
    }

    public void migration(MigrationStrategy strategy, boolean initializeEmpty, String schema, File databaseUpdateFile, Connection connection, OpenfactSession session) {
        JpaUpdaterProvider updater = session.getProvider(JpaUpdaterProvider.class);

        JpaUpdaterProvider.Status status = updater.validate(connection, schema);
        if (status == JpaUpdaterProvider.Status.VALID) {
            logger.debug("Database is up-to-date");
        } else if (status == JpaUpdaterProvider.Status.EMPTY) {
            if (initializeEmpty) {
                update(connection, schema, session, updater);
            } else {
                switch (strategy) {
                    case UPDATE:
                        update(connection, schema, session, updater);
                        break;
                    case MANUAL:
                        export(connection, schema, databaseUpdateFile, session, updater);
                        throw new ServerStartupError("Database not initialized, please initialize database with " + databaseUpdateFile.getAbsolutePath(), false);
                    case VALIDATE:
                        throw new ServerStartupError("Database not initialized, please enable database initialization", false);
                }
            }
        } else {
            switch (strategy) {
                case UPDATE:
                    update(connection, schema, session, updater);
                    break;
                case MANUAL:
                    export(connection, schema, databaseUpdateFile, session, updater);
                    throw new ServerStartupError("Database not up-to-date, please migrate database with " + databaseUpdateFile.getAbsolutePath(), false);
                case VALIDATE:
                    throw new ServerStartupError("Database not up-to-date, please enable database migration", false);
            }
        }
    }

    protected void update(Connection connection, String schema, OpenfactSession session, JpaUpdaterProvider updater) {
        DBLockProvider dbLock = new DBLockManager(session).getDBLock();
        if (dbLock.hasLock()) {
            updater.update(connection, schema);
        } else {
            OpenfactModelUtils.runJobInTransaction(session.getOpenfactSessionFactory(), new OpenfactSessionTask() {
                @Override
                public void run(OpenfactSession lockSession) {
                    DBLockManager dbLockManager = new DBLockManager(lockSession);
                    DBLockProvider dbLock2 = dbLockManager.getDBLock();
                    dbLock2.waitForLock();
                    try {
                        updater.update(connection, schema);
                    } finally {
                        dbLock2.releaseLock();
                    }
                }
            });
        }
    }

    protected void export(Connection connection, String schema, File databaseUpdateFile, OpenfactSession session, JpaUpdaterProvider updater) {
        DBLockProvider dbLock = new DBLockManager(session).getDBLock();
        if (dbLock.hasLock()) {
            updater.export(connection, schema, databaseUpdateFile);
        } else {
            OpenfactModelUtils.runJobInTransaction(session.getOpenfactSessionFactory(), new OpenfactSessionTask() {
                @Override
                public void run(OpenfactSession lockSession) {
                    DBLockManager dbLockManager = new DBLockManager(lockSession);
                    DBLockProvider dbLock2 = dbLockManager.getDBLock();
                    dbLock2.waitForLock();
                    try {
                        updater.export(connection, schema, databaseUpdateFile);
                    } finally {
                        dbLock2.releaseLock();
                    }
                }
            });
        }
    }

    @Override
    public Connection getConnection() {
        try {
            String dataSourceLookup = config.get("dataSource");
            if (dataSourceLookup != null) {
                DataSource dataSource = (DataSource) new InitialContext().lookup(dataSourceLookup);
                return dataSource.getConnection();
            } else {
                Class.forName(config.get("driver"));
                return DriverManager.getConnection(config.get("url"), config.get("user"), config.get("password"));
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to connect to database", e);
        }
    }

    @Override
    public String getSchema() {
        return config.get("schema");
    }

    @Override
    public Map<String, String> getOperationalInfo() {
        return operationalInfo;
    }

    private MigrationStrategy getMigrationStrategy() {
        String migrationStrategy = config.get("migrationStrategy");
        if (migrationStrategy == null) {
            // Support 'databaseSchema' for backwards compatibility
            migrationStrategy = config.get("databaseSchema");
        }

        if (migrationStrategy != null) {
            return MigrationStrategy.valueOf(migrationStrategy.toUpperCase());
        } else {
            return MigrationStrategy.UPDATE;
        }
    }

}


text:
package util.afd;

public class BBuf {

    private byte[] byteBuffer;
    private int byteBufferLen;

    public BBuf(int capacity) {
        this.byteBuffer = new byte[capacity];
    }

    public byte[] flush() {
        byte[] buffer = new byte[this.byteBufferLen];
        System.arraycopy(this.byteBuffer, 0, buffer, 0, this.byteBufferLen);

        this.byteBufferLen = 0;
        this.byteBuffer = new byte[8 * 1024];

        return buffer;
    }

    public void append(byte b) {
        if (this.byteBufferLen == this.byteBuffer.length) {
            byte[] newBuffer = new byte[this.byteBuffer.length * 2];
            System.arraycopy(this.byteBuffer, 0, newBuffer, 0, this.byteBufferLen);
            this.byteBuffer = newBuffer;
        }

        this.byteBuffer[this.byteBufferLen] = b;
        this.byteBufferLen++;
    }

    public void append(byte[] bs) {
        if (this.byteBufferLen + bs.length >= this.byteBuffer.length) {
            byte[] newBuffer = new byte[Math.max(
                    this.byteBuffer.length * 2,
                    this.byteBufferLen + bs.length)];
            System.arraycopy(this.byteBuffer, 0, newBuffer, 0, this.byteBufferLen);
            this.byteBuffer = newBuffer;
        }

        System.arraycopy(this.byteBuffer, this.byteBufferLen, bs, 0, bs.length);
        this.byteBufferLen++;
    }

}


text:
'use strict';

/*jshint undef:false */
(function () {
  var utils = require('../utils');
  describe('app', function () {
    var ptor;
    beforeEach(function () {
      ptor = protractor.getInstance();
      console.info('\nrunning:', jasmine.getEnv().currentSpec.description);
    });

    afterEach(function () {
      if (!jasmine.getEnv().currentSpec.results().passed()) {
        utils.takeScreenshot(browser, jasmine.getEnv().currentSpec.description.replace(/ /g, '-'));
      }
    });

    it('should load the homepage', function () {
      ptor.get('/');
      expect(ptor.isElementPresent(by.css('body'))).toBe(true);
    });

    it('should navigate to the docs page when clicking', function () {
      element(by.css('a[ui-sref="root.getting-started"]')).click();
      expect(ptor.getCurrentUrl()).toMatch(/\/getting-started/);
    });

  });
})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Sample Ceylon build script using Ant.
-->
<project name="project" default="default">

    <!-- Try to determine where Ceylon is installed -->
    <condition property="batExt" value=".bat">
        <os family="windows" />
    </condition>
    <property name="batExt" value=""/>
    <exec executable="ceylon${batExt}" outputproperty="ceylon.home" failifexecutionfails="false">
        <arg value="--show-home" />
    </exec>
    <property environment="env"/>
    <property name="ceylon.home" value="../.." />
    <property name="env.CEYLON_HOME" value="${ceylon.home}"/>

    <property name="ceylon.ant.lib" value="${env.CEYLON_HOME}/lib/ceylon-ant.jar" />

    <target name="ceylon-ant-taskdefs">
        <path id="ant-tasks">
            <pathelement location="${ceylon.ant.lib}" />
        </path>
        <typedef resource="com/redhat/ceylon/ant/antlib.xml" classpathref="ant-tasks" />
    </target>

    <target name="default" depends="doc">
    </target>

    <target name="compile" depends="ceylon-ant-taskdefs">
        <ceylon-compile encoding="UTF-8">
            <module name="com.example.plugin" />
        </ceylon-compile>
    </target>

    <target name="plugin" depends="compile">
        <ceylon-plugin mode="pack">
            <module name="com.example.plugin" />
        </ceylon-plugin>
        <ceylon-plugin mode="install" local="true" force="true">
            <module name="com.example.plugin" />
        </ceylon-plugin>
    </target>

    <target name="doc" depends="plugin">
        <echo>********************************</echo>
        <echo>Now type "ceylon example-plugin"</echo>
        <echo>********************************</echo>
    </target>

    <target name="clean">
        <delete dir="modules" />
    </target>

</project>


text:
using System;
using MessagePack;
using osu.Game.Online.Rooms;

namespace osu.Game.Online.Multiplayer
{
    [Serializable]
    [MessagePackObject]
    public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
    {
        [Key(0)]
        public string Name { get; set; } = "Unnamed room";

        [Key(1)]
        public long PlaylistItemId { get; set; }

        [Key(2)]
        public string Password { get; set; } = string.Empty;

        [Key(3)]
        public MatchType MatchType { get; set; } = MatchType.HeadToHead;

        [Key(4)]
        public QueueMode QueueMode { get; set; } = QueueMode.HostOnly;

        public bool Equals(MultiplayerRoomSettings? other)
        {
            if (ReferenceEquals(this, other)) return true;
            if (other == null) return false;

            return Password.Equals(other.Password, StringComparison.Ordinal)
                   && Name.Equals(other.Name, StringComparison.Ordinal)
                   && PlaylistItemId == other.PlaylistItemId
                   && MatchType == other.MatchType
                   && QueueMode == other.QueueMode;
        }

        public override string ToString() => $"Name:{Name}"
                                             + $" Password:{(string.IsNullOrEmpty(Password) ? "no" : "yes")}"
                                             + $" Type:{MatchType}"
                                             + $" Item:{PlaylistItemId}"
                                             + $" Queue:{QueueMode}";
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Ruby Concepts: the Enumerable "any?" Method</title>
  <meta name="description" content="What is the any? Method?">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://mrrts.github.io/ruby/enumerable/2016/01/28/ruby-enumerable-any.html">
  <link rel="alternate" type="application/rss+xml" title="Ryan Smith, Web Developer in Chicago, IL" href="http://mrrts.github.io/feed.xml">

    Ryan Smith, Web Developer in Chicago, IL

        <svg viewBox="0 0 18 15">
          <path fill="#424242" d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.031C17.335,0,18,0.665,18,1.484L18,1.484z"/>
          <path fill="#424242" d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484 h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z"/>
          <path fill="#424242" d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z"/>
        </svg>

            About

            Blog

Ruby Concepts: the Enumerable "any?" Method

<time datetime="2016-01-28T10:56:33-06:00" itemprop="datePublished">Jan 28, 2016</time>

What is the any? Method?

The Enumerable module in Ruby contains many useful methods that can traverse, search, and sort arrays and hashes.

The any? method is used to search through the object and evaluate each item in it using the block that you supply. If any of the items causes that block to return true, the any? method itself will return true. If none of the items causes the block to evaluate to true, then the any? method will return false.

Usage

Consider the following code, which determines whether there are any even numbers in the array.

my_array = [3, 7, 5, 1]
my_other_array = [3, 7, 6, 5, 1]

my_array.any? {|item| item % 2 == 0}
    # returns FALSE

my_other_array.any? {|item| item % 2 == 0}
    # returns TRUE

We called the any? method on our arrays, and then we supplied a block to it ({ ... }). Then, in between the pipes we created a variable to refer to the current item we're testing in the array: |item|. Then, we wrote an expression to evaluate using that current item: item % 2 == 0. This expression will evaluate as true if the item is an even number, and it will evaluate to false if it isn't. If any of the items cause that expression to evaluate as true, then the whole any? method will return true. The method essentially asks, "Are any of the numbers in this list even?"

Example With Strings

Let's use the any? method in a game to evaluate whether the user was able to successfully, say, describe a koala using only words with 4 letters or fewer.

response1 = "It is wee and can look like a bear in a tree"
response2 = "It is a wee animal with a soft bear face"
responses = [response1, response2]

responses.each do |response|
    if response.split(' ').any? {|word| word.length > 4}
        puts "'#{response}' is not a winning sentence."
    else
        puts "'#{response}' is a winning sentence!"
    end
end

This outputs the following:

'It is a wee and can look like a bear in a tree' is a winning sentence!

'It is a wee animal with a soft bear face' is not a winning sentence.

Contact

mrryantsmith@gmail.com

              GitHub

              LinkedIn

I am a growing full-stack web developer in Chicago, IL. I'm currently attending DevBootcamp and looking forward to starting this new career adventure.


text:
package com.subinkrishna.circularimageview.demo.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.subinkrishna.widget.CircularImageView;

/**
 * Extension of CircularImageView that overrides the check mark color and width.
 *
 * @author Subinkrishna Gopi
 */
public class AvatarView extends CircularImageView {

    public AvatarView(Context context) {
        this(context, null, 0);
    }

    public AvatarView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AvatarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        allowCheckStateAnimation(true);
    }

    @Override
    protected Paint getCheckMarkPaint() {
        Paint paint = super.getCheckMarkPaint();
        // Overriding stroke color
        paint.setColor(Color.WHITE);
        return paint;
    }

    @Override
    protected int getCheckMarkStrokeWidthInPixels() {
        // Overriding stroke width to 5dp (default is 3dp)
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                8, // DIPs
                getResources().getDisplayMetrics());
    }

    @Override
    protected boolean shouldDrawBorder() {
        return true;
    }
}


text:
layout: docs
title: CoffeeScript Support
permalink: /documentation/test-api/coffeescript-support.html
---
# CoffeeScript Support

TestCafe allows you to write tests with [CoffeeScript](https://coffeescript.org/).

**Example**

```coffee
import { Selector } from 'testcafe'

fixture 'CoffeeScript Example'
    .page 'https://devexpress.github.io/testcafe/example/'

nameInput = Selector '#developer-name'

test 'Test', (t) =>
    await t
        .typeText(nameInput, 'Peter')
        .typeText(nameInput, 'Paker', { replace: true })
        .typeText(nameInput, 'r', { caretPos: 2 })
        .expect(nameInput.value).eql 'Parker';
```

You can run CoffeeScript tests in the same manner as JavaScript tests. TestCafe automatically compiles the CoffeeScript code, so you do not need to compile it manually.


text:
Add movie

    <form>

            Favourite lists

            <select ng-model="value" ng-options="obj.name for obj in favouriteLists"></select>

    </form>

    <button class="btn btn-primary" ng-click="ok()">OK</button>
    <button class="btn btn-warning" ng-click="cancel()">Cancel</button>


text:
package ch.open.arquillian.lab02;

public interface FluidOuncesConverter {

    double convertToMilliliters(double ounces);

}


text:
<?php

namespace React\Promise;

class When
{
    public static function resolve($promiseOrValue = null)
    {
        return Util::promiseFor($promiseOrValue);
    }

    public static function reject($promiseOrValue = null)
    {
        return Util::rejectedPromiseFor($promiseOrValue);
    }

    public static function lazy($factory)
    {
        return new LazyPromise($factory);
    }

    public static function all($promisesOrValues, $fulfilledHandler = null, $errorHandler = null, $progressHandler = null)
    {
        $promise = static::map($promisesOrValues, function ($val) {
            return $val;
        });

        return $promise->then($fulfilledHandler, $errorHandler, $progressHandler);
    }

    public static function any($promisesOrValues, $fulfilledHandler = null, $errorHandler = null, $progressHandler = null)
    {
        $unwrapSingleResult = function ($val) use ($fulfilledHandler) {
            $val = array_shift($val);

            return $fulfilledHandler ? $fulfilledHandler($val) : $val;
        };

        return static::some($promisesOrValues, 1, $unwrapSingleResult, $errorHandler, $progressHandler);
    }

    public static function some($promisesOrValues, $howMany, $fulfilledHandler = null, $errorHandler = null, $progressHandler = null)
    {
        return When::resolve($promisesOrValues)->then(function ($array) use ($howMany, $fulfilledHandler, $errorHandler, $progressHandler) {
            if (!is_array($array)) {
                $array = array();
            }

            $len       = count($array);
            $toResolve = max(0, min($howMany, $len));
            $values    = array();
            $deferred  = new Deferred();

            if (!$toResolve) {
                $deferred->resolve($values);
            } else {
                $toReject = ($len - $toResolve) + 1;
                $reasons  = array();

                $progress = array($deferred, 'progress');

                $fulfillOne = function ($val, $i) use (&$values, &$toResolve, $deferred) {
                    $values[$i] = $val;

                    if (0 === --$toResolve) {
                        $deferred->resolve($values);

                        return true;
                    }
                };

                $rejectOne = function ($reason, $i) use (&$reasons, &$toReject, $deferred) {
                    $reasons[$i] = $reason;

                    if (0 === --$toReject) {
                        $deferred->reject($reasons);

                        return true;
                    }
                };

                foreach ($array as $i => $promiseOrValue) {
                    $fulfiller = function ($val) use ($i, &$fulfillOne, &$rejectOne) {
                        $reset = $fulfillOne($val, $i);

                        if (true === $reset) {
                            $fulfillOne = $rejectOne = function () {};
                        }
                    };

                    $rejecter = function ($val) use ($i, &$fulfillOne, &$rejectOne) {
                        $reset = $rejectOne($val, $i);

                        if (true === $reset) {
                            $fulfillOne = $rejectOne = function () {};
                        }
                    };

                    When::resolve($promiseOrValue)->then($fulfiller, $rejecter, $progress);
                }
            }

            return $deferred->then($fulfilledHandler, $errorHandler, $progressHandler);
        });
    }

    public static function map($promisesOrValues, $mapFunc)
    {
        return When::resolve($promisesOrValues)->then(function ($array) use ($mapFunc) {
            if (!is_array($array)) {
                $array = array();
            }

            $toResolve = count($array);
            $results   = array();
            $deferred  = new Deferred();

            if (!$toResolve) {
                $deferred->resolve($results);
            } else {
                $resolve = function ($item, $i) use ($mapFunc, &$results, &$toResolve, $deferred) {
                    When::resolve($item)
                        ->then($mapFunc)
                        ->then(
                            function ($mapped) use (&$results, $i, &$toResolve, $deferred) {
                                $results[$i] = $mapped;

                                if (0 === --$toResolve) {
                                    $deferred->resolve($results);
                                }
                            },
                            array($deferred, 'reject')
                        );
                };

                foreach ($array as $i => $item) {
                    $resolve($item, $i);
                }
            }

            return $deferred->promise();
        });
    }

    public static function reduce($promisesOrValues, $reduceFunc , $initialValue = null)
    {
        return When::resolve($promisesOrValues)->then(function ($array) use ($reduceFunc, $initialValue) {
            if (!is_array($array)) {
                $array = array();
            }

            $total = count($array);
            $i = 0;

            // Wrap the supplied $reduceFunc with one that handles promises and then
            // delegates to the supplied.
            $wrappedReduceFunc = function ($current, $val) use ($reduceFunc, $total, &$i) {
                return When::resolve($current)->then(function ($c) use ($reduceFunc, $total, &$i, $val) {
                    return When::resolve($val)->then(function ($value) use ($reduceFunc, $total, &$i, $c) {
                        return call_user_func($reduceFunc, $c, $value, $i++, $total);
                    });
                });
            };

            return array_reduce($array, $wrappedReduceFunc, $initialValue);
        });
    }
}


text:
diirt: Data Integration In Real-Time
====================================

The full documentation is provided in the [project wiki](https://github.com/diirt/diirt/wiki).

The documentation includes information for different use cases (using Diirt, contributing to Diirt, etc.).


text:
<resources>
    <string name="ip_all_images">所有图片</string>
    <string name="ip_folder_image_count">共%1$d张</string>
    <string name="ip_preview_image_count">%1$d/%2$d</string>
    <string name="ip_select_limit">最多选择%1$d张图片</string>
    <string name="ip_complete">完成</string>
    <string name="ip_select_complete">完成(%1$d/%2$d)</string>
    <string name="ip_preview">预览</string>
    <string name="ip_preview_count">预览(%1$d)</string>
    <string name="ip_photo_crop">图片裁剪</string>
    <string name="ip_origin">原图</string>
    <string name="ip_origin_size">原图(%1$s)</string>
</resources>


text:
<com.tle.beans.mime.MimeEntry>
  <id>116224</id>
  <institution>
    <id>116095</id>
    <uniqueId>0</uniqueId>
    <enabled>true</enabled>
  </institution>
  <extensions class="list"/>
  <type>equella/attachment-youtube</type>
  <attributes/>
</com.tle.beans.mime.MimeEntry>


text:
var mongoose = require('mongoose'),
    approvable = require('./Approvable.js'),
    element = require('./Element.js');

var Comment = new mongoose.Schema({
    author: {type : mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
    parent: {type : mongoose.Schema.Types.ObjectId, required: true },
    content: {type : String, required: true }
});

Comment.plugin(element);
Comment.plugin(approvable);

Comment.statics.queryDefaults.populate = 'author';

Comment.statics.queries.byParent = function (id) {
    this._query.and({
        parent: id
    });

    return this;
};

module.exports = mongoose.model('Comment', Comment);


text:
    #pragma implementation "dbgrid.h"
#endif

#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_ODBC
#if wxUSE_GRID

#ifndef WX_PRECOMP
    #include "wx/textctrl.h"
    #include "wx/dc.h"
#endif // WX_PRECOMP

#include "wx/generic/gridctrl.h"
#include "wx/dbgrid.h"

// DLL options compatibility check:
#include "wx/app.h"
WX_CHECK_BUILD_OPTIONS("wxDbGrid")

wxDbGridCellAttrProvider::wxDbGridCellAttrProvider()
{
    m_data=NULL;
    m_ColInfo=NULL;
}

wxDbGridCellAttrProvider::wxDbGridCellAttrProvider(wxDbTable *tab, wxDbGridColInfoBase* ColInfo)
{
    m_data=tab;
    m_ColInfo=ColInfo;
}

wxDbGridCellAttrProvider::~wxDbGridCellAttrProvider()
{
}

wxGridCellAttr *wxDbGridCellAttrProvider::GetAttr(int row, int col,
                                      wxGridCellAttr::wxAttrKind  kind) const
{
    wxGridCellAttr *attr = wxGridCellAttrProvider::GetAttr(row,col,kind);

    if (m_data && m_ColInfo && (m_data->GetNumberOfColumns() > m_ColInfo[col].DbCol))
    {
        //FIXME: this test could.
        //  ??::InsertPending == m_data->get_ModifiedStatus()
        //  and if InsertPending use colDef[].InsertAllowed
        if (!(m_data->GetColDefs()[(m_ColInfo[col].DbCol)].Updateable))
        {
            switch(kind)
            {
                case (wxGridCellAttr::Any):
                    if (!attr)
                    {
                        attr = new wxGridCellAttr;
                        // Store so we don't keep creating / deleting this...
                        wxDbGridCellAttrProvider * self = wxConstCast(this, wxDbGridCellAttrProvider) ;
                        attr->IncRef();
                        self->SetColAttr(attr, col);
                        attr->SetReadOnly();
                    }
                    else
                    {
                        //We now must check what we were returned. and do the right thing (tm)
                        wxGridCellAttr::wxAttrKind attrkind = attr->GetKind();
                        if ((attrkind == (wxGridCellAttr::Default)) || (attrkind == (wxGridCellAttr::Cell)) ||
                            (attrkind == (wxGridCellAttr::Col)))
                        {
                                wxGridCellAttr *attrtomerge = attr;
                                attr = new wxGridCellAttr;
                                attr->SetKind(wxGridCellAttr::Merged);
                                attr->MergeWith(attrtomerge);
                                attr->SetReadOnly();
                                attrtomerge->DecRef();
                        }
                        attr->SetReadOnly();
                    }
                break;
                case (wxGridCellAttr::Col):
                    //As we must have a Coll, and were setting Coll attributes
                    // we can based on wxdbTable's so just set RO if attr valid
                    if (!attr)
                    {
                        attr = new wxGridCellAttr;
                        wxDbGridCellAttrProvider * self = wxConstCast(this, wxDbGridCellAttrProvider) ;
                        attr->IncRef();
                        self->SetColAttr(attr, col);
                    }
                    attr->SetReadOnly();
                break;
                default:
                    //Dont add RO for...
                    //  wxGridCellAttr::Cell - Not required, will inherit on merge from row.
                    //  wxGridCellAttr::Row - If wxDbtable ever supports row locking could add
                    //                        support to make RO on a row basis also.
                    //  wxGridCellAttr::Default - Don't edit this ! or all cell with a attr will become readonly
                    //  wxGridCellAttr::Merged - This should never be asked for.
                break;
            }
        }

    }
    return attr;
}

void wxDbGridCellAttrProvider::AssignDbTable(wxDbTable *tab)
{
    m_data = tab;
}

wxDbGridTableBase::wxDbGridTableBase(wxDbTable *tab, wxDbGridColInfo*  ColInfo,
                     int count, bool takeOwnership)  :
    m_keys(),
    m_data(tab),
    m_dbowner(takeOwnership),
    m_rowmodified(false)
{

    if (count == wxUSE_QUERY)
    {
        m_rowtotal = m_data ? m_data->Count() : 0;
    }
    else
    {
        m_rowtotal = count;
    }
//    m_keys.Size(m_rowtotal);
    m_row = -1;
    if (ColInfo)
    {
        m_nocols = ColInfo->Length();
        m_ColInfo = new wxDbGridColInfoBase[m_nocols];
        //Do Copy.
        wxDbGridColInfo *ptr = ColInfo;
        int i =0;
        while (ptr && i < m_nocols)
        {
            m_ColInfo[i] = ptr->m_data;
            ptr = ptr->m_next;
            i++;
        }
#ifdef __WXDEBUG__
        if (ptr)
        {
            wxLogDebug(wxT("NoCols over length after traversing %i items"),i);
        }
        if (i < m_nocols)
        {
            wxLogDebug(wxT("NoCols under length after traversing %i items"),i);
        }
#endif
    }
}

wxDbGridTableBase::~wxDbGridTableBase()
{
    wxDbGridCellAttrProvider *provider;

    //Can't check for update here as

    //FIXME: should i remove m_ColInfo and m_data from m_attrProvider if a wxDbGridAttrProvider
//    if ((provider = dynamic_cast<wxDbGridCellAttrProvider *>(GetAttrProvider())))
     // Using C casting for now until we can support dynamic_cast with wxWidgets
    provider = (wxDbGridCellAttrProvider *)(GetAttrProvider());
    if (provider)
    {
        provider->AssignDbTable(NULL);
    }
    delete [] m_ColInfo;

    Writeback();
    if (m_dbowner)
    {
        delete m_data;
    }
}

bool wxDbGridTableBase::CanHaveAttributes()
{
    if (!GetAttrProvider())
    {
        // use the default attr provider by default
        SetAttrProvider(new wxDbGridCellAttrProvider(m_data, m_ColInfo));
    }
    return true;
}

bool wxDbGridTableBase::AssignDbTable(wxDbTable *tab, int count, bool takeOwnership)
{
    wxDbGridCellAttrProvider *provider;

    //Remove Information from grid about old data
    if (GetView())
    {
        wxGrid *grid = GetView();
        grid->BeginBatch();
        grid->ClearSelection();
        if (grid->IsCellEditControlEnabled())
        {
            grid->DisableCellEditControl();
        }
        wxGridTableMessage msg(this, wxGRIDTABLE_NOTIFY_ROWS_DELETED,0,m_rowtotal);
        grid->ProcessTableMessage(msg);
    }

    //reset our internals...
    Writeback();
    if (m_dbowner)
    {
        delete m_data;
    }
    m_keys.Empty();
    m_data = tab;
    //FIXME: Remove dynamic_cast before sumision to wxwin
//    if ((provider = dynamic_cast<wxDbGridCellAttrProvider *> (GetAttrProvider())))
     // Using C casting for now until we can support dynamic_cast with wxWidgets
    provider = (wxDbGridCellAttrProvider *)(GetAttrProvider());
    if (provider)
    {
        provider->AssignDbTable(m_data);
    }

    if (count == wxUSE_QUERY)
    {
        m_rowtotal = m_data ? m_data->Count() : 0;
    }
    else
    {
         m_rowtotal = count;
    }
    m_row = -1;

    //Add Information to grid about new data
    if (GetView())
    {
        wxGrid * grid = GetView();
        wxGridTableMessage msg(this, wxGRIDTABLE_NOTIFY_ROWS_APPENDED, m_rowtotal);
        grid->ProcessTableMessage(msg);
        grid->EndBatch();
    }
    m_dbowner = takeOwnership;
    m_rowmodified = false;
    return true;
}

wxString wxDbGridTableBase::GetTypeName(int WXUNUSED(row), int col)
{
    if (GetNumberCols() > col)
    {
        if (m_ColInfo[col].wxtypename == wxGRID_VALUE_DBAUTO)
        {
            if (m_data->GetNumberOfColumns() <= m_ColInfo[col].DbCol)
            {
                wxFAIL_MSG (_T("You can not use wxGRID_VALUE_DBAUTO for virtual columns"));
            }
            switch(m_data->GetColDefs()[(m_ColInfo[col].DbCol)].SqlCtype)
            {
                case SQL_C_CHAR:
#ifdef SQL_C_WCHAR
                case SQL_C_WCHAR:
#endif
                    return wxGRID_VALUE_STRING;
                case SQL_C_SHORT:
                case SQL_C_SSHORT:
                    return wxGRID_VALUE_NUMBER;
                case SQL_C_USHORT:
                    return wxGRID_VALUE_NUMBER;
                case SQL_C_LONG:
                case SQL_C_SLONG:
                    return wxGRID_VALUE_NUMBER;
                case SQL_C_ULONG:
                    return wxGRID_VALUE_NUMBER;
                case SQL_C_FLOAT:
                    return wxGRID_VALUE_FLOAT;
                case SQL_C_DOUBLE:
                    return wxGRID_VALUE_FLOAT;
                case SQL_C_DATE:
                    return wxGRID_VALUE_DATETIME;
                case SQL_C_TIME:
                    return wxGRID_VALUE_DATETIME;
                case SQL_C_TIMESTAMP:
                    return wxGRID_VALUE_DATETIME;
                default:
                    return wxGRID_VALUE_STRING;
            }
        }
        else
        {
            return m_ColInfo[col].wxtypename;
        }
    }
    wxFAIL_MSG (_T("unknown column"));
    return wxString();
}

bool wxDbGridTableBase::CanGetValueAs(int row, int col, const wxString& typeName)
{
    wxLogDebug(wxT("CanGetValueAs() on %i,%i"),row,col);
    //Is this needed? As it will be validated on GetValueAsXXXX
    ValidateRow(row);

    if (typeName == wxGRID_VALUE_STRING)
    {
        //FIXME ummm What about blob field etc.
        return true;
    }

    if (m_data->IsColNull((UWORD)m_ColInfo[col].DbCol))
    {
        return false;
    }

    if (m_data->GetNumberOfColumns() <= m_ColInfo[col].DbCol)
    {
        //If a virtual column then we can't find it's type. we have to
        // return false to get using wxVariant.
        return false;
    }
    int sqltype = m_data->GetColDefs()[(m_ColInfo[col].DbCol)].SqlCtype;

    if (typeName == wxGRID_VALUE_DATETIME)
    {
        if ((sqltype == SQL_C_DATE) ||
            (sqltype == SQL_C_TIME) ||
            (sqltype == SQL_C_TIMESTAMP))
        {
            return true;
        }
        return false;
    }
    if (typeName == wxGRID_VALUE_NUMBER)
    {
        if ((sqltype == SQL_C_SSHORT) ||
            (sqltype == SQL_C_USHORT) ||
            (sqltype == SQL_C_SLONG)  ||
            (sqltype == SQL_C_ULONG))
        {
            return true;
        }
        return false;
    }
    if (typeName == wxGRID_VALUE_FLOAT)
    {
        if ((sqltype == SQL_C_SSHORT) ||
            (sqltype == SQL_C_USHORT) ||
            (sqltype == SQL_C_SLONG)  ||
            (sqltype == SQL_C_ULONG)  ||
            (sqltype == SQL_C_FLOAT)  ||
            (sqltype == SQL_C_DOUBLE))
        {
            return true;
        }
        return false;
    }
    return false;
}

bool wxDbGridTableBase::CanSetValueAs(int WXUNUSED(row), int col, const wxString& typeName)
{
    if (typeName == wxGRID_VALUE_STRING)
    {
        //FIXME ummm What about blob field etc.
        return true;
    }

    if (!(m_data->GetColDefs()[(m_ColInfo[col].DbCol)].Updateable))
    {
        return false;
    }

    if (m_data->GetNumberOfColumns() <= m_ColInfo[col].DbCol)
    {
        //If a virtual column then we can't find it's type. we have to faulse to
        //get using wxVairent.
        return false;
    }

    int sqltype = m_data->GetColDefs()[(m_ColInfo[col].DbCol)].SqlCtype;
    if (typeName == wxGRID_VALUE_DATETIME)
    {
        if ((sqltype == SQL_C_DATE) ||
            (sqltype == SQL_C_TIME) ||
            (sqltype == SQL_C_TIMESTAMP))
        {
            return true;
        }
        return false;
    }
    if (typeName == wxGRID_VALUE_NUMBER)
    {
        if ((sqltype == SQL_C_SSHORT) ||
            (sqltype == SQL_C_USHORT) ||
            (sqltype == SQL_C_SLONG)  ||
            (sqltype == SQL_C_ULONG))
        {
            return true;
        }
        return false;
    }
    if (typeName == wxGRID_VALUE_FLOAT)
    {
        if ((sqltype == SQL_C_SSHORT) ||
            (sqltype == SQL_C_USHORT) ||
            (sqltype == SQL_C_SLONG)  ||
            (sqltype == SQL_C_ULONG)  ||
            (sqltype == SQL_C_FLOAT)  ||
            (sqltype == SQL_C_DOUBLE))
        {
            return true;
        }
        return false;
    }
    return false;
}

long wxDbGridTableBase::GetValueAsLong(int row, int col)
{
    ValidateRow(row);

    if (m_data->GetNumberOfColumns() <= m_ColInfo[col].DbCol)
    {
        wxFAIL_MSG (_T("You can not use GetValueAsLong for virtual columns"));
        return 0;
    }
    int sqltype = m_data->GetColDefs()[(m_ColInfo[col].DbCol)].SqlCtype;
    if ((sqltype == SQL_C_SSHORT) ||
        (sqltype == SQL_C_USHORT) ||
        (sqltype == SQL_C_SLONG) ||
        (sqltype == SQL_C_ULONG))
    {
        wxVariant val = m_data->GetColumn(m_ColInfo[col].DbCol);
        return val.GetLong();
    }
    wxFAIL_MSG (_T("unknown column, "));
    return 0;
}

double wxDbGridTableBase::GetValueAsDouble(int row, int col)
{
    wxLogDebug(wxT("GetValueAsDouble() on %i,%i"),row,col);
    ValidateRow(row);

    if (m_data->GetNumberOfColumns() <= m_ColInfo[col].DbCol)
    {
        wxFAIL_MSG (_T("You can not use GetValueAsDouble for virtual columns"));
        return 0.0;
    }
    int sqltype = m_data->GetColDefs()[(m_ColInfo[col].DbCol)].SqlCtype;
    if ((sqltype == SQL_C_SSHORT) ||
        (sqltype == SQL_C_USHORT) ||
        (sqltype == SQL_C_SLONG) ||
        (sqltype == SQL_C_ULONG) ||
        (sqltype == SQL_C_FLOAT) ||
        (sqltype == SQL_C_DOUBLE))
    {
        wxVariant val = m_data->GetColumn(m_ColInfo[col].DbCol);
        return val.GetDouble();
    }
    wxFAIL_MSG (_T("unknown column"));
    return 0.0;
}

bool wxDbGridTableBase::GetValueAsBool(int row, int col)
{
    wxLogDebug(wxT("GetValueAsBool() on %i,%i"),row,col);
    ValidateRow(row);

    if (m_data->GetNumberOfColumns() <= m_ColInfo[col].DbCol)
    {
        wxFAIL_MSG (_T("You can not use GetValueAsBool for virtual columns"));
        return 0;
    }
    int sqltype = m_data->GetColDefs()[(m_ColInfo[col].DbCol)].SqlCtype;
    if ((sqltype == SQL_C_SSHORT) ||
        (sqltype == SQL_C_USHORT) ||
        (sqltype == SQL_C_SLONG) ||
        (sqltype == SQL_C_ULONG))
    {
        wxVariant val = m_data->GetColumn(m_ColInfo[col].DbCol);
        return val.GetBool();
    }
    wxFAIL_MSG (_T("unknown column, "));
    return 0;
}

void* wxDbGridTableBase::GetValueAsCustom(int row, int col, const wxString& typeName)
{
    wxLogDebug(wxT("GetValueAsCustom() on %i,%i"),row,col);
    ValidateRow(row);

    if (m_data->GetNumberOfColumns() <= m_ColInfo[col].DbCol)
    {
        wxFAIL_MSG (_T("You can not use GetValueAsCustom for virtual columns"));
        return NULL;
    }
    if (m_data->IsColNull((UWORD)m_ColInfo[col].DbCol))
        return NULL;

    if (typeName == wxGRID_VALUE_DATETIME)
    {
        wxDbColDef *pColDefs = m_data->GetColDefs();
        int sqltype = pColDefs[(m_ColInfo[col].DbCol)].SqlCtype;

        if ((sqltype == SQL_C_DATE) ||
            (sqltype == SQL_C_TIME) ||
            (sqltype == SQL_C_TIMESTAMP))
        {
            wxVariant val = m_data->GetColumn(m_ColInfo[col].DbCol);
            return new wxDateTime(val.GetDateTime());
        }
    }
    wxFAIL_MSG (_T("unknown column data type "));
    return NULL;
}

void wxDbGridTableBase::SetValueAsCustom(int row, int col, const wxString& typeName, void* value)
{
    wxLogDebug(wxT("SetValueAsCustom() on %i,%i"),row,col);
    ValidateRow(row);

    if (m_data->GetNumberOfColumns() <= m_ColInfo[col].DbCol)
    {
        wxFAIL_MSG (_T("You can not use SetValueAsCustom for virtual columns"));
        return;
    }

    if (typeName == wxGRID_VALUE_DATETIME)
    {
        int sqltype = m_data->GetColDefs()[(m_ColInfo[col].DbCol)].SqlCtype;
        if ((sqltype == SQL_C_DATE) ||
            (sqltype == SQL_C_TIME) ||
            (sqltype == SQL_C_TIMESTAMP))
        {
            //FIXME: you can't dynamic_cast from (void *)
            //wxDateTime *date = wxDynamicCast(value, wxDateTime);
            wxDateTime *date = (wxDateTime *)value;
            if (!date)
            {
                wxFAIL_MSG (_T("Failed to convert data"));
                return;
            }
            wxVariant val(date);
            m_rowmodified = true;
            m_data->SetColumn(m_ColInfo[col].DbCol,val);
        }
    }
    wxFAIL_MSG (_T("unknown column data type"));
    return ;
}

wxString wxDbGridTableBase::GetColLabelValue(int col)
{
    if (GetNumberCols() > col)
    {
        return m_ColInfo[col].Title;
    }
    wxFAIL_MSG (_T("unknown column"));
    return wxString();
}

bool wxDbGridTableBase::IsEmptyCell(int row, int col)
{
    wxLogDebug(wxT("IsEmtpyCell on %i,%i"),row,col);

    ValidateRow(row);
    return m_data->IsColNull((UWORD)m_ColInfo[col].DbCol);
}

wxString wxDbGridTableBase::GetValue(int row, int col)
{
    wxLogDebug(wxT("GetValue() on %i,%i"),row,col);

    ValidateRow(row);
    wxVariant val = m_data->GetColumn(m_ColInfo[col].DbCol);
    wxLogDebug(wxT("\tReturning \"%s\"\n"),val.GetString().c_str());

    return val.GetString();
}

void wxDbGridTableBase::SetValue(int row, int col,const wxString& value)
{
    wxLogDebug(wxT("SetValue() on %i,%i"),row,col);

    ValidateRow(row);
    wxVariant val(value);

    m_rowmodified = true;
    m_data->SetColumn(m_ColInfo[col].DbCol,val);
}

void wxDbGridTableBase::SetValueAsLong(int row, int col, long value)
{
    wxLogDebug(wxT("SetValueAsLong() on %i,%i"),row,col);

    ValidateRow(row);
    wxVariant val(value);

    m_rowmodified = true;
    m_data->SetColumn(m_ColInfo[col].DbCol,val);
}

void wxDbGridTableBase::SetValueAsDouble(int row, int col, double value)
{
    wxLogDebug(wxT("SetValueAsDouble() on %i,%i"),row,col);

    ValidateRow(row);
    wxVariant val(value);

    m_rowmodified = true;
    m_data->SetColumn(m_ColInfo[col].DbCol,val);

}

void wxDbGridTableBase::SetValueAsBool(int row, int col, bool value)
{
    wxLogDebug(wxT("SetValueAsBool() on %i,%i"),row,col);

    ValidateRow(row);
    wxVariant val(value);

    m_rowmodified = true;
    m_data->SetColumn(m_ColInfo[col].DbCol,val);
}

void wxDbGridTableBase::ValidateRow(int row)
{
    wxLogDebug(wxT("ValidateRow(%i) currently on row (%i). Array count = %i"),row,m_row,m_keys.GetCount());

    if (row == m_row)
         return;
    Writeback();

    //We add to row as Count is unsigned!
    if ((unsigned)(row+1) > m_keys.GetCount())
    {
        wxLogDebug(wxT("\trow key unknown"));
        // Extend Array, iterate through data filling with keys
        m_data->SetRowMode(wxDbTable::WX_ROW_MODE_QUERY);
        int trow;
        for (trow = m_keys.GetCount(); trow <= row; trow++)
        {
            wxLogDebug(wxT("Fetching row %i.."), trow);
            bool ret = m_data->GetNext();

            wxLogDebug(wxT(" ...success=(%i)"),ret);
            GenericKey k = m_data->GetKey();
            m_keys.Add(k);
        }
        m_row = row;
    }
    else
    {
        wxLogDebug(wxT("\trow key known centering data"));
        GenericKey k = m_keys.Item(row);
        m_data->SetRowMode(wxDbTable::WX_ROW_MODE_INDIVIDUAL);
        m_data->ClearMemberVars();
        m_data->SetKey(k);
        if (!m_data->QueryOnKeyFields())
        {
            wxDbLogExtendedErrorMsg(_T("ODBC error during Query()\n\n"), m_data->GetDb(),__TFILE__,__LINE__);
        }

        m_data->GetNext();

        m_row = row;
    }
    m_rowmodified = false;
}

bool wxDbGridTableBase::Writeback() const
{
    if (!m_rowmodified)
    {
        return true;
    }

    bool result=true;
    wxLogDebug(wxT("\trow key unknown"));

// FIXME: this code requires dbtable support for record status
#if 0
    switch (m_data->get_ModifiedStatus())
    {
        case wxDbTable::UpdatePending:
            result = m_data->Update();
           break;
        case wxDbTable::InsertPending:
            result = (m_data->Insert() == SQL_SUCCESS);
        break;
        default:
            //Nothing
        break;
    }
#else
    wxLogDebug(wxT("WARNING : Row writeback not implemented "));
#endif
    return result;
}

#include "wx/arrimpl.cpp"

WX_DEFINE_EXPORTED_OBJARRAY(keyarray);

#endif  // #if wxUSE_GRID
#endif  // #if wxUSE_ODBC


text:
require 'spec_helper'

describe ClaimsController do
  context 'claims#create' do
    it 'should create a Claim' do
      assert_difference 'Claim.count' do
        session[:user] = Claimant.at_random.id
        post :create
      end

      assert_redirected_to personal_details_claim_path( assigns :claim )
    end
  end

  context 'claims#post_personal_details' do
    before :each do
      @claimant = Claimant.create(:address => Address.create)
      @defendant = Defendant.create(:address => Address.create)
      @property_address = Address.create

      @claim = Claim.create(:address => @property_address, :owner => @claimant)
      @claim.claimants << @claimant
      @claim.defendants << @defendant

      session[:bypass_auth] = true
      session[:referer] = 'personal_details'
    end

    context 'Save & Continue' do
      it 'should redirect to the next page in sequence' do
        patch :post_personal_details, id: @claim.id, commit: 'save-and-continue', claim: @claim.attributes
        assert_redirected_to case_details_claim_path( @claim )
      end
    end

    context 'Close' do
      it 'should redirect to the index page' do
        patch :post_personal_details, id: @claim.id, commit: 'close', claim: @claim.attributes
        assert_redirected_to root_path
      end
    end

    context 'Add another landlord' do
      it 'should add a claimant' do
        assert_difference( '@claim.claimants.count', +1 ) do
          patch :post_personal_details, id: @claim.id, commit: 'Add another landlord', claim: @claim.attributes
        end
      end
      it 'should stay on the personal_details page' do
        patch :post_personal_details, id: @claim.id, commit: 'Add another landlord', claim: @claim.attributes
        assert_redirected_to personal_details_claim_path @claim
      end
    end

    context 'Add another tenant' do
      it 'should add a defendant' do
        assert_difference( '@claim.defendants.count', +1 ) do
          patch :post_personal_details, id: @claim.id, commit: 'Add another tenant', claim: @claim.attributes
        end
      end
      it 'should stay on the personal_details page' do
        patch :post_personal_details, id: @claim.id, commit: 'Add another tenant', claim: @claim.attributes
        assert_redirected_to personal_details_claim_path @claim
      end
    end
  end

end


text:
from nn_wtf.tests.neural_network_graph_test import NeuralNetworkGraphTest
from nn_wtf.tests.images_labels_data_set_test import ImagesLabelsDataSetTest
from nn_wtf.tests.input_data_test import InputDataTest
from nn_wtf.tests.predictor_test import PredictorTest
from nn_wtf.tests.neural_network_optimizer_test import NeuralNetworkOptimizerTest
from nn_wtf.tests.trainer_test import TrainerTest
from nn_wtf.tests.save_and_restore_test import SaveAndRestoreTest

import unittest

__author__ = 'Lene Preuss <lene.preuss@gmx.net>'

unittest.main()


text:
try {
  var p = new Proxy({}, {
      getPropertyDescriptor: function() { return [] }
    });
  var o = Object.create(p);
  with (o) { unresolved_name() }
} catch(e) {
}


text:
using System.Collections.Generic;
using System.Web.Mvc;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using eidss.model.Schema;
using eidss.webclient.Utils;
using eidss.model.Core;
using eidss.model.Resources;
using eidss.model.Enums;
using System.Collections.Specialized;
using System.Web;
using System;

namespace eidss.webclient.Controllers
{
    [AuthorizeEIDSS]
    public class ASCampaignController : Controller
    {

        #region Campaign
        public ActionResult Index()
        {
            var accessor = AsCampaignListItem.Accessor.Instance(null);
            IObject initObject = null;
            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                initObject = accessor.CreateNew(manager, null);
            }
            ViewBag.InitObject = initObject;
            ViewBag.Filter = SearchPanelHelper.GetDefaultFilter(accessor.SearchPanelMeta, initObject);

            return View(accessor);
        }

        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            FilterParams filter = SearchPanelHelper.SearchPanelParseValues(form, AsCampaignListItem.Accessor.Instance(null).SearchPanelMeta);
            ViewBag.Filter = filter;
            ViewBag.InitObject = null;
            AsCampaignListItem.AsCampaignListItemGridModelList list = GetGridModelList(filter);
            ModelStorage.Put(Session.SessionID, AutoGridRoots.AsCampaignList, AutoGridRoots.AsCampaignList, "Grid", list);
            int totalRows = list.Count;
            return Json(new { data = list, total = totalRows }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Details(long? id)
        {
            if (id == 0)
                id = null;
            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                var acc = AsCampaign.Accessor.Instance(null);
                var camp = id.HasValue ? acc.SelectByKey(manager, id.Value) : acc.CreateNewT(manager, null);
                ModelStorage.Put(Session.SessionID, camp.idfCampaign, camp.idfCampaign, null, camp);
                return View(camp);
            }

        }

        [HttpPost]
        public ActionResult Details(FormCollection form)
        {
            var key = long.Parse(form["idfCampaign"]);
            var camp = ModelStorage.Get(Session.SessionID, key, null) as AsCampaign;

            var clone = (IObject)camp.Clone();

            ViewData["ErrorMessage"] = null;

            camp.ParseFormCollection(form, true, false);

            if (String.IsNullOrWhiteSpace(form["actualsave"])) // if not real submission
            {
                return Json("ok", JsonRequestBehavior.AllowGet);
            }

            camp.Validation += object_ValidationDetails;

            if (ViewData["ErrorMessage"] == null)
            {
                using (var manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
                {
                    var acc = AsCampaign.Accessor.Instance(null);
                    acc.Post(manager, camp);
                }
            }

            camp.Validation -= object_ValidationDetails;

            CompareModel comparision = new CompareModel();

            if (ViewData["ErrorMessage"] != null)
            {
                comparision.Add("ErrorMessage", "ErrorMessage", "ErrorMessage",
                                ViewData["ErrorMessage"].ToString(),
                                false, false, false);
            }
            else
            {
                comparision = camp.Compare(clone);
            }

            return Json(comparision, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult RemoveSession(long idfCampaign, long idfSession)
        {
            var camp = ModelStorage.Get(Session.SessionID, idfCampaign, null) as AsCampaign;

            int sessionIndexInList = camp.Sessions.FindIndex(x=>x.idfMonitoringSession == idfSession);
            if (sessionIndexInList > -1)
            {
                camp.Sessions[sessionIndexInList].MarkToDelete();
                return Json("ok", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("Invalid input", JsonRequestBehavior.AllowGet);
            }

        }

        #endregion

        void object_ValidationDetails(object sender, ValidationEventArgs args)
        {
            ViewData["ErrorMessage"] = EidssMessages.GetValidationErrorMessage(args);
        }

        public ActionResult Select()
        {
            var accessor = AsCampaignListItem.Accessor.Instance(null);
            IObject initObject = null;
            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                initObject = accessor.CreateNew(manager, null);
            }
            ViewBag.InitObject = initObject;
            FilterParams filter = SearchPanelHelper.GetDefaultFilter(accessor.SearchPanelMeta, initObject);
            filter.Add("idfsCampaignStatus", "=", (long)AsCampaignStatus.Open);
            ViewBag.Filter = filter;
            AsCampaignListItem.AsCampaignListItemGridModelList list = GetGridModelList(filter);
            ViewBag.GridItems = list;
            ModelStorage.Put(Session.SessionID, 0, AutoGridRoots.AsCampaignSelectList, "Grid", list);

            return View(accessor);
        }

        [HttpPost]
        public ActionResult Select(string formData)
        {
            FilterParams filter = SearchPanelHelper.SearchPanelParseValues(formData, AsCampaignListItem.Accessor.Instance(null).SearchPanelMeta);
            ViewBag.Filter = filter;
            ViewBag.InitObject = null;
            AsCampaignListItem.AsCampaignListItemGridModelList list = GetGridModelList(filter);
            ModelStorage.Put(Session.SessionID, AutoGridRoots.AsCampaignList, AutoGridRoots.AsCampaignList, "Grid", list);
            int totalRows = list.Count;
            return Json(new { data = list, total = totalRows }, JsonRequestBehavior.AllowGet);
        }

        private static AsCampaignListItem.AsCampaignListItemGridModelList GetGridModelList(FilterParams filter)
        {
            List<AsCampaignListItem> items = GetAsCampaignList(filter);
            var list = new AsCampaignListItem.AsCampaignListItemGridModelList(AutoGridRoots.AsCampaignSelectList, items);
            return list;
        }

        private static List<AsCampaignListItem> GetAsCampaignList(FilterParams filter)
        {
            var accessor = AsCampaignListItem.Accessor.Instance(null);
            using (var dbmanager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
            {
                List<AsCampaignListItem> items = accessor.SelectListT(dbmanager, filter);
                return items;
            }
        }
    }
}


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Trans. Proc. Palaeont. Soc. Japan (N. S. ) No. 65: 23.

#### Original name
null

### Remarks
null


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.RemoveUnnecessaryImports;

namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryImports
{
    [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryImports), Shared]
    [ExtensionOrder(After = PredefinedCodeFixProviderNames.AddMissingReference)]
    internal class CSharpRemoveUnnecessaryImportsCodeFixProvider : AbstractRemoveUnnecessaryImportsCodeFixProvider
    {
        [ImportingConstructor]
        [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
        public CSharpRemoveUnnecessaryImportsCodeFixProvider()
        {
        }

        protected override string GetTitle()
            => CSharpCodeFixesResources.Remove_Unnecessary_Usings;
    }
}


text:
package com.aspose.imaging.examples.ManipulatingTIFFImages;

import com.aspose.imaging.Color;
import com.aspose.imaging.Image;
import com.aspose.imaging.examples.Logger;
import com.aspose.imaging.examples.Utils;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.fileformats.tiff.TiffFrame;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.sources.FileCreateSource;

public class ExtractTIFFFramestoOtherImageFormatusingCoreFunctionality
{
    public static void main(String... args)
    {
		Logger.startExample("ExtractTIFFFramestoOtherImageFormatusingCoreFunctionality");

        // The path to the documents directory.
        String dataDir = Utils.getSharedDataDir() + "ManipulatingTIFFImages/";

		try (TiffImage multiImage = (TiffImage) Image.load(dataDir + "sample.tif"))
		{
			int frameCounter = 0;
			for (TiffFrame tiffFrame : multiImage.getFrames())
			{
				multiImage.setActiveFrame(tiffFrame);
				Color[] pixels = multiImage.loadPixels(tiffFrame.getBounds());
				JpegOptions jpgCreateOptions = new JpegOptions();

				jpgCreateOptions
						.setSource(new FileCreateSource(Utils.getOutDir() + "Concat" + frameCounter + ".jpg", false));
				JpegImage jpgImage = (JpegImage) Image.create(jpgCreateOptions, tiffFrame.getWidth(),
						tiffFrame.getHeight());
				try
				{
					jpgImage.savePixels(tiffFrame.getBounds(), pixels);
					jpgImage.save();
				}
				finally
				{
					jpgImage.close();
					jpgCreateOptions.close();
				}

				frameCounter++;
			}
		}
		Logger.endExample();
    }

}


text:
require 'google/apis/servicemanagement_v1/service.rb'
require 'google/apis/servicemanagement_v1/classes.rb'
require 'google/apis/servicemanagement_v1/representations.rb'

module Google
  module Apis
    # Google Service Management API
    #
    # Google Service Management allows service producers to publish their services
    # on Google Cloud Platform so that they can be discovered and used by service
    # consumers.
    #
    # @see https://cloud.google.com/service-management/
    module ServicemanagementV1
      VERSION = 'V1'
      REVISION = '20170428'

      # Manage your Google API service configuration
      AUTH_SERVICE_MANAGEMENT = 'https://www.googleapis.com/auth/service.management'

      # View your data across Google Cloud Platform services
      AUTH_CLOUD_PLATFORM_READ_ONLY = 'https://www.googleapis.com/auth/cloud-platform.read-only'

      # View your Google API service configuration
      AUTH_SERVICE_MANAGEMENT_READONLY = 'https://www.googleapis.com/auth/service.management.readonly'

      # View and manage your data across Google Cloud Platform services
      AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
    end
  end
end


text:
title: "Test Dependencies"
weight: 6
type: docs
---
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

# Dependencies for Testing

Flink provides utilities for testing your job that you can add as dependencies.

## DataStream API Testing

You need to add the following dependencies if you want to develop tests for a job built with the
DataStream API:

{{< artifact_tabs flink-test-utils withTestScope >}}

Among the various test utilities, this module provides `MiniCluster`, a lightweight configurable Flink cluster runnable in a JUnit test that can directly execute jobs.

For more information on how to use these utilities, check out the section on [DataStream API testing]({{< ref "docs/dev/datastream/testing" >}})

## Table API Testing

If you want to test the Table API & SQL programs locally within your IDE, you can add the following
dependency, in addition to the aforementioned `flink-test-utils`:

{{< artifact_tabs flink-table-test-utils withTestScope >}}

This will automatically bring in the query planner and the runtime, required respectively to plan
and execute the queries.

{{< hint info >}}
The module `flink-table-test-utils` has been introduced in Flink 1.15 and is considered experimental.
{{< /hint >}}