text:
require 'test_helper'

module Leaders
  class DepartmentsTest < ActionDispatch::IntegrationTest
    setup do
      login_as users(:fabricio)
    end

    test 'viewing only led departments' do
      visit departments_path

      assert_content 'Financeiro'
      assert_no_content 'Contábil'

      visit department_path(departments(:financial))

      assert_content 'Financeiro'
      assert_content 'Ademar'
      assert_content 'Carlos'
      assert_no_content 'Nilson'

      assert_raise ActiveRecord::RecordNotFound do
        visit department_path(departments(:accounting))
      end
    end

    test 'cannot manage department' do
      visit departments_path
      assert_no_link 'Novo'
      assert_no_link 'Editar'
      assert_no_link 'Remover'

      visit department_path(departments(:financial))
      assert_no_link 'Editar'
      assert_no_link 'Remover'

      visit new_department_path
      assert_no_access

      visit edit_department_path(departments(:accounting))
      assert_no_access
    end

    private

    def assert_no_access
      assert_flash 'Você não tem acesso.'
      assert_current_path root_path
    end
  end
end


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

namespace DrynksMe.DataAccess.Models
{
    /// <summary>
    /// A class which represents the MerchantType table.
    /// </summary>
	[Table("MerchantType")]
	public partial class MerchantType
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual string TypeDescription { get; set; }
	}

    /// <summary>
    /// A class which represents the MerchantTag table.
    /// </summary>
	[Table("MerchantTag")]
	public partial class MerchantTag
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual int MerchantId { get; set; }
		public virtual int TagId { get; set; }
	}

    /// <summary>
    /// A class which represents the UserMerchantComment table.
    /// </summary>
	[Table("UserMerchantComment")]
	public partial class UserMerchantComment
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual int? UserId { get; set; }
		public virtual int? MerchantId { get; set; }
		public virtual string Comment { get; set; }
		public virtual bool IsApproved { get; set; }
		public virtual DateTime? CreateDate { get; set; }
		public virtual DateTime? UpdateDate { get; set; }
		public virtual bool IsShared { get; set; }
	}

    /// <summary>
    /// A class which represents the MerchantTypeAssociation table.
    /// </summary>
	[Table("MerchantTypeAssociation")]
	public partial class MerchantTypeAssociation
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual int MerchantId { get; set; }
		public virtual int MerchantTypeId { get; set; }
	}

    /// <summary>
    /// A class which represents the Drink table.
    /// </summary>
	[Table("Drink")]
	public partial class Drink
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual string DrinkName { get; set; }
		public virtual string DrinkDescription { get; set; }
		public virtual string FoundAt { get; set; }
		public virtual string Origin { get; set; }
		public virtual DateTime? CreateDt { get; set; }
		public virtual DateTime? UpdateDt { get; set; }
		public virtual string ImageSmall { get; set; }
		public virtual string ImageLarge { get; set; }
		public virtual string ImageMedium { get; set; }
		public virtual string StandardPicUrl { get; set; }
		public virtual decimal? AlcoholContent { get; set; }
		public virtual bool IsShared { get; set; }
	}

    /// <summary>
    /// A class which represents the User table.
    /// </summary>
	[Table("User")]
	public partial class User
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual string FirstName { get; set; }
		public virtual string LastName { get; set; }
		public virtual string MiddleInitial { get; set; }
		public virtual string DeviceId { get; set; }
		public virtual string TwitterId { get; set; }
		public virtual string FacebookId { get; set; }
		public virtual DateTime? CreateDt { get; set; }
		public virtual DateTime? UpdateDt { get; set; }
		public virtual string TwitterPicUrl { get; set; }
		public virtual int UserProfileId { get; set; }
		public virtual bool Share { get; set; }
		public virtual string AnonymousSystemId { get; set; }
	}

    /// <summary>
    /// A class which represents the Tag table.
    /// </summary>
	[Table("Tag")]
	public partial class Tag
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual string TagName { get; set; }
		public virtual string TagDescription { get; set; }
		public virtual bool? IsAdminGenerated { get; set; }
		public virtual DateTime? CreateDt { get; set; }
		public virtual DateTime? UpdateDt { get; set; }
	}

    /// <summary>
    /// A class which represents the DrinkPrice table.
    /// </summary>
	[Table("DrinkPrice")]
	public partial class DrinkPrice
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual int DrinkId { get; set; }
		public virtual string Size { get; set; }
		public virtual decimal? RetailPrice { get; set; }
		public virtual DateTime? CreateDt { get; set; }
		public virtual DateTime? UpdateDt { get; set; }
	}

    /// <summary>
    /// A class which represents the Merchant table.
    /// </summary>
	[Table("Merchant")]
	public partial class Merchant
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual string MerchantName { get; set; }
		public virtual string ProfileName { get; set; }
		public virtual string Description { get; set; }
		public virtual string Location { get; set; }
		public virtual string PrimaryContact { get; set; }
		public virtual string ContactNumber { get; set; }
		public virtual string CustomerNumber { get; set; }
		public virtual DateTime? CreateDt { get; set; }
		public virtual DateTime? UpdateDt { get; set; }
		public virtual string ShortVenueInformation { get; set; }
		public virtual string AddressInfo { get; set; }
		public virtual string City { get; set; }
		public virtual string State { get; set; }
		public virtual string Zip { get; set; }
		public virtual string TwitterHandle { get; set; }
		public virtual string Website { get; set; }
		public virtual string VenueType { get; set; }
		public virtual string ImageSmall { get; set; }
		public virtual string ImageLarge { get; set; }
		public virtual string ImageMedium { get; set; }
		public virtual bool IsActive { get; set; }
		public virtual string Email { get; set; }
		public virtual bool IsPremierMerchant { get; set; }
		public virtual decimal? Longitude { get; set; }
		public virtual decimal? Latitude { get; set; }
	}

    /// <summary>
    /// A class which represents the MerchantDrink table.
    /// </summary>
	[Table("MerchantDrink")]
	public partial class MerchantDrink
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual int MerchantId { get; set; }
		public virtual int DrinkId { get; set; }
		public virtual bool? IsSignature { get; set; }
	}

    /// <summary>
    /// A class which represents the DrinkUser table.
    /// </summary>
	[Table("DrinkUser")]
	public partial class DrinkUser
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual int DrinkId { get; set; }
		public virtual int UserId { get; set; }
		public virtual bool? IsLiked { get; set; }
		public virtual DateTime? CreateDt { get; set; }
		public virtual DateTime? UpdateDt { get; set; }
		public virtual string UserNotes { get; set; }
		public virtual bool UserRating { get; set; }
		public virtual string UserUploadedPictureUrl { get; set; }
	}

    /// <summary>
    /// A class which represents the UserTag table.
    /// </summary>
	[Table("UserTag")]
	public partial class UserTag
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual int UserId { get; set; }
		public virtual int TagId { get; set; }
		public virtual DateTime? CreateDt { get; set; }
		public virtual DateTime? UpdateDt { get; set; }
	}

    /// <summary>
    /// A class which represents the DrinkTag table.
    /// </summary>
	[Table("DrinkTag")]
	public partial class DrinkTag
	{
		[Key]
		public virtual int DrinkTagId { get; set; }
		public virtual int DrinkId { get; set; }
		public virtual int TagId { get; set; }
		public virtual DateTime? CreateDt { get; set; }
		public virtual DateTime? UpdateDt { get; set; }
	}

    /// <summary>
    /// A class which represents the Campaign table.
    /// </summary>
	[Table("Campaign")]
	public partial class Campaign
	{
		[Key]
		public virtual int Id { get; set; }
		public virtual int MerchantId { get; set; }
		public virtual bool IsActive { get; set; }
		public virtual DateTime? StartDate { get; set; }
		public virtual DateTime? EndDate { get; set; }
		public virtual string Name { get; set; }
		public virtual string Description { get; set; }
	}

    /// <summary>
    /// A class which represents the UserProfile table.
    /// </summary>
	[Table("UserProfile")]
	public partial class UserProfile
	{
		[Key]
		public virtual int UserId { get; set; }
		public virtual string UserName { get; set; }
		public virtual bool IsActive { get; set; }
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<head>

<meta charset=UTF-8>

<title>Brahma</title>

<link rel="stylesheet" href="style.css">

<script src=Client.js></script>

</head>

<body>

<audio autoplay></audio>

<iframe src="about:blank"></iframe>

<canvas></canvas>

<script> main() </script>

</body>


text:
package butterknife;

import android.app.Activity;
import android.util.Property;
import android.view.View;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.util.Arrays;
import java.util.List;

import butterknife.shadow.EditModeShadowView;

import static butterknife.ButterKnife.Finder.arrayOf;
import static butterknife.ButterKnife.Finder.listOf;
import static org.fest.assertions.api.ANDROID.assertThat;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.entry;
import static org.fest.assertions.api.Assertions.fail;

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ButterKnifeTest {
  private static final Property<View, Boolean> PROPERTY_ENABLED =
      new Property<View, Boolean>(Boolean.class, "enabled") {
        @Override public Boolean get(View view) {
          return view.isEnabled();
        }

        @Override public void set(View view, Boolean enabled) {
          view.setEnabled(enabled);
        }
      };
  private static final ButterKnife.Setter<View, Boolean> SETTER_ENABLED =
      new ButterKnife.Setter<View, Boolean>() {
        @Override public void set(View view, Boolean value, int index) {
          view.setEnabled(value);
        }
      };
  private static final ButterKnife.Action<View> ACTION_DISABLE = new ButterKnife.Action<View>() {
    @Override public void apply(View view, int index) {
      view.setEnabled(false);
    }
  };
  private static final ButterKnife.Action<View> ACTION_ZERO_ALPHA = new ButterKnife.Action<View>() {
    @Override public void apply(View view, int index) {
      view.setAlpha(0f);
    }
  };

  @Before @After // Clear out cache of binders before and after each test.
  public void resetViewsCache() {
    ButterKnife.BINDERS.clear();
  }

  @Test public void listOfFiltersNull() {
    assertThat(listOf(null, null, null)).isEmpty();
    assertThat(listOf("One", null, null)).containsExactly("One");
    assertThat(listOf(null, "One", null)).containsExactly("One");
    assertThat(listOf(null, null, "One")).containsExactly("One");
    assertThat(listOf("One", "Two", null)).containsExactly("One", "Two");
    assertThat(listOf("One", null, "Two")).containsExactly("One", "Two");
    assertThat(listOf(null, "One", "Two")).containsExactly("One", "Two");
  }

  @Test public void arrayOfFiltersNull() {
    assertThat(arrayOf(null, null, null)).isEmpty();
    assertThat(arrayOf("One", null, null)).containsExactly("One");
    assertThat(arrayOf(null, "One", null)).containsExactly("One");
    assertThat(arrayOf(null, null, "One")).containsExactly("One");
    assertThat(arrayOf("One", "Two", null)).containsExactly("One", "Two");
    assertThat(arrayOf("One", null, "Two")).containsExactly("One", "Two");
    assertThat(arrayOf(null, "One", "Two")).containsExactly("One", "Two");
  }

  @Test public void propertyAppliedToView() {
    View view = new View(Robolectric.application);
    assertThat(view).isEnabled();
    ButterKnife.apply(view, PROPERTY_ENABLED, false);

    assertThat(view).isDisabled();
  }

  @Test public void propertyAppliedToEveryView() {
    View view1 = new View(Robolectric.application);
    View view2 = new View(Robolectric.application);
    View view3 = new View(Robolectric.application);
    assertThat(view1).isEnabled();
    assertThat(view2).isEnabled();
    assertThat(view3).isEnabled();

    List<View> views = Arrays.asList(view1, view2, view3);
    ButterKnife.apply(views, PROPERTY_ENABLED, false);

    assertThat(view1).isDisabled();
    assertThat(view2).isDisabled();
    assertThat(view3).isDisabled();
  }

  @Test public void actionAppliedToView() {
    View view = new View(Robolectric.application);
    assertThat(view).isEnabled();

    ButterKnife.apply(view, ACTION_DISABLE);

    assertThat(view).isDisabled();
  }

  @Test public void actionsAppliedToView() {
    View view = new View(Robolectric.application);
    assertThat(view).isEnabled();
    assertThat(view).hasAlpha(1f);

    ButterKnife.apply(view, ACTION_DISABLE, ACTION_ZERO_ALPHA);

    assertThat(view).isDisabled();
    assertThat(view).hasAlpha(0f);
  }

  @Test public void actionAppliedToEveryView() {
    View view1 = new View(Robolectric.application);
    View view2 = new View(Robolectric.application);
    View view3 = new View(Robolectric.application);
    assertThat(view1).isEnabled();
    assertThat(view2).isEnabled();
    assertThat(view3).isEnabled();

    List<View> views = Arrays.asList(view1, view2, view3);
    ButterKnife.apply(views, ACTION_DISABLE);

    assertThat(view1).isDisabled();
    assertThat(view2).isDisabled();
    assertThat(view3).isDisabled();
  }

  @Test public void actionsAppliedToEveryView() {
    View view1 = new View(Robolectric.application);
    View view2 = new View(Robolectric.application);
    View view3 = new View(Robolectric.application);
    assertThat(view1).isEnabled();
    assertThat(view2).isEnabled();
    assertThat(view3).isEnabled();
    assertThat(view1).hasAlpha(1f);
    assertThat(view2).hasAlpha(1f);
    assertThat(view3).hasAlpha(1f);

    List<View> views = Arrays.asList(view1, view2, view3);
    ButterKnife.apply(views, ACTION_DISABLE, ACTION_ZERO_ALPHA);

    assertThat(view1).isDisabled();
    assertThat(view2).isDisabled();
    assertThat(view3).isDisabled();
    assertThat(view1).hasAlpha(0f);
    assertThat(view2).hasAlpha(0f);
    assertThat(view3).hasAlpha(0f);
  }

  @Test public void setterAppliedToView() {
    View view = new View(Robolectric.application);
    assertThat(view).isEnabled();

    ButterKnife.apply(view, SETTER_ENABLED, false);

    assertThat(view).isDisabled();
  }

  @Test public void setterAppliedToEveryView() {
    View view1 = new View(Robolectric.application);
    View view2 = new View(Robolectric.application);
    View view3 = new View(Robolectric.application);
    assertThat(view1).isEnabled();
    assertThat(view2).isEnabled();
    assertThat(view3).isEnabled();

    List<View> views = Arrays.asList(view1, view2, view3);
    ButterKnife.apply(views, SETTER_ENABLED, false);

    assertThat(view1).isDisabled();
    assertThat(view2).isDisabled();
    assertThat(view3).isDisabled();
  }

  @Test public void bindingViewReturnsView() {
    View view = new View(Robolectric.application);

    View one = ButterKnife.bind(view);
    assertThat(one).isSameAs(view);

    View two = ButterKnife.bind(new Object(), view);
    assertThat(two).isSameAs(view);
  }

  @Test public void zeroBindingsBindDoesNotThrowException() {
    class Example {
    }

    Example example = new Example();
    ButterKnife.bind(example, null, null);
    assertThat(ButterKnife.BINDERS).contains(entry(Example.class, ButterKnife.NOP_VIEW_BINDER));
  }

  @Test public void zeroBindingsUnbindDoesNotThrowException() {
    class Example {
    }

    Example example = new Example();
    ButterKnife.unbind(example);
    assertThat(ButterKnife.BINDERS).contains(entry(Example.class, ButterKnife.NOP_VIEW_BINDER));
  }

  @Test public void bindingKnownPackagesIsNoOp() {
    ButterKnife.bind(new Activity());
    assertThat(ButterKnife.BINDERS).isEmpty();
    ButterKnife.bind(new Object(), new Activity());
    assertThat(ButterKnife.BINDERS).isEmpty();
  }

  @Test public void finderThrowsNiceError() {
    View view = new View(Robolectric.application);
    try {
      ButterKnife.Finder.VIEW.findRequiredView(view, android.R.id.button1, "yo mama");
      fail("View 'button1' with ID " + android.R.id.button1 + " should not have been found.");
    } catch (IllegalStateException e) {
      assertThat(e).hasMessage("Required view 'button1' with ID "
          + android.R.id.button1
          + " for yo mama was not found. If this view is optional add '@Nullable' annotation.");
    }
  }

  @Config(shadows = EditModeShadowView.class)
  @Test public void finderThrowsLessNiceErrorInEditMode() {
    View view = new View(Robolectric.application);
    try {
      ButterKnife.Finder.VIEW.findRequiredView(view, android.R.id.button1, "yo mama");
      fail("View 'button1' with ID " + android.R.id.button1 + " should not have been found.");
    } catch (IllegalStateException e) {
      assertThat(e).hasMessage("Required view '<unavailable while editing>' "
          + "with ID " + android.R.id.button1
          + " for yo mama was not found. If this view is optional add '@Nullable' annotation.");
    }
  }
}


text:
require 'rubygems'

require 'simplecov'
require 'coveralls'
SimpleCov.formatter = Coveralls::SimpleCov::Formatter
SimpleCov.start do
  add_filter 'spec'
end

require 'rspec'
require File.dirname(__FILE__) + '/../lib/indoor_voice'


text:
<ion-view>
    <ion-nav-title><mm-format-text watch="true">{{ title }}</mm-format-text></ion-nav-title>
    <ion-nav-buttons side="secondary">

        <button class="button button-icon ion-more" ng-if="showToc && !loadingToc && toc && toc.length" ng-click="popover.show($event)">
        </button>
        <ion-spinner ng-if="showToc && loadingToc"></ion-spinner>
    </ion-nav-buttons>
    <ion-content padding="true">
        <mm-loading hide-until="loaded">

                <mm-navigation-bar previous="previousSco" next="nextSco" action="loadSco" info="description" title="{{ 'mm.core.description' | translate }}"></mm-navigation-bar>
                <mm-iframe ng-if="src" src="src" class="mma-mod-scorm-iframe-container" iframe-width="{{scorm.popup ? scorm.width : undefined}}" iframe-height="{{scorm.popup ? scorm.height : undefined}}"></mm-iframe>

{{ errorMessage | translate }}

	    </mm-loading>
    </ion-content>
</ion-view>


text:
'use strict';

describe('Service: Distorsion', function () {

  // load the service's module
  beforeEach(module('webClientSideApp'));

  // instantiate service
  var Distorsion;
  beforeEach(inject(function (_Distorsion_) {
    Distorsion = _Distorsion_;
  }));

  it('should do something', function () {
    expect(!!Distorsion).toBe(true);
  });

});


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>About.initHelpMsg Method ()</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            SQL Schema Tool Help

About.initHelpMsg Method ()

private void initHelpMsg();

See Also

        About Class | Lewis.SST.Help Namespace | About.initHelpMsg Overload List

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="initHelpMsg method">
        </param>
        <param name="Keyword" value="initHelpMsg method, About class">
        </param>
        <param name="Keyword" value="About.initHelpMsg method">
        </param>
      </object>

Generated from assembly SST [1.0.2793.35291]


text:
    var getBarItemStyle = require('../../model/mixin/makeStyleMapper')(
        [
            ['fill', 'color'],
            ['stroke', 'borderColor'],
            ['lineWidth', 'borderWidth'],
            // Compatitable with 2
            ['stroke', 'barBorderColor'],
            ['lineWidth', 'barBorderWidth'],
            ['opacity'],
            ['shadowBlur'],
            ['shadowOffsetX'],
            ['shadowOffsetY'],
            ['shadowColor']
        ]
    );
    module.exports = {
        getBarItemStyle: function (excludes) {
            var style = getBarItemStyle.call(this, excludes);
            if (this.getBorderLineDash) {
                var lineDash = this.getBorderLineDash();
                lineDash && (style.lineDash = lineDash);
            }
            return style;
        }
    };


text:
package paths

import (
	"fmt"
	"os"
	"path/filepath"
)

type Path struct {
	Home   string
	Config string
	Data   string
	Logs   string
}

// FileType is an enumeration type representing the file types.
// Currently existing file types are: Home, Config, Data
type FileType string

const (
	Home   FileType = "home"
	Config FileType = "config"
	Data   FileType = "data"
	Logs   FileType = "logs"
)

// Paths is the Path singleton on which the top level functions from this
// package operate.
var Paths = New()

// New creates a new Paths object with all values set to empty values.
func New() *Path {
	return &Path{}
}

// InitPaths sets the default paths in the configuration based on CLI flags,
// configuration file and default values. It also tries to create the data
// path with mode 0750 and returns an error on failure.
func (paths *Path) InitPaths(cfg *Path) error {
	err := paths.initPaths(cfg)
	if err != nil {
		return err
	}

	// make sure the data path exists
	err = os.MkdirAll(paths.Data, 0750)
	if err != nil {
		return fmt.Errorf("Failed to create data path %s: %v", paths.Data, err)
	}

	return nil
}

// InitPaths sets the default paths in the configuration based on CLI flags,
// configuration file and default values. It also tries to create the data
// path with mode 0750 and returns an error on failure.
func InitPaths(cfg *Path) error {
	return Paths.InitPaths(cfg)
}

// initPaths sets the default paths in the configuration based on CLI flags,
// configuration file and default values.
func (paths *Path) initPaths(cfg *Path) error {
	*paths = *cfg

	// default for config path
	if paths.Config == "" {
		paths.Config = paths.Home
	}

	// default for data path
	if paths.Data == "" {
		paths.Data = filepath.Join(paths.Home, "data")
	}

	// default for logs path
	if paths.Logs == "" {
		paths.Logs = filepath.Join(paths.Home, "logs")
	}

	return nil
}

// Resolve resolves a path to a location in one of the default
// folders. For example, Resolve(Home, "test") returns an absolute
// path for "test" in the home path.
func (paths *Path) Resolve(fileType FileType, path string) string {
	// absolute paths are not changed
	if filepath.IsAbs(path) {
		return path
	}

	switch fileType {
	case Home:
		return filepath.Join(paths.Home, path)
	case Config:
		return filepath.Join(paths.Config, path)
	case Data:
		return filepath.Join(paths.Data, path)
	case Logs:
		return filepath.Join(paths.Logs, path)
	default:
		panic(fmt.Sprintf("Unknown file type: %s", fileType))
	}
}

// Resolve resolves a path to a location in one of the default
// folders. For example, Resolve(Home, "test") returns an absolute
// path for "test" in the home path.
func Resolve(fileType FileType, path string) string {
	return Paths.Resolve(fileType, path)
}

// String returns a textual representation
func (paths *Path) String() string {
	return fmt.Sprintf("Home path: [%s] Config path: [%s] Data path: [%s] Logs path: [%s]",
		paths.Home, paths.Config, paths.Data, paths.Logs)
}


text:
struct RGBA
{
    CGFloat red;
    CGFloat green;
    CGFloat blue;
    CGFloat alpha;
};

@interface TyphoonColorConversionUtils : NSObject

+ (struct RGBA)colorFromHexString:(NSString *)hexString;
+ (struct RGBA)colorFromCssStyleString:(NSString *)cssString;

@end


text:
from futurefinity.client import HTTPClient
from futurefinity.utils import ensure_str

import cgi
import json
import asyncio
import unittest
import http.server

class ClientGetTestCollector(unittest.TestCase):
    def make_http_server_handler(self, http_version="HTTP/1.0",
                                 has_link_args=False,
                                 response_by_chunk=False):
        class ServerHandler(http.server.SimpleHTTPRequestHandler):
            def do_GET(server):
                self.assertEqual(server.request_version, http_version)
                if has_link_args:
                    self.assertEqual(server.path, "/get_test/?a=b")
                else:
                    self.assertEqual(server.path, "/get_test/")
                if response_by_chunk:
                    server.wfile.write(b"HTTP/1.1 200 OK\r\n")
                else:
                    server.send_response(http.server.HTTPStatus.OK)
                if not response_by_chunk:
                    server.send_header("Content-Length", "13")
                else:
                    server.send_header("Transfer-Encoding", "Chunked")
                server.send_header("Content-Type", "text/plain")
                server.end_headers()
                if not response_by_chunk:
                    server.wfile.write(b"Hello, World!")
                else:
                    server.wfile.write(
                        b"7\r\nHello, \r\n6\r\nWorld!\r\n0\r\n\r\n")

            def log_request(server, *args, **kwargs):
                pass

        return ServerHandler

    def setUp(self):
        self.v10_client = HTTPClient(http_version=10, allow_keep_alive=False)
        self.v11_client = HTTPClient()
        self.loop = asyncio.get_event_loop()

    async def get_coro_result(self, coro):
        self.coro_result = await coro
        self.loop.stop()

    def test_v10_get_request(self):
        ServerHandler = self.make_http_server_handler()
        server = http.server.HTTPServer(("localhost", 8000), ServerHandler)
        asyncio.ensure_future(
            self.loop.run_in_executor(None, server.serve_forever))

        asyncio.ensure_future(
            self.get_coro_result(
                self.v10_client.get("http://localhost:8000/get_test/")))

        self.loop.run_forever()
        server.shutdown()
        server.server_close()

        response = self.coro_result

        self.assertEqual(response.status_code, 200,
                         "Wrong Status Code")
        self.assertEqual(response.body, b"Hello, World!")

    def test_v11_get_request(self):
        ServerHandler = self.make_http_server_handler("HTTP/1.1")
        server = http.server.HTTPServer(("localhost", 8000), ServerHandler)
        asyncio.ensure_future(
            self.loop.run_in_executor(None, server.serve_forever))

        asyncio.ensure_future(
            self.get_coro_result(
                self.v11_client.get("http://localhost:8000/get_test/")))

        self.loop.run_forever()
        server.shutdown()
        server.server_close()

        response = self.coro_result

        self.assertEqual(response.status_code, 200,
                         "Wrong Status Code")
        self.assertEqual(response.body, b"Hello, World!")

    def test_v11_get_link_args(self):
        ServerHandler = self.make_http_server_handler("HTTP/1.1",
                                                      has_link_args=True)
        server = http.server.HTTPServer(("localhost", 8000), ServerHandler)
        asyncio.ensure_future(
            self.loop.run_in_executor(None, server.serve_forever))

        asyncio.ensure_future(
            self.get_coro_result(
                self.v11_client.get("http://localhost:8000/get_test/",
                                    link_args={"a": "b"})))

        self.loop.run_forever()
        server.shutdown()
        server.server_close()

        response = self.coro_result

        self.assertEqual(response.status_code, 200,
                         "Wrong Status Code")
        self.assertEqual(response.body, b"Hello, World!")

    def test_v11_get_chunked_response(self):
        ServerHandler = self.make_http_server_handler("HTTP/1.1",
                                                      response_by_chunk=True)
        server = http.server.HTTPServer(("localhost", 8000), ServerHandler)
        asyncio.ensure_future(
            self.loop.run_in_executor(None, server.serve_forever))

        asyncio.ensure_future(
            self.get_coro_result(
                self.v11_client.get("http://localhost:8000/get_test/")))

        self.loop.run_forever()
        server.shutdown()
        server.server_close()

        response = self.coro_result

        self.assertEqual(response.status_code, 200,
                         "Wrong Status Code")
        self.assertEqual(response.body, b"Hello, World!")

class ClientPostTestCollector(unittest.TestCase):
    def setUp(self):
        self.v11_client = HTTPClient()
        self.loop = asyncio.get_event_loop()

    def make_http_server_handler(self, http_version="HTTP/1.0"):
        class ServerHandler(http.server.SimpleHTTPRequestHandler):
            def do_POST(server):
                content_type = server.headers.get("Content-Type")
                content_length = server.headers.get("Content-Length")
                if content_type.lower().find("json") == -1:
                    body = cgi.FieldStorage(fp=server.rfile, environ={
                        "REQUEST_METHOD": "POST",
                        "CONTENT_TYPE": content_type,
                        "CONTENT_LENGTH": content_length
                    })
                else:
                    body = json.loads(
                        ensure_str(server.rfile.read(int(content_length))))

                self.received_body = body

                server.send_response(http.server.HTTPStatus.OK)
                server.send_header("Content-Length", "13")
                server.send_header("Content-Type", "text/plain")
                server.end_headers()
                server.wfile.write(b"Hello, World!")

            def log_request(server, *args, **kwargs):
                pass

        return ServerHandler

    async def get_coro_result(self, coro):
        self.coro_result = await coro
        self.loop.stop()

    def test_post_urlencoded_request(self):
        ServerHandler = self.make_http_server_handler("HTTP/1.1")
        server = http.server.HTTPServer(("localhost", 8000), ServerHandler)
        asyncio.ensure_future(
            self.loop.run_in_executor(None, server.serve_forever))

        asyncio.ensure_future(
            self.get_coro_result(
                self.v11_client.post("http://localhost:8000/post_test/",
                                     body_args={"a": "b"})))

        self.loop.run_forever()
        server.shutdown()
        server.server_close()

        response = self.coro_result

        self.assertEqual(response.status_code, 200,
                         "Wrong Status Code")
        self.assertEqual(response.body, b"Hello, World!")

        body = self.received_body

        self.assertEqual(body.getfirst("a"), "b")

    def test_post_multipart_request(self):
        ServerHandler = self.make_http_server_handler("HTTP/1.1")
        server = http.server.HTTPServer(("localhost", 8000), ServerHandler)
        asyncio.ensure_future(
            self.loop.run_in_executor(None, server.serve_forever))

        asyncio.ensure_future(
            self.get_coro_result(
                self.v11_client.post(
                    "http://localhost:8000/post_test/",
                    body_args={"a": "b"},
                    headers={"content-type": "multipart/form-data"})))

        self.loop.run_forever()
        server.shutdown()
        server.server_close()

        response = self.coro_result

        self.assertEqual(response.status_code, 200,
                         "Wrong Status Code")
        self.assertEqual(response.body, b"Hello, World!")

        body = self.received_body

        self.assertEqual(body.getfirst("a"), "b")

    def test_post_json_request(self):
        ServerHandler = self.make_http_server_handler("HTTP/1.1")
        server = http.server.HTTPServer(("localhost", 8000), ServerHandler)
        asyncio.ensure_future(
            self.loop.run_in_executor(None, server.serve_forever))

        asyncio.ensure_future(
            self.get_coro_result(
                self.v11_client.post(
                    "http://localhost:8000/post_test/",
                    body_args={"a": "b"},
                    headers={"content-type": "application/json"})))

        self.loop.run_forever()
        server.shutdown()
        server.server_close()

        response = self.coro_result

        self.assertEqual(response.status_code, 200,
                         "Wrong Status Code")
        self.assertEqual(response.body, b"Hello, World!")

        body = self.received_body

        if hasattr(body, "getfirst"):
            self.assertEqual(body.getfirst("a"), "b")
        else:
            self.assertEqual(body.get("a"), "b")


text:
import logging
import multiprocessing
import os
import subprocess  # nopep8, used by included files
import sys  # nopep8, used by included files

from celery.signals import after_setup_logger
from django.core.exceptions import SuspiciousOperation
from django.utils.log import AdminEmailHandler
from pymongo import MongoClient

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ONADATA_DIR = BASE_DIR
PROJECT_ROOT= os.path.abspath(os.path.join(ONADATA_DIR, '..'))

PRINT_EXCEPTION = False

TEMPLATED_EMAIL_TEMPLATE_DIR = 'templated_email/'

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS

DEFAULT_FROM_EMAIL = 'noreply@ona.io'
SHARE_PROJECT_SUBJECT = '{} Ona Project has been shared with you.'
DEFAULT_SESSION_EXPIRY_TIME = 21600  # 6 hours

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGES = (
    ('en-us', 'English'),
)
LANGUAGE_CODE = 'en-us'

ugettext = lambda s: s

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = 'http://localhost:8000/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(ONADATA_DIR, 'static')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Enketo URL.
# Configurable settings.
ENKETO_URL = os.environ.get('ENKETO_URL', 'https://enketo.kobotoolbox.org')
ENKETO_URL= ENKETO_URL.rstrip('/')
ENKETO_API_TOKEN = os.environ.get('ENKETO_API_TOKEN', 'enketorules')
ENKETO_VERSION= os.environ.get('ENKETO_VERSION', 'express').lower()
assert ENKETO_VERSION in ['legacy', 'express']
# Constants.
ENKETO_API_ENDPOINT_ONLINE_SURVEYS = '/survey'
ENKETO_API_ENDPOINT_OFFLINE_SURVEYS = '/survey/offline'
ENKETO_API_ENDPOINT_INSTANCE= '/instance'
ENKETO_API_ENDPOINT_INSTANCE_IFRAME= '/instance/iframe'
# Computed settings.
if ENKETO_VERSION == 'express':
    ENKETO_API_ROOT= '/api/v2'
    ENKETO_OFFLINE_SURVEYS= os.environ.get('ENKETO_OFFLINE_SURVEYS', 'True').lower() == 'true'
    ENKETO_API_ENDPOINT_PREVIEW= '/preview'
    ENKETO_API_ENDPOINT_SURVEYS= ENKETO_API_ENDPOINT_OFFLINE_SURVEYS if ENKETO_OFFLINE_SURVEYS \
            else ENKETO_API_ENDPOINT_ONLINE_SURVEYS
else:
    ENKETO_API_ROOT= '/api_v1'
    ENKETO_API_ENDPOINT_PREVIEW= '/webform/preview'
    ENKETO_OFFLINE_SURVEYS= False
    ENKETO_API_ENDPOINT_SURVEYS= ENKETO_API_ENDPOINT_ONLINE_SURVEYS
ENKETO_API_SURVEY_PATH = ENKETO_API_ROOT + ENKETO_API_ENDPOINT_SURVEYS
ENKETO_API_INSTANCE_PATH = ENKETO_API_ROOT + ENKETO_API_ENDPOINT_INSTANCE
ENKETO_PREVIEW_URL = ENKETO_URL + ENKETO_API_ENDPOINT_PREVIEW
ENKETO_API_INSTANCE_IFRAME_URL = ENKETO_URL + ENKETO_API_ROOT + ENKETO_API_ENDPOINT_INSTANCE_IFRAME

KPI_URL = os.environ.get('KPI_URL', False)

# specifically for site urls sent to enketo for form retrieval
ENKETO_PROTOCOL = os.environ.get('ENKETO_PROTOCOL', 'https')

LOGIN_URL = '/users/accounts/login/'
LOGIN_REDIRECT_URL = '/login_redirect/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    # 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages',
    'readonly.context_processors.readonly',
    'onadata.apps.main.context_processors.google_analytics',
    'onadata.apps.main.context_processors.site_name',
    'onadata.apps.main.context_processors.base_url',
    'onadata.apps.eventlog.context_processors.events'
)

