text:
<?php
/**
 * This file is part of the DVSA MOT Frontend project.
 *
 * @link http://gitlab.clb.npm/mot/mot
 */
use Dvsa\Mot\Frontend\PersonModule\Controller\ChangeAddressController;
use Dvsa\Mot\Frontend\PersonModule\Controller\ChangeNameController;
use Dvsa\Mot\Frontend\PersonModule\Controller\ChangeTelephoneController;
use Dvsa\Mot\Frontend\PersonModule\Controller\PersonProfileController;
use Dvsa\Mot\Frontend\PersonModule\Factory\Controller\ChangeAddressControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\Factory\Controller\ChangeNameControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\Factory\Controller\ChangeTelephoneControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\Factory\Controller\PersonProfileControllerFactory;
use Dashboard\Controller\UserTradeRolesController;
use Dashboard\Factory\Controller\UserTradeRolesControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\GracePeriod\Controller\ExtendGracePeriodController;
use Dvsa\Mot\Frontend\PersonModule\GracePeriod\Controller\GracePeriodConfirmationController;
use Dvsa\Mot\Frontend\PersonModule\GracePeriod\Factory\Controller\ExtendGracePeriodControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\GracePeriod\Factory\Controller\GracePeriodConfirmationControllerFactory;
use UserAdmin\Controller\EmailAddressController;
use UserAdmin\Controller\UserSearchController;
use UserAdmin\Factory\Controller\ChangeQualificationStatusControllerFactory;
use UserAdmin\Controller\ChangeQualificationStatusController;
use UserAdmin\Factory\Controller\EmailAddressControllerFactory;
use UserAdmin\Factory\Controller\UserProfileControllerFactory;
use UserAdmin\Controller\UserProfileController;
use Dvsa\Mot\Frontend\PersonModule\Controller\ChangeDateOfBirthController;
use Dvsa\Mot\Frontend\PersonModule\Factory\Controller\ChangeDateOfBirthControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Controller\ChangeSecurityQuestionsController;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Factory\Controller\ChangeSecurityQuestionsControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Controller\ChangeSecurityQuestionOneController;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Factory\Controller\ChangeSecurityQuestionOneControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Controller\ChangeSecurityQuestionTwoController;
use \Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Factory\Controller\ChangeSecurityQuestionTwoControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Controller\ChangeSecurityQuestionsConfirmationController;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Factory\Controller\ChangeSecurityQuestionsConfirmationControllerFactory;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Controller\ChangeSecurityQuestionsReviewController;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Factory\Controller\ChangeSecurityQuestionsReviewControllerFactory;
use UserAdmin\Factory\Controller\UserSearchControllerFactory;

return [
    'factories' => [
        UserProfileControllerFactory::class => UserProfileController::class,
        UserSearchController::class => UserSearchControllerFactory::class,
        PersonProfileController::class => PersonProfileControllerFactory::class,
        UserTradeRolesController::class => UserTradeRolesControllerFactory::class,
        ChangeQualificationStatusController::class => ChangeQualificationStatusControllerFactory::class,
        ChangeAddressController::class => ChangeAddressControllerFactory::class,
        ChangeQualificationStatusController::class => ChangeQualificationStatusControllerFactory::class,
        ChangeNameController::class => ChangeNameControllerFactory::class,
        ChangeDateOfBirthController::class => ChangeDateOfBirthControllerFactory::class,
        ChangeTelephoneController::class => ChangeTelephoneControllerFactory::class,
        EmailAddressController::class => EmailAddressControllerFactory::class,
        ChangeSecurityQuestionsController::class => ChangeSecurityQuestionsControllerFactory::class,
        ChangeSecurityQuestionOneController::class => ChangeSecurityQuestionOneControllerFactory::class,
        ChangeSecurityQuestionTwoController::class => ChangeSecurityQuestionTwoControllerFactory::class,
        ChangeSecurityQuestionsReviewController::class => ChangeSecurityQuestionsReviewControllerFactory::class,
        ChangeSecurityQuestionsConfirmationController::class => ChangeSecurityQuestionsConfirmationControllerFactory::class,
        ExtendGracePeriodController::class => ExtendGracePeriodControllerFactory::class,
        GracePeriodConfirmationController::class => GracePeriodConfirmationControllerFactory::class
    ],
];


text:
<?php

namespace KoolKode\Meta\Info;

use KoolKode\Meta\TypeNotFoundException as TNF,
	KoolKode\Meta\MethodNotFoundException;

/** Just a test */
interface TestInterface extends \Countable, \IteratorAggregate
{
	/** FOO! */
	public function foo(\stdClass $foo = NULL);
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.ddth.dao;

import com.github.ddth.cacheadapter.CacheException;
import com.github.ddth.cacheadapter.ICache;
import com.github.ddth.cacheadapter.ICacheFactory;
import com.github.ddth.dao.utils.ProfilingRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;
import java.util.List;

/**
 * Base class for application DAOs.
 *
 * @author Thanh Nguyen <btnguyen2k@gmail.com>
 * @since 0.1.0
 */
public abstract class BaseDao implements AutoCloseable {

    private final Logger LOGGER = LoggerFactory.getLogger(BaseDao.class);

    private static ThreadLocal<List<ProfilingRecord>> profilingRecords = ThreadLocal
            .withInitial(() -> new LinkedList<>());

    /**
     * Initializes profiling data.
     */
    public static void startProfiling() {
        profilingRecords.remove();
    }

    /**
     * Clears profiling data.
     */
    public static void clearProfiling() {
        profilingRecords.remove();
    }

    /**
     * Gets current profiling data.
     *
     * @return
     */
    public static ProfilingRecord[] getProfiling() {
        return profilingRecords.get().toArray(ProfilingRecord.EMPTY_ARRAY);
    }

    /**
     * Adds a new profiling record.
     *
     * @param execTimeMs
     * @param command
     * @return
     */
    public static ProfilingRecord addProfiling(long execTimeMs, String command, long durationMs) {
        ProfilingRecord record = new ProfilingRecord(execTimeMs, command, durationMs);
        List<ProfilingRecord> records = profilingRecords.get();
        records.add(record);
        while (records.size() > 100) {
            records.remove(0);
        }
        return record;
    }

    /*--------------------------------------------------------------------------------*/

    private ICacheFactory cacheFactory;
    private boolean cacheItemsExpireAfterWrite = false;

    /**
     * Initializing method.
     *
     * @return
     */
    public BaseDao init() {
        return this;
    }

    /**
     * Destroy method.
     */
    public void destroy() {
    }

    /**
     * {@inheritDoc}
     *
     * @since 0.8.5
     */
    @Override
    public void close() {
        this.destroy();
    }

    /**
     * Cache factory used to cache DAO data.
     *
     * @return
     */
    protected ICacheFactory getCacheFactory() {
        return cacheFactory;
    }

    /**
     * Cache factory used to cache DAO data.
     *
     * @param cacheFactory
     * @return
     */
    public BaseDao setCacheFactory(ICacheFactory cacheFactory) {
        this.cacheFactory = cacheFactory;
        return this;
    }

    protected boolean isCacheEnabled() {
        return cacheFactory != null;
    }

    protected ICache getCache(String cacheName) {
        return cacheFactory != null ? cacheFactory.createCache(cacheName) : null;
    }

    /**
     * Check if cache items, by default, expire after write or read/access.
     *
     * @return
     */
    public boolean isCacheItemsExpireAfterWrite() {
        return cacheItemsExpireAfterWrite;
    }

    /**
     * Set if cache items, by default, expire after write or read/access.
     *
     * @param cacheItemsExpireAfterWrite
     */
    public void setCacheItemsExpireAfterWrite(boolean cacheItemsExpireAfterWrite) {
        this.cacheItemsExpireAfterWrite = cacheItemsExpireAfterWrite;
    }

