text:
'use strict';
/*global $:false, FB:false, jQuery:false */

angular.module('chatty').factory('sockets', function ($q, $rootScope, $timeout, chats) {

  var data = {'lists': {'onlineList': [], 'userList': []},
              'cons': {'conversationsList' : [], 'gettingConvos': false},
              'messages': {'changedId': null, 'changedIndex': null}
             };

  var getListsData = function() {
    return data.lists;
  };

  var getConsData = function() {
    return data.cons;
  };

  var getMessagesData = function() {
    return data.messages;
  };

  var listDataChanged = 0,
      consDataChanged = 0,
      messagesDataChanged = 0;

  // var dataChanged = 0;

  var notAuthenticated = true;

  var checkListsData = function() {
    return listDataChanged;
  }

  var checkConsData = function() {
    return consDataChanged;
  }

  var checkMessagesData = function() {
    return messagesDataChanged;
  }

  var reload = function(src) {
    $('script[src="' + src + '"]').remove();
    $('<script>').attr('src', src + '?cachebuster='+ new Date().getTime()).appendTo('head');
  };

  var authenticate = function(socket, user) {
    var deferred = $q.defer();
    socket.user = user.username; //maybe remove this - should probably remove this
    console.log("authenticating");

    defineSocket(socket, deferred, user.username);

    socket.emit('authentication', user);

    var authInterval = setInterval(function() {
                         if (notAuthenticated) {
                            reload('//cdn.socket.io/socket.io-1.3.5.js');
                            socket = io();
                            defineSocket(socket, deferred, user.username);
                            socket.emit('authentication', user);
                            console.log("trying login again");
                         } else {
                          if (authInterval) {
                            clearInterval(authInterval);
                          }
                         }
                       }, 10000);

    return deferred.promise;
  }

  var defineSocket = function(socket, deferred, username) {
    socket.on('authenticated', function() {
      notAuthenticated = false;
      deferred.resolve(socket);
    });

    socket.on('unauthorized', function(err){
      notAuthenticated = false;
      console.log("There was an error with the authentication:", err.message);
      deferred.reject(err.message);
    });

    socket.on('onlineList', function(onlineList) {
      data.lists.onlineList = onlineList;
      listDataChanged += 1;
      $rootScope.$apply();
    });

    socket.on('userList', function(serverData) {
      data.lists.userList = serverData.userList;
      listDataChanged += 1;
      $rootScope.$apply();
    });

    socket.on('initialMessage', function(response) {
      processMessage(response, {'older' : false, 'online' : false});
    });

    socket.on('onlineMessage', function(response) {
      processMessage(response, {'older' : false, 'online' : true});
      messagesDataChanged += 1;
      $rootScope.$apply();
    });

    socket.on('initialConversation', function(conversation) {
      processConversation(conversation, username, true);
    });

    socket.on('olderMessage', function(response) {
      processMessage(response, {'older' : true, 'online' : false});
    });

    socket.on('olderConversation', function(conversation) {
      console.log('older cons');
      processConversation(conversation, username, false);
    });
  };

  var getParentConversation = function(conversationId) {
    var i;
    for (i = 0; i < data.cons.conversationsList.length; i++) {
      if (data.cons.conversationsList[i].id == conversationId) {
        return {conversation: data.cons.conversationsList[i], index: i};
      }
    }
    return false;
  };

  var processConversation = function(conversation, username, initial) {
    console.log('latest conversation');
    console.log(conversation);
    //CURRENTLY ASSUMING CONVERSATIONS ARRIVE IN ORDER
    conversation = chats.getConversationInfo(conversation, username)
    if (initial) {
      data.cons.conversationsList.unshift(conversation);
    } else {
      console.log('trying to add to con list');
      var i;
      for (i = data.cons.conversationsList.length - 1; i >= 0; i--) {
        if (conversation.unixTime < data.cons.conversationsList[i].unixTime) {
          console.log(i);
          data.cons.conversationsList.splice(i + 1, 0, conversation);
          console.log(data.cons.conversationsList);
          break;
        }
      }
      data.cons.gettingConvos = false;
    }
    console.debug(data.cons.conversationsList);
    //not updating changedId and changedIndex
    consDataChanged += 1;
    console.info(data.cons.gettingConvos);
    $rootScope.$apply();
  };

  var processMessage = function(response, args) {
    console.log(response);
    //ASSUMING MESSAGES ARRIVE IN ORDER
    var parentInfo = getParentConversation(response.conversationId);
    if (parentInfo) {
      addToConversation(response, args, parentInfo);
    } else {
      var messageInterval = setInterval(function() {
                              console.warn('message interval is running');
                              parentInfo = getParentConversation(response.conversationId);
                              if (parentInfo) {
                                clearInterval(messageInterval);
                                addToConversation(response, args, parentInfo);
                              }
                            }, 1000)
      console.warn('Got message with no conversation parent');
    }
  };

  var addToConversation = function(response, args, parentInfo) {
    var conversation = parentInfo.conversation;
    var conIndex = parentInfo.index;
    if (args.older) {

    } else {
      conversation.messages.push(response.message);
      chats.updateConversationInfo(conversation, response.message.time);
      if (args.online) {
        console.log('updated conversation');
        console.log(conversation);
        data.cons.conversationsList.splice(conIndex, 1);
        data.cons.conversationsList.unshift(conversation);
        data.messages.changedId = conversation.id;
        data.messages.changedIndex = 0;
        consDataChanged += 1;
        $rootScope.$apply();
      }
    }
  };

  var getConversations = function(socket) {
    //ASSUMES DATA.CONVERSATION IS SORTED
    if (!data.cons.gettingConvos) {
      data.cons.gettingConvos = true;
      console.log('getting conversations');
      var length = data.cons.conversationsList.length;
      var latestTime;
      if (length) {
        latestTime = data.cons.conversationsList[length - 1].unixTime - 1;
      } else {
        latestTime = Date.now();
      }
      consDataChanged += 1;
      $rootScope.$apply();
      $timeout(function() {
        data.cons.gettingConvos = false;
        consDataChanged += 1;
        $rootScope.$apply();
      }, 2000);
      socket.emit('getConversations', latestTime);
    }
  };

  var getMessages = function(socket, conversation) {
    console.log('getting messages');
    var latestTime;
    if (conversation.messages) {
      console.log(conversation.messages);
      latestTime = conversation.messages[0].time - 1;
    } else {
      latestTime = Date.now();
    }
    socket.emit('getMessages', {conversationId: conversation.id,
                                latestTime: latestTime});
  };

  var sendConversation = function(socket, conversation) {
    socket.emit('sendConversation', conversation);
  };

  var sendMessage = function(socket, message, conversationId) {
    socket.emit('sendMessage', {message: message,
                                conversationId: conversationId});
  };

  var readMessage = function(socket, conversationId) {
    socket.emit('readMessage', conversationId);
  };

  var disconnect = function(socket) {
    socket.emit('disconnect');
  };

  return {
    reload: reload,
    authenticate: authenticate,
    defineSocket: defineSocket,
    getListsData: getListsData,
    getConsData: getConsData,
    getMessagesData: getMessagesData,
    checkListsData: checkListsData,
    checkConsData: checkConsData,
    checkMessagesData: checkMessagesData,
    getConversations: getConversations,
    getMessages: getMessages,
    sendConversation: sendConversation,
    sendMessage: sendMessage,
    readMessage: readMessage,
    disconnect: disconnect
  };
});


text:
// Karma configuration

module.exports = function (config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['browserify', 'mocha'],

        // list of files / patterns to load in the browser
        files: [
            'mopidy_musicbox_webclient/static/vendors/**/*.js',
            'mopidy_musicbox_webclient/static/js/**/*.js',
            'tests/**/test_*.js'
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'tests/**/test_*.js': [ 'browserify' ],
            'mopidy_musicbox_webclient/static/js/**/*.js': ['coverage']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['PhantomJS'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

        // add additional browserify configuration properties here
        // such as transform and/or debug=true to generate source maps
        browserify: {
            debug: true,
            transform: [
                'babelify',
                ['browserify-istanbul', { instrumenter: require('isparta') }]
            ]
        },

        coverageReporter: {
            // specify a common output directory
            dir: '.karma_coverage/',
            reporters: [
                { type: 'lcov', subdir: '.' },
                { type: 'text' }
            ]
        }
    })
}