MIDDLEWARE_CLASSES = (
    'reversion.middleware.RevisionMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'onadata.libs.utils.middleware.LocaleMiddlewareWithTweaks',
    # BrokenClientMiddleware must come before AuthenticationMiddleware
    'onadata.libs.utils.middleware.BrokenClientMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Django 1.8 removes TransactionMiddleware (was deprecated in 1.6). See:
    # https://docs.djangoproject.com/en/1.6/topics/db/transactions/#transaction-middleware
    #'django.middleware.transaction.TransactionMiddleware',
    'onadata.libs.utils.middleware.HTTPResponseNotAllowedMiddleware',
    'readonly.middleware.DatabaseReadOnlyMiddleware',
    'linaro_django_pagination.middleware.PaginationMiddleware',
    'webstack_django_sorting.middleware.SortingMiddleware',
    'onadata.apps.users.middleware.RoleMiddleware',
    # 'onadata.apps.api.middleware.DisableCSRFOnDebug',

)

ROOT_URLCONF = 'onadata.apps.main.urls'
USE_TZ = True

TEMPLATE_DIRS = (
    os.path.join(ONADATA_DIR, 'libs/templates'),
    # Put strings here, like "/home/html/django_templates"
    # or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# needed by guardian
ANONYMOUS_USER_ID = -1

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'django.contrib.admin',
    'django.contrib.admindocs',
    'django.contrib.gis',
    'registration',
    'reversion',
    'django_nose',
    'django_digest',
    'corsheaders',
    'oauth2_provider',
    'rest_framework',
    'rest_framework.authtoken',
    'taggit',
    'readonly',
    'onadata.apps.logger',
    'onadata.apps.viewer',
    'onadata.apps.main',
    'onadata.apps.restservice',
    'onadata.apps.api',
    'onadata.apps.fieldsight',
    'onadata.apps.users',
    'onadata.apps.userrole',
    'onadata.apps.fsforms',
    'onadata.apps.eventlog',
    'onadata.apps.staff',
    'onadata.apps.geo',
    'onadata.apps.remote_app',
    'guardian',
    'onadata.apps.stats',
    'onadata.apps.sms_support',
    'onadata.libs',
    'onadata.apps.survey_report',
    'onadata.apps.export',
    'pure_pagination',
    'linaro_django_pagination',
    'webstack_django_sorting',
)