    /**
     * Remove an entry from cache.
     *
     * @param cacheName
     * @param key
     */
    protected void removeFromCache(String cacheName, String key) {
        try {
            ICache cache = getCache(cacheName);
            if (cache != null) {
                cache.delete(key);
            }
        } catch (CacheException e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }

    /**
     * Put an entry to cache, with default TTL.
     *
     * @param cacheName
     * @param key
     * @param value
     */
    protected void putToCache(String cacheName, String key, Object value) {
        putToCache(cacheName, key, value, 0);
    }

    /**
     * Put an entry to cache, with specific TTL.
     *
     * @param cacheName
     * @param key
     * @param value
     * @param ttlSeconds
     */
    protected void putToCache(String cacheName, String key, Object value, long ttlSeconds) {
        if (cacheItemsExpireAfterWrite) {
            putToCache(cacheName, key, value, ttlSeconds, 0);
        } else {
            putToCache(cacheName, key, value, 0, ttlSeconds);
        }
    }

    /**
     * Put an entry to cache, with specific {@code expireAfterWriteSeconds/expireAfterAccessSeconds}.
     *
     * @param cacheName
     * @param key
     * @param value
     * @param expireAfterWriteSeconds
     * @param expireAfterAccessSeconds
     */
    protected void putToCache(String cacheName, String key, Object value, long expireAfterWriteSeconds,
            long expireAfterAccessSeconds) {
        try {
            ICache cache = getCache(cacheName);
            if (value != null && cache != null) {
                cache.set(key, value, expireAfterWriteSeconds, expireAfterAccessSeconds);
            }
        } catch (CacheException e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }

    /**
     * Get an entry from cache.
     *
     * @param cacheName
     * @param key
     * @return
     */
    protected Object getFromCache(String cacheName, String key) {
        try {
            ICache cache = getCache(cacheName);
            return cache != null && key != null ? cache.get(key) : null;
        } catch (CacheException e) {
            LOGGER.warn(e.getMessage(), e);
            return null;
        }
    }

    /**
     * Get an entry from cache.
     *
     *

     * Note: if the object from cache is not assignable to clazz,
     * null is returned.
     *

     *
     * @param cacheName
     * @param key
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    protected <T> T getFromCache(String cacheName, String key, Class<T> clazz) {
        Object obj = getFromCache(cacheName, key);
        if (obj == null) {
            return null;
        }
        if (clazz.isAssignableFrom(obj.getClass())) {
            return (T) obj;
        }
        return null;
    }
}


text:
<!DOCTYPE html>

		<title>Test Simple List</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
		<meta name="viewport" content="width=570" />

A basic list, instantiated with no constructor arguments


text:
MESSAGE(STATUS "Using bundled Findlibadbase_lua.cmake...")
  FIND_PATH(
      LIBADBASE_LUA_INCLUDE_DIR
      Lua.hpp
      /usr/local/include/adbase
     /usr/include/
  )

FIND_LIBRARY(
  LIBADBASE_LUA_LIBRARIES NAMES libadbase_lua.a
  PATHS /usr/lib/ /usr/local/lib/ /usr/lib64 /usr/local/lib64
  )


text:
if ENV['CODECLIMATE_REPO_TOKEN']
  require 'codeclimate-test-reporter'
  require 'code_climate/parallel/test_reporter'
  CodeClimate::TestReporter.start
end


text:
'use strict';

var utils = require('../lib/utils');

module.exports = function (grunt) {
    grunt.registerTask('configureRewriteRules', 'Configure connect rewriting rules.', function () {
        var options = this.options({
            rulesProvider: 'connect.rules'
        });
        utils.log = grunt.log;
        (grunt.config(options.rulesProvider) || []).forEach(function (rule) {
            rule = rule || {};
            var registeredRule = utils.registerRule({from: rule.from, to: rule.to, redirect: rule.redirect});
            if (registeredRule) {
                grunt.log.ok('Rewrite rule created for: [' + registeredRule + '].');
            } else {
                grunt.log.error('Wrong rule given.');
            }
        });
    });
};


text:
package main

import (
  "bufio"
  "log"
  "os"

  "gopkg.in/fsnotify.v1"
)

func startWatch(filename string, out chan string) {
  // Create Watcher
  watcher, err := fsnotify.NewWatcher()
  if err != nil {
    log.Fatal(err)
  }
  defer watcher.Close()

  file, err := os.Open(filename)
  if err != nil {
    log.Fatal(err)
  }
  defer file.Close()

  fileStats, err := os.Stat(filename)
  if err != nil {
    log.Fatal(err)
  }

  // Get current size of file
  lastSize := fileStats.Size()

  // Start Watcher
  err = watcher.Add(filename);
  if err != nil {
    log.Fatal(err)
  }

  // Watch file for writes
  done := make(chan bool)
  func() {
    for {
      select {
      case event := <-watcher.Events:
        if event.Op&fsnotify.Write == fsnotify.Write {
          file.Seek(0, 0) // Seek to beginning of file
          fileStats, err := os.Stat(filename)
          if err != nil {
            panic(err)
          }

          // Seek to previous end of file
          file.Seek(lastSize, 0)
          scanner := bufio.NewScanner(file)
          for scanner.Scan() {
            out <- scanner.Text() // Send line out
          }

          // Set new end of file
          lastSize = fileStats.Size()
        }
      case err := <-watcher.Errors:
        log.Println("error:", err);
      }
    }
  }()
  <- done
}


text:
package com.employment.presenter.contract;

import com.employment.base.BasePresenter;
import com.employment.base.BaseView;

/**
 * Created by roy on 2017/4/8.
 */

public interface LoginContract {

    interface View extends BaseView{

        void loginSuccess();

        void loginFailure();
    }

    interface Presenter extends BasePresenter<View>{

        void login(String userName,String passWord,String type);
    }
}


text: import './ingest-file-links-sk';


text:
	    <meta charset="utf-8">
	    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	    <meta name="description" content="">
	    <meta name="author" content="">

	    <title>EasyFollow</title>

	    <link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

Easy Follow

Follow the followers of any user with just one click!

		                <form role="form" action="login.php" method="post">

		                        <input type="text" class="form-control input-lg" id="user" name="user" placeholder="@username" style="width:230px; margin:auto; text-align:center; border-radius:20px;">

		                    <input type="submit" value="Follow now!" class="btn btn-lg btn-primary" />
		              </form>


text:
#include <stdio.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <math.h>

// Gertboard D to A is an 8-bit unit.

#define	B_SIZE	256

#include <wiringPi.h>
#include <gertboard.h>

int main (void)
{
  double angle ;
  int i, inputValue ;
  int  buffer [B_SIZE] ;
  int   cols ;
  struct winsize w ;

  printf ("Raspberry Pi Gertboard SPI test program\n") ;
  printf ("=======================================\n") ;

  ioctl (fileno (stdin), TIOCGWINSZ, &w);
  cols = w.ws_col - 2 ;

// Always initialise wiringPi. Use wiringPiSys() if you don't need
//	(or want) to run as root

  wiringPiSetupSys () ;

// Initialise the Gertboard analog hardware at pin 100

  gertboardAnalogSetup (100) ;

// Generate a Sine Wave and store in our buffer

  for (i = 0 ; i < B_SIZE ; ++i)
  {
    angle = ((double)i / (double)B_SIZE) * M_PI * 2.0 ;
    buffer [i] = (int)rint ((sin (angle)) * 127.0 + 128.0) ;
  }

// Loop, output the sine wave on analog out port 0, read it into A-D port 0
//	and display it on the screen

  for (;;)
  {
    for (i = 0 ; i < B_SIZE ; ++i)
    {
      analogWrite (100, buffer [i]) ;

      inputValue = analogRead (100) ;

// We don't need to wory about the scale or sign - the analog hardware is
//	a 10-bit value, so 0-1023. Just scale this to our terminal

      printf ("%*s\n", (inputValue * cols) / 1023, "*") ;
      delay (2) ;
    }
  }

  return 0 ;
}


text:
        X :
        Y

        X :
        Y

        X :
        Y


text:
package org.niklas.elemental.Elemental.client.elements;

import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;

@JsType(
    prototype = "WindowSessionStorage"
)
interface WindowSessionStorage {
  @JsProperty
  Storage getSessionStorage();
}


text:
package com.jcertif.android.dao;

import java.util.List;

import android.content.Context;

import com.jcertif.android.model.Session;
import com.jcertif.android.model.Speaker;

public class SpeakerProvider extends JCertifDb4oHelper<Speaker> {

	public SpeakerProvider(Context ctx) {
		super(ctx);
	}

	public Speaker getByEmail(final String email) {
		List<Speaker> list =getAll(Speaker.class);
		if (!list.isEmpty())
		for(Speaker s: list){
			if(s.getEmail().equals(email)){
				return s;
			}
		}
			return new Speaker();
	}

}


text:
import ActorClient from '../utils/ActorClient';
import Raven from '../utils/Raven';

import ActorAppDispatcher from '../dispatcher/ActorAppDispatcher';
import { ActionTypes, AuthSteps } from '../constants/ActorAppConstants';

import { EventEmitter } from 'events';
import assign from 'object-assign';

const CHANGE_EVENT = 'change';

let errors = {
  phone: null,
  code: null,
  signup: null
};

let step = AuthSteps.PHONE_WAIT;

let isSmsRequested = false;
let isSignupStarted = false;
let myUid = null;

var LoginStore = assign({}, EventEmitter.prototype, {
  isLoggedIn: function () {
    return (ActorClient.isLoggedIn());
  },

  getStep: () => step,

  getErrors: () => errors,

  isSmsRequested: function () {
    return (isSmsRequested);
  },

  isSignupStarted: function () {
    return (isSignupStarted);
  },

  emitChange: function () {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function (callback) {
    this.on(CHANGE_EVENT, callback);
  },

  removeChangeListener: function (callback) {
    this.removeListener(CHANGE_EVENT, callback);
  },

  getMyId: function () {
    return (myUid);
  }
});

const processPhoneExpired = () => {
  errors.name = null;
  errors.phone = 'Phone code is expired';
  step = AuthSteps.PHONE_WAIT;
  LoginStore.emitChange();
};

LoginStore.dispatchToken = ActorAppDispatcher.register(function (action) {
  switch (action.type) {
    case ActionTypes.AUTH_SMS_REQUEST_SUCCESS:
      errors.phone = null;
      step = AuthSteps.CODE_WAIT;

      LoginStore.emitChange();
      break;
    case ActionTypes.AUTH_SMS_REQUEST_FAILURE:
      switch (action.error) {
        case 'PHONE_NUMBER_INVALID':
          errors.phone = 'Invalid number';
          break;
        default:
          errors.phone = action.error;
      }

      LoginStore.emitChange();
      break;
    case ActionTypes.SEND_CODE_SUCCESS:
      errors.code = null;

      if (action.needSignup) {
        step = AuthSteps.SIGNUP_NAME_WAIT;
      }

      LoginStore.emitChange();
      break;
    case ActionTypes.SEND_CODE_FAILURE:
      switch (action.error) {
        case 'PHONE_CODE_INVALID':
          errors.code = 'Invalid code';
          break;
        case 'PHONE_CODE_EXPIRED':
          processPhoneExpired();
          break;
        default:
          errors.code = action.error;
      }

      LoginStore.emitChange();
      break;
    case ActionTypes.SEND_SIGNUP_SUCCESS:
      errors.name = null;
      step = AuthSteps.COMPLETED;
      LoginStore.emitChange();
      break;
    case ActionTypes.SEND_SIGNUP_FAILURE:
      switch (action.error) {
        case 'NAME_INVALID':
          errors.signup = 'Invalid name';
          break;
        case 'PHONE_CODE_EXPIRED':
          errors.signup = null;
          processPhoneExpired();
          break;
        default:
          errors.name = action.error;
      }
      LoginStore.emitChange();
      break;
    case ActionTypes.AUTH_WRONG_NUMBER_CLICK:
      errors.phone = null;
      step = AuthSteps.PHONE_WAIT;
      LoginStore.emitChange();
      break;
    case ActionTypes.SET_LOGGED_IN:
      myUid = ActorClient.getUid();
      Raven.setUserContext({
        id: myUid
      });
      LoginStore.emitChange();
      break;
    case ActionTypes.SET_LOGGED_OUT:
      Raven.setUserContext();
      localStorage.clear();
      location.reload();
      break;
    default:
  }
});

export default LoginStore;


text:
import aiounittest
import unittest

import asyncio
from pyvast import VAST
import json

class TestConnection(aiounittest.AsyncTestCase):
    def setUp(self):
        self.vast = VAST(binary="/opt/tenzir/bin/vast")

    async def test_connection(self):
        self.assertTrue(await self.vast.test_connection())

class TestCallStackCreation(unittest.TestCase):
    def setUp(self):
        self.vast = VAST(binary="/opt/tenzir/bin/vast")

    def test_call_chaining(self):
        self.assertEqual(self.vast.call_stack, [])
        query = "#timestamp < 1 hour ago"
        self.vast.export().arrow(query)
        self.assertEqual(self.vast.call_stack, ["export", "arrow", query])

    def test_boolean_flag_handling(self):
        self.assertEqual(self.vast.call_stack, [])
        query = ":addr == 192.168.1.104 && #timestamp < 1 hour ago"
        self.vast.export(continuous=True).json(query)
        self.assertEqual(
            self.vast.call_stack, ["export", "--continuous", "json", query]
        )

    def test_import_keyword(self):
        self.assertEqual(self.vast.call_stack, [])
        path = "/some/file"
        self.vast.import_().pcap(read=path)
        self.assertEqual(self.vast.call_stack, ["import", "pcap", f"--read={path}"])

    def test_underscore_replacement(self):
        self.assertEqual(self.vast.call_stack, [])
        self.vast.export(max_events=10).json("192.168.1.104")
        self.assertEqual(
            self.vast.call_stack, ["export", "--max-events=10", "json", "192.168.1.104"]
        )


text:
package com.xiecc.seeWeather.modules.city.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.xiecc.seeWeather.common.utils.Util;
import com.xiecc.seeWeather.modules.city.domain.City;
import com.xiecc.seeWeather.modules.city.domain.Province;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hugo on 2015/9/30 0030.
 * 封装数据库操作
 */
public class WeatherDB {

    public WeatherDB() {

    }

    public static List<Province> loadProvinces(SQLiteDatabase db) {

        List<Province> list = new ArrayList<>();

        Cursor cursor = db.query("T_Province", null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                Province province = new Province();
                province.mProSort = cursor.getInt(cursor.getColumnIndex("ProSort"));
                province.mProName = cursor.getString(cursor.getColumnIndex("ProName"));
                list.add(province);
            } while (cursor.moveToNext());
        }
        Util.closeQuietly(cursor);
        return list;
    }

    public static List<City> loadCities(SQLiteDatabase db, int ProID) {
        List<City> list = new ArrayList<>();
        Cursor cursor = db.query("T_City", null, "ProID = ?", new String[] { String.valueOf(ProID) }, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                City city = new City();
                city.mCityName = cursor.getString(cursor.getColumnIndex("CityName"));
                city.mProID = ProID;
                city.mCitySort = cursor.getInt(cursor.getColumnIndex("CitySort"));
                list.add(city);
            } while (cursor.moveToNext());
        }
        Util.closeQuietly(cursor);
        return list;
    }
}


text:
<?php

namespace RK\HelperModule\Form\DataTransformer;

use RK\HelperModule\Form\DataTransformer\Base\AbstractUserFieldTransformer;

/**
 * User field transformer implementation class.
 *
 * This data transformer treats user fields.
 */
class UserFieldTransformer extends AbstractUserFieldTransformer
{
    // feel free to add your customisation here
}


text:
PHPC-1239: Passing SSL driverOptions overrides SSL options from URI
--SKIPIF--
<?php require __DIR__ . "/../utils/basic-skipif.inc"; ?>
<?php skip_if_not_live(); ?>
--FILE--
<?php
require_once __DIR__ . "/../utils/basic.inc";

$manager = create_test_manager(URI, array(), array());

$manager->executeCommand(DATABASE_NAME, new MongoDB\Driver\Command(['ping' => 1]));
?>
===DONE===
<?php exit(0); ?>
--EXPECT--
===DONE===


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;

namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
    internal abstract class CType
    {
        private protected CType(TypeKind kind)
        {
            TypeKind = kind;
        }

        public bool IsWindowsRuntimeType => (AssociatedSystemType.Attributes & TypeAttributes.WindowsRuntime) != 0;

        [ExcludeFromCodeCoverage] // Should only be called through override.
        public virtual Type AssociatedSystemType => throw Error.InternalCompilerError();

        public TypeKind TypeKind { get; }

        public virtual CType BaseOrParameterOrElementType => null;

        ////////////////////////////////////////////////////////////////////////////////
        // Given a symbol, determine its fundamental type. This is the type that
        // indicate how the item is stored and what instructions are used to reference
        // if. The fundamental types are:
        // one of the integral/float types (includes enums with that underlying type)
        // reference type
        // struct/value type
        public virtual FUNDTYPE FundamentalType => FUNDTYPE.FT_NONE;

        public virtual ConstValKind ConstValKind => ConstValKind.Int;

        ////////////////////////////////////////////////////////////////////////////////
        // Strips off ArrayType, ParameterModifierType, PointerType, PinnedType and optionally NullableType
        // and returns the result.
        public CType GetNakedType(bool fStripNub)
        {
            for (CType type = this; ;)
            {
                switch (type.TypeKind)
                {
                    default:
                        return type;

                    case TypeKind.TK_NullableType:
                        if (!fStripNub)
                        {
                            goto default;
                        }

                        goto case TypeKind.TK_ArrayType;

                    case TypeKind.TK_ArrayType:
                    case TypeKind.TK_ParameterModifierType:
                    case TypeKind.TK_PointerType:
                        type = type.BaseOrParameterOrElementType;
                        break;
                }
            }
        }

        public virtual CType StripNubs() => this;

        public virtual CType StripNubs(out bool wasNullable)
        {
            wasNullable = false;
            return this;
        }

        public virtual bool IsDelegateType => false;

        ////////////////////////////////////////////////////////////////////////////////
        // A few types are considered "simple" types for purposes of conversions and so
        // on. They are the fundamental types the compiler knows about for operators and
        // conversions.
        public virtual bool IsSimpleType => false;

        public virtual bool IsSimpleOrEnum => false;

        public virtual bool IsSimpleOrEnumOrString => false;

        ////////////////////////////////////////////////////////////////////////////////
        // A few types are considered "numeric" types. They are the fundamental number
        // types the compiler knows about for operators and conversions.
        public virtual bool IsNumericType => false;

        public virtual bool IsStructOrEnum => false;

        public virtual bool IsStructType => false;

        public virtual bool IsEnumType => false;

        public virtual bool IsInterfaceType => false;

        public virtual bool IsClassType => false;

        [ExcludeFromCodeCoverage] // Should only be called through override.
        public virtual AggregateType UnderlyingEnumType => throw Error.InternalCompilerError();

        public virtual bool IsUnsigned => false;

        // Pointer types (or arrays of them) are the only unsafe types.
        // Note that generics may not be instantiated with pointer types
        public virtual bool IsUnsafe() => false;

        public virtual bool IsPredefType(PredefinedType pt) => false;

        public virtual bool IsPredefined => false;

        [ExcludeFromCodeCoverage] // Should only be called through override.
        public virtual PredefinedType PredefinedType => throw Error.InternalCompilerError();

        public virtual bool IsStaticClass => false;

        // These check for AGGTYPESYMs, TYVARSYMs and others as appropriate.
        public virtual bool IsValueType => false;

        public virtual bool IsNonNullableValueType => false;

        public virtual bool IsReferenceType => false;
    }
}


text:
using System.Collections.Generic;

namespace KenticoInspector.Core.Models
{
    public class TableResult<T>
    {
        public string Name { get; set; }