redpajama_set_name: RedPajamaGithub


text:
from django_filters import rest_framework as filters
from .models import Process

class ProcessingHistoryFilter(filters.FilterSet):
    ''' filter on Processing History fields '''
    end__isnull = filters.BooleanFilter(name='end', lookup_expr='isnull')

    class Meta:
        model = Process
        fields = (
          'exposure_id',
          'exposure__tile',
          'exposure__telra',
          'exposure__night',
          'exposure__exptime',
          'exposure__flavor',
          'exposure__program',
          'exposure__dateobs',
          'exposure__airmass',
          'exposure__teldec',
          'end__isnull',
          'end',
          'status')


text:
/**
 * @fileoverview Rule to warn about translation template variables
 * @author Apache
 */

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
  rules: {
    'no-template-vars': {
      create(context) {
        function handler(node) {
          if (node.arguments.length) {
            const firstArgs = node.arguments[0];
            if (
              firstArgs.type === 'TemplateLiteral' &&
              firstArgs.expressions.length
            ) {
              context.report({
                node,
                message:
                  "Don't use variables in translation string templates. Flask-babel is a static translation translation service, so it can't handle strings that include variables",
              });
            }
          }
        }
        return {
          "CallExpression[callee.name='t']": handler,
          "CallExpression[callee.name='tn']": handler,
        };
      },
    },
  },
};


text:
class CreateResponses < ActiveRecord::Migration
  def change
    create_table :responses do |t|
      t.belongs_to :ad, index: true
      t.belongs_to :user, index: true
      t.timestamps null: false
    end
  end
end


text:
package composite;

/**
 * @author JUANJUAN
 * @version 2017年7月27日下午4:03:04
 */
public class CompositePatternDemo {
	public static void main(String[] args) {
		Employee CEO = new Employee("John", "CEO", 30000);

		Employee headSales = new Employee("Robert", "Head Sales", 20000);

		Employee headMarketing = new Employee("Michel", "Head Marketing", 20000);

		Employee clerk1 = new Employee("Laura", "Marketing", 10000);
		Employee clerk2 = new Employee("Bob", "Marketing", 10000);

		Employee salesExecutive1 = new Employee("Richard", "Sales", 10000);
		Employee salesExecutive2 = new Employee("Rob", "Sales", 10000);

		CEO.add(headSales);
		CEO.add(headMarketing);

		headSales.add(salesExecutive1);
		headSales.add(salesExecutive2);

		headMarketing.add(clerk1);
		headMarketing.add(clerk2);

		// 打印该组织的所有员工
		System.out.println(CEO);
		for (Employee headEmployee : CEO.getSubordinates()) {
			System.out.println(headEmployee);
			for (Employee employee : headEmployee.getSubordinates()) {
				System.out.println(employee);
			}
		}
	}
}


text:
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Fungus
{
    namespace Examples
    {
        public class SpriteColorChangeFromFungusMouseEvent : MonoBehaviour
        {
            private SpriteRenderer rend;

            private void Start()
            {
                rend = GetComponent<SpriteRenderer>();
            }

            void OnMouseEventFromFungus()
            {
                rend.color = Color.HSVToRGB(Random.value, Random.Range(0.7f, 0.9f), Random.Range(0.7f, 0.9f));
            }
        }
    }
}


text:
-- phpMyAdmin SQL Dump
-- version 4.0.9
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Apr 11, 2015 at 10:52 PM
-- Server version: 5.5.34
-- PHP Version: 5.4.22

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `k2`
--

-- --------------------------------------------------------

--
-- Table structure for table `agency`
--