OAUTH2_PROVIDER = {
    # this is the list of available scopes
    'SCOPES': {
        'read': 'Read scope',
        'write': 'Write scope',
        'groups': 'Access to your groups'}
}

REST_FRAMEWORK = {
    # Use hyperlinked styles by default.
    # Only used if the `serializer_class` attribute is not set on a view.
    'DEFAULT_MODEL_SERIALIZER_CLASS':
    'rest_framework.serializers.HyperlinkedModelSerializer',

    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'onadata.libs.authentication.DigestAuthentication',
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        'onadata.libs.authentication.HttpsOnlyBasicAuthentication',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        # Keep JSONRenderer at the top "in order to send JSON responses to
        # clients that do not specify an Accept header." See
        # http://www.django-rest-framework.org/api-guide/renderers/#ordering-of-renderer-classes
        'rest_framework.renderers.JSONRenderer',
        'rest_framework_jsonp.renderers.JSONPRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'rest_framework_xml.renderers.XMLRenderer',
        'rest_framework_csv.renderers.CSVRenderer',
    ),
    'VIEW_NAME_FUNCTION': 'onadata.apps.api.tools.get_view_name',
    'VIEW_DESCRIPTION_FUNCTION': 'onadata.apps.api.tools.get_view_description',
}

SWAGGER_SETTINGS = {
    "exclude_namespaces": [],    # List URL namespaces to ignore
    "api_version": '1.0',  # Specify your API's version (optional)
    "enabled_methods": [         # Methods to enable in UI
        'get',
        'post',
        'put',
        'patch',
        'delete'
    ],
}

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'dev.ona.io',
)