        public IEnumerable<T> Rows { get; set; }
    }
}


text:
Data Sources

                     {{dataSource.name}}
                    <button class="btn btn-xs btn-danger pull-right" ng-click="deleteDataSource($event, dataSource)">Delete</button>

                     Add Data Source


text:
module Jashboard
  module Plugin
    class MonitorPluginDispatcher
      def initialize
        @plugins = {}
      end

      def register_adapter(type, clazz)
        @plugins[type] = clazz.new
      end

      def get_runtime_info(monitor)
        @plugins[monitor.type].get_runtime_info(monitor.configuration)
      end
    end
  end
end


text:
namespace Mandrill.Model
{
    internal class MandrillTemplateListRequest : MandrillRequestBase
    {
        public string Label { get; set; }
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v11/resources/ad_group_customizer.proto

package com.google.ads.googleads.v11.resources;

public interface AdGroupCustomizerOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v11.resources.AdGroupCustomizer)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Immutable. The resource name of the ad group customizer.
   * Ad group customizer resource names have the form:
   * `customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}`
   *

   *
   * string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The resourceName.
   */
  java.lang.String getResourceName();
  /**
   *

   * Immutable. The resource name of the ad group customizer.
   * Ad group customizer resource names have the form:
   * `customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}`
   *

   *
   * string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The bytes for resourceName.
   */
  com.google.protobuf.ByteString
      getResourceNameBytes();

