text:
<?php

namespace Torann\GeoIP\Services;

use Exception;
use Illuminate\Support\Arr;
use Torann\GeoIP\Support\HttpClient;

/**
 * Class GeoIP
 * @package Torann\GeoIP\Services
 */
class IPData extends AbstractService
{
    /**
     * Http client instance.
     *
     * @var HttpClient
     */
    protected $client;

    /**
     * The "booting" method of the service.
     *
     * @return void
     */
    public function boot()
    {
        $this->client = new HttpClient([
            'base_uri' => 'https://api.ipdata.co/',
            'query'    => [
                'api-key' => $this->config('key'),
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     * @throws Exception
     */
    public function locate($ip)
    {
        // Get data from client
        $data = $this->client->get($ip);

        // Verify server response
        if ($this->client->getErrors() !== null || empty($data[0])) {
            throw new Exception('Request failed (' . $this->client->getErrors() . ')');
        }

        $json = json_decode($data[0], true);

        return $this->hydrate([
            'ip' => $ip,
            'iso_code' => $json['country_code'],
            'country' => $json['country_name'],
            'city' => $json['city'],
            'state' => $json['region_code'],
            'state_name' => $json['region'],
            'postal_code' => $json['postal'],
            'lat' => $json['latitude'],
            'lon' => $json['longitude'],
            'timezone' => Arr::get($json, 'time_zone.name'),
            'continent' => Arr::get($json, 'continent_code'),
            'currency' => Arr::get($json, 'currency.code'),
        ]);
    }
}


text:
package com.hauldata.dbpa.manage.health;

import com.codahale.metrics.health.HealthCheck;
import com.hauldata.dbpa.manage.resources.SchemaResource;

public class SchemaHealthCheck extends HealthCheck {

	@Override
	protected Result check() throws Exception {

		SchemaResource schemaResource = new SchemaResource();

		try {
			return schemaResource.confirm() ? Result.healthy(): Result.unhealthy("Full DBPA job management Schema does not exist");
		}
		catch (RuntimeException ex) {
			return Result.unhealthy(ex.getMessage());
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import Page from '../Page/Page';

const Privacy = () => (
  <div className="Privacy">
    <Page
      title="Privacy Policy"
      subtitle="Last updated May 29th, 2017"
      page="privacy"
    />
  </div>
);

export default Privacy;


text:
using Newtonsoft.Json;
namespace LoginRadiusSDK.V2.Models.RequestModels

{

    /// <summary>
    ///	Model Class containing Definition for Family Property
    /// </summary>
    public class Family
    {
		/// <summary>
		///	Family id
		/// </summary>
		[JsonProperty(PropertyName = "Id")]
        public  string Id {get;set;}

		/// <summary>
		///	Family name
		/// </summary>
		[JsonProperty(PropertyName = "Name")]
        public  string Name {get;set;}

		/// <summary>
		///	Family relationship
		/// </summary>
		[JsonProperty(PropertyName = "Relationship")]
        public  string Relationship {get;set;}

    }
}


text:
Informasi Website

		<?php
			//Menghitung jumlah data berita di database//
			$berita=mysql_query("SELECT * FROM sh_berita");
			$jmlberita=mysql_num_rows($berita);

			//Menghitung jumlah data komentar di database//
			$komentar=mysql_query("SELECT * FROM sh_komentar");
			$jmlkomentar=mysql_num_rows($komentar);

			//Menghitung jumlah data kategori di database//
			$kategori=mysql_query("SELECT * FROM sh_kategori");
			$jmlkategori=mysql_num_rows($kategori);

			//Menghitung jumlah data buku tamu di database//
			$bukutamu=mysql_query("SELECT * FROM sh_buku_tamu");
			$jmltamu=mysql_num_rows($bukutamu);

			//Menghitung jumlah data agenda di database//
			$agenda=mysql_query("SELECT * FROM sh_agenda");
			$jmlagenda=mysql_num_rows($agenda);

			//Menghitung jumlah file materi di database//
			$materi=mysql_query("SELECT * FROM sh_materi");
			$jmlfile=mysql_num_rows($materi);

			//Menghitung jumlah data pengumuman di database//
			$pengumuman=mysql_query("SELECT * FROM sh_pengumuman");
			$jmlpengumuman=mysql_num_rows($pengumuman);

			//Menghitung jumlah data pendaftar PSB di database//
			$psb=mysql_query("SELECT * FROM sh_psb");
			$jmlpsb=mysql_num_rows($psb);

			//Menghitung jumlah data kelas di database//
			$kelas=mysql_query("SELECT * FROM sh_kelas");
			$jmlkelas=mysql_num_rows($kelas);

			//Menghitung jumlah data siswa di database//
			$siswa=mysql_query("SELECT * FROM sh_siswa WHERE status_siswa='1'");
			$jmlsiswa=mysql_num_rows($siswa);

			//Menghitung jumlah data alumni di database//
			$alumni=mysql_query("SELECT * FROM sh_siswa WHERE status_siswa='0'");
			$jmlalumni=mysql_num_rows($alumni);

			//Menghitung jumlah data guru di database//
			$guru=mysql_query("SELECT * FROM sh_guru_staff WHERE posisi='guru'");
			$jmlguru=mysql_num_rows($guru);

			//Menghitung jumlah file foto di database//
			$foto=mysql_query("SELECT * FROM sh_galeri");
			$jmlfoto=mysql_num_rows($foto);

			//Menghitung jumlah data staff di database//
			$staff=mysql_query("SELECT * FROM sh_guru_staff WHERE posisi='staff'");
			$jmlstaff=mysql_num_rows($staff);

			//Menghitung jumlah data administrator di database//
			$users=mysql_query("SELECT * FROM sh_users");
			$jmlusers=mysql_num_rows($users);

			  $ip      = $_SERVER['REMOTE_ADDR'];
              $tanggal = date("Ymd");
              $waktu   = time();

			//Menghitung jumlah pengunjung online di database//
			  $pengunjung       = mysql_num_rows(mysql_query("SELECT * FROM sh_statistik WHERE tanggal='$tanggal' GROUP BY ip_addres"));

			//Menghitung jumlah total pengunjung di database//
              $totalpengunjung  = mysql_result(mysql_query("SELECT COUNT(mengunjungi) FROM sh_statistik"), 0);

			//Menghitung jumlah pengunjung hari ini di database//
              $bataswaktu       = time() - 300;
              $pengunjungonline = mysql_num_rows(mysql_query("SELECT * FROM sh_statistik WHERE online > '$bataswaktu'"));
		?>

<?php echo "$jmlberita"; ?>	Berita
			<?php echo "$jmlkomentar"; ?>	Komentar

<?php echo "$jmlkategori"; ?>	Kategori
			<?php echo "$jmltamu"; ?>	Buku Tamu

<?php echo "$jmlagenda"; ?>	Agenda
			<?php echo "$jmlfile"; ?>	File Materi

<?php echo "$jmlpengumuman"; ?>	Pengumuman
			<?php echo "$jmlpsb"; ?>	Pendaftar

<?php echo "$jmlkelas"; ?>	Semester
			<?php echo "$totalpengunjung"; ?>	Total Pengunjung

<?php echo "$jmlsiswa"; ?>	Mahasiswa
			<?php echo "$pengunjung"; ?>	Pengunjung Hari ini

<?php echo "$jmlalumni"; ?>	Alumni
			<?php echo "$pengunjungonline"; ?>	Online

<?php echo "$jmlguru"; ?>	Dosen
			<?php echo "$jmlfoto"; ?>	Foto

<?php echo "$jmlstaff"; ?>	Staff
			<?php echo "$jmlusers"; ?>	Administrator


text:
from filebeat import BaseTest
import os
import logging
import logging.handlers
import json
import time
import unittest
from nose.plugins.skip import Skip, SkipTest
from nose.plugins.attrib import attr

"""
Test filebeat under different load scenarios
"""

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

class Test(BaseTest):

    def test_no_missing_events(self):
        """
        Test that filebeat does not loose any events under heavy file rotation and load
        """

        if os.name == "nt":
            # This test is currently skipped on windows because very fast file
            # rotation cannot happen when harvester has file handler still open.
            raise SkipTest

        log_file = self.working_dir + "/log/test.log"
        os.mkdir(self.working_dir + "/log/")

        logger = logging.getLogger('beats-logger')
        total_lines = 1000
        lines_per_file = 10
        # Each line should have the same length + line ending
        # Some spare capacity is added to make sure all events are presisted
        line_length = len(str(total_lines)) + 1

        # Setup python log handler
        handler = logging.handlers.RotatingFileHandler(
            log_file, maxBytes=line_length * lines_per_file + 1,
            backupCount=total_lines / lines_per_file + 1)
        logger.addHandler(handler)

        self.render_config_template(
            path=os.path.abspath(self.working_dir) + "/log/*",
            rotate_every_kb=(total_lines * (line_length + 1)),    # With filepath, each line can be up to 1KB is assumed
            clean_removed="false",
        )

        # Start filebeat
        filebeat = self.start_beat()

        # wait until filebeat is fully running
        self.wait_until(
            lambda: self.log_contains("Loading and starting Prospectors completed."),
            max_timeout=15)

        # Start logging and rotating
        for i in range(total_lines):
            # Make sure each line has the same length
            line = format(i, str(line_length - 1))
            logger.debug("%d", i)

        # wait until all lines are read
        self.wait_until(
            lambda: self.output_has(lines=total_lines),
            max_timeout=15)

        filebeat.check_kill_and_wait()

        entry_list = []

        with open(self.working_dir + "/output/filebeat") as f:
            for line in f:
                content = json.loads(line)
                v = int(content["message"])
                entry_list.append(v)

        ### This lines can be uncomemnted for debugging ###
        # Prints out the missing entries
        # for i in range(total_lines):
        #    if i not in entry_list:
        #        print i
        # Stats about the files read
        #unique_entries = len(set(entry_list))
        # print "Total lines: " + str(total_lines)
        # print "Total unique entries: " + str(unique_entries)
        # print "Total entries: " + str(len(entry_list))
        # print "Registry entries: " + str(len(data))

        # Check that file exist
        data = self.get_registry()

        paths = os.listdir(self.working_dir + "/log/")
        assert len(paths) == len(data)

        for i in range(total_lines):
            assert i in entry_list

        # Compares unique entries
        assert len(set(entry_list)) == total_lines
        assert len(entry_list) == total_lines

    @unittest.skipUnless(LOAD_TESTS, "load test")
    @attr('load')
    def test_large_number_of_files(self):
        """
        Tests the number of files filebeat can open on startup
        """

        number_of_files = 1000
        lines_per_file = 3

        # Create content for each file
        content = ""
        for n in range(lines_per_file):
            content += "Line " + str(n + 1) + "\n"

        os.mkdir(self.working_dir + "/log/")
        testfile = self.working_dir + "/log/test"

        for n in range(number_of_files):
            with open(testfile + "-" + str(n + 1), 'w') as f:
                f.write(content)

        self.render_config_template(
            path=os.path.abspath(self.working_dir) + "/log/*",
            rotate_every_kb=number_of_files * lines_per_file * 12 * 2,
            scan_frequency="40s",
            # close_inactive="5s",
            # close_eof=True,
        )
        filebeat = self.start_beat()

        total_lines = number_of_files * lines_per_file
        # wait until all lines are read
        self.wait_until(
            lambda: self.output_has(lines=total_lines),
            max_timeout=120)

        filebeat.check_kill_and_wait()

        data = self.get_registry()
        assert len(data) == number_of_files

    @unittest.skipUnless(LOAD_TESTS, "load test")
    @attr('load')
    def test_concurrent_harvesters(self):
        """
        Test large number of files on startup if harvester overlap happens and would create too many events
        """
        number_of_files = 5000
        lines_per_file = 10

        # Create content for each file
        content = ""
        for n in range(lines_per_file):
            content += "Line " + str(n + 1) + "\n"

        os.mkdir(self.working_dir + "/log/")
        testfile = self.working_dir + "/log/test"

        for n in range(number_of_files):
            with open(testfile + "-" + str(n + 1), 'w') as f:
                f.write(content)

        self.render_config_template(
            path=os.path.abspath(self.working_dir) + "/log/*",
            rotate_every_kb=number_of_files * lines_per_file * 12 * 2,
        )
        filebeat = self.start_beat()

        total_lines = number_of_files * lines_per_file

        print(total_lines)
        # wait until all lines are read
        self.wait_until(
            lambda: self.output_has(lines=total_lines),
            max_timeout=120)

        time.sleep(2)

        # make sure not further lines were read
        self.wait_until(
            lambda: self.output_has(lines=total_lines),
            max_timeout=120)

        filebeat.check_kill_and_wait()

        data = self.get_registry()
        assert len(data) == number_of_files


text:
class MapContainerManager {
    constructor(backgroundInterface, webpageParser, mapManager, containerHTML) {
        this.webpageParser = webpageParser;
        this.backgroundInterface = backgroundInterface;
        this.mapManager = mapManager;
        this.containerHTML = containerHTML;
        this.isMapHidden = true;
    }

    async start() {
        this.addContainerToPageIfNeeded()
        .then(this.updateItems.bind(this))
        .catch(e => logError(e));
    }

    async updateItems() {
        let items = this.webpageParser.parseItems();
        log("Parse items : " + items.length + " items were found on the page.");

        log("Please wait for geocoding...")
        const geocodedItems = await this.backgroundInterface.getGeocodedItems(items);
        log("Geocoding done ! Will update the map with " + geocodedItems.length + " geocoded items.");
        this.mapManager.updateItems(geocodedItems);
    }

    async addContainerToPageIfNeeded() {
        const self = this;

        // If the container already exists on the page, abort.
        const element = document.getElementById('lbca_button_toggle');
        if (element) {
            return Promise.resolve();
        }

        //Retrieve body
        let body = self.webpageParser.getBody();

        //Load the map container in the corner
        const container = new DOMParser().parseFromString(this.containerHTML, 'text/html').body.firstElementChild;
        body.appendChild(container);

        //Store DOM references for future usage
        this.mapContainer = $('#lbca_map_container');
        this.mapContainer = $('#lbca_map_container');
        this.toggleButton = $('#lbca_button_toggle');
        this.refreshButton = $('#lbca_button_refresh');
        this.blackOverlay = $('#lbca_black_overlay');

        self.updateToggleButtonText(this.isMapHidden);

        this.mapContainer.css('visibility', 'hidden');
        this.blackOverlay.css('visibility', 'hidden');
        this.refreshButton.css('visibility', 'hidden');

        //Finish setup
        await this.mapManager.loadMap();
        this.mapContainer.css('visibility', 'visible');
        this.blackOverlay.css('visibility', 'visible');
        this.refreshButton.css('visibility', 'visible');
        if (this.isMapHidden) {
            this.mapContainer.hide();
            this.blackOverlay.hide();
            this.refreshButton.hide();
        }

        self.toggleButton.click(toggleMap);
        self.blackOverlay.click(hideMap);
        self.refreshButton.click(refreshMap);

        function refreshMap() {
            self.updateItems();
            self.refreshButton.blur();
        }

        function toggleMap() {
            self.blackOverlay.fadeToggle(125);
            self.mapContainer.slideToggle(125, function() {
                var isMapHidden = self.mapContainer.is(":hidden");
                self.isMapHidden = isMapHidden;
                self.backgroundInterface.setIsMapHidden(isMapHidden);

                self.updateToggleButtonText(isMapHidden);
                self.refreshButton.toggle();

                self.toggleButton.blur();
            });
        }

        function hideMap() {
            const isMapHidden = self.mapContainer.is(":hidden");
            if (isMapHidden) { return; }

            self.blackOverlay.fadeOut(125);
            self.mapContainer.slideToggle(125, function() {
                self.isMapHidden = true;
                self.backgroundInterface.setIsMapHidden(true);
                self.updateToggleButtonText(true);
                self.refreshButton.hide();
            });
        }

        return Promise.resolve();
    }

    updateToggleButtonText(isMapHidden) {
        this.toggleButton.html(isMapHidden ? 'Afficher la recherche sur la carte' : 'Masquer la carte');
    }
}


text:
require 'serverspec'

set :backend, :exec

require 'consul_parameters'

include ConsulParameters
properties = { consul_parameters: read, servers: read_servers }

RSpec.configure do |c|
  if ENV['ASK_SUDO_PASSWORD']
    require 'highline/import'
    c.sudo_password = ask('Enter sudo password: ') { |q| q.echo = false }
  else
    c.sudo_password = ENV['SUDO_PASSWORD']
  end

  set_property properties
end

def generate_password(key = '')
  salt = property[:consul_parameters][:cloudconductor][:salt]
  OpenSSL::Digest::SHA256.hexdigest(salt + key)
end


text:
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.collide.client.history;

import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;

/**
 * Mock {@link Place}s used for testing.
 *
 */
public class MockPlaces {

  /**
   * A Mock Child.
   *
   * Lets call him "Child A".
   */
  public static class MockChildPlaceA extends MockPlace {

    /**
     * The {@link PlaceNavigationEvent} for Child A.
     */
    public class NavigationEvent extends PlaceNavigationEvent<MockChildPlaceA> {

      int someNumber;
      String someString;

      protected NavigationEvent() {
        super(MockChildPlaceA.this);
      }

      @Override
      public JsonStringMap<String> getBookmarkableState() {
        JsoStringMap<String> keyValues = JsoStringMap.create();
        keyValues.put(SOME_STRING_KEY, someString);
        keyValues.put(SOME_NUMBER_KEY, someNumber + "");
        return keyValues;
      }
    }

    /**
     * The {@link PlaceNavigationHandler} for Child A.
     */
    public static class NavigationHandler extends MockPlaceNavigationHandler<
        MockChildPlaceA.NavigationEvent> {

      @Override
      protected void enterPlace(MockChildPlaceA.NavigationEvent navigationEvent) {
        super.enterPlace(navigationEvent);

        navigationEvent.getPlace().registerChildHandler(GRANDCHILD_A, GRANDCHILD_A_NAV);
      }
    }

    protected MockChildPlaceA() {
      super("MockChildPlaceA");
    }

    @Override
    public MockChildPlaceA.NavigationEvent createNavigationEvent(
        JsonStringMap<String> decodedState) {

      // If this decoded string is not a valid integer, this will throw. Which
      // is fine. Let it break the test.
      return createNavigationEvent(
          decodedState.get(SOME_STRING_KEY), Integer.parseInt(decodedState.get(SOME_NUMBER_KEY)));
    }

    public MockChildPlaceA.NavigationEvent createNavigationEvent(
        String someString, int someNumber) {
      MockChildPlaceA.NavigationEvent navEvent = new MockChildPlaceA.NavigationEvent();
      navEvent.someString = someString;
      navEvent.someNumber = someNumber;
      return navEvent;
    }
  }

  /**
   * A Mock Child with no bookmarkable state.
   *
   * Lets call him "GrandChild B".
   */
  public static class MockGrandChildPlaceA extends MockPlace {

    /**
     * The {@link PlaceNavigationEvent} for GrandChild B.
     */
    public class NavigationEvent extends PlaceNavigationEvent<MockGrandChildPlaceA> {

      protected NavigationEvent() {
        super(MockGrandChildPlaceA.this);
      }

      @Override
      public JsonStringMap<String> getBookmarkableState() {
        return JsoStringMap.create();
      }
    }

    /**
     * The {@link PlaceNavigationHandler} for Child B.
     */
    public static class NavigationHandler extends MockPlaceNavigationHandler<
        MockGrandChildPlaceA.NavigationEvent> {
    }

    protected MockGrandChildPlaceA() {
      super("MockGrandChildPlaceA");
    }

    @Override
    public MockGrandChildPlaceA.NavigationEvent createNavigationEvent(
        JsonStringMap<String> decodedState) {
      return new MockGrandChildPlaceA.NavigationEvent();
    }
  }

  /**
   * A Mock Parent.
   *
   * Lets call him "A".
   */
  public static class MockParentPlaceA extends MockPlace {
    /**
     * The {@link PlaceNavigationEvent} for A.
     */
    public class NavigationEvent extends PlaceNavigationEvent<MockParentPlaceA> {

      String someString;

      protected NavigationEvent() {
        super(MockParentPlaceA.this);
      }

      @Override
      public JsonStringMap<String> getBookmarkableState() {
        JsoStringMap<String> keyValues = JsoStringMap.create();
        keyValues.put(SOME_STRING_KEY, someString);
        return keyValues;
      }
    }

    /**
     * The {@link PlaceNavigationHandler} for A.
     */
    public static class NavigationHandler extends MockPlaceNavigationHandler<
        MockParentPlaceA.NavigationEvent> {

      @Override
      protected void enterPlace(MockParentPlaceA.NavigationEvent navigationEvent) {
        super.enterPlace(navigationEvent);

        // Add a Child to ParentA.
        navigationEvent.getPlace().registerChildHandler(MockPlaces.CHILD_A, CHILD_A_NAV);
      }
    }

    protected MockParentPlaceA() {
      super("MockParentPlaceA");
    }

    @Override
    public MockParentPlaceA.NavigationEvent createNavigationEvent(
        JsonStringMap<String> decodedState) {
      return createNavigationEvent(decodedState.get(SOME_STRING_KEY));
    }

    public MockParentPlaceA.NavigationEvent createNavigationEvent(String someString) {
      MockParentPlaceA.NavigationEvent navEvent = new MockParentPlaceA.NavigationEvent();
      navEvent.someString = someString;
      return navEvent;
    }
  }

  /**
   * A Mock Parent.
   *
   * Lets call him "B".
   */
  public static class MockParentPlaceB extends MockPlace {
    /**
     * The {@link PlaceNavigationEvent} for B.
     */
    public class NavigationEvent extends PlaceNavigationEvent<MockParentPlaceB> {

      protected NavigationEvent() {
        super(MockParentPlaceB.this);
      }

      @Override
      public JsonStringMap<String> getBookmarkableState() {
        // We keep no state.
        return JsoStringMap.create();
      }
    }

    /**
     * The {@link PlaceNavigationHandler} for B.
     */
    public static class NavigationHandler extends MockPlaceNavigationHandler<
        MockParentPlaceB.NavigationEvent> {
    }

    protected MockParentPlaceB() {
      super("MockParentPlaceB");
    }

    @Override
    public MockParentPlaceB.NavigationEvent createNavigationEvent() {
      return new MockParentPlaceB.NavigationEvent();
    }

    @Override
    public MockParentPlaceB.NavigationEvent createNavigationEvent(
        JsonStringMap<String> decodedState) {
      return createNavigationEvent();
    }
  }

  /**
   * Base class for all mock Places.
   */
  public abstract static class MockPlace extends Place {
    protected MockPlace(String placeName) {
      super(placeName);
    }
  }

  /**
   * Base class for mock PlaceNavigationHandlers. Lets us track invocation
   * counts.
   */
  abstract static class MockPlaceNavigationHandler<E extends PlaceNavigationEvent<?>>
      extends PlaceNavigationHandler<E> {
    private int enterCount;
    private int cleanupCount;
    private int reEnterCount;
    private boolean hadNewState;

    MockPlaceNavigationHandler() {
    }

    @Override
    protected void cleanup() {
      cleanupCount++;
    }

    @Override
    protected void enterPlace(E navigationEvent) {
      enterCount++;
    }

    @Override
    protected void reEnterPlace(E navigationEvent, boolean newState) {
      reEnterCount++;
      hadNewState = newState;
    }

    public boolean hadNewState() {
      return hadNewState;
    }

    public int getEnterCount() {
      return enterCount;
    }

    public int getCleanupCount() {
      return cleanupCount;
    }

    public int getReEnterCount() {
      return reEnterCount;
    }

    public void resetCounts() {
      enterCount = 0;
      cleanupCount = 0;
      reEnterCount = 0;
    }
  }

  public static final MockChildPlaceA CHILD_A = new MockChildPlaceA();
  public static final MockChildPlaceA.NavigationHandler CHILD_A_NAV =
      new MockChildPlaceA.NavigationHandler();
  public static final MockGrandChildPlaceA GRANDCHILD_A = new MockGrandChildPlaceA();
  public static final MockGrandChildPlaceA.NavigationHandler GRANDCHILD_A_NAV =
      new MockGrandChildPlaceA.NavigationHandler();
  public static final MockParentPlaceA PARENT_A = new MockParentPlaceA();
  public static final MockParentPlaceA.NavigationHandler PARENT_A_NAV =
      new MockParentPlaceA.NavigationHandler();
  public static final MockParentPlaceB PARENT_B = new MockParentPlaceB();
  public static final MockParentPlaceB.NavigationHandler PARENT_B_NAV =
      new MockParentPlaceB.NavigationHandler();

  public static final String SOME_NUMBER_KEY = "someNumber";
  public static final String SOME_STRING_KEY = "someString";

  public static void resetCounts() {
    CHILD_A_NAV.resetCounts();
    CHILD_A.setIsActive(false, null);

    GRANDCHILD_A_NAV.resetCounts();
    GRANDCHILD_A.setIsActive(false, null);

    PARENT_A_NAV.resetCounts();
    PARENT_A.setIsActive(false, null);

    PARENT_B_NAV.resetCounts();
    PARENT_B.setIsActive(false, null);
  }

  private MockPlaces() {
  }
}


text:
layout: single
title: "How to change form mode?"
body: "
You can use the specific methods setQueryMode, setInsertMode, setUpdateMode or setFormMode  general method to change the form mode that you want. You can check how the form modes here.

It will be something like this:

  <o-form ... (onFormModeChange)=\"setFormMode($event)\" ..>

    ...

  </o-form>

public setFormMode(mode: number): void {

    if (mode !== OFormComponent.Mode().INSERT) {

        this.form.setInsertMode(); // this.form.setFormMode(OFormComponent.Mode().INSERT);

    }

  }

However, if you want to change the mode at the time the form loads.

It will be something like this:

    @ViewChild('form', { static: true }) form: OFormComponent;
    this.form.onFormInitStream.subscribe(() => {
        this.form.setInsertMode();
   &nbsp});

"

---


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('goals', '0027_dedup_user_associations'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='useraction',
            unique_together=set([('user', 'action')]),
        ),
        migrations.AlterUniqueTogether(
            name='userbehavior',
            unique_together=set([('user', 'behavior')]),
        ),
        migrations.AlterUniqueTogether(
            name='usercategory',
            unique_together=set([('user', 'category')]),
        ),
        migrations.AlterUniqueTogether(
            name='usergoal',
            unique_together=set([('user', 'goal')]),
        ),
    ]


text:
describe('Module: tableMgmt, filter: price', function () {
    'use strict';
    beforeEach(module('app.table-mgmt'));

    it('should add EUR suffix to the price', inject(function (priceFilter) {
        //given when then
        expect(priceFilter(2000)).toEqual('2000 EUR');
    }));
});


text:
require File.dirname(__FILE__) + '/helper'

class MysqlAdapterTest < ActiveRecord::TestCase
  include Foreigner::MysqlAdapter

  def test_add_without_options
    assert_equal(
      "ALTER TABLE `employees` ADD CONSTRAINT `employees_company_id_fk` FOREIGN KEY (`company_id`) REFERENCES `companies`(id)",
      add_foreign_key(:employees, :companies)
    )
  end

  def test_add_with_name
    assert_equal(
      "ALTER TABLE `employees` ADD CONSTRAINT `favorite_company_fk` FOREIGN KEY (`company_id`) REFERENCES `companies`(id)",
      add_foreign_key(:employees, :companies, :name => 'favorite_company_fk')
    )
  end

  def test_add_with_column
    assert_equal(
      "ALTER TABLE `employees` ADD CONSTRAINT `employees_last_employer_id_fk` FOREIGN KEY (`last_employer_id`) REFERENCES `companies`(id)",
      add_foreign_key(:employees, :companies, :column => 'last_employer_id')
    )
  end

  def test_add_with_column_and_name
    assert_equal(
      "ALTER TABLE `employees` ADD CONSTRAINT `favorite_company_fk` FOREIGN KEY (`last_employer_id`) REFERENCES `companies`(id)",
      add_foreign_key(:employees, :companies, :column => 'last_employer_id', :name => 'favorite_company_fk')
    )
  end

  def test_add_with_delete_dependency
    assert_equal(
      "ALTER TABLE `employees` ADD CONSTRAINT `employees_company_id_fk` FOREIGN KEY (`company_id`) REFERENCES `companies`(id) " +
      "ON DELETE CASCADE",
      add_foreign_key(:employees, :companies, :dependent => :delete)
    )
  end

  def test_add_with_nullify_dependency
    assert_equal(
      "ALTER TABLE `employees` ADD CONSTRAINT `employees_company_id_fk` FOREIGN KEY (`company_id`) REFERENCES `companies`(id) " +
      "ON DELETE SET NULL",
      add_foreign_key(:employees, :companies, :dependent => :nullify)
    )
  end

  def test_remove_by_table
    assert_equal(
      "ALTER TABLE `suppliers` DROP FOREIGN KEY `suppliers_company_id_fk`",
      remove_foreign_key(:suppliers, :companies)
    )
  end

  def test_remove_by_name
    assert_equal(
      "ALTER TABLE `suppliers` DROP FOREIGN KEY `belongs_to_supplier`",
      remove_foreign_key(:suppliers, :name => "belongs_to_supplier")
    )
  end

  def test_remove_by_column
    assert_equal(
      "ALTER TABLE `suppliers` DROP FOREIGN KEY `suppliers_ship_to_id_fk`",
      remove_foreign_key(:suppliers, :column => "ship_to_id")
    )
  end

  private
    def execute(sql, name = nil)
      sql
    end

    def quote_column_name(name)
      "`#{name}`"
    end

    def quote_table_name(name)
      quote_column_name(name).gsub('.', '`.`')
    end
end


text:
package net.dv8tion.jda;

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

public enum Permission
{
    CREATE_INSTANT_INVITE(0, true, true),
    KICK_MEMBERS(1, true, false),
    BAN_MEMBERS(2, true, false),
    ADMINISTRATOR(3, true, false),
    MANAGE_CHANNEL(4, true, true),
    MANAGE_SERVER(5, true, false),

    MESSAGE_READ(10, true, true),
    MESSAGE_WRITE(11, true, true),
    MESSAGE_TTS(12, true, true),
    MESSAGE_MANAGE(13, true, true),
    MESSAGE_EMBED_LINKS(14, true, true),
    MESSAGE_ATTACH_FILES(15, true, true),
    MESSAGE_HISTORY(16, true, true),
    MESSAGE_MENTION_EVERYONE(17, true, true),

    VOICE_CONNECT(20, true, true),
    VOICE_SPEAK(21, true, true),
    VOICE_MUTE_OTHERS(22, true, true),
    VOICE_DEAF_OTHERS(23, true, true),
    VOICE_MOVE_OTHERS(24, true, true),
    VOICE_USE_VAD(25, true, true),

    NICKNAME_CHANGE(26, true, false),
    NICKNAME_MANAGE(27, true, false),

    MANAGE_ROLES(28, true, false),
    MANAGE_PERMISSIONS(28, false, true),

    UNKNOWN(-1, false, false);

    private final int offset;
    private final boolean isGuild, isChannel;

    Permission(int offset, boolean isGuild, boolean isChannel)
    {
        this.offset = offset;
        this.isGuild = isGuild;
        this.isChannel = isChannel;
    }

    /**
     * The binary offset of the permission.

     * For more information about Discord's offset system refer to
     * Discord Permission Numbers.
     *
     * @return
     *      The offset that represents this {@link net.dv8tion.jda.Permission Permission}.
     */
    public int getOffset()
    {
        return offset;
    }

    /**
     * Gets the {@link net.dv8tion.jda.Permission Permission} relating to the provided offset.

     * If there is no {@link net.dv8tion.jda.Permission Permssions} that matches the provided
     * offset, {@link net.dv8tion.jda.Permission#UNKNOWN Permission.UNKNOWN} is returned.
     *
     * @param offset
     *          The offset to match a {@link net.dv8tion.jda.Permission Permission} to.
     * @return
     *      {@link net.dv8tion.jda.Permission Permission} relating to the provided offset.
     */
    public static Permission getFromOffset(int offset)
    {
        for (Permission perm : values())
        {
            if (perm.offset == offset)
                return perm;
        }
        return UNKNOWN;
    }

    /**
     * Returns whether or not this Permission is present Guild-side (configurable via roles)
     *
     * @return
     *      True if this permission is present Guild-side
     */
    public boolean isGuild()
    {
        return isGuild;
    }

    /**
     * Returns whether or not this Permission is present Channel-side (configurable via chanel-overrides)
     *
     * @return
     *      True if this permission is present Channel-side
     */
    public boolean isChannel()
    {
        return isChannel;
    }

    /**
     * A list of all {@link net.dv8tion.jda.Permission Permissions} that are specified by this raw int representation of
     * permissions. The is best used with the getRaw methods in {@link net.dv8tion.jda.entities.Role Role},
     * {@link net.dv8tion.jda.entities.PermissionOverride PermissionOverride} or {@link net.dv8tion.jda.utils.PermissionUtil}.
     *

     * Examples:

     * {@link net.dv8tion.jda.utils.PermissionUtil#getEffectivePermission(net.dv8tion.jda.entities.User, net.dv8tion.jda.entities.Channel) PermissionUtil.getEffectivePermission(user, channel)}

     * {@link net.dv8tion.jda.entities.PermissionOverride#getAllowedRaw() PermissionOverride.getAllowedRaw()}

     * {@link net.dv8tion.jda.entities.Role#getPermissionsRaw() Role.getPermissionsRaw()}
     *
     * @param permissions
     *          The raw int representation of permissions.
     * @return
     *      Possibly-empty list of {@link net.dv8tion.jda.Permission Permissions}.
     */
    public static List<Permission> getPermissions(int permissions)
    {
        List<Permission> perms = new LinkedList<>();
        for (Permission perm : Permission.values())
        {
            if (perm.equals(Permission.UNKNOWN))
                continue;
            if(((permissions >> perm.getOffset()) & 1) == 1)
                perms.add(perm);
        }
        return perms;
    }
}


text:
title: Microsoft + Education + Phishing =
date: '2013-05-02'
---

Just stumbled over [this][1] amazeballs piece of [phishing][4]. Although if you want to actually
read the article, use [this version][2]. It is actually sad how out of touch CS academia is. Please raise
your hand if you spend more than 60% of your day writing functions in a purely functional language? If your
hand is up and you are counting Javascript, use your other hand [to punch yourself in the balls][3]

[1]: http://blogs.msdn.com/b/alfredth/archive/2011/03/22/object-oriented-programming-is-dead.aspx
[2]: http://www.instapaper.com/text?u=http://blogs.msdn.com/b/alfredth/archive/2011/03/22/object-oriented-programming-is-dead.aspx
[3]: https://en.wikipedia.org/wiki/Prototype-based_programming
[4]: http://i.imgur.com/pd36g9f.jpg


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping  package="org.sakaiproject.signup.model" default-lazy="false">
	<class name="org.sakaiproject.signup.model.SignupTimeslot"
			table="signup_ts" optimistic-lock="version">

		<id name="id" type="long">
	    	<generator class="native">
                <param name="sequence">signup_ts_ID_SEQ</param>
	    	</generator>
		</id>

		<version name="version" access="field" column="version"/>

		<property name="startTime" column="start_time" type="java.util.Date" not-null="true" />
		<property name="endTime" column="end_time" type="java.util.Date" not-null="true"/>
		<property name="maxNoOfAttendees" column="max_no_of_attendees" type="int" />
		<property name="displayAttendees" column="display_attendees" type="boolean" />
		<property name="canceled" column="canceled" type="boolean" />
		<property name="locked" column="locked" type="boolean" />
		<property name="groupId" column="group_id" length="99" type="string" not-null="false" />
		<property name="uuid" column="vevent_uuid" length="36" type="string" not-null="false" />

		<list name="attendees" cascade="save-update,delete" table="signup_ts_attendees" fetch="join">
			<key column="timeslot_id" not-null="true"/>
			<list-index column="list_index" />
			<composite-element class="org.sakaiproject.signup.model.SignupAttendee" >
				<property name="attendeeUserId" column="attendee_user_id" length="99" type="string" not-null="true" />
	   			<property name="comments" column="comments" type="text" not-null="false" />
				<property name="signupSiteId" column="signup_site_id" length="99" type="string" not-null="true" />
				<property name="calendarEventId" column="calendar_event_id" length="2000" type="string" not-null="false" />
				<property name="calendarId" column="calendar_id" length="99" type="string" not-null="false" />
				<property name="attended"  type="boolean" >
					<column name="attended" default="0"/>
				</property>
				<!-- <property name="attended" column="attended" type="boolean" not-null="false" /> -->
			</composite-element>
		</list>
		<list name="waitingList" cascade="save-update,delete" table="signup_ts_waitinglist" fetch="join">
			<key column="timeslot_id" not-null="true"/>
			<list-index column="list_index" />
			<composite-element class="org.sakaiproject.signup.model.SignupAttendee" >
				<property name="attendeeUserId" column="attendee_user_id" length="99" type="string" not-null="true" />
	   			<property name="comments" column="comments" type="text" not-null="false" />
				<property name="signupSiteId" column="signup_site_id" length="99" type="string" not-null="true" />
				<property name="calendarEventId" column="calendar_event_id" length="2000" type="string" not-null="false" />
				<property name="calendarId" column="calendar_id" length="99" type="string" not-null="false" />
				<!-- <property name="attended" column="attended" type="boolean" not-null="false" /> -->
				<property name="attended"  type="boolean" >
					<column name="attended" default="0"/>
				</property>
			</composite-element>
		</list>
	</class>
</hibernate-mapping>


text:
namespace electron {

AutofillDriver::AutofillDriver(
    content::RenderFrameHost* render_frame_host,
    mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver> request)
    : render_frame_host_(render_frame_host),
      receiver_(this, std::move(request)) {
  autofill_popup_ = std::make_unique<AutofillPopup>();
}

AutofillDriver::~AutofillDriver() = default;

void AutofillDriver::ShowAutofillPopup(
    const gfx::RectF& bounds,
    const std::vector<std::u16string>& values,
    const std::vector<std::u16string>& labels) {
  v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  v8::HandleScope scope(isolate);
  auto* web_contents = api::WebContents::From(
      content::WebContents::FromRenderFrameHost(render_frame_host_));
  if (!web_contents || !web_contents->owner_window())
    return;

  auto* embedder = web_contents->embedder();

  bool osr =
      web_contents->IsOffScreen() || (embedder && embedder->IsOffScreen());
  gfx::RectF popup_bounds(bounds);
  content::RenderFrameHost* embedder_frame_host = nullptr;
  if (embedder) {
    auto* embedder_view = embedder->web_contents()->GetMainFrame()->GetView();
    auto* view = web_contents->web_contents()->GetMainFrame()->GetView();
    auto offset = view->GetViewBounds().origin() -
                  embedder_view->GetViewBounds().origin();
    popup_bounds.Offset(offset);
    embedder_frame_host = embedder->web_contents()->GetMainFrame();
  }

  autofill_popup_->CreateView(render_frame_host_, embedder_frame_host, osr,
                              web_contents->owner_window()->content_view(),
                              popup_bounds);
  autofill_popup_->SetItems(values, labels);
}

void AutofillDriver::HideAutofillPopup() {
  if (autofill_popup_)
    autofill_popup_->Hide();
}

}  // namespace electron


text:
package com.google.errorprone.bugpatterns;

/**
 * @author sgoldfeder@google.com (Steven Goldfeder)
 */
public class InjectOverlappingQualifierAndScopeAnnotationPositiveCases {

  // BUG: Diagnostic contains: remove
  @javax.inject.Scope
  // BUG: Diagnostic contains: remove
  @javax.inject.Qualifier
  @interface JavaxScopeAndJavaxQualifier {}

  // BUG: Diagnostic contains: remove
  @com.google.inject.ScopeAnnotation
  // BUG: Diagnostic contains: remove
  @javax.inject.Qualifier
  @interface GuiceScopeAndJavaxQualifier {}

  // BUG: Diagnostic contains: remove
  @com.google.inject.ScopeAnnotation
  // BUG: Diagnostic contains: remove
  @com.google.inject.BindingAnnotation
  @interface GuiceScopeAndGuiceBindingAnnotation {}

  // BUG: Diagnostic contains: remove
  @javax.inject.Scope
  // BUG: Diagnostic contains: remove
  @com.google.inject.BindingAnnotation
  @interface JavaxScopeAndGuiceBindingAnnotation {}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>pl.themolka</groupId>
    <artifactId>arcade</artifactId>
    <version>2.0</version>

    <packaging>jar</packaging>
    <name>Arcade</name>
    <description>Zarządzanie mini-grami w jednym pluginie</description>

    <properties>
        <plugin.mainClass>pl.themolka.arcade.ArcadePlugin</plugin.mainClass>
        <plugin.minecraft>1.13</plugin.minecraft>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

        <plugins>
            <!-- Apply the last Git commit into the version -->
            <plugin>
                <groupId>pl.project13.maven</groupId>
                <artifactId>git-commit-id-plugin</artifactId>
                <version>2.1.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>revision</goal>
                         </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.2</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <artifactSet>
                                <includes>
                                    <include>commons-io:commons-io</include>
                                    <include>org.jdom:jdom2</include>
                                    <include>net.engio:mbassador</include>
                                    <include>org.apache.commons:commons-lang3</include>
                                </includes>
                            </artifactSet>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>papermc</id>
            <url>https://papermc.io/repo/repository/maven-public/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.destroystokyo.paper</groupId>
            <artifactId>paper</artifactId>
            <version>1.13.2-R0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom2</artifactId>
            <version>2.0.6</version>
        </dependency>

        <dependency>
            <groupId>net.engio</groupId>
            <artifactId>mbassador</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
    </dependencies>
</project>


text:
from PyQt4 import QtGui

import Orange.data
from Orange.statistics import distribution
from Orange.preprocess import Continuize
from Orange.data.table import Table
from Orange.widgets import gui, widget
from Orange.widgets.settings import Setting

class OWContinuize(widget.OWWidget):
    name = "Continuize"
    description = ("Turns discrete attributes into continuous and, " +
                   "optionally, normalizes the continuous values.")
    icon = "icons/Continuize.svg"
    author = "Martin Frlin"
    category = "Data"
    keywords = ["data", "continuize"]

    inputs = [("Data", Orange.data.Table, "setData")]
    outputs = [("Data", Orange.data.Table)]

    want_main_area = False

    multinomial_treatment = Setting(0)
    zero_based = Setting(1)
    continuous_treatment = Setting(0)
    class_treatment = Setting(0)

    transform_class = Setting(False)

    autosend = Setting(True)

    multinomial_treats = (
        ("Target or First value as base", Continuize.FirstAsBase),
        ("Most frequent value as base", Continuize.FrequentAsBase),
        ("One attribute per value", Continuize.Indicators),
        ("Ignore multinomial attributes", Continuize.RemoveMultinomial),
        ("Remove all discrete attributes", Continuize.Remove),
        ("Treat as ordinal", Continuize.AsOrdinal),
        ("Divide by number of values", Continuize.AsNormalizedOrdinal))

    continuous_treats = (
        ("Leave them as they are", Continuize.Leave),
        ("Normalize by span", Continuize.NormalizeBySpan),
        ("Normalize by standard deviation", Continuize.NormalizeBySD))

    class_treats = (
        ("Leave it as it is", Continuize.Leave),
        ("Treat as ordinal", Continuize.AsOrdinal),
        ("Divide by number of values", Continuize.AsNormalizedOrdinal),
        ("One class per value", Continuize.Indicators),
    )

    value_ranges = ["from -1 to 1", "from 0 to 1"]

    def __init__(self, parent=None):
        widget.OWWidget.__init__(self, parent)

        box = gui.widgetBox(self.controlArea, "Multinomial attributes")
        gui.radioButtonsInBox(
            box, self, "multinomial_treatment",
            btnLabels=[x[0] for x in self.multinomial_treats],
            callback=self.settings_changed)

        box = gui.widgetBox(self.controlArea, "Continuous attributes")
        gui.radioButtonsInBox(
            box, self, "continuous_treatment",
            btnLabels=[x[0] for x in self.continuous_treats],
            callback=self.settings_changed)

        box = gui.widgetBox(self.controlArea, "Discrete class attribute")
        gui.radioButtonsInBox(
            box, self, "class_treatment",
            btnLabels=[t[0] for t in self.class_treats],
            callback=self.settings_changed)

        zbbox = gui.widgetBox(self.controlArea, "Value range")

        gui.radioButtonsInBox(
            zbbox, self, "zero_based",
            btnLabels=self.value_ranges,
            callback=self.settings_changed)

        gui.auto_commit(self.controlArea, self, "autosend", "Apply")

        self.data = None
        self.resize(150, 300)

    def settings_changed(self):
        self.commit()

    def setData(self, data):
        self.data = data
        if data is None:
            self.send("Data", None)
        else:
            self.unconditional_commit()

    def constructContinuizer(self):
        conzer = DomainContinuizer(
            zero_based=self.zero_based,
            multinomial_treatment=self.multinomial_treats[self.multinomial_treatment][1],
            continuous_treatment=self.continuous_treats[self.continuous_treatment][1],
            class_treatment=self.class_treats[self.class_treatment][1]
        )
        return conzer

    # def sendPreprocessor(self):
    #     continuizer = self.constructContinuizer()
    #     self.send("Preprocessor", PreprocessedLearner(
    #         lambda data, weightId=0, tc=(self.targetValue if self.classTreatment else -1):
    #             Table(continuizer(data, weightId, tc)
    #                 if data.domain.class_var and isinstance(self.data.domain.class_var, DiscreteVariable)
    #                 else continuizer(data, weightId), data)))

    def commit(self):
        continuizer = self.constructContinuizer()
        if self.data is not None:
            domain = continuizer(self.data)
            data = Table.from_table(domain, self.data)
            self.send("Data", data)
        else:
            self.send("Data", None)

    def sendReport(self):
        self.reportData(self.data, "Input data")
        self.reportSettings(
            "Settings",
            [("Multinominal attributes",
              self.multinomial_treats[self.multinomial_treatment][0]),
             ("Continuous attributes",
              self.continuous_treats[self.continuous_treatment][0]),
             ("Class", self.class_treats[self.class_tereatment][0]),
             ("Value range", self.value_ranges[self.zero_based])])

from Orange.preprocess.transformation import \
    Identity, Indicator, Indicator1, Normalizer

from functools import partial, wraps, reduce

# flip:: (a * b -> c) -> (b * a -> c)
def flip(func):
    """Flip parameter order"""
    return wraps(func)(lambda a, b: func(b, a))

is_discrete = partial(flip(isinstance), Orange.data.DiscreteVariable)
is_continuous = partial(flip(isinstance), Orange.data.ContinuousVariable)

class WeightedIndicator(Indicator):
    def __init__(self, variable, value, weight=1.0):
        super().__init__(variable, value)
        self.weight = weight

    def transform(self, c):
        t = super().transform(c) * self.weight
        if self.weight != 1.0:
            t *= self.weight
        return t

class WeightedIndicator_1(Indicator1):
    def __init__(self, variable, value, weight=1.0):
        super().__init__(variable, value)
        self.weight = weight

    def transform(self, c):
        t = super().transform(c) * self.weight
        if self.weight != 1.0:
            t *= self.weight
        return t

def make_indicator_var(source, value_ind, weight=None, zero_based=True):
    var = Orange.data.ContinuousVariable(
        "{}={}".format(source.name, source.values[value_ind])
    )
    if zero_based and weight is None:
        indicator = Indicator(source, value=value_ind)
    elif zero_based:
        indicator = WeightedIndicator(source, value=value_ind, weight=weight)
    elif weight is None:
        indicator = Indicator1(source, value=value_ind)
    else:
        indicator = WeightedIndicator_1(source, value=value_ind, weight=weight)
    var.compute_value = indicator
    return var

def dummy_coding(var, base_value=-1, zero_based=True):
    N = len(var.values)
    if base_value == -1:
        base_value = var.base_value if var.base_value >= 0 else 0
    assert 0 <= base_value < len(var.values)
    return [make_indicator_var(var, i, zero_based=zero_based)
            for i in range(N) if i != base_value]

def one_hot_coding(var, zero_based=True):
    N = len(var.values)
    return [make_indicator_var(var, i, zero_based=zero_based)
            for i in range(N)]

def continuize_domain(data_or_domain,
                      multinomial_treatment=Continuize.Indicators,
                      continuous_treatment=Continuize.Leave,
                      class_treatment=Continuize.Leave,
                      zero_based=True):

    if isinstance(data_or_domain, Orange.data.Domain):
        data, domain = None, data_or_domain
    else:
        data, domain = data_or_domain, data_or_domain.domain

    def needs_dist(var, mtreat, ctreat):
        "Does the `var` need a distribution given specified flags"
        if isinstance(var, Orange.data.DiscreteVariable):
            return mtreat == Continuize.FrequentAsBase
        elif isinstance(var, Orange.data.ContinuousVariable):
            return ctreat != Continuize.Leave
        else:
            raise ValueError

    # Compute the column indices which need a distribution.
    attr_needs_dist = [needs_dist(var, multinomial_treatment,
                                  continuous_treatment)
                       for var in domain.attributes]
    cls_needs_dist = [needs_dist(var, class_treatment, Continuize.Leave)
                      for var in domain.class_vars]

    columns = [i for i, needs in enumerate(attr_needs_dist + cls_needs_dist)
               if needs]

    if columns:
        if data is None:
            raise TypeError("continuizer requires data")
        dist = distribution.get_distributions_for_columns(data, columns)
    else:
        dist = []

    dist_iter = iter(dist)

    newattrs = [continuize_var(var, next(dist_iter) if needs_dist else None,
                               multinomial_treatment, continuous_treatment,
                               zero_based)
                for var, needs_dist in zip(domain.attributes, attr_needs_dist)]

    newclass = [continuize_var(var,
                               next(dist_iter) if needs_dist else None,
                               class_treatment, Continuize.Remove,
                               zero_based)
                for var, needs_dist in zip(domain.class_vars, cls_needs_dist)]

    newattrs = reduce(list.__iadd__, newattrs, [])
    newclass = reduce(list.__iadd__, newclass, [])
    return Orange.data.Domain(newattrs, newclass, domain.metas)

def continuize_var(var,
                   data_or_dist=None,
                   multinomial_treatment=Continuize.Indicators,
                   continuous_treatment=Continuize.Leave,
                   zero_based=True):

    if isinstance(var, Orange.data.ContinuousVariable):
        if continuous_treatment == Continuize.NormalizeBySpan:
            return [normalize_by_span(var, data_or_dist, zero_based)]
        elif continuous_treatment == Continuize.NormalizeBySD:
            return [normalize_by_sd(var, data_or_dist)]
        else:
            return [var]

    elif isinstance(var, Orange.data.DiscreteVariable):
        if len(var.values) > 2 and \
                multinomial_treatment == Continuize.ReportError:
            raise ValueError("{0.name} is a multinomial variable".format(var))
        if len(var.values) < 2 or \
                multinomial_treatment == Continuize.Remove or \
                (multinomial_treatment == Continuize.RemoveMultinomial
                 and len(var.values) > 2):
            return []
        elif multinomial_treatment == Continuize.AsOrdinal:
            return [ordinal_to_continuous(var)]
        elif multinomial_treatment == Continuize.AsNormalizedOrdinal:
            return [ordinal_to_normalized_continuous(var, zero_based)]
        elif multinomial_treatment == Continuize.Indicators:
            return one_hot_coding(var, zero_based)
        elif multinomial_treatment == Continuize.FirstAsBase or \
                multinomial_treatment == Continuize.RemoveMultinomial:
            return dummy_coding(var, zero_based=zero_based)
        elif multinomial_treatment == Continuize.FrequentAsBase:
            dist = _ensure_dist(var, data_or_dist)
            modus = dist.modus()
            return dummy_coding(var, base_value=modus, zero_based=zero_based)
        elif multinomial_treatment == Continuize.Leave:
            return [var]
        else:
            raise NotImplementedError  # ValueError??

def _ensure_dist(var, data_or_dist):
    if isinstance(data_or_dist, distribution.Discrete):
        if not is_discrete(var):
            raise TypeError
        return data_or_dist
    elif isinstance(data_or_dist, distribution.Continuous):
        if not is_continuous(var):
            raise TypeError
        return data_or_dist
    elif isinstance(data_or_dist, Orange.data.Storage):
        return distribution.get_distribution(data_or_dist, var)
    else:
        raise ValueError("Need a distribution or data.")

def normalized_var(var, translate, scale):
    new_var = Orange.data.ContinuousVariable(var.name)
    norm = Normalizer(var, translate, scale)
    new_var.compute_value = norm
    return new_var

def ordinal_to_continuous(var):
    new_var = Orange.data.ContinuousVariable(var.name)
    new_var.compute_value = Identity(var)
    return new_var

def ordinal_to_normalized_continuous(var, zero_based=True):
    n_values = len(var.values)
    if zero_based:
        return normalized_var(var, 0, 1 / (n_values - 1))
    else:
        return normalized_var(var, (n_values - 1) / 2, 2 / (n_values - 1))

def normalize_by_span(var, data_or_dist, zero_based=True):
    dist = _ensure_dist(var, data_or_dist)
    v_max, v_min = dist.max(), dist.min()
    span = v_max - v_min
    if span < 1e-15:
        span = 1

    if zero_based:
        return normalized_var(var, v_min, 1 / span)
    else:
        return normalized_var(var, (v_min + v_max) / 2, 2 / span)

def normalize_by_sd(var, data_or_dist):
    dist = _ensure_dist(var, data_or_dist)
    mean, sd = dist.mean(), dist.standard_deviation()
    return normalized_var(var, mean, 1 / sd)

class DomainContinuizer:
    def __new__(cls, data=None, zero_based=True,
                multinomial_treatment=Continuize.Indicators,
                continuous_treatment=Continuize.Leave,
                class_treatment=Continuize.Leave):
        self = super().__new__(cls)
        self.zero_based = zero_based
        self.multinomial_treatment = multinomial_treatment
        self.continuous_treatment = continuous_treatment
        self.class_treatment = class_treatment
        return self if data is None else self(data)

    def __call__(self, data):
        treat = self.multinomial_treatment
        if isinstance(data, Orange.data.Domain):
            domain, data = data, None
        else:
            domain = data.domain

        if treat == Continuize.ReportError and \
                any(isinstance(var, Orange.data.DiscreteVariable) and
                    len(var.values) > 2
                    for var in domain):
            raise ValueError("Domain has multinomial attributes")

        newdomain = continuize_domain(
            data or domain,
            self.multinomial_treatment,
            self.continuous_treatment,
            self.class_treatment,
            self.zero_based
        )
        return newdomain

if __name__ == "__main__":
    import sys
    a = QtGui.QApplication(sys.argv)
    ow = OWContinuize()
    data = Table("lenses")
    ow.setData(data)
    ow.show()
    a.exec_()
    ow.saveSettings()


text:
'use strict'

/**
 * Module dependencies
 */

var utils = require('lazy-cache')(require)

/**
 * Temporarily re-assign `require` to trick browserify and
 * webpack into reconizing lazy dependencies.
 *
 * This tiny bit of ugliness has the huge dual advantage of
 * only loading modules that are actually called at some
 * point in the lifecycle of the application, whilst also
 * allowing browserify and webpack to find modules that
 * are depended on but never actually called.
 */

var fn = require
require = utils // eslint-disable-line no-undef, no-native-reassign

/**
 * Lazily required module dependencies
 */

require('define-property')
require('get-fn-name')
require('is-extendable')
require('namify')

/**
 * Restore `require`
 */

require = fn // eslint-disable-line no-undef, no-native-reassign

utils.isInvalid = function isInvalid (args, name, isObject) {
  if (args.length === 1) return true
  if (args.length === 2 && !isObject && typeof name !== 'string') return true
  return false
}

/**
 * Expose `utils` modules
 */

module.exports = utils


text:
;(function() {
	'use strict';

	angular.module('app.search')
		.config(configure);

	configure.$inject = ['$stateProvider'];

	function configure($stateProvider) {
		$stateProvider
			.state('app.search', {
		  		url: "/search",
		  		views: {
			      'menuContent': {
			      	controller: 'SearchCtrl as vm',
			        templateUrl: "js/search/form.html"
			      }
			    }
		  	});
	}

}());


text:
package com.greencatsoft.angularjs

trait Factory[A] extends Service with Function0[A]


text:
# -- coding: UTF-8 --
import wx
import uimanager

class NodeProperties(wx.Dialog):
    xrc_name = "node_properties"

    def __init__(self):
        super().__init__()

    def post_init(self, node):
        self.node = node
        self.added_tags = []
        self.removed_tags = []
        self.FindWindowByName("tags").AppendItems(node.tags)

    def on_removetag_clicked(self, evt):
        if wx.MessageBox(_("Confirm"), _("Do you really want to remove the tag?"), style=wx.ICON_QUESTION|wx.YES_NO|wx.NO_DEFAULT, parent=self) == wx.YES:
            lst = self.FindWindowByName("tags")
            n = lst.Selection
            self.removed_tags.append(lst.GetString(n))
            lst.Delete(n)

    def on_addtag_clicked(self, evt):
        tag = wx.GetTextFromUser(_("Tag name"), _("Enter the tag name"), parent=self)
        if tag:
            self.added_tags.append(tag)
            self.FindWindowByName("tags").Append(tag)

    def on_ok_clicked(self, evt):
        for tag in self.removed_tags:
            self.node.tags.remove(tag)
        for tag in self.added_tags:
            self.node.tags.append(tag)
        if len(self.added_tags) or len(self.removed_tags):
            uimanager.get().top_level.file.modified = True
        self.Destroy() # From this place Close does not work

    def on_cancel_clicked(self, evt):
        self.Destroy()


text:
namespace Microsoft.Azure.Management.Automation.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.Automation;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Definition of the varible.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class Variable
    {
        /// <summary>
        /// Initializes a new instance of the Variable class.
        /// </summary>
        public Variable()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Variable class.
        /// </summary>
        /// <param name="id">Gets or sets the id of the resource.</param>
        /// <param name="name">Gets or sets the name of the variable.</param>
        /// <param name="value">Gets or sets the value of the variable.</param>
        /// <param name="isEncrypted">Gets or sets the encrypted flag of the
        /// variable.</param>
        /// <param name="creationTime">Gets or sets the creation time.</param>
        /// <param name="lastModifiedTime">Gets or sets the last modified
        /// time.</param>
        /// <param name="description">Gets or sets the description.</param>
        public Variable(string id = default(string), string name = default(string), string value = default(string), bool? isEncrypted = default(bool?), System.DateTime? creationTime = default(System.DateTime?), System.DateTime? lastModifiedTime = default(System.DateTime?), string description = default(string))
        {
            Id = id;
            Name = name;
            Value = value;
            IsEncrypted = isEncrypted;
            CreationTime = creationTime;
            LastModifiedTime = lastModifiedTime;
            Description = description;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the id of the resource.
        /// </summary>
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the name of the variable.
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the value of the variable.
        /// </summary>
        [JsonProperty(PropertyName = "properties.value")]
        public string Value { get; set; }

        /// <summary>
        /// Gets or sets the encrypted flag of the variable.
        /// </summary>
        [JsonProperty(PropertyName = "properties.isEncrypted")]
        public bool? IsEncrypted { get; set; }

        /// <summary>
        /// Gets or sets the creation time.
        /// </summary>
        [JsonProperty(PropertyName = "properties.creationTime")]
        public System.DateTime? CreationTime { get; set; }

        /// <summary>
        /// Gets or sets the last modified time.
        /// </summary>
        [JsonProperty(PropertyName = "properties.lastModifiedTime")]
        public System.DateTime? LastModifiedTime { get; set; }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        [JsonProperty(PropertyName = "properties.description")]
        public string Description { get; set; }

    }
}


text:
This is my output app upon finishing the [tutorial](https://www.youtube.com/watch?v=i_dHFvi1BJc "Traversy Media Angular 2 and Auth0 Tutorial") of Traversy Media.
Original Output/Source Code is [here](https://github.com/bradtraversy/ngauth0).

This is an Angular app that implements Auth0 platform.

### Tools used
•Angular (at least version 2.0)

•NodeJS

•Auth0

### Setup Project
• Clone this repository on your specified folder
•Go inside your project folder
```sh
$ cd <project_folder_name>
```
• Install dependencies
```sh
$ npm install
```
• Modify `auth.service.ts` inside `src/app/services/` and change Client ID and Domain (refer to your Auth0 client settings).
```Typescript
lock = new Auth0Lock('Client ID', 'Domain', {});
```
• Build Project
```sh
$ npm start
```


text:
import java.util.List;
import java.util.Vector;

/**
 * Created by nding on 01/11/2017.
 */
public class Node<V, P>{
    private V vertice;
    private P peso;
    private Vector<Node<V, P>> adjs = new Vector<>();
    private boolean isHead = false;

    public Node(V vertice, P peso){
        this.vertice = vertice;
        this.peso = peso;

        adjs = null;
    }

    public Node(V vertice, boolean isHead){
        this.vertice = vertice;
        this.peso = null;
        this.isHead = isHead;

        if(!this.isHead)
            adjs = null;
    }

    public V getVertice() {
        return vertice;
    }

    public void setVertice(V vertice) {
        this.vertice = vertice;
    }

    public P getPeso() {
        return peso;
    }

    public void setPeso(P peso) {
        this.peso = peso;
    }

    public Vector<Node<V, P>> getAdjs() {
        return adjs;
    }

    public void setAdjs(Vector<Node<V, P>> adjs) {
        this.adjs = adjs;
    }

    public boolean isHead() {
        return isHead;
    }

}


text:
# React Native Storybook Loader

A CLI for dynamically importing stories into [Storybook for React Native](https://storybook.js.org/docs/guides/guide-react-native/).

[![Build Status](https://travis-ci.org/elderfo/react-native-storybook-loader.svg?branch=master)](https://travis-ci.org/elderfo/react-native-storybook-loader) [![Known Vulnerabilities](https://snyk.io/test/github/elderfo/react-native-storybook-loader/badge.svg)](https://snyk.io/test/github/elderfo/react-native-storybook-loader)
[![AppVeyor](https://ci.appveyor.com/api/projects/status/github/elderfo/react-native-storybook-loader?svg=true)](https://ci.appveyor.com/project/elderfo/react-native-storybook-loader)
[![codecov](https://codecov.io/gh/elderfo/react-native-storybook-loader/branch/master/graph/badge.svg)](https://codecov.io/gh/elderfo/react-native-storybook-loader)
## Purpose

While using storybook for React Native, I repeatedly found myself manually creating a file with imports for all my stories.

`react native storybook-loader` solves this by searching directories, matching files to patterns and generating a story loader that Storybook can use to load all of your stories.

* [Installation](#installation)
* [Quick Start](#quick-start)
* [Configuration](#configuration)
* [Story Loader API](#story-loader-api)
* [Story Loader Formatting](#story-loader-formatting) (Prettier support)
* [Support](https://github.com/elderfo/react-native-storybook-loader/issues)

## Installation

```bash
yarn add react-native-storybook-loader -D
```

## Quick Start

1. Create a React Native project using [create-react-native-app](https://github.com/expo/create-react-native-app)

    ```bash
    yarn create react-native-app
    ```

2. Add [Storybook for React Native](https://storybook.js.org/docs/guides/guide-react-native/) to the project and follow instructions to finalize setup.

    ```bash
    cd <project name>
    npx -p @storybook/cli sb init --type react_native
    ```

3. Install react-native-storybook-loader

    ```bash
    yarn add react-native-storybook-loader -D
    ```

4. Add the `rnstl` cli to the scripts tag of the `package.json`

    ```json
    {
      "scripts": {
        "prestorybook": "rnstl"
      }
    }
    ```

5. Update `index.js` file in the `./storybook` directory to point to `storyLoader.js`

    ```javascript
    import { AppRegistry } from 'react-native';
    import { getStorybookUI, configure } from '@storybook/react-native';

    import { loadStories } from './storyLoader';

    import './rn-addons';

    // import stories
    configure(() => {
      loadStories();
    }, module);

    // Refer to https://github.com/storybookjs/storybook/tree/master/app/react-native#start-command-parameters
    // To find allowed options for getStorybookUI
    const StorybookUIRoot = getStorybookUI({});

    // If you are using React Native vanilla and after installation you don't see your app name here, write it manually.
    // If you use Expo you can safely remove this line.
    AppRegistry.registerComponent('%APP_NAME%', () => StorybookUIRoot);

    export default StorybookUIRoot;
    ```
    _Note:_ Step 4 ensures `storyLoader.js` will be created
6. Start Storybook

    ```bash
    yarn storybook
    ```

7. Run react native app in targeted platform

    ```bash
    yarn android
    ```

    Or

    ```bash
    yarn ios
    ```
    _Note: If you have problems connecting from your device to Storybook using Android issue the following command: `adb reverse tcp:7007 tcp:7007`._

## Configuration

Story loading is controlled by the `react-native-storybook-loader` section of the project's `package.json`.

### Options

| Setting | CLI Option | Type | Description | Default |
|---|---|---|---|---|
| **searchDir** | `--searchDir` | `string` or `string[]` | The directory or directories, relative to the project root, to search for files in. | Project root |
| **outputFile** | `--outputFile` | `string` | The output file that will be written. It is relative to the project directory. | `./storybook/storyLoader.js` |
| **pattern** | `--pattern` | `string` | The pattern of files to look at. It can be a specific file, or any valid glob. Note: if using the CLI, globs with `**/*...` must be escaped with quotes | `./storybook/stories/index.js` (The default React Native storybook file) |
|  | `--silent` | | Silences output. This option is not supported in the `package.json` file. |

> Note: When using the CLI, any of option passed will override the values in the `package.json`

### Examples:

Both examples below will search `src` and `packages` directories recursively for files that end with `.stories.js` and write the output to `./storybook/storyLoader.js`

#### `package.json`

```json
{
  "name": "awesome-project",
  "scripts": {
    "prestorybook": "rnstl"
  },
  "config": {
    "react-native-storybook-loader": {
      "searchDir": ["./src", "./packages"],
      "pattern": "**/*.stories.js",
      "outputFile": "./storybook/storyLoader.js"
    }
  }
}
```

## Story Loader API

A story loader is the file generated by `rnstl` used to load story files from your project in to Storybook.

### storyLoader.loadStories()

Loads the located stories

Returns: `void`

### storyLoader.stories

An array of the stories that are loaded.

Returns: `string[]`

### storyLoader.modules

An array of the modules to load.

Returns: `NodeRequire[]`

## Story Loader Formatting

To ensure the formatting of your story loader is on par with the rest of your code base, `rnstl` uses [Prettier](https://prettier.io/) to format the generated story loaders. It will travese up the tree looking for a [Prettier configuration file](https://prettier.io/docs/en/configuration.html). If none is found, the defaul Prettier settings will be used.


text:
"""
Classes for incoming webhook events
"""

# pylint: disable=unused-import
from .base import BaseWebhookEvent  # NOQA
from .delivery import (
    BounceEvent,
    DeferredEvent,
    DeliveredEvent,
    DroppedEvent,
    ProcessedEvent,
)
from .engagement import (
    ClickEvent,
    OpenEvent,
    SpamReportEvent,
    UnsubscribeEvent,
    GroupUnsubscribeEvent,
    GroupResubscribeEvent,
)

event_mapping = {
    'bounce': BounceEvent,
    'click': ClickEvent,
    'deferred': DeferredEvent,
    'delivered': DeliveredEvent,
    'dropped': DroppedEvent,
    'open': OpenEvent,
    'processed': ProcessedEvent,
    'spamreport': SpamReportEvent,
    'unsubscribe': UnsubscribeEvent,
    'group_unsubscribe': GroupUnsubscribeEvent,
    'group_resubscribe': GroupResubscribeEvent,
}


text:
package com.wanasit.chrono.refiner.en;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import com.wanasit.chrono.ChronoOption;
import com.wanasit.chrono.ParsedResult;
import com.wanasit.chrono.refiner.RefinerAbstract;

public class ENMergeDateRangeRefiner extends RefinerAbstract {

    protected static boolean ableToMerge(String text, ParsedResult prevResult, ParsedResult curResult){

        try{
            Pattern allowedPattern = Pattern.compile("\\s*(and|to|-|ー)?\\s*", Pattern.CASE_INSENSITIVE);
            String  textBetween = text.substring(prevResult.index + prevResult.text.length(), curResult.index);

            return allowedPattern.matcher(textBetween).matches();

        }catch(StringIndexOutOfBoundsException ex){

        }

        return false;
    }

    protected static ParsedResult mergeResult(String text, ParsedResult fromResult, ParsedResult toResult){

        if (fromResult.start.date().after(toResult.start.date())) {
            ParsedResult tmp = fromResult;
            toResult = fromResult;
            fromResult = tmp;
        }

        fromResult.end = toResult.start;

        int startIndex = Math.min(fromResult.index, toResult.index);
        int endIndex = Math.max(
                fromResult.index + fromResult.text.length(),
                toResult.index + toResult.text.length());

        fromResult.index = startIndex;
        fromResult.text  = text.substring(startIndex, endIndex);
        fromResult.tags.addAll(toResult.tags);
        fromResult.tags.add(ENMergeDateRangeRefiner.class.getName());
        return fromResult;
    }

    @Override
    public List<ParsedResult> refine(List<ParsedResult> results, String text, ChronoOption options) {

        if (results.size() < 2) return results;

        List<ParsedResult> mergedResult = new ArrayList<ParsedResult>();
        ParsedResult currResult = null;
        ParsedResult prevResult = null;

        for (int i=1; i<results.size(); i++){

            currResult = results.get(i);
            prevResult = results.get(i-1);

            if (prevResult.end == null && currResult.end == null
                    && ableToMerge(text, prevResult, currResult)) {

                prevResult = mergeResult(text, prevResult, currResult);
                currResult = null;
                i += 1;
            }

            mergedResult.add(prevResult);
        }

        if (currResult != null) {
            mergedResult.add(currResult);
        }

        return mergedResult;
    }

}


text:
from .Base import Base
from . import convert

#==========================================================================
class FastPollStatus ( Base ):
   """Fast polling status message

   After construction, will have the following attributes:

      DeviceMacId   int
      CoordMacId    int
      Frequency     float (sec)
      EndTime       float (UTC sec past 1-JAN-2000 00:00)

      End           datetime UTC time stamp
      EndUnix       float (UTC sec past 1-JAN-1970 00:00)

   Sample:

   <FastPollStatus>
     <DeviceMacId>0xd8d5b9000000103f</DeviceMacId>
     <MeterMacId>0x000781000086d0fe</MeterMacId>
     <Frequency>0x00</Frequency>
     <EndTime>0xFFFFFFFF</EndTime>
   </FastPollStatus>
   """

   # Hex keys turn into floats or ints.  Taken care of automatically
   # in Base.__init__().
   _numHexKeys = [ "Frequency", "EndTime" ]
   _intHexKeys = [ "DeviceMacId", "MeterMacId" ]

   _jsonKeys = [ "DeviceMacid", "Frequency" ]

   #------------------------------------------------------------------------
   def __init__( self, node ):
      """node == xml ETree node
      """
      assert( node.tag == "FastPollStatus" )
      Base.__init__( self, "FastPollStatus", node )

      convert.time( self, "End", "EndUnix", self.EndTime )

   #------------------------------------------------------------------------

#==========================================================================


text:
#import "SBNotificationCell.h"

@class SBNotificationCenterSeparatorView;

@interface SBNotificationsBulletinCell : SBNotificationCell
{
    SBNotificationCenterSeparatorView *_separator;
    _Bool _missed;
}

+ (id)defaultColorForRelevanceDate;
+ (struct CGSize)_preferredSizeForRelevanceDateLabel:(id)arg1;
+ (double)iconPaddingLeft;
@property(nonatomic, getter=isMissed) _Bool missed; // @synthesize missed=_missed;
- (struct CGRect)_separatorFrame;
- (void)setSectionLocation:(int)arg1 animated:(_Bool)arg2;
- (void)prepareForReuse;
- (void)layoutSubviews;
@property(nonatomic) _Bool showsSeparator;
- (void)setEventDateLabel:(id)arg1;
- (void)setRelevanceDateLabel:(id)arg1;
- (void)dealloc;
- (id)initWithStyle:(long long)arg1 reuseIdentifier:(id)arg2;

@end


text:
import requests
from bs4 import BeautifulSoup
import string
import re

ROOT_URL = 'http://www.iardc.org'
LAWYER_SEARCH = 'lawyersearch.asp'
ROLL = 'ardcroll.asp'

def scrapem():
    for letter in string.lowercase:
        data = {
            'ltype': 'all',
            'sLastName': letter,
            'sPbCountry': 'all',
            'stype':'phonetic'
        }
        headers = {'Referer': ROOT_URL}
        search = requests.get('%s/%s' % (ROOT_URL, LAWYER_SEARCH))
        cookie_one = search.cookies
        list_page = requests.post('%s/%s' % (ROOT_URL, ROLL), data=data, headers=headers)
        cookie_two = list_page.cookies
        soup = BeautifulSoup(list_page.content)
        links = [a.get('href') for a in soup.find_all(href=re.compile('ldetail.asp'))]
        headers = {'Referer': '%s/%s' % (ROOT_URL, ROLL)}
        for link in links:
            detail_page = requests.get('%s/%s' % (ROOT_URL, link), headers=headers, cookies=cookie_two)
            detail_soup = BeautifulSoup(detail_page.content)
            table = detail_soup.find('table', cellspacing='3')
            rows = iter(table)
            for row in rows:
                title = row.find('b')
                value = row.find_all('td')[1]
                if title > 0 and title.string:
                    key = title.string
                    value = val.string
                    print '%s: %s' % (key, value)
    return None

if __name__ == '__main__':
    scrapem()


text:
<?php

function read() {
	system("stty sane");
	return trim(fgets(STDIN));
}

function get_char($chars = 1) {
	system("stty -icanon");
	return trim(fread(STDIN, $chars));
	system("stty sane");
	echo "\010";
}

function prompt() {
	echo ">> ";
	return read();
}

function writeln($string) {
	echo "$string \n";
}
$COLS = (int)shell_exec("tput cols");
$margin_w = ($COLS - 39) / 2;
$margin = str_repeat(" ", $margin_w);
$logo  = "$margin  ____  _           ____  _____  ____  \r\n";
$logo .= "$margin / ___|| |         / ___||_   _||  _ \ \r\n";
$logo .= "$margin| |    | |        | |  _   | |  | | | |\r\n";
$logo .= "$margin| |___ | |___     | |_| |  | |  | |_| |\r\n";
$logo .= "$margin \____||_____|_____\____|  |_|  |____/ \r\n";
$logo .= "$margin             |_____|                   \r\n";

// =========================
// = ANSI Colorizing Class =
// =========================
class Colors {
	private $foreground_colors = array();
	private $background_colors = array();

	public function __construct() {
		// Set up shell colors
		$this->foreground_colors['black'] = '0;30';
		$this->foreground_colors['dark_gray'] = '1;30';
		$this->foreground_colors['blue'] = '0;34';
		$this->foreground_colors['light_blue'] = '1;34';
		$this->foreground_colors['green'] = '0;32';
		$this->foreground_colors['light_green'] = '1;32';
		$this->foreground_colors['cyan'] = '0;36';
		$this->foreground_colors['light_cyan'] = '1;36';
		$this->foreground_colors['red'] = '0;31';
		$this->foreground_colors['light_red'] = '1;31';
		$this->foreground_colors['purple'] = '0;35';
		$this->foreground_colors['light_purple'] = '1;35';
		$this->foreground_colors['brown'] = '0;33';
		$this->foreground_colors['yellow'] = '1;33';
		$this->foreground_colors['light_gray'] = '0;37';
		$this->foreground_colors['white'] = '1;37';

		$this->background_colors['black'] = '40';
		$this->background_colors['red'] = '41';
		$this->background_colors['green'] = '42';
		$this->background_colors['yellow'] = '43';
		$this->background_colors['blue'] = '44';
		$this->background_colors['magenta'] = '45';
		$this->background_colors['cyan'] = '46';
		$this->background_colors['light_gray'] = '47';
	}

	// Returns colored string
	public function getColoredString($string, $foreground_color = null, $background_color = null) {
		$colored_string = "";

		// Check if given foreground color found
		if (isset($this->foreground_colors[$foreground_color])) {
			$colored_string .= "\033[" . $this->foreground_colors[$foreground_color] . "m";
		}
		// Check if given background color found
		if (isset($this->background_colors[$background_color])) {
			$colored_string .= "\033[" . $this->background_colors[$background_color] . "m";
		}

		// Add string and end coloring
		$colored_string .=  $string . "\033[0m";

		return $colored_string;
	}

	// Returns all foreground color names
	public function getForegroundColors() {
		return array_keys($this->foreground_colors);
	}

	// Returns all background color names
	public function getBackgroundColors() {
		return array_keys($this->background_colors);
	}
}
$colors = new Colors;

function print_tasks($tasks) {
	global $theme;
	$COLS = (int)shell_exec("tput cols");
	$colors = new Colors;
	if ($tasks != null) {
		echo $colors->getColoredString(str_repeat("=", $COLS), $theme["task divider"]["foreground"], $theme["task divider"]["background"]);
		$id = 1;
		foreach ($tasks as $task) {
			$date = preg_replace("/(\d{4})(\d{2})(\d{2})/", "$2/$3/$1", $task->due);
			$tags = preg_replace("/\s?+\,\s?+/", " " . $colors->getColoredString("|", $theme["tags divider"]["foreground"], $theme["tags divider"]["background"]) . " ", $task->tags);
			$title = $task->title;
			$pad = 3 - strlen((string)$id);
			echo str_repeat(" ", $pad) . $colors->getColoredString("$id: ", $theme["id"]["foreground"], $theme["id"]["background"]);
			echo $colors->getColoredString("\033[1m$task->title\033[22m", $theme["title"]["foreground"], $theme["title"]["background"]);
			$space = $COLS - strlen($title) - strlen($date) - 5;
			echo str_repeat(" ", $space);
			echo $colors->getColoredString("\033[3m$date\033[24m", $theme["date"]["foreground"], $theme["date"]["background"]);
			echo $colors->getColoredString(str_repeat("-", $COLS), $theme["header rule"]["foreground"], $theme["header rule"]["background"]);
			writeln($tags);
			echo "\n";
			writeln(trim($task->description));
			echo $colors->getColoredString(str_repeat("=", $COLS), $theme["task divider"]["foreground"], $theme["task divider"]["background"]);
			$id++;
		}
	}
}

$options  = $colors->getColoredString("\033[1mA\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "ll ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("\033[1mT\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "itle ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " Tags (";
$options .= $colors->getColoredString("\033[1mO\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "R) ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " Tags (AND) ";
$options .= $colors->getColoredString("\033[1m&\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("\033[1mD\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "ate ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("\033[1mS\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "elect ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("\033[1mN\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "ew ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("\033[1mE\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "dit ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " Delete (";
$options .= $colors->getColoredString("\033[1m-\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= ") ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " A";
$options .= $colors->getColoredString("\033[1mr\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "chived ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("\033[1mP\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "references ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("\033[1mB\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "ookmarks ";
$options .= $colors->getColoredString("|", $theme["toolbar divider"]["foreground"], $theme["toolbar divider"]["background"]);
$options .= " ";
$options .= $colors->getColoredString("\033[1mQ\033[22m", $theme["toolbar command"]["foreground"], $theme["toolbar command"]["background"]);
$options .= "uit ";
define(OPTIONS, $options);


text:
class Descriptor:
    def __init__(self, name=None, **opts):
        self.name = name
        self.__dict__.update(opts)

    def __set__(self, instance, value):
        instance.__dict__[self.name] = value

# Descriptor for enforcing types
class Typed(Descriptor):
    expected_type = type(None)

    def __set__(self, instance, value):
        if not isinstance(value, self.expected_type):
            raise TypeError('expected ' + str(self.expected_type))
        super().__set__(instance, value)

# Descriptor for enforcing values
class Unsigned(Descriptor):
    def __set__(self, instance, value):
        if value < 0:
            raise ValueError('Expected >= 0')
        super().__set__(instance, value)

class MaxSized(Descriptor):
    def __init__(self, name=None, **opts):
        if 'size' not in opts:
            raise TypeError('missing size option')
        self.size = opts['size']
        super().__init__(name, **opts)

    def __set__(self, instance, value):
        if len(value) >= self.size:
            raise ValueError('size must be < ' + str(self.size))
        super().__set__(instance, value)

class Integer(Typed):
    expected_type = int

class UnsignedInteger(Integer, Unsigned):
    pass

class Float(Typed):
    expected_type = float

class UnsignedFloat(Float, Unsigned):
    pass

class String(Typed):
    expected_type = str

class SizedString(String, MaxSized):
    pass

# Class decorator to apply constraints
def check_attributes(**kwargs):
    def decorate(cls):
        for key, value in kwargs.items():
            if isinstance(value, Descriptor):
                value.name = key
                setattr(cls, key, value)
            else:
                setattr(cls, key, value(key))
        return cls
    return decorate

# A metaclass that applies checking
class checkedmeta(type):
    def __new__(cls, clsname, bases, methods):
        # Attach attribute names to the descriptors
        for key, value in methods.items():
            if isinstance(value, Descriptor):
                value.name = key
        return type.__new__(cls, clsname, bases, methods)

# Testing code
def test(s):
    print(s.name)
    s.shares = 75
    print(s.shares)
    try:
        s.shares = -10
    except ValueError as e:
        print(e)
    try:
        s.price = 'a lot'
    except TypeError as e:
        print(e)

    try:
        s.name = 'ABRACADABRA'
    except ValueError as e:
        print(e)

# Various Examples:
if __name__ == '__main__':
    print("# --- Class with descriptors")
    class Stock:
        # Specify constraints
        name = SizedString('name',size=8)
        shares = UnsignedInteger('shares')
        price = UnsignedFloat('price')
        def __init__(self, name, shares, price):
            self.name = name
            self.shares = shares
            self.price = price

    s = Stock('ACME',50,91.1)
    test(s)

    print("# --- Class with class decorator")
    @check_attributes(name=SizedString(size=8),
                      shares=UnsignedInteger,
                      price=UnsignedFloat)
    class Stock:
        def __init__(self, name, shares, price):
            self.name = name
            self.shares = shares
            self.price = price

    s = Stock('ACME',50,91.1)
    test(s)

    print("# --- Class with metaclass")
    class Stock(metaclass=checkedmeta):
        name   = SizedString(size=8)
        shares = UnsignedInteger()
        price  = UnsignedFloat()
        def __init__(self, name, shares, price):
            self.name = name
            self.shares = shares
            self.price = price

    s = Stock('ACME',50,91.1)
    test(s)


text:
/* vim: set softtabstop=4 ts=4 sw=4 expandtab tw=120 syntax=javascript: */
/* jshint node:true, unused:true */
'use strict';

var isPromiseProviderSet = false;

module.exports = {
    connect: connect,
    createConnection: createConnection,
    setPromiseProvider: setPromiseProvider,
    isPromiseProviderSet: isPromiseProviderSet,
};

/**
 * connect to mongoDB using mongoose's default connection
 *
 * unlike the mongoose.connect method we return the default connection
 */
function connect() {
    setPromiseProvider();
    mongoose.connect.apply(mongoose, arguments);
    var conn = mongoose.connection;
    setupConnectionEventListeners(conn);
    return conn;
}

/**
 * obtain a connection to mongoDB
 */
function createConnection() {
    setPromiseProvider();
    var conn = mongoose.createConnection.apply(mongoose, arguments);
    setupConnectionEventListeners(conn);
    return conn;
}

/**
 * sets the mongoose promise provider
 * @param promiseProvider promiseProvider defaults to q.Promise
 */
function setPromiseProvider(promiseProvider) {
    if (isPromiseProviderSet) { return; }
    promiseProvider = promiseProvider || q.Promise;
    mongoose.PromiseProvider.set(promiseProvider);
}

/**
 * setup an connection error listener and setup handlers to close
 * open connections if the process terminates.
 */
function setupConnectionEventListeners(conn) {
    conn.on('connected', function() {
        var msg = util.format('mongoDB connection open: %s:%s/%s', conn.host, conn.port, conn.db.databaseName);
        console.log(msg);
    });
    conn.on('error', function(err) {
        console.error('mongoose error:', err);
    });
    process.on('SIGINT', closeConnections);
    process.on('SIGTERM', closeConnections);
}

/**
 * close connections to mongoDB when the process terminates
 */
function closeConnections() {
    console.log('\nclosing db connection due to app termination.');
    for (var i=0, len=mongoose.connections.length; i<len; i++) {
        mongoose.connections[i].close();
    }
    process.exit(0);
}

var util = require('util');

var mongoose = require('mongoose');
var q = require('q');


text:
A [Symfony](https://symfony.com/) bundle that creates flysystem services
based upon a url specified in the symfony configuration.

## Installation and configuration
Using [Composer](https://getcomposer.org/) add the bundle to your
dependencies using the require command:
`composer require bravesheep/flysystem-url-bundle`.

## Add the bundle to your AppKernel
Add the bundle in your `app/AppKernel.php`. **Note**: in order for the
parameters defined by this bundle to be picked up by other bundles using
them you need to put it before those bundles. See below for more
information.

```php
public function registerBundles()
{
    return array(
        // ...
        new Bravesheep\FlysystemUrlBundle\BravesheepFlysystemUrlBundle(),
        // ...
    );
}
```

## Configure the bundle
For this bundle you need to configure which urls should be used and what
the service names should be for the generated services. An example
configuration is shown below where the `media_fs_url` parameter (which
you can put in your `parameters.yml` for example) generates a
flysystem adapter service for you to use.

```yaml
bravesheep_flysystem_url:
    urls:
        # Generates media_fs_adapter.adapter service
        media:
            url: %media_fs_url%
            prefix: media_fs_adapter
```

## Accepted urls
Several url formats are accepted, a short overview of supported urls
is shown below:

* `local:///path/to/directory` or `file:///path/to/directory` for local
  filesystem storage. In case of local urls an absolute path is
  required. Use for example the `kernel.root_dir` parameter:
  `file://%kernel.root_dir%/../web/media`. The `lock` query parameter
  may be used to indicate different locking behavior:
  `local:///path/to/directory?lock=false`. Public file permissions may
  be set using the `file_perm` parameter:
  `local:///path/to/directory?file_perm=0744`. Similarly the
  `file_perm_private`, `dir_perm` and `dir_perm_private` parameters are
  available.
* `ftp://user:pass@host:port/path/to/dir` for FTP usage. Alternatively
  `ftps` scheme may be used for SSL secured FTP.
* `sftp://user:pass@host:port/path/to/dir?keyfile=path/to/keyfile` or
  alternatively the `ssh` scheme may be specified for the same
  behavior.
* `dropbox://access_token:app_secret@dropbox.com` for Dropbox access.
* `s3://key:secret@region/bucket` for Amazon AWS S3. Alternatively the
  `awss3` and `awss3v3` schemes are available. For the v2 version of the
  AWS API you may use `awss3v2` as a scheme.
* `null://` or just `null` may be specified for a testing storage
  adapter which does not store anything.
* `zip:///path/to/file.zip` may be used for local zip access.
* `webdav://user:pass@host:port/path/to/dir` may be used for WebDAV
  access. Alternatively `http://user:pass@host:port/path/to/dir` or
  `https://user:pass@host:port/path/to/dir` may be used as well.

## Extra variable encodings
By default this bundle does not just create a flysystem adapter service
but can also generate some extra parameters which you can directly use.

The bundle by default generates a parameter you can use in the
OneupFlysystemBundle as a value for your adapter:

```yaml
oneup_flysystem:
    adapters:
        media_adapter: %media_fs_adapter.oneup_adapter_params%
```

By default the bundle also generates a public prefix url for some
services if it can determine that url automatically. You could use this
for example with the VichUploaderBundle:

```yaml
vich_uploader:
    mappings:
        example:
            upload_destination: media_fs
            uri_prefix: %media_fs_adapter.public_url_prefix%
```

If you don't need these parameters you can change them in the
configuration of this bundle:

```yaml
bravesheep_flysystem_url:
    urls:
        example:
            url: %example_param%
            prefix: example_fs_prefix
            encoders: [] # In this case no parameter encoders are used, only the service is generated
```