USE_THOUSAND_SEPARATOR = True

COMPRESS = True

# extra data stored with users
AUTH_PROFILE_MODULE = 'onadata.apps.main.UserProfile'

# case insensitive usernames -- DISABLED for KoBoForm compatibility
AUTHENTICATION_BACKENDS = (
    #'onadata.apps.main.backends.ModelBackend',
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
)

# Settings for Django Registration
ACCOUNT_ACTIVATION_DAYS = 1

def skip_suspicious_operations(record):
    """Prevent django from sending 500 error
    email notifications for SuspiciousOperation
    events, since they are not true server errors,
    especially when related to the ALLOWED_HOSTS
    configuration

    background and more information:
    http://www.tiwoc.de/blog/2013/03/django-prevent-email-notification-on-susp\
    iciousoperation/
    """
    if record.exc_info:
        exc_value = record.exc_info[1]
        if isinstance(exc_value, SuspiciousOperation):
            return False
    return True

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s' +
                      ' %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        },
        # Define filter for suspicious urls
        'skip_suspicious_operations': {
            '()': 'django.utils.log.CallbackFilter',
            'callback': skip_suspicious_operations,
        },
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false', 'skip_suspicious_operations'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
            'stream': sys.stdout
        },
        'audit': {
            'level': 'DEBUG',
            'class': 'onadata.libs.utils.log.AuditLogHandler',
            'formatter': 'verbose',
            'model': 'onadata.apps.main.models.audit.AuditLog'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'console_logger': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True
        },
        'audit_logger': {
            'handlers': ['audit'],
            'level': 'DEBUG',
            'propagate': True
        }
    }
}