  /**
   *

   * Immutable. The ad group to which the customizer attribute is linked.
   *

   *
   * string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The adGroup.
   */
  java.lang.String getAdGroup();
  /**
   *

   * Immutable. The ad group to which the customizer attribute is linked.
   *

   *
   * string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The bytes for adGroup.
   */
  com.google.protobuf.ByteString
      getAdGroupBytes();

  /**
   *

   * Required. Immutable. The customizer attribute which is linked to the ad group.
   *

   *
   * string customizer_attribute = 3 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The customizerAttribute.
   */
  java.lang.String getCustomizerAttribute();
  /**
   *

   * Required. Immutable. The customizer attribute which is linked to the ad group.
   *

   *
   * string customizer_attribute = 3 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The bytes for customizerAttribute.
   */
  com.google.protobuf.ByteString
      getCustomizerAttributeBytes();

  /**
   *

   * Output only. The status of the ad group customizer.
   *

   *
   * .google.ads.googleads.v11.enums.CustomizerValueStatusEnum.CustomizerValueStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
   * @return The enum numeric value on the wire for status.
   */
  int getStatusValue();
  /**
   *

   * Output only. The status of the ad group customizer.
   *

   *
   * .google.ads.googleads.v11.enums.CustomizerValueStatusEnum.CustomizerValueStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
   * @return The status.
   */
  com.google.ads.googleads.v11.enums.CustomizerValueStatusEnum.CustomizerValueStatus getStatus();

  /**
   *

   * Required. The value to associate with the customizer attribute at this level. The
   * value must be of the type specified for the CustomizerAttribute.
   *

   *
   * .google.ads.googleads.v11.common.CustomizerValue value = 5 [(.google.api.field_behavior) = REQUIRED];
   * @return Whether the value field is set.
   */
  boolean hasValue();
  /**
   *

   * Required. The value to associate with the customizer attribute at this level. The
   * value must be of the type specified for the CustomizerAttribute.
   *

   *
   * .google.ads.googleads.v11.common.CustomizerValue value = 5 [(.google.api.field_behavior) = REQUIRED];
   * @return The value.
   */
  com.google.ads.googleads.v11.common.CustomizerValue getValue();
  /**
   *

   * Required. The value to associate with the customizer attribute at this level. The
   * value must be of the type specified for the CustomizerAttribute.
   *

   *
   * .google.ads.googleads.v11.common.CustomizerValue value = 5 [(.google.api.field_behavior) = REQUIRED];
   */
  com.google.ads.googleads.v11.common.CustomizerValueOrBuilder getValueOrBuilder();
}


text:
package org.brackit.server.node.el.index.log;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;

import org.brackit.server.io.buffer.PageID;
import org.brackit.server.store.index.aries.log.UpdateLogOperation;
import org.brackit.server.tx.log.LogException;
import org.brackit.server.tx.log.LogOperation;
import org.brackit.server.tx.log.LogOperationHelper;

/**
 * @author Sebastian Baechle
 *
 */
public class ElBPlusIndexLogOperationHelper implements LogOperationHelper {
	private static final ArrayList<Byte> operationTypes;

	static {
		operationTypes = new ArrayList<Byte>();
		operationTypes.add(ElUpdateLogOperation.USER_INSERT_SPECIAL);
		operationTypes.add(ElUpdateLogOperation.USER_DELETE_SPECIAL);
	}

	@Override
	public Collection<Byte> getOperationTypes() {
		return operationTypes;
	}

	@Override
	public LogOperation fromBytes(byte type, ByteBuffer buffer)
			throws LogException {
		PageID pageID = PageID.read(buffer);
		PageID rootPageID = PageID.read(buffer);

		switch (type) {
		case ElUpdateLogOperation.USER_INSERT_SPECIAL:
		case ElUpdateLogOperation.USER_DELETE_SPECIAL:
			return createUpdateLogOp(type, buffer, pageID, rootPageID);
		default:
			throw new LogException("Unknown operation type: %s.", type);
		}
	}

	public static UpdateLogOperation createUpdateLogOp(byte type,
			PageID pageID, PageID rootPageID, byte[] key, byte[] value,
			byte[] oldValue, int level) {
		return new ElUpdateLogOperation(type, pageID, rootPageID, key,
				oldValue, value, level);
	}

	private LogOperation createUpdateLogOp(byte type, ByteBuffer buffer,
			PageID pageID, PageID rootPageID) {
		byte[] key = new byte[buffer.getInt()];
		buffer.get(key);
		byte[] value = new byte[buffer.getInt()];
		buffer.get(value);
		byte[] oldValue = null;
		int level = buffer.get();

		return createUpdateLogOp(type, pageID, rootPageID, key, value,
				oldValue, level);
	}
}


text:
__author__ = 'fleks'

class GroupHelper:

    def __init__(self, app):
        self.app = app
    def open_groups_page(self):
        wd = self.app.wd
        wd.find_element_by_link_text("groups").click()
    def create(self, group):
        wd = self.app.wd
        self.open_groups_page()
        # init group creation
        wd.find_element_by_name("new").click()
        # fill group firm
        wd.find_element_by_name("group_name").click()
        wd.find_element_by_name("group_name").click()
        wd.find_element_by_name("group_name").clear()
        wd.find_element_by_name("group_name").send_keys(group.name)
        wd.find_element_by_name("group_header").click()
        wd.find_element_by_name("group_header").clear()
        wd.find_element_by_name("group_header").send_keys(group.header)
        wd.find_element_by_name("group_footer").click()
        wd.find_element_by_name("group_footer").clear()
        wd.find_element_by_name("group_footer").send_keys(group.footer)
        # submit group creation
        wd.find_element_by_name("submit").click()
        self.retunt_to_groups_page()
    def retunt_to_groups_page(self):
        wd = self.app.wd
        wd.find_element_by_link_text("groups").click()


text:
<?php

namespace Hail\Http\Middleware;

use Psr\Http\{
    Server\MiddlewareInterface,
    Server\RequestHandlerInterface,
    Message\ServerRequestInterface,
    Message\ResponseInterface
};

class ClientIp implements MiddlewareInterface
{
    /**
     * @var bool
     */
    private $remote = false;