CREATE TABLE IF NOT EXISTS `agency` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `NIPT` varchar(20) DEFAULT NULL,
  `address` varchar(150) NOT NULL,
  `email` varchar(50) NOT NULL,
  `tel` varchar(15) NOT NULL,
  `created_by` int(11) DEFAULT NULL,
  `updated_by` int(11) DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `created_by` (`created_by`,`updated_by`),
  KEY `updated_by` (`updated_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `agency`
--

INSERT INTO `agency` (`id`, `name`, `NIPT`, `address`, `email`, `tel`, `created_by`, `updated_by`, `updated_at`) VALUES
(1, 'Kalemi Travel', NULL, 'Sheshi Wilson, Tirane', 'turizem@kalemitravel.com', '+355694045921', 1, 1, '2015-04-11 12:19:43');

-- --------------------------------------------------------

--
-- Table structure for table `article`
--

CREATE TABLE IF NOT EXISTS `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `summary` text COLLATE utf8_unicode_ci NOT NULL,
  `content` text COLLATE utf8_unicode_ci NOT NULL,
  `status` int(11) NOT NULL,
  `category` int(11) NOT NULL,
  `created_at` int(11) NOT NULL,
  `updated_at` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

--
-- Dumping data for table `article`
--

INSERT INTO `article` (`id`, `user_id`, `title`, `summary`, `content`, `status`, `category`, `created_at`, `updated_at`) VALUES
(1, 1, 'This is just a test ', 'my first article on new template ', '

\n\n

\n\n
best
\n\n
Fabjan
\n', 2, 1, 1428483237, 1428483237),
(2, 1, 'test', 'some artikle', '
cfsdfs
\r\n', 2, 2, 1428599157, 1428599157);

-- --------------------------------------------------------

--
-- Table structure for table `auth_assignment`
--

CREATE TABLE IF NOT EXISTS `auth_assignment` (
  `item_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `user_id` int(11) NOT NULL,
  `created_at` int(11) DEFAULT NULL,
  PRIMARY KEY (`item_name`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `auth_assignment`
--

INSERT INTO `auth_assignment` (`item_name`, `user_id`, `created_at`) VALUES
('admin', 2, NULL),
('theCreator', 1, 1428483124);

-- --------------------------------------------------------

--
-- Table structure for table `auth_item`
--

CREATE TABLE IF NOT EXISTS `auth_item` (
  `name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `type` int(11) NOT NULL,
  `description` text COLLATE utf8_unicode_ci,
  `rule_name` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL,
  `data` text COLLATE utf8_unicode_ci,
  `created_at` int(11) DEFAULT NULL,
  `updated_at` int(11) DEFAULT NULL,
  PRIMARY KEY (`name`),
  KEY `rule_name` (`rule_name`),
  KEY `idx-auth_item-type` (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `auth_item`
--

INSERT INTO `auth_item` (`name`, `type`, `description`, `rule_name`, `data`, `created_at`, `updated_at`) VALUES
('admin', 1, 'Administrator of this application', NULL, NULL, 1428482459, 1428482459),
('adminArticle', 2, 'Allows admin+ roles to manage articles', NULL, NULL, 1428482459, 1428482459),
('createArticle', 2, 'Allows editor+ roles to create articles', NULL, NULL, 1428482459, 1428482459),
('deleteArticle', 2, 'Allows admin+ roles to delete articles', NULL, NULL, 1428482459, 1428482459),
('editor', 1, 'Editor of this application', NULL, NULL, 1428482459, 1428482459),
('manageUsers', 2, 'Allows admin+ roles to manage users', NULL, NULL, 1428482459, 1428482459),
('member', 1, 'Registered users, members of this site', NULL, NULL, 1428482459, 1428482459),
('premium', 1, 'Premium members. They have more permissions than normal members', NULL, NULL, 1428482459, 1428482459),
('support', 1, 'Support staff', NULL, NULL, 1428482459, 1428482459),
('theCreator', 1, 'You!', NULL, NULL, 1428482459, 1428482459),
('updateArticle', 2, 'Allows editor+ roles to update articles', NULL, NULL, 1428482459, 1428482459),
('updateOwnArticle', 2, 'Update own article', 'isAuthor', NULL, 1428482459, 1428482459),
('usePremiumContent', 2, 'Allows premium+ roles to use premium content', NULL, NULL, 1428482458, 1428482458);

-- --------------------------------------------------------

--
-- Table structure for table `auth_item_child`
--

CREATE TABLE IF NOT EXISTS `auth_item_child` (
  `parent` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `child` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`parent`,`child`),
  KEY `child` (`child`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `auth_item_child`
--

INSERT INTO `auth_item_child` (`parent`, `child`) VALUES
('theCreator', 'admin'),
('editor', 'adminArticle'),
('editor', 'createArticle'),
('admin', 'deleteArticle'),
('admin', 'editor'),
('admin', 'manageUsers'),
('support', 'member'),
('support', 'premium'),
('editor', 'support'),
('admin', 'updateArticle'),
('updateOwnArticle', 'updateArticle'),
('editor', 'updateOwnArticle'),
('premium', 'usePremiumContent');

-- --------------------------------------------------------

--
-- Table structure for table `auth_rule`
--

CREATE TABLE IF NOT EXISTS `auth_rule` (
  `name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `data` text COLLATE utf8_unicode_ci,
  `created_at` int(11) DEFAULT NULL,
  `updated_at` int(11) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `auth_rule`
--

INSERT INTO `auth_rule` (`name`, `data`, `created_at`, `updated_at`) VALUES
('isAuthor', 'O:25:"app\\rbac\\rules\\AuthorRule":3:{s:4:"name";s:8:"isAuthor";s:9:"createdAt";i:1428482457;s:9:"updatedAt";i:1428482457;}', 1428482457, 1428482457);

-- --------------------------------------------------------

--
-- Table structure for table `branch`
--

CREATE TABLE IF NOT EXISTS `branch` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `NIPT` varchar(20) DEFAULT NULL,
  `member_of` int(11) NOT NULL,
  `address` varchar(150) NOT NULL,
  `tel` varchar(20) NOT NULL,
  `email` varchar(100) NOT NULL,
  `created_by` int(11) DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_by` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `member_of` (`member_of`),
  KEY `created_by` (`created_by`),
  KEY `updated_by` (`updated_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `branch`
--

INSERT INTO `branch` (`id`, `name`, `NIPT`, `member_of`, `address`, `tel`, `email`, `created_by`, `updated_at`, `updated_by`) VALUES
(1, 'Kalemi Travel Shkoder', NULL, 1, 'Shkoder, Parruce', '+355694045921', 'shkoder@kalemitravel.com', 1, '2015-04-11 12:21:08', NULL);

-- --------------------------------------------------------

--
-- Table structure for table `client`
--

CREATE TABLE IF NOT EXISTS `client` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` int(11) NOT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_typeclient` (`type`),
  KEY `userclientcreated` (`created_by`),
  KEY `userclientupdated` (`updated_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `client`
--

INSERT INTO `client` (`id`, `type`, `created_by`, `updated_by`, `updated_at`) VALUES
(1, 1, 1, 1, '2015-04-11 11:34:11');

-- --------------------------------------------------------

--
-- Table structure for table `clientusers`
--

CREATE TABLE IF NOT EXISTS `clientusers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `client` int(11) NOT NULL,
  `firstName` varchar(225) NOT NULL,
  `lastName` varchar(225) NOT NULL,
  `NIPT` varchar(10) DEFAULT NULL,
  `agency` int(11) DEFAULT NULL,
  `branch` varchar(45) DEFAULT NULL,
  `tel` varchar(45) DEFAULT NULL,
  `cel` varchar(45) DEFAULT NULL,
  `fax` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `city` varchar(45) DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_client` (`client`),
  KEY `userclientuserscreated` (`created_by`),
  KEY `userclientusersupdated` (`updated_by`),
  KEY `agency` (`agency`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `clientusers`
--

INSERT INTO `clientusers` (`id`, `client`, `firstName`, `lastName`, `NIPT`, `agency`, `branch`, `tel`, `cel`, `fax`, `email`, `city`, `address`, `created_by`, `updated_by`, `updated_at`) VALUES
(1, 1, 'Fabjan', 'Lashi', 'N32322L', 1, '1', '+35569404592', '+35569404592', '', '', 'TIRANA', '30 duncan street', 1, NULL, '2015-04-11 12:21:42');

-- --------------------------------------------------------

--
-- Table structure for table `clientype`
--

CREATE TABLE IF NOT EXISTS `clientype` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(50) NOT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `userclientypecreated` (`created_by`),
  KEY `userclientypeupdated` (`updated_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `clientype`
--

INSERT INTO `clientype` (`id`, `description`, `created_by`, `updated_by`, `updated_at`) VALUES
(1, 'Agency', 1, 1, '2015-04-11 11:33:39');

-- --------------------------------------------------------

--
-- Table structure for table `migration`
--

CREATE TABLE IF NOT EXISTS `migration` (
  `version` varchar(180) NOT NULL,
  `apply_time` int(11) DEFAULT NULL,
  PRIMARY KEY (`version`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `migration`
--

INSERT INTO `migration` (`version`, `apply_time`) VALUES
('m000000_000000_base', 1428482425),
('m141022_115823_create_user_table', 1428482431),
('m141022_115912_create_rbac_tables', 1428482432),
('m150104_153617_create_article_table', 1428482432);

-- --------------------------------------------------------

--
-- Table structure for table `package`
--

CREATE TABLE IF NOT EXISTS `package` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(500) DEFAULT NULL,
  `startdate` datetime DEFAULT NULL,
  `enddate` datetime DEFAULT NULL,
  `type` varchar(45) DEFAULT NULL,
  `cost` decimal(10,2) DEFAULT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `userpackagecreated` (`created_by`),
  KEY `userpackageupdated` (`updated_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `package`
--

INSERT INTO `package` (`id`, `description`, `startdate`, `enddate`, `type`, `cost`, `created_by`, `updated_by`, `updated_at`) VALUES
(1, 'Kolashin 21 Maj', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '', '3200000.00', 1, NULL, '2015-04-11 11:49:51');

-- --------------------------------------------------------

--
-- Table structure for table `packageservices`
--

CREATE TABLE IF NOT EXISTS `packageservices` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `package` int(11) NOT NULL,
  `service` int(11) NOT NULL,
  `comments` varchar(300) DEFAULT NULL,
  `default_price` decimal(10,2) DEFAULT NULL,
  `start` datetime DEFAULT NULL,
  `end` datetime DEFAULT NULL,
  `cost` decimal(10,2) DEFAULT NULL,
  `agency` int(11) DEFAULT NULL,
  `branch` int(11) DEFAULT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_package` (`package`),
  KEY `fk_services` (`service`),
  KEY `userpackageservicescreated` (`created_by`),
  KEY `userpackageservicesupdated` (`updated_by`),
  KEY `agency` (`agency`,`branch`),
  KEY `branch` (`branch`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `payments`
--

CREATE TABLE IF NOT EXISTS `payments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `reservation` int(11) NOT NULL,
  `date` datetime DEFAULT NULL,
  `quantity` decimal(10,2) DEFAULT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_res` (`reservation`),
  KEY `userpaymentscreated` (`created_by`),
  KEY `userpaymentsupdated` (`updated_by`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `provider`
--

CREATE TABLE IF NOT EXISTS `provider` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `address` varchar(100) DEFAULT NULL,
  `tel` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `website` varchar(45) DEFAULT NULL,
  `owner` varchar(45) DEFAULT NULL,
  `city` varchar(45) DEFAULT NULL,
  `type` varchar(45) DEFAULT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `userprovidercreated` (`created_by`),
  KEY `userproviderupdated` (`updated_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `provider`
--

INSERT INTO `provider` (`id`, `name`, `address`, `tel`, `email`, `website`, `owner`, `city`, `type`, `created_by`, `updated_by`, `updated_at`) VALUES
(1, 'Fabjan Lashi', 'Tirane - Marko Bocari', '0694045921', 'flashi@e-shkolla.com', '', '1', 'TIRANA', '', 1, NULL, '2015-04-11 11:40:36');

-- --------------------------------------------------------

--
-- Table structure for table `reservation`
--

CREATE TABLE IF NOT EXISTS `reservation` (
  `id` int(11) NOT NULL,
  `client` int(11) NOT NULL,
  `packageservice` int(11) NOT NULL,
  `priceoffer` decimal(10,2) DEFAULT NULL,
  `finalprice` decimal(10,2) DEFAULT NULL,
  `fullypaid` char(1) DEFAULT NULL,
  `closed_deal` char(1) DEFAULT NULL,
  `amount_paid` decimal(10,2) DEFAULT NULL,
  `cost` decimal(10,2) DEFAULT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_client_res` (`client`),
  KEY `fk_pcg_service` (`packageservice`),
  KEY `userreservationcreated` (`created_by`),
  KEY `userreservationupdated` (`updated_by`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `services`
--

CREATE TABLE IF NOT EXISTS `services` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(250) NOT NULL,
  `provider` int(11) NOT NULL,
  `type` varchar(45) DEFAULT NULL,
  `default_price` decimal(10,2) DEFAULT NULL,
  `capacity` int(11) DEFAULT NULL,
  `price_per_unit` decimal(10,2) DEFAULT NULL,
  `created_by` int(10) DEFAULT NULL,
  `updated_by` int(10) DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`,`provider`),
  KEY `fk_provider` (`provider`),
  KEY `userservicescreated` (`created_by`),
  KEY `userservicesupdated` (`updated_by`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `services`
--

INSERT INTO `services` (`id`, `description`, `provider`, `type`, `default_price`, `capacity`, `price_per_unit`, `created_by`, `updated_by`, `updated_at`) VALUES
(1, 'Sherbim Autobuzi', 1, '1', '100000.00', 20, '5000.00', 1, NULL, '2015-04-11 11:42:39');

-- --------------------------------------------------------

--
-- Table structure for table `user`
--

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `status` smallint(6) NOT NULL,
  `auth_key` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `password_reset_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `account_activation_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` int(11) NOT NULL,
  `updated_at` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`id`, `username`, `email`, `password_hash`, `status`, `auth_key`, `password_reset_token`, `account_activation_token`, `created_at`, `updated_at`) VALUES
(1, 'banyx101', 'kaligrafik@gmail.com', '$2y$13$v/up5z7/4B5GOkoCPcBREO1CLTiFUhHWAn2fzscL.7dNrYzCWSm9e', 10, 'CJ5TSCcVLUoZa87_bVKBxZb0RyRdKkrA', NULL, NULL, 1428483124, 1428484035),
(2, 'denis', 'denis.saatciu@gmail.com', '$2y$13$K1gv693OxgXpTw8P0d.XbuPlM.qxYFbYq44dYPwDRMEbJaX27deOK', 10, '7Jn5BDAVN-a0zuF3ApuqyTQwLkvGNbhn', NULL, NULL, 1428483959, 1428483959);

--
-- Constraints for dumped tables
--

--
-- Constraints for table `agency`
--
ALTER TABLE `agency`
  ADD CONSTRAINT `userupdateagency` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `useragencycreate` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `article`
--
ALTER TABLE `article`
  ADD CONSTRAINT `article_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `auth_assignment`
--
ALTER TABLE `auth_assignment`
  ADD CONSTRAINT `auth_assignment_ibfk_1` FOREIGN KEY (`item_name`) REFERENCES `auth_item` (`name`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `auth_item`
--
ALTER TABLE `auth_item`
  ADD CONSTRAINT `auth_item_ibfk_1` FOREIGN KEY (`rule_name`) REFERENCES `auth_rule` (`name`) ON DELETE SET NULL ON UPDATE CASCADE;

--
-- Constraints for table `auth_item_child`
--
ALTER TABLE `auth_item_child`
  ADD CONSTRAINT `auth_item_child_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `auth_item` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `auth_item_child_ibfk_2` FOREIGN KEY (`child`) REFERENCES `auth_item` (`name`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `branch`
--
ALTER TABLE `branch`
  ADD CONSTRAINT `agencybranch` FOREIGN KEY (`member_of`) REFERENCES `agency` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userbranch` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userupdatebranch` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `client`
--
ALTER TABLE `client`
  ADD CONSTRAINT `fk_typeclient` FOREIGN KEY (`type`) REFERENCES `clientype` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `user-client-created` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `user-client-updated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userclientcreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userclientupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `clientusers`
--
ALTER TABLE `clientusers`
  ADD CONSTRAINT `fk_agency` FOREIGN KEY (`agency`) REFERENCES `agency` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_client` FOREIGN KEY (`client`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userclientuserscreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userclientusersupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `clientype`
--
ALTER TABLE `clientype`
  ADD CONSTRAINT `userclientypecreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userclientypeupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `package`
--
ALTER TABLE `package`
  ADD CONSTRAINT `userpackagecreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userpackageupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `packageservices`
--
ALTER TABLE `packageservices`
  ADD CONSTRAINT `fk_branch` FOREIGN KEY (`branch`) REFERENCES `branch` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_package` FOREIGN KEY (`package`) REFERENCES `package` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_services` FOREIGN KEY (`service`) REFERENCES `services` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `packageservices_agency` FOREIGN KEY (`agency`) REFERENCES `agency` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userpackageservicescreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userpackageservicesupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `payments`
--
ALTER TABLE `payments`
  ADD CONSTRAINT `fk_res` FOREIGN KEY (`reservation`) REFERENCES `reservation` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userpaymentscreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userpaymentsupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `provider`
--
ALTER TABLE `provider`
  ADD CONSTRAINT `userprovidercreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userproviderupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `reservation`
--
ALTER TABLE `reservation`
  ADD CONSTRAINT `fk_client_res` FOREIGN KEY (`client`) REFERENCES `clientusers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_pcg_service` FOREIGN KEY (`packageservice`) REFERENCES `packageservices` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userreservationcreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userreservationupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

--
-- Constraints for table `services`
--
ALTER TABLE `services`
  ADD CONSTRAINT `fk_provider` FOREIGN KEY (`provider`) REFERENCES `provider` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userservicescreated` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `userservicesupdated` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
package com.intellij.execution.dashboard.tree;

import com.intellij.execution.dashboard.RunDashboardGroup;

import javax.swing.*;

/**
 * @author konstantin.aleev
 */
public class RunDashboardGroupImpl<T> implements RunDashboardGroup {
  private final T myValue;
  private final String myName;
  private final Icon myIcon;

  public RunDashboardGroupImpl(T value, String name, Icon icon) {
    myValue = value;
    myName = name;
    myIcon = icon;
  }

  @Override
  public String getName() {
    return myName;
  }

  @Override
  public Icon getIcon() {
    return myIcon;
  }

  @Override
  public int hashCode() {
    return myValue.hashCode();
  }

  @Override
  public final boolean equals(Object obj) {
    if (obj instanceof RunDashboardGroupImpl) {
      return myValue.equals(((RunDashboardGroupImpl)obj).myValue);
    }
    return false;
  }
}


text:
package com.crane.coolweather.util;

import android.text.TextUtils;

import com.crane.coolweather.db.City;
import com.crane.coolweather.db.County;
import com.crane.coolweather.db.Province;
import com.crane.coolweather.gson.Weather;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2017/6/22/022.
 */

public class Utility {

    /**
     * 讲返回的JSON数据解析成Weather实体类
     */
    public static Weather handleWeatherResponse(String resonse) {
        try {
            JSONObject jsonObject = new JSONObject(resonse);
            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather");
            String weatherContent = jsonArray.getJSONObject(0).toString();
            return new Gson().fromJson(weatherContent, Weather.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析和处理服务器返回的省级数据
     */
    public static boolean handleProvinceResponse(String response) {
        if (!TextUtils.isEmpty(response)) {
            try {
                JSONArray allProvinces = new JSONArray(response);
                for (int i = 0 ; i < allProvinces.length() ; i ++)
                {
                    JSONObject provinceObject = allProvinces.getJSONObject(i);
                    Province province = new Province();
                    province.setProvinceName(provinceObject.getString("name"));
                    province.setProvinceCode(provinceObject.getInt("id"));
                    province.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 解析和处理服务器返回的市级数据
     */
    public static boolean handleCityResponse(String response,int provinceId){
        if (!TextUtils.isEmpty(response)){
            try {
                JSONArray allCities = new JSONArray(response);
                for(int i = 0 ; i < allCities.length() ; i ++ ) {
                    JSONObject cityObject = allCities.getJSONObject(i);
                    City city = new City();
                    city.setCityName(cityObject.getString("name"));
                    city.setCityCode(cityObject.getInt("id"));
                    city.setProvinceId(provinceId);
                    city.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();;
            }
        }
        return false;
    }

    /**
     * 解析和处理服务器返回的县级数据
     */
    public static boolean handleCountyResponse(String response,int cityId) {
        if (!TextUtils.isEmpty(response)){
            try {
                JSONArray allCounties = new JSONArray(response);
                for (int i = 0 ; i < allCounties.length() ; i ++ ) {
                    JSONObject countyObject = allCounties.getJSONObject(i);
                    County county = new County();
                    county.setCityId(cityId);
                    county.setCountyName(countyObject.getString("name"));
                    county.setWeatherId(countyObject.getString("weather_id"));
                    county.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (python_training)" project-jdk-type="Python SDK" />
</project>


text:
``` purescript
geolocation :: forall eff. Navigator -> Eff (dom :: DOM | eff) (Nullable NavigatorGeolocation)
```

geolocation returns a geolocation object if the current browser supports
the Geolocation API

#### `NavigatorGeolocation`

``` purescript
data NavigatorGeolocation :: *
```

NavigatorGeolocation is a dummy type for the geolocation object. It can
implement the 'proper' Geolocation Class

##### Instances
``` purescript
Geolocation NavigatorGeolocation
```


text:
Pattern: Multiple closures with trailing closure

Issue: -

## Description

Trailing closure syntax should not be used when passing more than one closure argument.

Examples of **correct** code:
```swift
foo.map { $0 + 1 }

foo.reduce(0) { $0 + $1 }

if let foo = bar.map({ $0 + 1 }) {

}

foo.something(param1: { $0 }, param2: { $0 + 1 })

UIView.animate(withDuration: 1.0) {
    someView.alpha = 0.0
}

```
Examples of **incorrect** code:
```swift

foo.something(param1: { $0 }) ↓{ $0 + 1 }

UIView.animate(withDuration: 1.0, animations: {
    someView.alpha = 0.0
}) ↓{ _ in
    someView.removeFromSuperview()
}

```

## Further Reading

* [SwiftLint - Multiple Closures with Trailing Closure](https://realm.github.io/SwiftLint/multiple_closures_with_trailing_closure.html)


text:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var check = require('express-check');
var rule = check.rule;

router.post('/login', check(
  'body',
  rule('tel').notEmpty(),
  rule('password').notEmpty()
), function(req, res, next) {
  var tel = req.body.tel;
  var password = req.body.password;
  mongoose.model('User').findOne({
    tel: tel,
    password: password
  }, function(err, user) {
    if (err || !user) {
      res.send('bad');
    } else {
      req.session.userId = user._id;
      res.json(user);
    }
  });
});

router.post('/add', check(
  'body',
  rule('tel').notEmpty(),
  rule('password').notEmpty()
), function(req, res, next) {
  var tel = req.body.tel;
  var password = req.body.password;
  mongoose.model('User').create({
    tel: tel,
    password: password
  }, function(err, user) {
    if (err) return next(err);
    res.send('ok');
  });
});

module.exports = router;


text:
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ConfigService } from './services/config.service';
import { GeoService } from './geo.service';

@NgModule({
  imports: [
    CommonModule
  ],
  providers: [GeoService]
})
export class GeoCodRefModule {
  static forRoot(configService: any, key: string): ModuleWithProviders {
    return {
      ngModule: GeoCodRefModule,
      providers: [
        { provide: ConfigService, useExisting: configService },
        { provide: 'geo-server', useValue: key }
      ]
    };
  }
}


text:
- Read about [`alias` and `import`][getting-started] in the Getting Started guide.
- Read about [module composition][elixir-school-module-composition] on elixirschool.com.

## 1. Fix compilation error `Race.__struct__/0 is undefined`

- An alias can be created with the [`alias`][alias] special form.

## 2. Fix compilation error `Car.__struct__/0 is undefined`

- An alias can be created with the [`alias`][alias] special form.
- The `alias` special form accepts an `:as` option.

## 3. Fix compilation error `undefined function puts/1`

- Functions can be imported with the [`import`][import] special form.
- The [`import`][import] special form accepts an `:only` option. Its value should be a keyword list with function name as keys and function arities as values.

## 4. Fix compilation error `undefined function default_color/0`

- Functions can be imported with the [`import`][import] special form.
- The [`import`][import] special form accepts an `:except` option. Its value should be a keyword list with function name as keys and function arities as values.

[alias]: https://hexdocs.pm/elixir/Kernel.SpecialForms.html#alias/2
[import]: https://hexdocs.pm/elixir/Kernel.SpecialForms.html#import/2
[elixir-school-module-composition]: https://elixirschool.com/en/lessons/basics/modules/#composition
[getting-started]: https://elixir-lang.org/getting-started/alias-require-and-import.html


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linehaul_Helper.Exceptions
{
    public class LayoutException : Exception
    {
        public LayoutException(string message)
            : base(message)
        {
        }
    }
}


text: require 'backgroundrb'


text:
package oshai.prefx.adapters;

import java.util.List;

import oshai.prefx.common.DataObject;

public interface IDataAdapter {
	void putD(DataObject data);
	List<String> getAllPhones();
	DataObject getD(String key);
	void deleteAll();
}


text:
package base

import (
	"context"
	"time"
)

var (
	_ Downloader = &RetryDownloader{}
)

// RetryDownloader retry the downloads
type RetryDownloader struct {
	Downloader
	ctx        context.Context
	RetryTimes int // the total execute times
	RetryDelay int // time to delay seconds
}

// NewRetryDownloader creates a retry downloader
func NewRetryDownloader(ctx context.Context, downloader Downloader, retryTimes, retryDelay int) *RetryDownloader {
	return &RetryDownloader{
		Downloader: downloader,
		ctx:        ctx,
		RetryTimes: retryTimes,
		RetryDelay: retryDelay,
	}
}

// SetContext set context
func (d *RetryDownloader) SetContext(ctx context.Context) {
	d.ctx = ctx
	d.Downloader.SetContext(ctx)
}

// GetRepoInfo returns a repository information with retry
func (d *RetryDownloader) GetRepoInfo() (*Repository, error) {
	var (
		times = d.RetryTimes
		repo  *Repository
		err   error
	)
	for ; times > 0; times-- {
		if repo, err = d.Downloader.GetRepoInfo(); err == nil {
			return repo, nil
		}
		if IsErrNotSupported(err) {
			return nil, err
		}
		select {
		case <-d.ctx.Done():
			return nil, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, err
}

// GetTopics returns a repository's topics with retry
func (d *RetryDownloader) GetTopics() ([]string, error) {
	var (
		times  = d.RetryTimes
		topics []string
		err    error
	)
	for ; times > 0; times-- {
		if topics, err = d.Downloader.GetTopics(); err == nil {
			return topics, nil
		}
		if IsErrNotSupported(err) {
			return nil, err
		}
		select {
		case <-d.ctx.Done():
			return nil, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, err
}

// GetMilestones returns a repository's milestones with retry
func (d *RetryDownloader) GetMilestones() ([]*Milestone, error) {
	var (
		times      = d.RetryTimes
		milestones []*Milestone
		err        error
	)
	for ; times > 0; times-- {
		if milestones, err = d.Downloader.GetMilestones(); err == nil {
			return milestones, nil
		}
		if IsErrNotSupported(err) {
			return nil, err
		}
		select {
		case <-d.ctx.Done():
			return nil, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, err
}

// GetReleases returns a repository's releases with retry
func (d *RetryDownloader) GetReleases() ([]*Release, error) {
	var (
		times    = d.RetryTimes
		releases []*Release
		err      error
	)
	for ; times > 0; times-- {
		if releases, err = d.Downloader.GetReleases(); err == nil {
			return releases, nil
		}
		if IsErrNotSupported(err) {
			return nil, err
		}
		select {
		case <-d.ctx.Done():
			return nil, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, err
}

// GetLabels returns a repository's labels with retry
func (d *RetryDownloader) GetLabels() ([]*Label, error) {
	var (
		times  = d.RetryTimes
		labels []*Label
		err    error
	)
	for ; times > 0; times-- {
		if labels, err = d.Downloader.GetLabels(); err == nil {
			return labels, nil
		}
		if IsErrNotSupported(err) {
			return nil, err
		}
		select {
		case <-d.ctx.Done():
			return nil, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, err
}

// GetIssues returns a repository's issues with retry
func (d *RetryDownloader) GetIssues(page, perPage int) ([]*Issue, bool, error) {
	var (
		times  = d.RetryTimes
		issues []*Issue
		isEnd  bool
		err    error
	)
	for ; times > 0; times-- {
		if issues, isEnd, err = d.Downloader.GetIssues(page, perPage); err == nil {
			return issues, isEnd, nil
		}
		if IsErrNotSupported(err) {
			return nil, false, err
		}
		select {
		case <-d.ctx.Done():
			return nil, false, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, false, err
}

// GetComments returns a repository's comments with retry
func (d *RetryDownloader) GetComments(issueNumber int64) ([]*Comment, error) {
	var (
		times    = d.RetryTimes
		comments []*Comment
		err      error
	)
	for ; times > 0; times-- {
		if comments, err = d.Downloader.GetComments(issueNumber); err == nil {
			return comments, nil
		}
		if IsErrNotSupported(err) {
			return nil, err
		}
		select {
		case <-d.ctx.Done():
			return nil, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, err
}

// GetPullRequests returns a repository's pull requests with retry
func (d *RetryDownloader) GetPullRequests(page, perPage int) ([]*PullRequest, bool, error) {
	var (
		times = d.RetryTimes
		prs   []*PullRequest
		err   error
		isEnd bool
	)
	for ; times > 0; times-- {
		if prs, isEnd, err = d.Downloader.GetPullRequests(page, perPage); err == nil {
			return prs, isEnd, nil
		}
		if IsErrNotSupported(err) {
			return nil, false, err
		}
		select {
		case <-d.ctx.Done():
			return nil, false, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, false, err
}

// GetReviews returns pull requests reviews
func (d *RetryDownloader) GetReviews(pullRequestNumber int64) ([]*Review, error) {
	var (
		times   = d.RetryTimes
		reviews []*Review
		err     error
	)
	for ; times > 0; times-- {
		if reviews, err = d.Downloader.GetReviews(pullRequestNumber); err == nil {
			return reviews, nil
		}
		if IsErrNotSupported(err) {
			return nil, err
		}
		select {
		case <-d.ctx.Done():
			return nil, d.ctx.Err()
		case <-time.After(time.Second * time.Duration(d.RetryDelay)):
		}
	}
	return nil, err
}


text:
// Copyright 2014 Extesla, LLC. All rights reserved.
//
// It is illegal to use, reproduce or distribute any part of this
// Intellectual Property without prior written authorization from
// Extesla, LLC.
using System.Reflection;

namespace OpenGamingLibrary.Ioc
{

	/// <summary>
	/// Interface that defines the contract by which classes implementing it
	/// must adhere to when registering new services with a container.
	/// </summary>
	/// <author>Sean Quinn</author>
	public interface IServiceRegistry
	{

		/// <summary>
		/// Registers the <paramref name="serviceType"/> with the <paramref name="implementingType"/>.
		/// </summary>
		/// <param name="serviceType">The service type to register.</param>
		/// <param name="implementingType">The implementing type.</param>
		//void Register(Type serviceType, Type implementingType);

		/// <summary>
		/// Registers the <paramref name="serviceType"/> with the <paramref name="implementingType"/>.
		/// </summary>
		/// <param name="serviceType">The service type to register.</param>
		/// <param name="implementingType">The implementing type.</param>
		/// <param name="serviceName">The name of the service.</param>
		//void Register(Type serviceType, Type implementingType, string serviceName);

		/// <summary>
		/// Register the <typeparamref name="TService"/> with the <typeparamref name="TImplementation">.
		/// </summary>
		/// <example>
		/// container.Register<IFoo, Foo>();
		/// </example>
		/// <typeparam name="TService">The service type to register.</typeparam>
		/// <typeparam name="TImplementation">The implementing type.</typeparam>
		void Register<TService, TImplementation> ()
			where TService : class
			where TImplementation : class, TService;

		/// <summary>
		/// Registers the <typeparamref name="TService"/> with the <typeparamref name="TImplementation"/>.
		/// </summary>
		/// <typeparam name="TService">The service type to register.</typeparam>
		/// <typeparam name="TImplementation">The implementing type.</typeparam>
		/// <param name="serviceName">The name of the service.</param>
		void Register<TService, TImplementation>(string serviceName)
			where TService : class
			where TImplementation : class, TService;

		/// <summary>
		/// Register the <typeparamref name="TService"/> with the <typeparamref name="TImplementation">.
		/// </summary>
		/// <example>
		/// container.Register<IFoo, Foo>();
		/// </example>
		/// <param name="instance">The instance of the implementation.</typeparam>
		/// <typeparam name="TService">The service type to register.</typeparam>
		/// <typeparam name="TImplementation">The implementing type.</typeparam>
		void Register<TService, TImplementation> (TImplementation instance)
			where TService : class
			where TImplementation : class, TService;

		/// <summary>
		/// Registers services from the given <paramref name="assembly"/>.
		/// </summary>
		/// <param name="assembly">The assembly to be scanned for services.</param>
		/// <remarks>
		/// If the target <paramref name="assembly"/> contains an implementation of the <see cref="ICompositionRoot"/> interface, this
		/// will be used to configure the container.
		/// </remarks>
		void RegisterAssembly(Assembly assembly);

		/// <summary>
		/// Verifies the state of the container.
		/// </summary>
		void Verify();
	}
}


text:
package com.LilG.pkmn;

import java.util.BitSet;

/**
 * Created by lil-g on 11/14/16.
 */
public interface pokemon {

	short getHealth();

	short getMaxHealth();

	String getName();

	Type getMainType();

	Type getSecondaryType();

	BitSet getStatus();

	boolean setStatus(StatusEffect status);

	boolean getStatus(StatusEffect status);

	int doDamage(int damageToDeal, Type type);

	int takeDamage(int damageTaken, Type type);

	Ability getAbility();
}


text:
#ifndef DIGSDFN_H
#define DIGSDFN_H

#include "dcmtk/config/osconfig.h"

#include "dcmtk/dcmimgle/didispfn.h"

#define INCLUDE_CSTDDEF               /* For NULL */
#include "dcmtk/ofstd/ofstdinc.h"

/*---------------------*
 *  class declaration  *
 *---------------------*/

/** Class to manage GSDF LUTs (for calibration)
 */
class DiGSDFunction
  : public DiDisplayFunction
{

 public:

    /** constructor, read device characteristics file.
     *  Keywords: "max" for maximum DDL (Device Driving Level, required at first position)
     *            "amb" for ambient light and "lum" for illumination (both optional)
     *            "ord" for the order of the polynomial curve fitting algorithm used to interpolate
     *                  the given base points (0 or absent = use cubic spline interpolation)
     *
     ** @param  filename    name of the characteristics file (luminance/OD for each DDL)
     *  @param  deviceType  type of the output device (default: monitor)
     *  @param  ord         order of the polynomial curve fitting algorithm used to interpolate
     *                      the given base points (-1 = use file setting, 0 = cubic spline)
     */
    DiGSDFunction(const char *filename,
                  const E_DeviceType deviceType = EDT_Monitor,
                  const signed int ord = -1);

    /** constructor, use given array of luminance/OD values. UNTESTED
     *  Values must be sorted and complete (i.e. there must be an entry for each DDL).
     *  The given arrays are copied internally.
     *
     ** @param  val_tab     pointer to array with luminance/OD values
     *  @param  count       number of array elements (should be equal to 'max + 1')
     *  @param  max         maximum DDL (device driving level)
     *  @param  deviceType  type of the output device (default: monitor)
     *  @param  ord         order of the polynomial curve fitting algorithm used to interpolate
     *                      the given base points (0 or negative = use cubic spline interpolation)
     */
    DiGSDFunction(const double *val_tab,
                  const unsigned long count,
                  const Uint16 max = 255,
                  const E_DeviceType deviceType = EDT_Monitor,
                  const signed int ord = 0);

    /** constructor, use given array of DDL and luminance/OD values. UNTESTED
     *  Values will be automatically sorted and missing values will be interpolated.
     *  The given arrays are copied internally.
     *
     ** @param  ddl_tab     pointer to array with DDL values (must be with the interval 0..max)
     *  @param  val_tab     pointer to array with luminance/OD values
     *  @param  count       number of array elements (2..65536)
     *  @param  max         maximum DDL (device driving level)
     *  @param  deviceType  type of the output device (default: monitor)
     *  @param  ord         order of the polynomial curve fitting algorithm used to interpolate
     *                      the given base points (0 or negative = use cubic spline interpolation)
     */
    DiGSDFunction(const Uint16 *ddl_tab,
                  const double *val_tab,
                  const unsigned long count,
                  const Uint16 max = 255,
                  const E_DeviceType deviceType = EDT_Monitor,
                  const signed int ord = 0);

    /** constructor, compute luminance/OD values automatically within the specified range.
     *
     ** @param  val_min     minimum luminance/OD value
     *  @param  val_max     maximum luminance/OD value
     *  @param  count       number of DDLs (device driving level, 1..65536))
     *  @param  deviceType  type of the output device (default: monitor)
     *  @param  ord         order of the polynomial curve fitting algorithm used to interpolate
     *                      the given base points (0 or negative = use cubic spline interpolation)
     */
    DiGSDFunction(const double val_min,
                  const double val_max,
                  const unsigned long count = 256,
                  const E_DeviceType deviceType = EDT_Monitor,
                  const signed int ord = 0);

    /** destructor
     */
    virtual ~DiGSDFunction();

    /** write curve data to a text file
     *
     ** @param  filename  name of the text file to which the data should be written
     *  @param  mode      write CC and PSC to file if OFTrue
     *
     ** @return status, true if successful, false otherwise
     */
    int writeCurveData(const char *filename,
                       const OFBool mode = OFTrue);

    /** set (reflected) ambient light value.
     *  measured in cd/m^2. applicable to softcopy and hardcopy devices.
     *  typical values: 0.5-5 for softcopy devices, 10 for transmissive hardcopy
     *  printer and 0 for reflective hardcopy printers.
     *
     ** @param  value  ambient light value to be set (>= 0)
     *
     ** @return status, true if successful, false otherwise
     */
    int setAmbientLightValue(const double value);

    /** set illumination value.
     *  measured in cd/m^2. applicable to hardcopy devices only.
     *  typical values: 2000 for transmissive hardcopy printer and 150 for
     *  reflective hardcopy printers.
     *
     ** @param  value  illumination value to be set (>= 0)
     *
     ** @return status, true if successful, false otherwise
     */
    int setIlluminationValue(const double value);

    /** set minimum optical density value "Dmin".
     *  measured in optical density (OD). applicable to printers only.
     *  typical value: 0.2
     *
     ** @param  value  Dmin value to be set (or < 0 to unset)
     *
     ** @return status, true if successful (1 = Dmax set, 2 = Dmax unset), false otherwise
     */
    int setMinDensityValue(const double value);

    /** set maximum optical density value "Dmax".
     *  measured in optical density (OD). applicable to printers only.
     *  typical value: 3.0
     *
     ** @param  value  Dmax value to be set (or < 0 to unset)
     *
     ** @return status, true if successful (1 = Dmax set, 2 = Dmax unset), false otherwise
     */
    int setMaxDensityValue(const double value);

    /** calculate the JND index for a given luminance value
     *
     ** @param  lum  luminance value
     *
     ** @return JND index if successful, -1 otherwise
     */
    static double getJNDIndex(const double lum);

 protected:

    /** create GSDF LUT with specified number of entries
     *
     ** @param  count  number of LUT entries
     *
     ** @return pointer to created LUT if successful, NULL otherwise
     */
    DiDisplayLUT *getDisplayLUT(unsigned long count);

    /** calculate GSDF (array of 1023 luminance/OD values)
     *
     ** @return status, true if successful, false otherwise
     */
    int calculateGSDF();

    /** calculate helper function for GSDF interpolation
     *
     ** @return status, true if successful, false otherwise
     */
    int calculateGSDFSpline();

    /** calculate 'JNDMin' and 'JNDMax' for the given luminance/OD range
     *
     ** @return status, true if successful, false otherwise
     */
    int calculateJNDBoundaries();

 private:

    /// minimum JND index value for the given display system
    double JNDMin;
    /// maximum JND index value for the given display system
    double JNDMax;

    /// costant defining the number JND indexes for the maximum luminance/OD range (1023)
    static const unsigned int GSDFCount;
    /// array of luminance/OD values defining the GSDF
    double *GSDFValue;
    /// array of values used for the interpolation of the GSDF
    double *GSDFSpline;

 // --- declarations to avoid compiler warnings

    DiGSDFunction(const DiGSDFunction &);
    DiGSDFunction &operator=(const DiGSDFunction &);
};

#endif

/*
 *
 * CVS/RCS Log:
 * $Log: digsdfn.h,v $
 * Revision 1.17  2010-10-14 13:16:26  joergr
 * Updated copyright header. Added reference to COPYRIGHT file.
 *
 * Revision 1.16  2010-03-01 09:08:46  uli
 * Removed some unnecessary include directives in the headers.
 *
 * Revision 1.15  2005-12-08 16:47:40  meichel
 * Changed include path schema for all DCMTK header files
 *
 * Revision 1.14  2003/12/08 18:21:00  joergr
 * Removed leading underscore characters from preprocessor symbols (reserved
 * symbols). Updated CVS header.
 *
 * Revision 1.13  2003/02/12 11:35:16  joergr
 * Added Dmin/max support to CIELAB calibration routines.
 *
 * Revision 1.12  2003/02/11 10:01:14  joergr
 * Added support for Dmin/max to calibration routines (required for printers).
 *
 * Revision 1.11  2002/07/19 08:24:21  joergr
 * Enhanced/corrected comments.
 *
 * Revision 1.10  2002/07/18 12:30:01  joergr
 * Added support for hardcopy and softcopy input devices (camera and scanner).
 * Added polygonal curve fitting algorithm as an alternate interpolation
 * method.
 *
 * Revision 1.9  2002/07/02 16:23:42  joergr
 * Added support for hardcopy devices to the calibrated output routines.
 *
 * Revision 1.8  2001/06/01 15:49:41  meichel
 * Updated copyright header
 *
 * Revision 1.7  2000/07/17 14:37:12  joergr
 * Moved method getJNDIndex to public part of the interface.
 *
 * Revision 1.6  2000/03/08 16:24:15  meichel
 * Updated copyright header.
 *
 * Revision 1.5  2000/03/06 18:19:36  joergr
 * Moved get-method to base class, renamed method and made method virtual to
 * avoid hiding of methods (reported by Sun CC 4.2).
 *
 * Revision 1.4  1999/10/18 15:05:51  joergr
 * Enhanced command line tool dcmdspfn (added new options).
 *
 * Revision 1.3  1999/09/17 12:11:31  joergr
 * Added/changed/completed DOC++ style comments in the header files.
 *
 * Revision 1.2  1999/09/10 12:17:56  joergr
 * Changed parameter type of copy constructor and assignment operator to avoid
 * compiler warnings reported by gcc/ecgs on Solaris (with additional flags).
 *
 * Revision 1.1  1999/09/10 08:50:23  joergr
 * Added support for CIELAB display function. Restructured class hierarchy
 * for display functions.
 *
 *
 */


text:
package com.microsoft.partnercatalyst.fortis.spark.analyzer

import com.microsoft.partnercatalyst.fortis.spark.dto.{Analysis, Location, Tag}
import com.microsoft.partnercatalyst.fortis.spark.transforms.language.LanguageDetector
import com.microsoft.partnercatalyst.fortis.spark.transforms.locations.LocationsExtractor
import com.microsoft.partnercatalyst.fortis.spark.transforms.people.PeopleRecognizer
import com.microsoft.partnercatalyst.fortis.spark.transforms.sentiment.SentimentDetector
import com.microsoft.partnercatalyst.fortis.spark.transforms.summary.Summarizer
import com.microsoft.partnercatalyst.fortis.spark.transforms.topic.{Blacklist, KeywordExtractor}

/**
  * Provides default analysis method implementations for a concrete [[Analyzer]].
  *
  * By implementing these traits, the concrete [[Analyzer]] explicitly enables the default implementations that are
  * applicable to it. If a default is not enabled, the compiler will enforce that a custom implementation is provided.
  *
  */
private[analyzer] object AnalysisDefaults {
  trait EnableAll[T] extends EnableKeyword[T]
    with EnableLocation[T]
    with EnableEntity[T]
    with EnableLanguage[T]
    with EnableBlacklist[T]
    with EnableEntitiesBlacklist[T]
    with EnableSummary[T]
    with EnableSentiment[T] {
    this: Analyzer[T] =>
  }

  trait EnableKeyword[T] {
    this: Analyzer[T] =>
    override def extractKeywords(details: ExtendedDetails[T], keywordExtractor: KeywordExtractor): List[Tag] = {
      keywordExtractor.extractKeywords(details.title) ::: keywordExtractor.extractKeywords(details.body)
    }
  }

  trait EnableLocation[T] {
    this: Analyzer[T] =>
    override def extractLocations(details: ExtendedDetails[T], locationsExtractor: LocationsExtractor): List[Location] = {
      val extractedLocations = locationsExtractor.analyze(details.body).toList
      if (details.sharedLocations == null || details.sharedLocations.isEmpty) {
        extractedLocations
      } else {
        details.sharedLocations ++ extractedLocations
      }
    }
  }

  trait EnableEntity[T] {
    this: Analyzer[T] =>
    override def extractEntities(details: ExtendedDetails[T], peopleRecognizer: PeopleRecognizer): List[Tag] = {
      if (!sys.env.getOrElse("FORTIS_ENTITY_RECOGNIZER_ENABLED", "false").toBoolean) {
        return List()
      }
      val bodyEntities = peopleRecognizer.extractPeople(details.body)
      val titleEntities = peopleRecognizer.extractPeople(details.title)
      (titleEntities ::: bodyEntities).map(entity => Tag(entity, confidence = None))
    }
  }

  trait EnableLanguage[T] {
    this: Analyzer[T] =>
    override def detectLanguage(details: ExtendedDetails[T], languageDetector: LanguageDetector): Option[String] = {
      languageDetector.detectLanguage(details.body)
    }
  }

  trait EnableSentiment[T] {
    this: Analyzer[T] =>
    override def detectSentiment(details: ExtendedDetails[T], sentimentDetector: SentimentDetector): List[Double] = {
      sentimentDetector.detectSentiment(details.body).toList
    }
  }

  trait EnableBlacklist[T] {
    this: Analyzer[T] =>
    override def hasBlacklistedTerms(details: ExtendedDetails[T], blacklist: Blacklist): Boolean = {
      blacklist.matches(details.body) || blacklist.matches(details.title)
    }
  }

  trait EnableEntitiesBlacklist[T] {
    this: Analyzer[T] =>
    override def hasBlacklistedEntities(analysis: Analysis, blacklist: Blacklist): Boolean = {
      val entities = analysis.entities.map(_.name).toSet
      blacklist.matches(entities)
    }
  }

  trait EnableSummary[T] {
    this: Analyzer[T] =>
    override def createSummary(details: ExtendedDetails[T], summarizer: Summarizer): Option[String] = {
      summarizer.summarize(details.body)
    }
  }
}


text:
package quark_md;

public class quark_spi_api_tracing_RuntimeProxy_schedule_Method extends quark.reflect.Method implements io.datawire.quark.runtime.QObject {
    public quark_spi_api_tracing_RuntimeProxy_schedule_Method() {
        super("quark.void", "schedule", new java.util.ArrayList(java.util.Arrays.asList(new Object[]{"quark.Task", "quark.float"})));
    }
    public Object invoke(Object object, java.util.ArrayList<Object> args) {
        quark.spi_api_tracing.RuntimeProxy obj = (quark.spi_api_tracing.RuntimeProxy) (object);
        (obj).schedule((quark.Task) ((args).get(0)), (Double) ((args).get(1)));
        return null;
    }
    public String _getClass() {
        return (String) (null);
    }
    public Object _getField(String name) {
        return null;
    }
    public void _setField(String name, Object value) {}
}


text:
require "rspec/core"
require "pain_in_the_rspec"

module PainInTheRspec
  class Formatter < RSpec::Core::Formatters::DocumentationFormatter
    RSpec::Core::Formatters.register self, :example_passed, :example_pending,
      :example_failed

    def example_failed(failure)
      output.puts failure_output(
        failure.example,
        failure.example.execution_result.exception
      )
    end

    def example_passed(passed)
      output.puts passed_output(passed.example)
    end

    private

    def passed_output(example)
      wrap(pun_description(example), :success)
    end

    def pending_output(example, message)
      wrap(
        "#{pun_description(example)} (PENDING: #{message})",
        :pending
      )
    end

    def failure_output(example, _exception)
      message = pun_description(example)

      wrap(
        "#{message} (FAILED - #{next_failure_index})",
        :failure
      )
    end

    def pun_description(example)
      current_indentation +
        Pundit.new(example.description.strip).pun
    end

    def wrap(message, status)
      RSpec::Core::Formatters::ConsoleCodes.wrap(message, status)
    end
  end
end


text:
package org.browsermob.proxy.util;

import java.util.logging.*;

public class Log {
    static {
        Logger logger = Logger.getLogger("");
        Handler[] handlers = logger.getHandlers();
        for (Handler handler : handlers) {
            logger.removeHandler(handler);
        }

        ConsoleHandler handler = new ConsoleHandler();
        handler.setFormatter(new StandardFormatter());
        handler.setLevel(Level.FINE);
        logger.addHandler(handler);
    }

    static {
        // tell commons-logging to use the JDK logging (otherwise it would default to log4j
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
    }

    protected Logger logger;
    private String className;

    public Log() {
        Exception e = new Exception();
        className = e.getStackTrace()[1].getClassName();
        logger = Logger.getLogger(className);
    }

    public Log(Class clazz) {
        className = clazz.getName();
        logger = Logger.getLogger(className);
    }

    public void severe(String msg, Throwable e) {
        log(Level.SEVERE, msg, e);
    }

    public void severe(String msg, Object... args) {
        log(Level.SEVERE, msg, args);
    }

    public void severe(String msg, Throwable e, Object... args) {
        log(Level.SEVERE, msg, e, args);
    }

    public RuntimeException severeAndRethrow(String msg, Throwable e, Object... args) {
        log(Level.SEVERE, msg, e, args);

        //noinspection ThrowableInstanceNeverThrown
        return new RuntimeException(new java.util.Formatter().format(msg, args).toString());
    }

    public void warn(String msg, Throwable e) {
        log(Level.WARNING, msg, e);
    }

    public void warn(String msg, Object... args) {
        log(Level.WARNING, msg, args);
    }

    public void warn(String msg, Throwable e, Object... args) {
        log(Level.WARNING, msg, e, args);
    }

    public void info(String msg, Throwable e) {
        log(Level.INFO, msg, e);
    }

    public void info(String msg, Object... args) {
        log(Level.INFO, msg, args);
    }

    public void info(String msg, Throwable e, Object... args) {
        log(Level.INFO, msg, e, args);
    }

    public void fine(String msg, Throwable e) {
        log(Level.FINE, msg, e);
    }

    public void fine(String msg, Object... args) {
        log(Level.FINE, msg, args);
    }

    public void fine(String msg, Throwable e, Object... args) {
        log(Level.FINE, msg, e, args);
    }

    private void log(Level level, String msg, Throwable e) {
        logger.log(level, msg, e);
    }

    private void log(Level level, String msg, Object... args) {
        logger.log(level, msg, args);
    }

    private void log(Level level, String msg, Throwable e, Object... args) {
        LogRecord lr = new LogRecord(level, msg);
        lr.setThrown(e);
        lr.setParameters(args);
        lr.setSourceMethodName("");
        lr.setSourceClassName(className);
        lr.setLoggerName(className);
        logger.log(lr);
    }
}


text:
package org.springframework.android.twittersearch;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * @author Roy Clarkson
 */
public class TwitterSearchActivity extends Activity {

	// ***************************************
	// Activity methods
	// ***************************************
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.twitter_search_activity_layout);

		final Button buttonJson = (Button) findViewById(R.id.search_button);
		buttonJson.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				search();
			}
		});
	}

	// ***************************************
	// Private methods
	// ***************************************
	private void search() {
		final EditText search_value = (EditText) findViewById(R.id.search_value);
		Intent intent = new Intent(this.getApplicationContext(), TwitterSearchResultsActivity.class);
		String searchValue = search_value.getText().toString();
		intent.putExtra("org.springframework.android.showcase.TwitterSearchResultsActivity.search", searchValue);
		startActivity(intent);
	}

}