def configure_logging(logger, **kwargs):
    admin_email_handler = AdminEmailHandler()
    admin_email_handler.setLevel(logging.ERROR)
    logger.addHandler(admin_email_handler)

after_setup_logger.connect(configure_logging)

GOOGLE_STEP2_URI = 'http://ona.io/gwelcome'
GOOGLE_CLIENT_ID = '617113120802.onadata.apps.googleusercontent.com'
GOOGLE_CLIENT_SECRET = '9reM29qpGFPyI8TBuB54Z4fk'

THUMB_CONF = {
    'large': {'size': 1280, 'suffix': '-large'},
    'medium': {'size': 640, 'suffix': '-medium'},
    'small': {'size': 240, 'suffix': '-small'},
}
# order of thumbnails from largest to smallest
THUMB_ORDER = ['large', 'medium', 'small']
IMG_FILE_TYPE = 'jpg'

# celery
BROKER_BACKEND = "librabbitmq"
BROKER_URL = 'amqp://guest:guest@localhost:5672/'
CELERY_RESULT_BACKEND = "amqp"  # telling Celery to report results to RabbitMQ
CELERY_ALWAYS_EAGER = False

# Celery defaults to having as many workers as there are cores. To avoid
# excessive resource consumption, don't spawn more than 6 workers by default
# even if there more than 6 cores.
CELERYD_MAX_CONCURRENCY = int(os.environ.get('CELERYD_MAX_CONCURRENCY', 6))
if multiprocessing.cpu_count() > CELERYD_MAX_CONCURRENCY:
    CELERYD_CONCURRENCY = CELERYD_MAX_CONCURRENCY

# Replace a worker after it completes 7 tasks by default. This allows the OS to
# reclaim memory allocated during large tasks
CELERYD_MAX_TASKS_PER_CHILD = int(os.environ.get(
    'CELERYD_MAX_TASKS_PER_CHILD', 7))

# Default to a 30-minute soft time limit and a 35-minute hard time limit
CELERYD_TASK_TIME_LIMIT = int(os.environ.get('CELERYD_TASK_TIME_LIMIT', 2100))
CELERYD_TASK_SOFT_TIME_LIMIT = int(os.environ.get(
    'CELERYD_TASK_SOFT_TIME_LIMIT', 1800))

# duration to keep zip exports before deletion (in seconds)
ZIP_EXPORT_COUNTDOWN = 3600  # 1 hour

# default content length for submission requests
DEFAULT_CONTENT_LENGTH = 10000000

TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = ['--with-fixture-bundling']

# fake endpoints for testing
TEST_HTTP_HOST = 'testserver.com'
TEST_USERNAME = 'bob'

# re-captcha in registrations
REGISTRATION_REQUIRE_CAPTCHA = False
RECAPTCHA_USE_SSL = False
RECAPTCHA_PRIVATE_KEY = ''
RECAPTCHA_PUBLIC_KEY = '6Ld52OMSAAAAAJJ4W-0TFDTgbznnWWFf0XuOSaB6'

# specify the root folder which may contain a templates folder and a static
# folder used to override templates for site specific details
TEMPLATE_OVERRIDE_ROOT_DIR = None

# Use 1 or 0 for multiple selects instead of True or False for csv, xls exports
BINARY_SELECT_MULTIPLES = False

# Use 'n/a' for empty values by default on csv exports
NA_REP = 'n/a'

# Set wsgi url scheme to HTTPS
os.environ['wsgi.url_scheme'] = 'https'

SUPPORTED_MEDIA_UPLOAD_TYPES = [
    'image/jpeg',
    'image/png',
    'audio/mpeg',
    'video/3gpp',
    'audio/wav',
    'audio/x-m4a',
    'audio/mp3',
    'text/csv',
    'application/zip'
]

# legacy setting for old sites who still use a local_settings.py file and have
# not updated to presets/
try:
    from local_settings import *  # nopep8
except ImportError:
    pass

if isinstance(TEMPLATE_OVERRIDE_ROOT_DIR, basestring):
    # site templates overrides
    TEMPLATE_DIRS = (
        os.path.join(ONADATA_DIR, TEMPLATE_OVERRIDE_ROOT_DIR, 'templates'),
    ) + TEMPLATE_DIRS
    # site static files path
    STATICFILES_DIRS += (
        os.path.join(ONADATA_DIR, TEMPLATE_OVERRIDE_ROOT_DIR, 'static'),
    )

# Transition from South to native migrations
try:
    from django.db import migrations
except ImportError:
    # Native migrations unavailable; use South instead
    INSTALLED_APPS += ('south',)

SOUTH_MIGRATION_MODULES = {
    'taggit': 'taggit.south_migrations',
    'reversion': 'reversion.south_migrations',
    'onadata.apps.restservice': 'onadata.apps.restservice.south_migrations',
    'onadata.apps.api': 'onadata.apps.api.south_migrations',
    'onadata.apps.main': 'onadata.apps.main.south_migrations',
    'onadata.apps.stats': 'onadata.apps.stats.south_migrations',
    'onadata.apps.logger': 'onadata.apps.logger.south_migrations',
    'onadata.apps.viewer': 'onadata.apps.viewer.south_migrations',
}
SERIALIZATION_MODULES = {
    "custom_geojson": "onadata.apps.fieldsight.serializers.GeoJSONSerializer",
    "full_detail_geojson": "onadata.apps.fieldsight.serializers.FullDetailGeoJSONSerializer",
}


text:
const assert  = require('assert');
const brains  = require('./helpers/brains');
const Browser = require('../src');

describe('EventSource', function() {
  const browser = new Browser();

  before(function() {
    return brains.ready();
  });

  before(function() {
    brains.static('/streaming', `
      <html>
        <head>
          <script>
            var source    = new EventSource("/stream");
            window.events = [];
            source.addEventListener("test", function(event) {
              window.events.push(event.data);
            });
            /*
            setTimeout(function() {
              window.events.push("timeout");
            }, 100);
            */
          </script>
        </head>
        <body>
          <button>1</button>
        </body>
      </html>
    `);

    brains.get('/stream', function(req, res) {
      res.writeHead(200, {
        'Content-Type':   'text/event-stream; charset=utf-8',
        'Cache-Control':  'no-cache',
        'Connection':     'keep-alive'
      });
      // Send first event immediately
      setTimeout(function() {
        res.write('event: test\nid: 1\ndata: first\n\n');
      }, 10);
      // Send second event with some delay, still get to see this because of
      // client-side timeout
      setTimeout(function() {
        res.write('event: test\nid: 2\ndata: second\n\n');
      }, 50);
      // Send third event with too much delay, browser.wait() concluded
      setTimeout(function() {
        res.write('event: test\nid: 3\ndata: third\n\n');
        res.end();
      }, 200);
    });
  });

  describe('when present', function() {
    before(async function() {
      await browser.visit('/streaming');
      await browser.pressButton('1');
    });

    it('pressButton should not timeout', function() {
      assert(true);
    });
  });

  describe('wait', function() {
    before(async function() {
      await browser.visit('/streaming');
      await browser.wait();
    });

    it('should not wait for server event', function() {
      assert.deepEqual(browser.window.events, []);
    });
  });

  describe('waitForServer', function() {
    before(async function() {
      await browser.visit('/streaming');
      await browser.waitForServer();
    });

    it('should capture synchronous event', function() {
      assert.deepEqual(browser.window.events, ['first']);
    });

    it('should not wait longer than specified', function(done) {
      function gotTwoEvents(window) {
        return (window.events && window.events.length >= 2);
      }

      browser.waitForServer({ function: gotTwoEvents }, function() {
        assert.deepEqual(browser.window.events, ['first', 'second']);
        done();
      });
    });
  });

  after(function() {
    browser.destroy();
  });
});


text:
<?php

declare(strict_types=1);

namespace Sphp\Validators;

use Sphp\Stdlib\MbString;
use Sphp\Exceptions\InvalidArgumentException;

/**
 * Validates string length
 *
 *  Validates the length of the given string
 *
 * @author  Sami Holck <sami.holck@gmail.com>
 * @license https://opensource.org/licenses/MIT The MIT License
 * @link    https://github.com/samhol/SPHP-framework GitHub repository
 * @filesource
 */
class StringLength extends AbstractValidator {

  public const TOO_SHORT = 'TOO_SHORT';
  public const TOO_LONG = 'TOO_LONG';
  public const NOT_IN_RANGE = 'NOT_IN_RANGE';

  /**
   * minimum length of the valid string
   */
  private ?int $min;

  /**
   * maximum length of the valid string
   */
  private ?int $max;

  /**
   * Constructs a new validator
   *
   * @param int $min minimum length of the valid string
   * @param int $max maximum length of the valid string
   */
  public function __construct(int $min = null, int $max = null) {
    parent::__construct('Invalid type given. String expected');
    if ($min !== null && $max !== null) {
      $this->setRangeValidation($min, $max);
    } else if ($min !== null) {
      $this->setLowerBoundValidation($min);
    } else if ($max !== null) {
      $this->setUpperBoundValidation($max);
    } else {
      throw new InvalidArgumentException("Paramaters are invalid: min: $min, max: $max given");
    }

    $this->getMessages()->setParameter(':min', $this->min);
    $this->getMessages()->setParameter(':max', $this->max);
    $this->getMessages()->setTemplate(static::TOO_SHORT, 'String is less than :min characters long');
    $this->getMessages()->setTemplate(static::TOO_LONG, 'The input is more than :max characters long');
    $this->getMessages()->setTemplate(static::NOT_IN_RANGE, 'The input length is not in range (:min-:max)');
  }