    /**
     * @var string The attribute name
     */
    private $attribute = 'client-ip';

    /**
     * @var array The trusted proxy headers
     */
    private $proxyHeaders = [];

    /**
     * @var array The trusted proxy ips
     */
    private $proxyIps = [];

    /**
     * Configure the proxy.
     *
     * @param array $ips
     * @param array $headers
     *
     * @return self
     */
    public function proxy(
        array $ips = [],
        array $headers = [
            'Forwarded',
            'Forwarded-For',
            'X-Forwarded',
            'X-Forwarded-For',
            'X-Cluster-Client-Ip',
            'Client-Ip',
        ]
    ) {
        $this->proxyIps = $ips;
        $this->proxyHeaders = $headers;

        return $this;
    }

    /**
     * To get the ip from a remote service.
     * Useful for testing purposes on localhost.
     *
     * @param bool $remote
     *
     * @return self
     */
    public function remote($remote = true)
    {
        $this->remote = $remote;

        return $this;
    }

    /**
     * Set the attribute name to store client's IP address.
     *
     * @param string $attribute
     *
     * @return self
     */
    public function attribute($attribute)
    {
        $this->attribute = $attribute;

        return $this;
    }

    /**
     * Process a server request and return a response.
     *
     * @param ServerRequestInterface  $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $ip = $this->getIp($request);

        return $handler->handle(
            $request->withAttribute($this->attribute, $ip)
        );
    }

    /**
     * Detect and return the ip.
     *
     * @param ServerRequestInterface $request
     *
     * @return string|null
     */
    private function getIp(ServerRequestInterface $request)
    {
        if ($this->remote && ($remoteIp = $this->getRemoteIp()) !== null) {
            // Found IP address via remote service.
            return $remoteIp;
        }

        $localIp = $this->getLocalIp($request);

        if ($this->proxyIps && !\in_array($localIp, $this->proxyIps, true)) {
            // Local IP address does not point at a known proxy, do not attempt
            // to read proxied IP address.
            return $localIp;
        }

        $proxiedIp = $this->getProxiedIp($request);

        if ($proxiedIp !== null) {
            // Found IP address via proxy-defined headers.
            return $proxiedIp;
        }

        return $localIp;
    }

    /**
     * Returns the IP address from remote service.
     *
     * @return string|null
     */
    private function getRemoteIp(): ?string
    {
        $ip = \file_get_contents('http://ipecho.net/plain');
        if (self::isValid($ip)) {
            return $ip;
        }

        return null;
    }

    /**
     * Returns the first valid proxied IP found.
     *
     * @param ServerRequestInterface $request
     *
     * @return string|null
     */
    private function getProxiedIp(ServerRequestInterface $request): ?string
    {
        foreach ($this->proxyHeaders as $name) {
            if ($request->hasHeader($name)) {
                $ip = self::getHeaderIp($request->getHeaderLine($name));
                if ($ip !== null) {
                    return $ip;
                }
            }
        }

        return null;
    }

    /**
     * Returns the remote address of the request, if valid.
     *
     * @param ServerRequestInterface $request
     *
     * @return string|null
     */
    private function getLocalIp(ServerRequestInterface $request): ?string
    {
        $server = $request->getServerParams();
        if (!empty($server['REMOTE_ADDR']) && self::isValid($server['REMOTE_ADDR'])) {
            return $server['REMOTE_ADDR'];
        }

        return null;
    }

    /**
     * Returns the first valid ip found in the header.
     *
     * @param string $header
     *
     * @return string|null
     */
    private static function getHeaderIp($header): ?string
    {
        foreach (\array_map('\trim', \explode(',', $header)) as $ip) {
            if (self::isValid($ip)) {
                return $ip;
            }
        }

        return null;
    }

    /**
     * Check that a given string is a valid IP address.
     *
     * @param string $ip
     *
     * @return bool
     */
    private static function isValid($ip)
    {
        return \filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6) !== false;
    }
}


text:
import test from 'ava';
import dogNames from '.';

test('main', t => {
	t.true(dogNames.female.length > 0);
	t.true(dogNames.male.length > 0);
	t.true(dogNames.all.length > 0);
	t.truthy(dogNames.femaleRandom());
	t.truthy(dogNames.maleRandom());
	t.truthy(dogNames.allRandom());
	t.not(dogNames.allRandom(), dogNames.allRandom());
	t.is(dogNames.all[0], 'Bella');
	t.is(dogNames.all[1], 'Max');
});


text:
using System;
using System.ComponentModel.DataAnnotations;

namespace AdvanceMockExample.Models
{
    public class NotificationEventLog
    {
        [Key]
        public int Id { get; set; }

        public DateTime SentAt { get; set; }

        public int NotificationEventId { get; set; }
        public virtual NotificationEvent NotificationEvent { get; set; }

        public int NotificationRecipientId { get; set; }
        public virtual NotificationRecipient NotificationRecipient { get; set; }

    }
}


text:
import re
import json
from datetime import time, datetime
from dateutil.relativedelta import relativedelta

from django.utils import timezone
from django.utils.translation import ugettext as _
from django.db import models
from django.core.exceptions import ValidationError

from app.storage import OverwriteStorage
from jsonfield import JSONField
from provider.models import Provider
from series.models import MediaType
from series.util import poster_path

class Series(models.Model):
    """
    Series
    """

    provider = models.ForeignKey(Provider, on_delete=models.CASCADE)
    title = models.CharField(max_length=160,
                             verbose_name="Name of the series")

    search_title = models.CharField(max_length=256,
                                    blank=True,
                                    default='',
                                    verbose_name="String to be used when searching for the series")

    save_path = models.CharField(max_length=256,
                                 default='',
                                 blank=True,
                                 verbose_name="Path to be sorted into")

    info_url = models.URLField(blank=True,
                               verbose_name="Information URL")

    start_date = models.DateField(default=None,
                                  null=True)
    end_date = models.DateField(default=None,
                                null=True)

    release_time = models.TimeField(default=time(hour=12))

    current_count = models.PositiveSmallIntegerField(default=0)
    total_count = models.PositiveSmallIntegerField(default=0)

    poster = models.ImageField(editable=True,
                               upload_to=poster_path,
                               storage=OverwriteStorage(),
                               null=True)

    media_type = models.ForeignKey(MediaType,
                                   on_delete=models.CASCADE,
                                   help_text="Series' media type")

    media_type_options = JSONField(blank=True,
                                   help_text="A JSON object of options"
                                   " made available from the media type")

    NONE = 'N'
    WEEKLY = 'W'
    FORTNIGHTLY = 'F'
    MONTHLY = 'M'
    DISCRETE = 'D'
    RELEASE_SCHEDULE_CHOICES = (
        (NONE, _('None')),
        (WEEKLY, _('Weekly')),
        (FORTNIGHTLY, _('Fortnightly')),
        (MONTHLY, _('Monthly')),
        (DISCRETE, _('Discrete')),
    )
    release_schedule = models.CharField(max_length=1,
                                        default=WEEKLY,
                                        choices=RELEASE_SCHEDULE_CHOICES)
    release_schedule_options = JSONField(blank=True,
                                         help_text="A JSON object of needed"
                                         " info for each type of release schedule")

    def clean(self):
        """
        Clean and validate model

        Throws ValidationError when:
            - current count is below 0
            - total count is defined & below zero
            - total count is defined & current is larger than total
        """
        if self.current_count < 0:
            raise ValidationError('Currnet count cannot be below zero')

        if self.total_count is not None:
            if self.total_count < 0:
                raise ValidationError('Currnet count cannot be below zero')
            if self.current_count > self.total_count != 0:
                raise ValidationError('Current count cannot be bigger than total count, unless total count is zero')

        if self.end_date is not None:
            if self.start_date > self.end_date:
                raise ValidationError('Start date cannot be greater than end date')

    def next_release(self):
        """
        Calculate the datetime of the next release of the series

        Returns:
            Return a DateTime object of the next next_release
            If the series is finished airing will return None
        """
        if self.start_date is None:
            return None

        if self.has_ended():
            return None

        if not self.has_started():
            return datetime.combine(self.start_date, self.release_time)

        # is airing
        release_date = self.start_date
        delta = None
        if self.release_schedule == Series.WEEKLY:
            delta = relativedelta(days=7)
        elif self.release_schedule == Series.FORTNIGHTLY:
            delta = relativedelta(days=14)
        elif self.release_schedule == Series.MONTHLY:
            delta = relativedelta(months=1)
        else:
            if self.end_date is not None:
                return datetime.combine(self.end_date, self.release_time)
            else:
                return None

        while datetime.combine(release_date, self.release_time) < datetime.now():
            release_date += delta

        release_datetime = datetime.combine(release_date, self.release_time)
        return release_datetime

    def has_started(self):
        """
        Series has started airing/publishing

        Note:
            uses release_time for time of day
        """
        return self.start_date is not None and \
                timezone.now() >= timezone.make_aware(
                    datetime.combine(self.start_date, self.release_time))

    def has_ended(self):
        """
        Series has ended airing/publishing

        Note:
            uses release_time for time of day
        """
        if self.total_count != 0 and self.current_count >= self.total_count:
            return True

        if self.end_date is not None:
            return timezone.now() > timezone.make_aware(
                   datetime.combine(self.end_date, self.release_time))

        return False

    def is_airing(self):
        """
        Boolean of if the series is currently airing/publishing

        note:
            relies on has_started() and has_ended()
        """
        return self.has_started() and not self.has_ended()

    def __str__(self):
        return "{} ({})".format(self.title, self.provider.name)

    def bootstrap_label_class(self):
        """
        Generate HTML class for label for bootstrap 3
        """
        if self.is_airing():
            return 'label-success'
        if self.has_ended():
            return 'label-danger'
        if not self.has_started():
            return 'label-info'

    def label_text(self):
        """
        Generate HTML class for label for bootstrap 3
        """
        if self.is_airing():
            return _('Airing')
        if self.has_ended():
            return _('Finished')
        if not self.has_started():
            return _('Soon')

    def bootstrap_progressbar(self):
        """
        Generate HTML for a progress bar for bootstrap 3
        """
        text = ""
        sr = ""
        pb_class = "progress-bar-success"
        value = self.current_count
        max = self.total_count

        if self.total_count == 0:
            pb_class = "progress-bar-warning progress-bar-striped"
            value = self.current_count
            max = self.current_count
            prec = 100
        else:
            prec = round(value/max * 100)

        return """

                {sr}
                {text}

        """.format(pb_class=pb_class,
                   value=value,
                   max=max,
                   prec=prec,
                   sr=sr,
                   text=text)

    def release_schedule_options_json(self):
        """
        dumps release_schedule as json
        """
        return json.dumps(self.release_schedule_options)

    def media_type_options_json(self):
        """
        dumps media_type_options as json
        """
        return json.dumps(self.media_type_options)

    def info_url_domain(self):
        """
        Get the domain name of the info_url
        """
        if type(self.info_url) is str:
            return re.sub('^.*://', '', self.info_url).split('/')[0]


text: sudo rm -r -f build/if2k.build build/Release build/Development build/if2kext.build


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <FrameLayout
        android:id="@+id/albumFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

    <FrameLayout
        android:id="@+id/playerFragment"
        android:layout_width="500dp"
        android:layout_height="150dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="false"
        android:layout_alignParentRight="false"
        android:layout_centerHorizontal="true"></FrameLayout>

</RelativeLayout>


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Match',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('is_active', models.BooleanField(default=True, help_text='Whether this item is active, use this instead of deleting')),
                ('created_on', models.DateTimeField(auto_now_add=True, help_text='When this item was originally created')),
                ('modified_on', models.DateTimeField(auto_now=True, help_text='When this item was last modified')),
                ('date', models.DateField()),
                ('created_by', models.ForeignKey(help_text='The user which originally created this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_match_creations', to=settings.AUTH_USER_MODEL)),
                ('modified_by', models.ForeignKey(help_text='The user which last modified this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_match_modifications', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Player',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('is_active', models.BooleanField(default=True, help_text='Whether this item is active, use this instead of deleting')),
                ('created_on', models.DateTimeField(auto_now_add=True, help_text='When this item was originally created')),
                ('modified_on', models.DateTimeField(auto_now=True, help_text='When this item was last modified')),
                ('name', models.CharField(help_text="The player's name", max_length=128)),
                ('created_by', models.ForeignKey(help_text='The user which originally created this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_player_creations', to=settings.AUTH_USER_MODEL)),
                ('modified_by', models.ForeignKey(help_text='The user which last modified this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_player_modifications', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ('name',),
            },
        ),
        migrations.CreateModel(
            name='PlayerScore',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('is_active', models.BooleanField(default=True, help_text='Whether this item is active, use this instead of deleting')),
                ('created_on', models.DateTimeField(auto_now_add=True, help_text='When this item was originally created')),
                ('modified_on', models.DateTimeField(auto_now=True, help_text='When this item was last modified')),
                ('game', models.IntegerField()),
                ('score', models.IntegerField()),
                ('created_by', models.ForeignKey(help_text='The user which originally created this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_playerscore_creations', to=settings.AUTH_USER_MODEL)),
                ('match', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scores', to='league.Match')),
                ('modified_by', models.ForeignKey(help_text='The user which last modified this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_playerscore_modifications', to=settings.AUTH_USER_MODEL)),
                ('player', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scores', to='league.Player')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Season',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('is_active', models.BooleanField(default=True, help_text='Whether this item is active, use this instead of deleting')),
                ('created_on', models.DateTimeField(auto_now_add=True, help_text='When this item was originally created')),
                ('modified_on', models.DateTimeField(auto_now=True, help_text='When this item was last modified')),
                ('name', models.CharField(help_text='Season Name', max_length=128)),
                ('start_date', models.DateField(help_text='When the season started')),
                ('end_date', models.DateField(help_text='When the season ended')),
                ('created_by', models.ForeignKey(help_text='The user which originally created this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_season_creations', to=settings.AUTH_USER_MODEL)),
                ('modified_by', models.ForeignKey(help_text='The user which last modified this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_season_modifications', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Team',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('is_active', models.BooleanField(default=True, help_text='Whether this item is active, use this instead of deleting')),
                ('created_on', models.DateTimeField(auto_now_add=True, help_text='When this item was originally created')),
                ('modified_on', models.DateTimeField(auto_now=True, help_text='When this item was last modified')),
                ('name', models.CharField(help_text='The team name', max_length=128)),
                ('created_by', models.ForeignKey(help_text='The user which originally created this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_team_creations', to=settings.AUTH_USER_MODEL)),
                ('modified_by', models.ForeignKey(help_text='The user which last modified this item', on_delete=django.db.models.deletion.CASCADE, related_name='league_team_modifications', to=settings.AUTH_USER_MODEL)),
                ('season', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='league.Season')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='playerscore',
            name='team',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scores', to='league.Team'),
        ),
        migrations.AddField(
            model_name='match',
            name='season',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='matches', to='league.Season'),
        ),
        migrations.AddField(
            model_name='match',
            name='team1',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='team1_matches', to='league.Team'),
        ),
        migrations.AddField(
            model_name='match',
            name='team2',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='team2_matches', to='league.Team'),
        ),
    ]


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015 the original author or authors.
  ~
  ~ Licensed 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>dist</artifactId>
        <groupId>io.rest-assured</groupId>
        <version>3.0.2-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <packaging>pom</packaging>
    <artifactId>dist-spring-mock-mvc</artifactId>

    <name>Spring Mock MVC distribution jar</name>
    <build>
        <finalName>spring-mock-mvc-${project.version}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>package-rest-assured</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <appendAssemblyId>false</appendAssemblyId>
                            <finalName>spring-mock-mvc-${project.version}</finalName>
                            <descriptors>
                                <descriptor>src/main/assembly/spring-mock-mvc-full-jar.xml</descriptor>
                            </descriptors>
                        </configuration>
                    </execution>
                    <execution>
                        <id>package-rest-assured-deps</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <appendAssemblyId>false</appendAssemblyId>
                            <finalName>spring-mock-mvc-${project.version}-deps</finalName>
                            <descriptors>
                                <descriptor>src/main/assembly/dependencies.xml</descriptor>
                            </descriptors>
                        </configuration>
                    </execution>
                    <execution>
                        <id>package-spring-mock-mvc-dist</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <appendAssemblyId>false</appendAssemblyId>
                            <finalName>spring-mock-mvc-${project.version}-dist</finalName>
                            <descriptors>
                                <descriptor>src/main/assembly/spring-mock-mvc-dist.xml</descriptor>
                            </descriptors>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>spring-mock-mvc</artifactId>
            <version>${project.version}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>


text:
package co.omise.requests;

import co.omise.models.Charge;
import co.omise.models.OmiseException;
import co.omise.models.ScopedList;
import co.omise.models.schedules.*;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class ScheduleRequestTest extends RequestTest {

    private final String SCHEDULE_ID = "schd_test_57s33hm9fg1pzcqihxs";

    private Requester requester;

    @Before
    public void setUp() {
        requester = getTestRequester();
    }

    @Test
    public void testGet() throws IOException, OmiseException {
        Request<Schedule> request = new Schedule.GetRequestBuilder(SCHEDULE_ID).build();

        Schedule schedule = requester.sendRequest(request);

        assertRequested("GET", "/schedules/" + SCHEDULE_ID, 200);

        assertEquals(SCHEDULE_ID, schedule.getId());
        assertEquals(ScheduleStatus.Running, schedule.getStatus());
        assertEquals(1, schedule.getEvery());
        assertEquals(SchedulePeriod.Month, schedule.getPeriod());
        assertEquals(11, schedule.getNextOccurrencesOn().size());
    }

    @Test
    public void testList() throws IOException, OmiseException {
        Request<ScopedList<Schedule>> request = new Schedule.ListRequestBuilder().build();

        ScopedList<Schedule> scheduleList = requester.sendRequest(request);

        assertRequested("GET", "/schedules", 200);
        assertEquals(11, scheduleList.getTotal());
    }

    @Test
    public void testCreate() throws IOException, OmiseException {
        Request<Schedule> request = new Schedule.CreateRequestBuilder()
                .every(1)
                .period(SchedulePeriod.Month)
                .on(new ScheduleOn.Params().daysOfMonth(2))
                .startDate(LocalDate.parse("2017-04-27"))
                .endDate(LocalDate.parse("2018-04-27"))
                .charge(new ChargeSchedule.Params()
                        .customer("cust_test_55bb3hkywglfyyachha")
                        .amount(88800)
                        .description("Monthly membership fee"))
                .build();

        Schedule schedule = requester.sendRequest(request);

        assertRequested("POST", "/schedules", 200);

        assertEquals(SCHEDULE_ID, schedule.getId());
        assertEquals(1, schedule.getEvery());
        assertEquals(SchedulePeriod.Month, schedule.getPeriod());
        assertEquals(11, schedule.getNextOccurrencesOn().size());
    }

    @Test
    public void testDelete() throws IOException, OmiseException {
        Request<Schedule> request = new Schedule.DeleteRequestBuilder(SCHEDULE_ID).build();

        Schedule schedule = requester.sendRequest(request);

        assertRequested("DELETE", "/schedules/" + SCHEDULE_ID, 200);

        assertEquals(SCHEDULE_ID, schedule.getId());
        assertEquals(ScheduleStatus.Deleted, schedule.getStatus());
    }

    @Test
    public void testChargeScheduleList() throws IOException, OmiseException {
        Request<ScopedList<Schedule>> request = new Charge.ListSchedulesRequestBuilder().build();

        ScopedList<Schedule> schedules = requester.sendRequest(request);

        assertRequested("GET", "/charges/schedules", 200);
        assertEquals(5, schedules.getTotal());
    }

    @Test
    public void testCustomerScheduleList() throws IOException, OmiseException {
        String customerId = "cust_test_4yq6txdpfadhbaqnwp3";
        Request<ScopedList<Schedule>> request = new Schedule.CustomerScheduleListRequestBuilder(customerId).build();

        ScopedList<Schedule> schedules = requester.sendRequest(request);

        assertRequested("GET", "/customers/" + customerId + "/schedules", 200);
        assertEquals(2, schedules.getTotal());
    }

    @Test
    public void testTransferScheduleListGet() throws IOException, OmiseException {
        Request<ScopedList<Schedule>> request = new Schedule.TransferScheduleListRequestBuilder().build();

        ScopedList<Schedule> scheduleList = requester.sendRequest(request);

        assertRequested("GET", "/transfers/schedules", 200);
        assertEquals(1, scheduleList.getTotal());
    }

    @Test
    public void testRecipientScheduleListGet() throws IOException, OmiseException {
        String recipientId = "recp_test_50894vc13y8z4v51iuc";
        Request<ScopedList<Schedule>> request = new Schedule.RecipientScheduleListRequestBuilder(recipientId).build();

        ScopedList<Schedule> scheduleList = requester.sendRequest(request);

        assertRequested("GET", "/recipients/" + recipientId + "/schedules", 200);
        assertEquals(1, scheduleList.getTotal());
    }
}


text:
<?php

namespace spec\Sylius\Bundle\PayumBundle\Action\Offline;

use Payum\Core\Action\ActionInterface;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\PayumBundle\Action\Offline\ResolveNextRouteAction;
use Sylius\Bundle\PayumBundle\Request\ResolveNextRoute;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
final class ResolveNextRouteActionSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(ResolveNextRouteAction::class);
    }

    function it_is_a_payum_action()
    {
        $this->shouldImplement(ActionInterface::class);
    }

    function it_resolves_next_route(ResolveNextRoute $resolveNextRouteRequest)
    {
        $resolveNextRouteRequest->setRouteName('sylius_shop_order_thank_you')->shouldBeCalled();

        $this->execute($resolveNextRouteRequest);
    }
}


text:
<?php
defined('WYSIJA') or die('Restricted access');

class WYSIJA_control_front_stats extends WYSIJA_control_front{
    var $model=''   ;
    var $view='';