  /**
   * Sets the range of the valid string length
   *
   * @param  int $min minimum length of the valid string
   * @param  int $max maximum length of the valid string
   * @return $this for a fluent interface
   * @throws InvalidArgumentException
   */
  public function setRangeValidation(int $min, int $max) {
    if ($min < 0 || $min > $max) {
      throw new InvalidArgumentException("Given Range ($min - $max) is invalid");
    }
    $this->min = $min;
    $this->max = $max;

    $this->getMessages()->setParameter(':min', $this->min);
    $this->getMessages()->setParameter(':max', $this->max);
    return $this;
  }

  /**
   * Checks whether the validator acts as a range validator or not
   *
   * @return bool true if the validator acts as a range validator, false otherwise
   */
  public function isRangeValidator(): bool {
    return $this->min !== null && $this->max !== null;
  }

  /**
   * Sets the minimum length of the valid string
   *
   * **Important:** Unsets the maximum length setting making the validator act
   * as a lower bound validator
   *
   * @param  int $min minimum length of the valid string
   * @return $this for a fluent interface
   */
  public function setLowerBoundValidation(int $min) {
    $this->min = $min;
    $this->max = null;
    $this->getMessages()->setParameter(':min', $this->min);
    $this->getMessages()->setParameter(':max', $this->max);
    return $this;
  }

  /**
   * Checks whether the validator acts as a lower bound validator or not
   *
   * @return bool true if the validator acts as a lower bound validator, false otherwise
   */
  public function isLowerBoundValidator(): bool {
    return $this->min >= 0 && $this->max === null;
  }

  /**
   * Sets the maximum length of the valid string
   *
   * **Important:** Unsets the minimum length setting making the validator act
   * as a upper bound validator
   *
   * @param  int $max maximum length of the valid string
   * @return $this for a fluent interface
   * @throws InvalidArgumentException
   */
  public function setUpperBoundValidation(int $max) {
    if ($max < 0) {
      throw new InvalidArgumentException("Upper bound must be zero or a positive integer: $max given");
    }
    $this->min = null;
    $this->max = $max;
    $this->getMessages()->setParameter(':min', $this->min);
    $this->getMessages()->setParameter(':max', $this->max);
    return $this;
  }

  /**
   * Checks whether the validator acts as a upper bound validator or not
   *
   * @return bool true if the validator acts as a upper bound validator, false otherwise
   */
  public function isUpperBoundValidator(): bool {
    return $this->min === null && $this->max > 0;
  }

  public function isValid(mixed $value): bool {
    $this->setValue($value);
    if (!is_string($value)) {
      $this->setError(self::INVALID);
      return false;
    }
    $valid = true;
    $string = new MbString($value);
    $length = $string->count();
    if ($this->isRangeValidator() && ($length < $this->min || $this->max < $length)) {
      $valid = false;
      $this->setError(self::NOT_IN_RANGE);
    } else if ($this->isLowerBoundValidator() && $length < $this->min) {
      $valid = false;
      $this->setError(self::TOO_SHORT);
    } else if ($this->isUpperBoundValidator() && $length > $this->max) {
      $valid = false;
      $this->setError(self::TOO_LONG);
    }
    return $valid;
  }

}


text:
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*
    Created on : Jan 7, 2015, 3:48:27 PM
    Author     : manoj
*/

.container{
    border-color: rgb(232, 233, 237);
    border-width: 0px 1px 0px 1px;
    border-style: dashed;
}
.dashboard-thumbnails{
    height: 120px;
    width: 90%;
    border-radius: 100%;
    display: block;
}
.loading-img{
    height: 80px;
    width: 80px;
    display: none;
    position: fixed;
    top: 50%;
    left: 43%;
}


text:
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.test.client import RequestFactory
from django.db.models import query
from django.contrib.admin.sites import AdminSite

from cities_light import admin as cl_admin
from cities_light import models as cl_models

class AdminTestCase(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.admin_site = AdminSite()

    def testCityChangeList(self):
        user = get_user_model().objects.create(is_superuser=True, username="test")
        request = self.factory.get('/some/path/', data={'q': 'some query'})
        request.user = user
        city_admin = cl_admin.CityAdmin(cl_models.City, self.admin_site)
        changelist = cl_admin.CityChangeList(
            request, cl_models.City, cl_admin.CityAdmin.list_display,
            cl_admin.CityAdmin.list_display_links, cl_admin.CityAdmin.list_filter,
            cl_admin.CityAdmin.date_hierarchy, cl_admin.CityAdmin.search_fields,
            cl_admin.CityAdmin.list_select_related, cl_admin.CityAdmin.list_per_page,
            cl_admin.CityAdmin.list_max_show_all, cl_admin.CityAdmin.list_editable, city_admin, "id")

        self.assertIsInstance(changelist.get_queryset(request), query.QuerySet)


text:
<?php
class Kwc_Directories_Top_Model extends Kwf_Model_FnF
{
    public function __construct($config = array())
    {
        $config = array(
            'columns' => array('id', 'name', 'component_id'),
            'primaryKey' => 'id',
            'data'=> array(
                array('id'=>1, 'name'=>'Foo', 'component_id'=>'root_directory'),
                array('id'=>2, 'name'=>'Bar', 'component_id'=>'root_directory'),
                array('id'=>3, 'name'=>'Baz', 'component_id'=>'root_directory'),
                array('id'=>4, 'name'=>'Foo1', 'component_id'=>'root_directory'),
                array('id'=>5, 'name'=>'Foo2', 'component_id'=>'root_directory'),
                array('id'=>6, 'name'=>'Foo3', 'component_id'=>'root_directory'),
                array('id'=>7, 'name'=>'Foo4', 'component_id'=>'root_directory'),
                array('id'=>8, 'name'=>'Foo5', 'component_id'=>'root_directory'),
            )
        );
        parent::__construct($config);
    }
}


text:
package org.camunda.bpm.extension.cloud.workload.event;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TaskDeletedEvent implements TaskEvent {

  private String assignee;
  private String caseDefinitionId;
  private String caseExecutionId;
  private String createTime;
  private String description;
  private String dueDate;
  private String formKey;
  private String engineId;
  private String eventType;
  private String name;
  private String owner;
  private String priority;
  private String processInstanceId;
  private String tenantId;
  private String taskDefinitionKey;
  private String taskId;

}


text:
var Member = require('../models/member');
var md5 = require('md5');

module.exports = function(router) {
    router.route('/members')
    .post(function(req, res) {
        var member = new Member();

        member = updateMemberFromReq(member, req);

        memberExists(member, function(existsRes) {
            console.log(existsRes);
            if(existsRes.err) return res.json(existsRes);
            if(existsRes.result) return res.json({err: true, message: 'A member already exists with the email ' + member.email});

            member.save(function(err) {
                if(err) res.json({err: true, message: err});

                res.json({err: false, message: 'Member created!'});
            });
        });
    })
    .get(function(req, res) {
        Member.find(function(err, members) {
            if(err) res.json({err: true, message: err});

            res.json({err: false, members: members});
        })
    });

router.route('/members/:memberId')
    .get(function(req, res) {
        Member.findById(req.params.memberId, function(err, member) {
            if(err) res.json({err: true, message: err});
            if(!member) res.json({err: true, message: 'Could not find member by id ' + req.params.memberId});

            res.json({err: false, member: member});
        });
    })
    .put(function(req, res) {
        Member.findById(req.params.memberId, function(err, member) {
            if(err) res.json({err: true, message: err});
            if(!member) res.json({err: true, message: 'Could not find member by id ' + req.params.memberId});

            member = updateMemberFromReq(member, req);

            member.save(function(err) {
                if(err) res.json({err: true, message: err});

                res.json({err: false, message: 'Member updated!'});
            });
        });
    })
    .delete(function(req, res) {
        Member.remove({
            _id: req.params.memberId
        }, function(err, member) {
            if(err) res.json({err: true, message: err});

            res.json({err: false, message: 'Successfully deleted'})
        });
    });

    var updateMemberFromReq = function(member, req) {
        member.email = req.body.email;
        member.fname = req.body.fname;
        member.lname = req.body.lname;
        member.pword = md5(req.body.pword);
        member.role = req.body.role;

        return member;
    };

    var memberExists = function(member, cb) {
        Member.find({email: member.email}).limit(1).exec(function(err, result) {
            if(err) return cb({err: true, message: err});
            cb({err: false, result: result.length > 0});
        });
    };
};


text:
import { uniqueId, remove, assign } from 'lodash';
import { default as swal } from 'sweetalert2';

import {
    ADD_TASK,
    ADD_TASK_SUCCESS,
    ADD_TASK_FAILURE,
    UPDATE_TASK,
    UPDATE_TASK_SUCCESS,
    UPDATE_TASK_FAILURE,
    DELETE_TASK,
    DELETE_TASK_SUCCESS,
    DELETE_TASK_FAILURE
} from './taskConstants';

const tasks = (state = [], action) => {
    switch (action.type) {
        case ADD_TASK:
            return [
                ...state,
                assign({ id: action.meta.temporaryId }, action.meta.task)
            ];
        case ADD_TASK_SUCCESS:
            return state.map(task => {
                //replace the item with temporary ID by the actual object
                if (task.id == action.meta.temporaryId) {
                    return action.payload;
                } else {
                    return task;
                }
            });

        case UPDATE_TASK:
            return state.map(
                task =>
                    (task.id === action.meta.task.id
                        ? assign({}, task, action.meta.task)
                        : task)
            );

        case DELETE_TASK:
            remove(state, { id: action.meta.id });
            return [...state];

        case ADD_TASK_FAILURE:
            swal(
                'Error!',
                'An error occured while creating the task, sorry.',
                'error'
            );
            return state;
        case UPDATE_TASK_FAILURE:
            swal(
                'Error!',
                'An error occured while saving the task, sorry.',
                'error'
            );
            return state;
        case DELETE_TASK_FAILURE:
            swal(
                'Error!',
                'An error occured while deleting the task, sorry.',
                'error'
            );
            return state;

        default:
            return state;
    }
};

export default tasks;


text:
package org.apache.spark.ml.classification;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.ml.impl.TreeTests;
import org.apache.spark.mllib.classification.LogisticRegressionSuite;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.sql.DataFrame;

public class JavaRandomForestClassifierSuite implements Serializable {

  private transient JavaSparkContext sc;

  @Before
  public void setUp() {
    sc = new JavaSparkContext("local", "JavaRandomForestClassifierSuite");
  }

  @After
  public void tearDown() {
    sc.stop();
    sc = null;
  }

  @Test
  public void runDT() {
    int nPoints = 20;
    double A = 2.0;
    double B = -1.5;

    JavaRDD<LabeledPoint> data = sc.parallelize(
      LogisticRegressionSuite.generateLogisticInputAsList(A, B, nPoints, 42), 2).cache();
    Map<Integer, Integer> categoricalFeatures = new HashMap<Integer, Integer>();
    DataFrame dataFrame = TreeTests.setMetadata(data, categoricalFeatures, 2);

    // This tests setters. Training with various options is tested in Scala.
    RandomForestClassifier rf = new RandomForestClassifier()
      .setMaxDepth(2)
      .setMaxBins(10)
      .setMinInstancesPerNode(5)
      .setMinInfoGain(0.0)
      .setMaxMemoryInMB(256)
      .setCacheNodeIds(false)
      .setCheckpointInterval(10)
      .setSubsamplingRate(1.0)
      .setSeed(1234)
      .setNumTrees(3)
      .setMaxDepth(2); // duplicate setMaxDepth to check builder pattern
    for (String impurity: RandomForestClassifier.supportedImpurities()) {
      rf.setImpurity(impurity);
    }
    for (String featureSubsetStrategy: RandomForestClassifier.supportedFeatureSubsetStrategies()) {
      rf.setFeatureSubsetStrategy(featureSubsetStrategy);
    }
    RandomForestClassificationModel model = rf.fit(dataFrame);

    model.transform(dataFrame);
    model.totalNumNodes();
    model.toDebugString();
    model.trees();
    model.treeWeights();

    /*
    // TODO: Add test once save/load are implemented.  SPARK-6725
    File tempDir = Utils.createTempDir(System.getProperty("java.io.tmpdir"), "spark");
    String path = tempDir.toURI().toString();
    try {
      model3.save(sc.sc(), path);
      RandomForestClassificationModel sameModel =
          RandomForestClassificationModel.load(sc.sc(), path);
      TreeTests.checkEqual(model3, sameModel);
    } finally {
      Utils.deleteRecursively(tempDir);
    }
    */
  }
}


text:
package wookie.collector.utils

import scalaz.{Id, Kleisli, Reader}

object DI {

  implicit def funToKleisli[Conf, A](r: Conf => A): Kleisli[Id.Id, Conf, A] = Kleisli[Id.Id, Conf, A](Reader(r).run)
}


text:
using System;
using System.Windows.Forms;
using Csla.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WindowsApplication2
{
  static class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      var services = new ServiceCollection();
      services.AddCsla();
      var provider = services.BuildServiceProvider();
      ApplicationContext = provider.GetRequiredService<Csla.ApplicationContext>();

      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
    }

    public static Csla.ApplicationContext ApplicationContext { get; private set; }
  }
}


text:
package characteristic

const TypeSetDuration = "D3"

type SetDuration struct {
	*Int
}

func NewSetDuration() *SetDuration {
	char := NewInt(TypeSetDuration)
	char.Format = FormatUInt32
	char.Perms = []string{PermRead, PermWrite, PermEvents}
	char.SetMinValue(0)
	char.SetMaxValue(3600)
	char.SetStepValue(1)
	char.SetValue(0)

	return &SetDuration{char}
}


text:
/**
 * A Bot for Slack!
 */

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function (err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */

var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment. If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment');
    process.exit(1);
}

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function (bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function (bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/**
 * Core bot logic goes here!
 */
// BEGIN EDITING HERE!

var date = new Date()
console.log('------timestamp-----' + date.toLocaleTimeString());

var schedule = require('node-schedule');
var request = require('request');

controller.on('bot_channel_join', function (bot, message) {
    bot.reply(message, "I'm here!")
});

const botAPI = controller.spawn({
  token: token,
  retry: 'Infinity'
})

controller.hears(['give me a question','question','give us a question'], 'direct_mention,mention', function(bot, message){

    request.post(
    'https://engine.adzerk.net/api/v2',
    { json: {
        placements: [
                {divName: "div1", networkId: 9820, siteId: 687249, adTypes: [20] }
                    ],
        user: {key: "ue1-8237b4ed067542f65438ad0e2556de45"}
            }
    },

    function (error, response, body) {

      if (error)
        console.log("Error:", error);
      else if (response.statusCode !== 200) {
        console.log("Expected status 200, got", response.statusCode);
	  }
      else
        console.log("OK:", JSON.stringify(body, null, 2));
        chosen_message = response.body.decisions.div1.contents[0].data.customData.chosen_message
        bot.say({text: chosen_message, channel:"C3P05V49W"})

        impression = response.body.decisions.div1.impressionUrl
            request(impression, function (error, response, body) {
            if (!error && response.statusCode == 200) {  }
                                                                 }
                    )

            request.post(
    'https://slack.com/api/channels.history?channel=C3P05V49W&pretty=1&token=' + process.env.TOKEN,
        function (error, response, body) {
    if (error)
        console.log("Error:", error)
    else
        var time = JSON.parse(response.body)
        var timestamp = time.messages[0].ts

            bot.api.reactions.add({
                 timestamp: timestamp,
                 channel: "C3P05V49W",
                 name: 'thumbsup'});
            setTimeout(function(){
                bot.api.reactions.add({
                         timestamp: timestamp,
                         channel: "C3P05V49W",
                         name: 'thumbsdown'})
                                }, 250);
                  });

});
});

    var j = schedule.scheduleJob(' */1 9-14 * * 1-5 ', function () {

    var chosen_message;

    controller.on('bot_channel_join', function (bot, message) {
    bot.reply(message, "I'm here!")
});

const botAPI = controller.spawn({
  token: token,
  retry: 'Infinity'
})

request.post(         //Find the time the last message was posted, set to lastmessagedelay
    'https://slack.com/api/channels.history?channel=C3P05V49W&pretty=1&count=1&token=' + process.env.TOKEN,
        function (error, response, body) {
    if (error)
        console.log("Error:", error)
    else
        var time = JSON.parse(response.body);
        var timestamp = time.messages[0].ts     // find Slack timestamp
        var milliseconds = (new Date).getTime(); // find epoch timestamp
        var currenttime = (milliseconds/1000) // convert epoch to seconds
        var lastmessagedelay = currenttime-timestamp; // calculate time since last message
        var timetowait = 3600
        var postmessage = (lastmessagedelay > timetowait) ? "Post":"Dont Post";

            console.log('----currenttime-------->'+ currenttime)
            console.log('----slacktimestamp----->'+ timestamp)
            console.log('-----seconds since last message-------->'+ lastmessagedelay)
            console.log('-----time to wait-------->' + timetowait)
            console.log('-----lastmessagedelay - time to wait -------->' + lastmessagedelay-timetowait)
            console.log('----TF-------' + postmessage)

if (postmessage == "Post"){
    console.log(`---------test passes -------`)

request.post(
    'https://engine.adzerk.net/api/v2',
    { json: {
        placements: [
                {divName: "div1", networkId: 9820, siteId: 687249, adTypes: [20] }
                    ],
        user: {key: "ue1-d1f00b07c1a84fe880efa9232dc2296e"}
            }
    },

    function (error, response, body) {

      if (error)
        console.log("Error:", error);
      else if (response.statusCode !== 200) {
        console.log("Expected status 200, got", response.statusCode);
	  }
      else
        console.log("OK:", JSON.stringify(body, null, 2));
        chosen_message = response.body.decisions.div1.contents[0].data.customData.chosen_message

        impression = response.body.decisions.div1.impressionUrl
  request(impression, function (error, response, body) {
      if (!error && response.statusCode == 200) {  }

    }
)

  controller.on('bot_channel_join', function (bot, message) {
    bot.reply(message, "I'm here!")
});

const botAPI = controller.spawn({
  token: token,
  retry: 'Infinity'
})

            botAPI.startRTM((err, bot, payload) => {
            bot.say({text: chosen_message, channel:"C3P05V49W"})
            setTimeout(function(){console.log('hihihi')}, 500)

  request.post(
    'https://slack.com/api/channels.history?channel=C3P05V49W&pretty=1&token=' + process.env.TOKEN,
        function (error, response, body) {
    if (error)
        console.log("Error:", error)
    else
        var time = JSON.parse(response.body)
        var timestamp = time.messages[0].ts

            bot.api.reactions.add({
                 timestamp: timestamp,
                 channel: "C3P05V49W",
                 name: 'thumbsup'})
            setTimeout(function(){
                bot.api.reactions.add({
                         timestamp: timestamp,
                         channel: "C3P05V49W",
                         name: 'thumbsdown'})
                                }, 250)
                  })

  })

            })

    }})
});


text:
package org.atlasapi.query.common;

import java.util.Set;

import org.atlasapi.annotation.Annotation;
import org.atlasapi.query.annotation.ActiveAnnotations;
import org.atlasapi.query.annotation.ContextualAnnotationIndex;
import org.atlasapi.query.annotation.ResourceAnnotationIndex;
import org.atlasapi.query.common.exceptions.InvalidAnnotationException;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class ResourceAnnotationIndexTest {

    private final Set<Annotation> annotations
            = ImmutableSet.of(Annotation.ID, Annotation.TAGS, Annotation.EXTENDED_DESCRIPTION);

    private final ResourceAnnotationIndex topicIndex
            = ResourceAnnotationIndex.builder(Resource.TOPIC, annotations).build();
    private final ResourceAnnotationIndex channelIndex
            = ResourceAnnotationIndex.builder(Resource.CHANNEL, annotations)
            .attach(Annotation.TAGS, topicIndex, Annotation.ID)
            .build();

    private final ContextualAnnotationIndex combinedIndex
            = ResourceAnnotationIndex.combination()
            .addExplicitSingleContext(topicIndex)
            .addImplicitListContext(channelIndex)
            .combine();

    @Test
    public void testListLookupTopLevelContextless() throws Exception {
        check(channelIndex.resolveListContext(ImmutableList.of("extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testListLookupTopLevelContext() throws Exception {
        check(channelIndex.resolveListContext(ImmutableList.of("channels.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testListLookupAttachedTopContextless() throws Exception {
        check(channelIndex.resolveListContext(ImmutableList.of("tags")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.ID
        );
    }

    @Test
    public void testListLookupAttachedTopContext() throws Exception {
        check(channelIndex.resolveListContext(ImmutableList.of("channels.tags")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.ID
        );
    }

    @Test
    public void testListLookupAttachedSubContextless() throws Exception {
        check(channelIndex.resolveListContext(ImmutableList.of("tags.topic.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testListLookupAttachedSubContext() throws Exception {
        check(channelIndex.resolveListContext(ImmutableList.of(
                "channels.tags.topic.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testSingleLookupTopLevelContextless() throws Exception {
        check(channelIndex.resolveSingleContext(ImmutableList.of("extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testSingleLookupTopLevelContext() throws Exception {
        check(channelIndex.resolveSingleContext(ImmutableList.of("channel.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testSingleLookupAttachedTopContextless() throws Exception {
        check(channelIndex.resolveSingleContext(ImmutableList.of("tags")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.ID
        );
    }

    @Test
    public void testSingleLookupAttachedTopContext() throws Exception {
        check(channelIndex.resolveSingleContext(ImmutableList.of("channel.tags")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.ID
        );
    }

    @Test
    public void testSingleLookupAttachedSubContextless() throws Exception {
        check(channelIndex.resolveSingleContext(ImmutableList.of("tags.topic.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testSingleLookupAttachedSubContext() throws Exception {
        check(channelIndex.resolveSingleContext(ImmutableList.of(
                "channel.tags.topic.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testSingleLookupMixed() throws Exception {
        check(channelIndex.resolveSingleContext(ImmutableList.of("channel.tags",
                "extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS, Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testListLookupMixed() throws Exception {
        check(channelIndex.resolveListContext(ImmutableList.of("channels.tags",
                "extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS, Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test(expected = InvalidAnnotationException.class)
    public void testSingleLookupInvalidForPlural() throws Exception {
        channelIndex.resolveSingleContext(ImmutableList.of("channels.extended_description"));
    }

    @Test(expected = InvalidAnnotationException.class)
    public void testListLookupInvalidForSingular() throws Exception {
        channelIndex.resolveListContext(ImmutableList.of("channel.extended_description"));
    }

    @Test(expected = InvalidAnnotationException.class)
    public void testListLookupInvalidForBadPath() throws Exception {
        channelIndex.resolveListContext(ImmutableList.of("topics.description"));
    }

    @Test
    public void testCombinedLookupContextless() throws Exception {
        check(combinedIndex.resolve(ImmutableList.of("extended_description",
                "topic.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.EXTENDED_DESCRIPTION,
                ImmutableList.of(Resource.TOPIC), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testCombinedLookupContext() throws Exception {
        check(combinedIndex.resolve(ImmutableList.of("channels.extended_description",
                "topic.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.EXTENDED_DESCRIPTION,
                ImmutableList.of(Resource.TOPIC), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testCombinedLookupAttachedTopContextless() throws Exception {
        check(combinedIndex.resolve(ImmutableList.of("tags")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.ID
        );
    }

    @Test
    public void testCombinedLookupAttachedTopContext() throws Exception {
        check(combinedIndex.resolve(ImmutableList.of("channels.tags")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.ID
        );
    }

    @Test
    public void testCombinedLookupAttachedSubContextless() throws Exception {
        check(combinedIndex.resolve(ImmutableList.of("tags.topic.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test
    public void testCombinedLookupAttachedSubContext() throws Exception {
        check(combinedIndex.resolve(ImmutableList.of("channels.tags.topic.extended_description")),
                ImmutableList.of(Resource.CHANNEL), Annotation.TAGS,
                ImmutableList.of(Resource.CHANNEL, Resource.TOPIC), Annotation.EXTENDED_DESCRIPTION
        );
    }

    @Test(expected = InvalidAnnotationException.class)
    public void testCombinedLookupInvalidForBadPath() throws Exception {
        ResourceAnnotationIndex topicIndex = ResourceAnnotationIndex.builder(
                Resource.TOPIC,
                annotations
        ).build();
        ResourceAnnotationIndex contentIndex = ResourceAnnotationIndex.builder(
                Resource.CONTENT,
                annotations
        )
                .attach(Annotation.TAGS, topicIndex, Annotation.ID)
                .build();
        ResourceAnnotationIndex.combination()
                .addImplicitListContext(contentIndex)
                .addExplicitSingleContext(topicIndex)
                .combine()
                .resolve(ImmutableList.of("topics.extended_description"));
    }

    private void check(ActiveAnnotations actual, ImmutableList<Resource> path,
            Annotation... annotations) {
        assertThat(
                String.format("%s -> %s", path, annotations),
                actual.forPath(path),
                is(ImmutableSet.copyOf(annotations))
        );
    }

    private void check(ActiveAnnotations actual, ImmutableList<Resource> path1,
            Annotation annotation1, ImmutableList<Resource> path2, Annotation annotation2) {
        check(actual, path1, annotation1);
        check(actual, path2, annotation2);
    }

}


text:
package com.anttoolkit.sql.tasks;

import com.anttoolkit.general.tasks.GenericTask;
import org.apache.tools.ant.*;

import com.anttoolkit.sql.common.*;

public class SqlExistTask
		extends GenericTask
{
	private String query = null;
	private String delimiter = ";";
	private String property = null;

	public void setQuery(String query)
	{
		this.query = query;
	}

	public void setDelimiter(String delimiter)
	{
		this.delimiter = delimiter;
	}

	public void addText(String text)
	{
		query = getProject().replaceProperties(text);
	}

	public void setProperty(String property)
	{
		this.property = property;
	}

	public void doWork() throws BuildException
	{
		boolean exist = SqlHelper.exist(SqlSessionManager.getSession(), query, delimiter);
		this.setPropertyThreadSafe(property, Boolean.toString(exist));
	}

	protected void validate()
	{
		if (query == null)
		{
			throw new BuildException("SQL query should be specified");
		}

		if (property == null)
		{
			throw new BuildException("Property should be specified");
		}
	}
}


text:
package tlc2.tool.suite;

import static org.junit.Assert.assertFalse;

import org.junit.Test;

import tlc2.output.EC;
import tlc2.output.EC.ExitStatus;

public class Test210 extends SuiteETestCase {

	public Test210() {
		super(ExitStatus.ERROR_SPEC_PARSE);
	}

	@Test
	public void testSpec() {
		assertFalse(recorder.recorded(EC.GENERAL));
		assertSubstring("Semantic errors:\n" +
				"\n" +
				"*** Errors: 9\n" +
				"\n" +
				"line 33, col 16 to line 33, col 19 of module test210\n" +
				"\n" +
				"Accessing subexpression labeled `laby' of ASSUME/PROVE clause within the scope of a declaration\n" +
				" from outside that declaration's scope.\n" +
				"\n" +
				"\n" +
				"line 35, col 16 to line 35, col 16 of module test210\n" +
				"\n" +
				"Accessing ASSUME/PROVE clause within the scope of a declaration\n" +
				" from outside that declaration's scope.\n" +
				"\n" +
				"\n" +
				"line 42, col 41 to line 42, col 55 of module test210\n" +
				"\n" +
				"Label not allowed within scope of declaration in nested ASSUME/PROVE.\n" +
				"\n" +
				"\n" +
				"line 43, col 30 to line 43, col 44 of module test210\n" +
				"\n" +
				"Label not allowed within scope of declaration in nested ASSUME/PROVE.\n" +
				"\n" +
				"\n" +
				"line 55, col 16 to line 55, col 16 of module test210\n" +
				"\n" +
				"Accessing non-existent subexpression of a SUFFICES\n" +
				"\n" +
				"\n" +
				"line 62, col 15 to line 62, col 18 of module test210\n" +
				"\n" +
				"Accessing subexpression labeled `laby' of ASSUME/PROVE clause within the scope of a declaration\n" +
				" from outside that declaration's scope.\n" +
				"\n" +
				"\n" +
				"line 63, col 15 to line 63, col 18 of module test210\n" +
				"\n" +
				"Accessing subexpression labeled `labi' of ASSUME/PROVE clause within the scope of a declaration\n" +
				" from outside that declaration's scope.\n" +
				"\n" +
				"\n" +
				"line 64, col 15 to line 64, col 18 of module test210\n" +
				"\n" +
				"Accessing subexpression labeled `labu' of ASSUME/PROVE clause within the scope of a declaration\n" +
				" from outside that declaration's scope.\n" +
				"\n" +
				"\n" +
				"line 65, col 15 to line 65, col 15 of module test210\n" +
				"\n" +
				"Accessing ASSUME/PROVE clause within the scope of a declaration\n" +
				" from outside that declaration's scope.\n" +
				"\n" +
				"\n");
	}
}