    function WYSIJA_control_front_stats(){
        parent::WYSIJA_control_front();
    }

    /**
     * count the click statistic and redirect to the right url
     * @return boolean
     */
    function analyse(){
        if(isset($_REQUEST['email_id']) && isset($_REQUEST['user_id'])){

            $WJ_Stats = new WJ_Stats();
            if(!empty($WJ_Stats->clicked_url)){
                //clicked stats
                $url = $WJ_Stats->subscriber_clicked();
                do_action('mpoet_click_stats', $WJ_Stats);
                $this->redirect($url);
            }else{
                //opened stat */
                $WJ_Stats->subscriber_opened();
            }
        }

        return true;
    }

}


text:
require 'gitlab/markdown'

module Gitlab
  module Markdown
    # HTML filter that replaces issue references with links. References to
    # issues that do not exist are ignored.
    #
    # This filter supports cross-project references.
    class IssueReferenceFilter < ReferenceFilter
      include CrossProjectReference

      # Public: Find `#123` issue references in text
      #
      #   IssueReferenceFilter.references_in(text) do |match, issue, project_ref|
      #     "##{issue}"
      #   end
      #
      # text - String text to search.
      #
      # Yields the String match, the Integer issue ID, and an optional String of
      # the external project reference.
      #
      # Returns a String replaced with the return of the block.
      def self.references_in(text)
        text.gsub(Issue.reference_pattern) do |match|
          yield match, $~[:issue].to_i, $~[:project]
        end
      end

      def call
        replace_text_nodes_matching(Issue.reference_pattern) do |content|
          issue_link_filter(content)
        end
      end

      # Replace `#123` issue references in text with links to the referenced
      # issue's details page.
      #
      # text - String text to replace references in.
      #
      # Returns a String with `#123` references replaced with links. All links
      # have `gfm` and `gfm-issue` class names attached for styling.
      def issue_link_filter(text)
        self.class.references_in(text) do |match, id, project_ref|
          project = self.project_from_ref(project_ref)

          if project && issue = project.get_issue(id)
            push_result(:issue, issue)

            url = url_for_issue(id, project, only_path: context[:only_path])

            title = escape_once("Issue: #{issue.title}")
            klass = reference_class(:issue)
            data  = data_attribute(project.id)

            %(#{match})
          else
            match
          end
        end
      end

      def url_for_issue(*args)
        IssuesHelper.url_for_issue(*args)
      end
    end
  end
end


text:
package com.facebook.react.views.textinput;

import androidx.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.Event;

/** Event emitted by EditText native view when the text selection changes. */
/* package */ class ReactTextInputSelectionEvent extends Event<ReactTextInputSelectionEvent> {

  private static final String EVENT_NAME = "topSelectionChange";

  private int mSelectionStart;
  private int mSelectionEnd;

  @Deprecated
  public ReactTextInputSelectionEvent(int viewId, int selectionStart, int selectionEnd) {
    this(-1, viewId, selectionStart, selectionEnd);
  }

  public ReactTextInputSelectionEvent(
      int surfaceId, int viewId, int selectionStart, int selectionEnd) {
    super(surfaceId, viewId);
    mSelectionStart = selectionStart;
    mSelectionEnd = selectionEnd;
  }

  @Override
  public String getEventName() {
    return EVENT_NAME;
  }

  @Nullable
  @Override
  protected WritableMap getEventData() {
    WritableMap eventData = Arguments.createMap();

    WritableMap selectionData = Arguments.createMap();
    selectionData.putInt("end", mSelectionEnd);
    selectionData.putInt("start", mSelectionStart);

    eventData.putMap("selection", selectionData);
    return eventData;
  }
}


text:
from lasagne.layers import Layer, InputLayer, DropoutLayer, DenseLayer, NonlinearityLayer, ElemwiseMergeLayer, SliceLayer, ConcatLayer, get_output, get_all_params
from lasagne.objectives import categorical_crossentropy, squared_error, aggregate
from lasagne.nonlinearities import softmax, rectify, sigmoid
from lasagne.updates import sgd, adagrad, adam, adadelta, apply_nesterov_momentum
from lasagne.init import Constant
import theano.tensor as T
import theano
import numpy as np

from utils import BatchIterator
from neuralforestlayer import NeuralForestLayer

__DEBUG_NO_FOREST__ = False

class ShallowNeuralForest:
    def __init__(self, n_inputs, n_outputs, regression, multiclass=False, depth=5, n_estimators=20, n_hidden=128, learning_rate=0.01, num_epochs=500, pi_iters=20, sgd_iters=10, batch_size=1000, momentum=0.0, dropout=0.0, loss=None, update=adagrad):
        """
        Parameters
        ----------
        n_inputs : number of input features
        n_outputs : number of classes to predict (1 for regression)
            for 2 class classification n_outputs should be 2, not 1
        regression : True for regression, False for classification
        multiclass : not used
        depth : depth of each tree in the ensemble
        n_estimators : number of trees in the ensemble
        n_hidden : number of neurons in the hidden layer
        pi_iters : number of iterations for the iterative algorithm that updates pi
        sgd_iters : number of full iterations of sgd between two consequtive updates of pi
        loss : theano loss function. If None, squared error will be used for regression and
            cross entropy will be used for classification
        update : theano update function
        """
        self._depth = depth
        self._n_estimators = n_estimators
        self._n_hidden = n_hidden
        self._n_outputs = n_outputs
        self._loss = loss
        self._regression = regression
        self._multiclass = multiclass
        self._learning_rate = learning_rate
        self._num_epochs = num_epochs
        self._pi_iters = pi_iters
        self._sgd_iters = sgd_iters
        self._batch_size = batch_size
        self._momentum = momentum
        self._update = update

        self.t_input = T.matrix('input')
        self.t_label = T.matrix('output')

        self._cached_trainable_params = None
        self._cached_params = None

        self._n_net_out = n_estimators * ((1 << depth) - 1)

        self.l_input = InputLayer((None, n_inputs))
        self.l_dense1 = DenseLayer(self.l_input, self._n_hidden, nonlinearity=rectify)
        if dropout != 0:
            self.l_dense1 = DropoutLayer(self.l_dense1, p=dropout)
        if not __DEBUG_NO_FOREST__:
            self.l_dense2 = DenseLayer(self.l_dense1, self._n_net_out, nonlinearity=sigmoid)
            self.l_forest = NeuralForestLayer(self.l_dense2, self._depth, self._n_estimators, self._n_outputs, self._pi_iters)
        else:
            self.l_forest = DenseLayer(self.l_dense1, self._n_outputs, nonlinearity=softmax)

    def _create_functions(self):
        self._update_func = self._update(self._get_loss_function(), self._get_all_trainable_params(), self._learning_rate)
        if self._momentum != 0:
            self._update_func = apply_nesterov_momentum(self._update_func, self._get_all_trainable_params(), self._momentum)
        self._loss_func = self._get_loss_function()
        self._train_function = theano.function([self.t_input, self.t_label], self._get_loss_function(), updates=self._update_func)

    def fit(self, X, y, X_val = None, y_val = None, on_epoch = None, verbose = False):
        """ Train the model

        Parameters
        ----------
        X : input vector for the training set
        y : output vector for the training set. Onehot is required for classification
        X_val : if not None, input vector for the validation set
        y_val : it not None, input vector for the validation set
        on_epoch : a callback that is called after each epoch
            if X_val is None, the signature is (epoch, training_error, accuracy)
            if X_val is not None, the signature is (epoch, training_error, validation_error, accuracy)
            on iterations that update pi the training error is reported for the previous iteration
        verbose : if True, spams current step on each epoch
        """
        self._create_functions()

        X = X.astype(np.float32)
        y = y.astype(np.float32)
        self._x_mean = np.mean(X, axis=0)
        self._x_std = np.std(X, axis=0)
        self._x_std[self._x_std == 0] = 1
        X = (X - self._x_mean) / self._x_std
        if y_val is not None:
            assert X_val is not None
            X_val = X_val.astype(np.float32)
            y_val = y_val.astype(np.float32)
            X_val = (X_val - self._x_mean) / self._x_std

        if X_val is not None:
            assert y_val is not None

            predictions = self._predict_internal(self._get_output())
            accuracy = T.mean(T.eq(predictions, self._predict_internal(self.t_label)))

            test_function = theano.function([self.t_input, self.t_label], [self._get_loss_function(), accuracy])

        iterator = BatchIterator(self._batch_size)

        loss = 0
        for epoch in range(self._num_epochs):

            # update the values of pi
            if not __DEBUG_NO_FOREST__ and epoch % self._sgd_iters == 0:
                if verbose: print "updating pi"
                self.l_forest.update_pi(X, y)
                if verbose: print "recreating update funcs"
                self._create_functions()

            else:
                if verbose: print "updating theta"
                loss = 0
                deno = 0
                # update the network parameters
                for Xb, yb in iterator(X, y):
                    loss += self._train_function(Xb, yb)
                    deno += 1

                loss /= deno

            if X_val is not None:
                tloss = 0
                accur = 0
                deno = 0
                iterator = BatchIterator(self._batch_size)
                for Xb, yb in iterator(X_val, y_val):
                    tl, ac = test_function(Xb, yb)
                    tloss += tl
                    accur += ac
                    deno += 1
                tloss /= deno
                accur /= deno

            if on_epoch is not None:
                if X_val is None:
                    on_epoch(epoch, loss)
                else:
                    on_epoch(epoch, loss, tloss, accur)

        return self

    def _predict_internal(self, y):
        if not self._regression and not self._multiclass:
            return y.argmax(axis=1)
        else:
            return y >= 0.5

    def predict(self, X):
        ret = self.predict_proba(X)
        return self._predict_internal(ret)

    def predict_proba(self, X):
        X = X.astype(np.float32)
        X = (X - self._x_mean) / self._x_std
        predict_function = theano.function([self.t_input], self._get_output())
        return predict_function(X)

    def _get_loss_function(self):
        # TODO: remove `or True`
        if self._loss is None:
            if self._regression:
                self._loss = squared_error
            else:
                self._loss = categorical_crossentropy
        return aggregate(self._loss(self._get_output(), self.t_label), mode='mean')

    def _get_output(self):
        return get_output(self.l_forest, self.t_input)

    def _get_all_trainable_params(self):
        if self._cached_trainable_params is None:
            self._cached_trainable_params = get_all_params(self.l_forest, trainable=True)
        return self._cached_trainable_params

    def _get_all_params(self):
        if self._cached_params is None:
            self._cached_params = get_all_params(self.l_forest)
        return self._cached_params


text:
  Value: <input spellcheck="false" autofocus="" value="considerations">
  stems to: <output>consider</output>


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-7
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.10.24 at 10:41:34 PM CDT
//

package org.statmantis.mport.mlb.gen;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for gameEventInning complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="gameEventInning">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="top" type="{http://gdx.mlb.com/components/schema/1}gameEventInningHalf"/>
 *         <element name="bottom" type="{http://gdx.mlb.com/components/schema/1}gameEventInningHalf"/>
 *       </sequence>
 *       <attribute name="num" type="{http://www.w3.org/2001/XMLSchema}int" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "gameEventInning", propOrder = {
    "top",
    "bottom"
})
public class GameEventInning {

    @XmlElement(required = true)
    protected GameEventInningHalf top;
    @XmlElement(required = true)
    protected GameEventInningHalf bottom;
    @XmlAttribute(name = "num")
    protected Integer num;

    /**
     * Gets the value of the top property.
     *
     * @return
     *     possible object is
     *     {@link GameEventInningHalf }
     *
     */
    public GameEventInningHalf getTop() {
        return top;
    }

    /**
     * Sets the value of the top property.
     *
     * @param value
     *     allowed object is
     *     {@link GameEventInningHalf }
     *
     */
    public void setTop(GameEventInningHalf value) {
        this.top = value;
    }

    /**
     * Gets the value of the bottom property.
     *
     * @return
     *     possible object is
     *     {@link GameEventInningHalf }
     *
     */
    public GameEventInningHalf getBottom() {
        return bottom;
    }

    /**
     * Sets the value of the bottom property.
     *
     * @param value
     *     allowed object is
     *     {@link GameEventInningHalf }
     *
     */
    public void setBottom(GameEventInningHalf value) {
        this.bottom = value;
    }

    /**
     * Gets the value of the num property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getNum() {
        return num;
    }

    /**
     * Sets the value of the num property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setNum(Integer value) {
        this.num = value;
    }

}