text:
import { __testMethods } from './SpellingDictionaryMethods';
import { createSpellingDictionary } from './createSpellingDictionary';
import { SpellingDictionaryFromTrie } from './SpellingDictionaryFromTrie';
import { Trie } from 'cspell-trie-lib';

// cSpell:ignore aple

describe('Verify building Dictionary', () => {
    test('build from word list', async () => {
        const words = ['apple', 'ape', 'able', 'apple', 'banana', 'orange', 'pear', 'aim', 'approach', 'bear'];

        const dict = await createSpellingDictionary(words, 'words', 'test', {});
        expect(dict.name).toBe('words');
        expect(dict.has('apple')).toBe(true);
        const suggestions = dict.suggest('aple').map(({ word }) => word);
        expect(suggestions).toEqual(expect.arrayContaining(['apple']));
        expect(suggestions).toEqual(expect.arrayContaining(['ape']));
        expect(suggestions).toEqual(expect.not.arrayContaining(['banana']));
    });

    test('compounds from word list', async () => {
        const words = [
            'apple',
            'apples',
            'ape',
            'able',
            'apple',
            'banana',
            'orange',
            'pear',
            'aim',
            'approach',
            'bear',
        ];

        const dict = await createSpellingDictionary(words, 'words', 'test', { useCompounds: true });
        expect(dict.has('apple')).toBe(true);
        expect(dict.has('Apple')).toBe(true);
        expect(dict.has('APPLE')).toBe(true);
        expect(dict.has('APPLEs')).toBe(true);
        expect(dict.has('APPles')).toBe(true); // cspell:disable-line
        // cspell:ignore applebanana applebananas applebananaorange
        expect(dict.has('applebanana')).toBe(true);
        expect(dict.has('applebananaorange')).toBe(true);
        expect(dict.has('applebananas')).toBe(false);
    });

    test('case-sensitive word list', async () => {
        const words = ['apple', 'Seattle', 'Amsterdam', 'surf', 'words', 'English', 'McGreyer'];

        const dict = await createSpellingDictionary(words, 'words', 'test', {
            caseSensitive: true,
        });
        const ignoreCase = { ignoreCase: true };
        const useCase = { ignoreCase: false };
        expect(dict.has('apple', useCase)).toBe(true);
        expect(dict.has('Apple', ignoreCase)).toBe(true);
        expect(dict.has('Apple', useCase)).toBe(true);
        expect(dict.has('APPLE', useCase)).toBe(true);
        expect(dict.has('Seattle', useCase)).toBe(true);
        expect(dict.has('seattle', useCase)).toBe(false);
        expect(dict.has('English', useCase)).toBe(true);
        expect(dict.has('english', useCase)).toBe(false);
        expect(dict.has('ENGLISH', useCase)).toBe(true);
        expect(dict.has('McGreyer', useCase)).toBe(true);
        expect(dict.has('mcgreyer', useCase)).toBe(false); // cspell:disable-line
        // We do not support mixed case as all caps matching at this point.
        expect(dict.has('MCGREYER', useCase)).toBe(false); // cspell:disable-line
        expect(dict.has('MCGREYER', ignoreCase)).toBe(true); // cspell:disable-line
    });

    test('Suggest Trie', () => {
        const words = [
            'apple',
            'ape',
            'able',
            'apple',
            'banana',
            'orange',
            'pear',
            'aim',
            'approach',
            'bear',
            'cattle',
            'rattle',
            'battle',
            'rattles',
            'battles',
            'tattles',
        ];
        const trie = Trie.create(words);
        const dict = new SpellingDictionaryFromTrie(trie, 'trie', {});
        // cspell:ignore cattles
        const results = dict.suggest('Cattles');
        const suggestions = results.map(({ word }) => word);
        expect(suggestions).toEqual(['cattle', 'battles', 'rattles', 'tattles', 'battle', 'rattle']);
        expect(suggestions).toEqual(expect.not.arrayContaining(['banana']));
    });

    test('build from list containing non-strings', async () => {
        // eslint-disable-next-line no-sparse-arrays
        const words = ['apple', 'ape', 'able', , 'apple', 'banana', 'orange', 5, 'pear', 'aim', 'approach', 'bear'];

        const dict = await createSpellingDictionary(words as string[], 'words', 'test', {});
        expect(dict.name).toBe('words');
        // expect(dict).toBeInstanceOf(SpellingDictionaryFromTrie);
        expect(dict.has('apple')).toBe(true);
        const suggestions = dict.suggest('aple').map(({ word }) => word);
        expect(suggestions).toEqual(expect.arrayContaining(['apple']));
        expect(suggestions).toEqual(expect.arrayContaining(['ape']));
        expect(suggestions).toEqual(expect.not.arrayContaining(['banana']));
    });

    type Test = [string, boolean, string[]];
    // cspell:ignore café
    const tests: Test[] = [
        ['house', false, ['house']],
        ['House', false, ['House', 'house']],
        ['café', false, ['cafe', 'café']],
        ['Café', false, ['Cafe', 'Café', 'cafe', 'café']],
        ['House', true, ['House', '~house']],
        ['HOUSE', true, ['HOUSE', '~house']],
        ['Café', true, ['Café', '~Cafe', '~cafe', '~café']],
        // Make sure all accent forms work.
        ['café'.normalize(), false, ['cafe', 'café']],
        ['café'.normalize('NFD'), false, ['cafe', 'café']],
        ['café'.normalize('NFKC'), false, ['cafe', 'café']],
        ['café'.normalize('NFKD'), false, ['cafe', 'café']],
    ];
    test.each(tests)(
        'wordDictionaryFormsCollector %s %o %o',
        (word: string, isCaseSensitive: boolean, expected: string[]) => {
            const collector = __testMethods.wordDictionaryFormsCollector(isCaseSensitive ? '~' : '');
            expect([...collector(word)].sort()).toEqual(expected.sort());
            expect([...collector(word)]).toEqual([]);
        }
    );
});

describe('Validate wordSearchForms', () => {
    test.each`
        word                        | isCaseSensitive | ignoreCase | expected
        ${'house'}                  | ${false}        | ${false}   | ${['house']}
        ${'House'}                  | ${false}        | ${false}   | ${['house']}
        ${'House'}                  | ${false}        | ${false}   | ${['house']}
        ${'House'}                  | ${true}         | ${false}   | ${['House', 'house']}
        ${'HOUSE'}                  | ${false}        | ${false}   | ${['house']}
        ${'HOUSE'}                  | ${true}         | ${false}   | ${['HOUSE', 'House', 'house']}
        ${'café'}                   | ${false}        | ${false}   | ${['café']}
        ${'café'}                   | ${true}         | ${false}   | ${['café']}
        ${'café'}                   | ${true}         | ${true}    | ${['café']}
        ${'Café'}                   | ${false}        | ${false}   | ${['café']}
        ${'Café'}                   | ${false}        | ${true}    | ${['café']}
        ${'Café'}                   | ${true}         | ${false}   | ${['Café', 'café']}
        ${'Café'}                   | ${true}         | ${true}    | ${['café']}
        ${'CAFÉ'}                   | ${false}        | ${false}   | ${['café']}
        ${'CAFÉ'}                   | ${false}        | ${true}    | ${['café']}
        ${'CAFÉ'}                   | ${true}         | ${false}   | ${['CAFÉ', 'Café', 'café']}
        ${'CAFÉ'}                   | ${true}         | ${true}    | ${['café']}
        ${'café'.normalize()}       | ${false}        | ${false}   | ${['café']}
        ${'café'.normalize('NFD')}  | ${false}        | ${false}   | ${['café']}
        ${'café'.normalize('NFKC')} | ${false}        | ${false}   | ${['café']}
        ${'café'.normalize('NFKD')} | ${false}        | ${false}   | ${['café']}
    `('$word $isCaseSensitive $ignoreCase $expected', ({ word, isCaseSensitive, ignoreCase, expected }) => {
        const words = __testMethods.wordSearchFormsArray(word, isCaseSensitive, ignoreCase);
        expect(words.sort()).toEqual(expected.sort());
    });
});

describe('Verify Case Sensitive Dictionaries', () => {
    test.each`
        word       | ignoreCase   | expected
        ${'Paris'} | ${undefined} | ${true}
        ${'PARIS'} | ${undefined} | ${true}
        ${'paris'} | ${undefined} | ${true}
        ${'Paris'} | ${true}      | ${true}
        ${'PARIS'} | ${true}      | ${true}
        ${'paris'} | ${true}      | ${true}
        ${'Paris'} | ${false}     | ${true}
        ${'PARIS'} | ${false}     | ${true}
        ${'paris'} | ${false}     | ${false}
        ${'Köln'}  | ${false}     | ${true}
        ${'köln'}  | ${false}     | ${false}
        ${'KÖLN'}  | ${false}     | ${true}
    `(`Has $word Case: $ignoreCase Exp: $expected`, ({ word, ignoreCase, expected }) => {
        const dict = sampleDict();
        expect(dict.has(word, { ignoreCase })).toBe(expected);
    });

    // cspell:ignore kuln
    test.each`
        word      | ignoreCase | expected
        ${'köln'} | ${false}   | ${['Köln']}
        ${'köln'} | ${true}    | ${['köln', 'koln', 'Köln']}
        ${'koln'} | ${true}    | ${['koln', 'köln', 'Köln']}
        ${'kuln'} | ${false}   | ${['Köln']}
        ${'kuln'} | ${true}    | ${['koln', 'köln', 'Köln']}
    `('Suggestions for $word $ignoreCase $expected', ({ word, ignoreCase, expected }) => {
        // cspell:ignore koln
        const dict = sampleDict();
        const sugs = dict.suggest(word, { ignoreCase });
        const sugWords = sugs.map((s) => s.word);
        expect(sugWords).toEqual(expected);
    });
});

function sampleDict() {
    const words = sampleWords();
    return createSpellingDictionary(words, 'words', 'test', { caseSensitive: true });
}

// cspell:words métro Rhône Köln Düsseldorf
function sampleWords() {
    return `
        England Canada Netherlands France German China Belgium
        Paris Chicago Amsterdam Antwerp Brussels Rhône Cologne Köln Düsseldorf
        métro cafe café metro
        apple apples ape apes around astound profound compound
        table tables tabled
    `.split(/\s+/g);
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Events extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('dbmodel');
        $this->load->model('dbdashboard');
        $this->load->model('dbsetting');
        $this->load->model('dbevent');
        $this->load->helper('url');
        $this->load->helper(array('form', 'url'));
        $this->load->library('pagination');
        $this->load->helper('seourl_helper');
    }

    public function index() {
        redirect('bnw');
    }
     function getRandomStringForCoupen($length) {
        $validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789abcdefghijklmnopqrstuvwxyz";
        $validCharNumber = strlen($validCharacters);
        $result = "";

        for ($i = 0; $i < $length; $i++) {
            $index = mt_rand(0, $validCharNumber - 1);
            $result .= $validCharacters[$index];
        }
        return $result;
    }
    //================================ START EVENTS ======================================================//
    function allevents() {
        $url = current_url();
        if ($this->session->userdata('admin_logged_in')) {
            $data['meta'] = $this->dbsetting->get_meta_data();
            $config = array();
            $config["base_url"] = base_url() . "index.php/events/allevents";
            $config["total_rows"] = $this->dbevent->get_event();
            $config["per_page"] = 6;
            $this->pagination->initialize($config);
            $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
            $data["event"] = $this->dbevent->get_event_data($config["per_page"], $page);
            $data["links"] = $this->pagination->create_links();
            $data["query"] = $this->dbdashboard->get_menu();
            $this->session->set_userdata("urlPagination", $config["base_url"]."/".$page);
            $this->load->view('bnw/templates/header', $data);
            $this->load->view('bnw/templates/menu');
            $this->load->view('bnw/event/eventList', $data);
        } else {
            redirect('login/index/?url=' . $url, 'refresh');
        }
    }

     function editevent($id = 0) {
        $url = current_url();
        if ($this->session->userdata('admin_logged_in')) {
            $data['meta'] = $this->dbsetting->get_meta_data();
            $data['event'] = $this->dbevent->get_event_id($id);
            $this->load->view("bnw/templates/header", $data);
            $this->load->view("bnw/templates/menu");
            $this->load->view('bnw/event/editEvent', $data);
        } else {
            redirect('login/index/?url=' . $url, 'refresh');
        }
    }

    function delevent() {
        $id = $_POST['id'];
        $url = current_url();
        if ($this->session->userdata('admin_logged_in')) {
            $data['event'] = $this->dbevent->get_event_id($id);
            foreach ($data['event'] as $a) {
                $img = $a->image;
            }
            if (!empty($img)) {
               $filename1 = './content/uploads/images/'.$img;
            $filename2 = './content/uploads/images/thumb_'.$img;
if (file_exists($filename1)) {
    unlink($filename1);
} else {}
if (file_exists($filename2)) {
    unlink($filename2);
} else {}
            }
            $this->dbevent->delete($id);
        } else {
            redirect('login/index/?url=' . $url, 'refresh');
        }
    }
    function update_event() {
         ini_set('memory_limit', '-1');
        $url = current_url();
        if ($this->session->userdata('admin_logged_in')) {
            $config['upload_path'] = './content/uploads/images/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';

            $this->load->library('upload',$config);
            $this->load->library(array('form_validation', 'session'));
            $this->form_validation->set_rules('Name', 'Name', 'required|callback_xss_clean|max_length[200]');

            if (($this->form_validation->run() == TRUE)) {
                if ($_FILES && $_FILES['file']['name'] !== "") {
                    if (!$this->upload->do_upload('file')) {

                        $data['error'] = $this->upload->display_errors('file');
                        $id = $this->input->post('id');
                        $data['query'] = $this->dbevent->get_event_id($id);
                        $this->load->view('bnw/event/editEvent', $data);
                    } else {
                        include_once 'imagemanipulator.php';
                        $manipulator = new ImageManipulator($_FILES['file']['tmp_name']);
                         $realwidth = $manipulator->getWidth();

                        $newWidth = (int) $_POST['w'];
                        $newHeight = (int) $_POST['h'];
                        $ratio = $realwidth/1000;
                        $ax1 = (int) $_POST['x'];
                        $ay1 = (int) $_POST['y'];
                        $x1 = $ax1*$ratio;
                        $y1 = $ay1*$ratio;
                        $height = $newHeight*$ratio;
                        $width = $newWidth*$ratio;

                        $x2 = $x1 + $width;
                        $y2 = $y1 + $height;

                        // center cropping to 200x130
                        $newImage = $manipulator->crop($x1, $y1, $x2, $y2);
                        $name = $_FILES['file']['name'];
                        $key = $this->getRandomStringForCoupen(5);
                        $image = $key.$name;
                        $manipulator->save('./content/uploads/images/' .$image);
                        $filename1 = './content/uploads/images/'.$name;
if (file_exists($filename1)) {
    unlink($filename1);
} else {}

                       // $imgname = $img_name;
                        $image_thumb = dirname('thumb_' . $image . '/demo');
                        $config['image_library'] = 'gd2';
                        $config['source_image'] = './content/uploads/images/' . $image;
                        $config['new_image'] = $image_thumb;
                        $config['maintain_ratio'] = TRUE;
                        $config['width'] = 240;
                        $config['height'] = 180;
                        $this->load->library('image_lib', $config);
                        $this->image_lib->resize();
                        $id = $this->input->post('id');
                        $title = $this->input->post('Name');
                        $content = $this->input->post('description');
                        $location = $this->input->post('location');
                        $type = $this->input->post('event_type');
                        $start_date = $this->input->post('start_date');
                        $end_date = $this->input->post('end_date');
                        $start_hour = $this->input->post('start_hour');
                        $end_hour = $this->input->post('end_hour');
                        $start_min = $this->input->post('start_min');
                         $end_min = $this->input->post('end_min');
                        $sec = 0;
                        $start_dateTime = $start_date . ' ' . $start_hour . ':' . $start_min . ':' . $sec;
                        $end_dateTime = $end_date . ' ' . $end_hour . ':' . $end_min . ':' . $sec;
                        date_default_timezone_set('Asia/Kathmandu');
                        $updatedOn = date('Y-m-d');
                        $config = array(
                            'field' => 'seo_title',
                            'table' => 'events',
                             'id'=> 'id'
                        );
                        $this->load->library('slug', $config);
                        $seoTitle = $this->slug->create_uri($title, $id);
                        $this->dbevent->update_event($id, $title, $content, $location, $image, $start_dateTime, $end_dateTime, $type, $updatedOn, $seoTitle);
                        $this->session->set_flashdata('message', 'Data Modified Sucessfully');
                        $redirectPagination = $this->session->userdata("urlPagination");
                        redirect($redirectPagination);
                    }
                } else {
                    // die('not');
                    $id = $this->input->post('id');
                    $title = $this->input->post('Name');
                    $content = $this->input->post('description');

                    $image = $this->input->post('hidden_image');
                    $location = $this->input->post('location');
                    $type = $this->input->post('event_type');
                    $start_date = $this->input->post('start_date');
                        $end_date = $this->input->post('end_date');
                        $start_hour = $this->input->post('start_hour');
                        $end_hour = $this->input->post('end_hour');
                        $start_min = $this->input->post('start_min');
                         $end_min = $this->input->post('end_min');
                        $sec = 0;
                        $start_dateTime = $start_date . ' ' . $start_hour . ':' . $start_min . ':' . $sec;
                        $end_dateTime = $end_date . ' ' . $end_hour . ':' . $end_min . ':' . $sec;
                    date_default_timezone_set('Asia/Kathmandu');
                    $updatedOn = date('Y-m-d');
                    $config = array(
                            'field' => 'seo_title',
                            'table' => 'events',
                         'id'=> 'id'
                        );
                        $this->load->library('slug', $config);
                        $seoTitle = $this->slug->create_uri($title, $id);
                    $this->dbevent->update_event($id, $title, $content, $location, $image, $start_dateTime, $end_dateTime, $type, $updatedOn, $seoTitle);
                    $this->session->set_flashdata('message', 'Data Modified Sucessfully');
                    $redirectPagination = $this->session->userdata("urlPagination");
                    redirect($redirectPagination);
                }
            } else {
                $id = $this->input->post('id');
                $data['query'] = $this->dbevent->get_event_id($id);
                $this->load->view('bnw/event/editEvent', $data);
            }
        } else {
            redirect('login/index/?url=' . $url, 'refresh');
        }
    }

    function addevent() {
         ini_set('memory_limit', '-1');
        $url = current_url();
        if ($this->session->userdata('admin_logged_in')) {
           $config['upload_path'] = './content/uploads/images/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';

            $data["links"] = $this->pagination->create_links();
            $data['meta'] = $this->dbsetting->get_meta_data();
            $data["links"] = $this->pagination->create_links();
            $data["query"] = $this->dbdashboard->get_menu();
            $this->load->view('bnw/templates/header', $data);
            $this->load->view('bnw/templates/menu');
            $this->load->helper('form');
             $this->load->library('upload');

            $this->load->library(array('form_validation', 'session'));
            $this->form_validation->set_rules('event_name', 'Name', 'required|callback_xss_clean|max_length[200]');

            if ($this->form_validation->run() == FALSE) {

                $this->load->view('bnw/event/addEvent');
            } else {
                 if (!empty($_FILES['file']['name'])) {

                    // Initialize config for File 1
                    $this->upload->initialize($config);
                    // Upload file 1
                    if ($this->upload->do_upload('file')) {
                         include_once 'imagemanipulator.php';
                        $manipulator = new ImageManipulator($_FILES['file']['tmp_name']);
                         $realwidth = $manipulator->getWidth();
                        $newWidth = (int) $_POST['w'];
                        $newHeight = (int) $_POST['h'];
                        $ratio = $realwidth/1000;
                        $ax1 = (int) $_POST['x'];
                        $ay1 = (int) $_POST['y'];
                        $x1 = $ax1*$ratio;
                        $y1 = $ay1*$ratio;
                        $height = $newHeight*$ratio;
                        $width = $newWidth*$ratio;
                        $x2 = $x1 + $width;
                        $y2 = $y1 + $height;

                        // center cropping to 200x130
                        $newImage = $manipulator->crop($x1, $y1, $x2, $y2);
                        $name = $_FILES['file']['name'];
                        $key = $this->getRandomStringForCoupen(5);
                        $image = $key.$name;
                        $manipulator->save('./content/uploads/images/' .$image);
                        $filename1 = './content/uploads/images/'.$name;
if (file_exists($filename1)) {
    unlink($filename1);
} else {}

                       // $imgname = $img_name;
                        $image_thumb = dirname('thumb_' . $image . '/demo');
                        $config['image_library'] = 'gd2';
                        $config['source_image'] = './content/uploads/images/' . $image;
                        $config['new_image'] = $image_thumb;
                        $config['maintain_ratio'] = TRUE;
                        $config['width'] = 240;
                        $config['height'] = 180;
                        $this->load->library('image_lib', $config);
                        $this->image_lib->resize();
                         $name = $this->input->post('event_name');
                        $detail = $this->input->post('detail');
                        $location = $this->input->post('location');
                        $type = $this->input->post('event_type');
                        $start_date = $this->input->post('start_date');
                        $end_date = $this->input->post('end_date');
                        $start_hour = $this->input->post('start_hour');
                        $end_hour = $this->input->post('end_hour');
                        $start_min = $this->input->post('start_min');
                         $end_min = $this->input->post('end_min');
                        $sec = 0;
                        $start_dateTime = $start_date . ' ' . $start_hour . ':' . $start_min . ':' . $sec;
                        $end_dateTime = $end_date . ' ' . $end_hour . ':' . $end_min . ':' . $sec;
                        $dt = new DateTime();
                        $insert_date = $dt->format('Y-m-d H:i:s');
                        $config = array(
                            'field' => 'seo_title',
                            'table' => 'events',
                        );
                        $this->load->library('slug', $config);
                        $seoTitle = $this->slug->create_uri($name);
                      if($type == "news") {
                        $this->dbevent->add_news($name, $detail, $location, $insert_date, $image, $type, $seoTitle);
                        $this->session->set_flashdata('message', 'One news added sucessfully');
                      }
                      if($type == "event") {
                        $this->dbevent->add_event($name, $detail, $location, $start_dateTime,$end_dateTime, $insert_date, $image, $type, $seoTitle);
                        $this->session->set_flashdata('message', 'One event added sucessfully');
                      }
                        redirect('events/allevents');
                    } else {
                        $error = array('error' => $this->upload->display_errors('file'));
                        $this->load->view('bnw/event/addEvent', $error);
                    }
               }
                else {
                    //if valid
                    $image = NULL;
                    $name = $this->input->post('event_name');
                    $detail = $this->input->post('detail');
                    $location = $this->input->post('location');
                    $type = $this->input->post('event_type');
                     $start_date = $this->input->post('start_date');
                        $end_date = $this->input->post('end_date');
                        $start_hour = $this->input->post('start_hour');
                        $end_hour = $this->input->post('end_hour');
                        $start_min = $this->input->post('start_min');
                         $end_min = $this->input->post('end_min');
                        $sec = 0;
                        $start_dateTime = $start_date . ' ' . $start_hour . ':' . $start_min . ':' . $sec;
                        $end_dateTime = $end_date . ' ' . $end_hour . ':' . $end_min . ':' . $sec;
                    $dt = new DateTime();
                    $insert_date = $dt->format('Y-m-d H:i:s');
                    $config = array(
                            'field' => 'seo_title',
                            'table' => 'events',
                        );
                        $this->load->library('slug', $config);
                        $seoTitle = $this->slug->create_uri($name);
                      if($type == "news") {
                        $this->dbevent->add_news($name, $detail, $location, $insert_date, $image, $type, $seoTitle);
                        $this->session->set_flashdata('message', 'One news added sucessfully');
                      }
                      if($type == "event") {
                        $this->dbevent->add_event($name, $detail, $location, $start_dateTime, $end_dateTime, $insert_date, $image, $type, $seoTitle);
                        $this->session->set_flashdata('message', 'One event added sucessfully');
                      }
                    redirect('events/allevents');
                }
            }
        } else {
            redirect('login/index/?url=' . $url, 'refresh');
        }
    }

    function Imgdelete($id = 0) {
        $url = current_url();
        if ($this->session->userdata('admin_logged_in')) {

            $id = $_GET['id'];
            $data['event'] = $this->dbevent->get_event_id($id);
            foreach ($data['event'] as $a) {
                $img = $a->image;
            }
            // die($img);
            if ($img == !NULL) {
               // die($img);
                $filename1 = './content/uploads/images/'.$img;
            $filename2 = './content/uploads/images/thumb_'.$img;
if (file_exists($filename1)) {
    unlink($filename1);
} else {}
if (file_exists($filename2)) {
    unlink($filename2);
} else {}
            }
            $this->dbevent->Imgdelete($id);

            $this->editevent($id);
        } else {
            redirect('login/index/?url=' . $url, 'refresh');
        }
    }
    public function xss_clean($str)
	{
		if ($this->security->xss_clean($str, TRUE) === FALSE)
		{
			$this->form_validation->set_message('xss_clean', 'The %s is invalid charactor');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
    //=============================== CLOSE EVENTS ================================================//
}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.security.web.reactive.result.method.annotation;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.expression.BeanResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.web.method.ResolvableMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.*;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

/**
 * @author Rob Winch
 * @since 5.0
 */
@RunWith(MockitoJUnitRunner.class)
public class AuthenticationPrincipalArgumentResolverTests {
	@Mock
	ServerWebExchange exchange;
	@Mock
	BindingContext bindingContext;
	@Mock
	Authentication authentication;
	@Mock
	BeanResolver beanResolver;

	ResolvableMethod authenticationPrincipal = ResolvableMethod.on(getClass()).named("authenticationPrincipal").build();
	ResolvableMethod spel = ResolvableMethod.on(getClass()).named("spel").build();
	ResolvableMethod meta = ResolvableMethod.on(getClass()).named("meta").build();
	ResolvableMethod bean = ResolvableMethod.on(getClass()).named("bean").build();

	AuthenticationPrincipalArgumentResolver resolver;

	@Before
	public void setup() {
		resolver =  new AuthenticationPrincipalArgumentResolver(new ReactiveAdapterRegistry());
		this.resolver.setBeanResolver(this.beanResolver);
	}

	@Test
	public void supportsParameterAuthenticationPrincipal() throws Exception {
		assertThat(resolver.supportsParameter(this.authenticationPrincipal.arg(String.class))).isTrue();
	}

	@Test
	public void supportsParameterCurrentUser() throws Exception {
		assertThat(resolver.supportsParameter(this.meta.arg(String.class))).isTrue();
	}

	@Test
	public void resolveArgumentWhenIsAuthenticationThenObtainsPrincipal() throws Exception {
		MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
		when(authentication.getPrincipal()).thenReturn("user");
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument.block()).isEqualTo(authentication.getPrincipal());
	}

	@Test
	public void resolveArgumentWhenIsNotAuthenticationThenMonoEmpty() throws Exception {
		MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
		when(exchange.getPrincipal()).thenReturn(Mono.just(() -> ""));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument).isNotNull();
		assertThat(argument.block()).isNull();
	}

	@Test
	public void resolveArgumentWhenIsEmptyThenMonoEmpty() throws Exception {
		MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
		when(exchange.getPrincipal()).thenReturn(Mono.empty());

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument).isNotNull();
		assertThat(argument.block()).isNull();
	}

	@Test
	public void resolveArgumentWhenMonoIsAuthenticationThenObtainsPrincipal() throws Exception {
		MethodParameter parameter = this.authenticationPrincipal.arg(Mono.class, String.class);
		when(authentication.getPrincipal()).thenReturn("user");
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument.cast(Mono.class).block().block()).isEqualTo(authentication.getPrincipal());
	}

	@Test
	public void resolveArgumentWhenMonoIsAuthenticationAndNoGenericThenObtainsPrincipal() throws Exception {
		MethodParameter parameter = ResolvableMethod.on(getClass()).named("authenticationPrincipalNoGeneric").build().arg(Mono.class);
		when(authentication.getPrincipal()).thenReturn("user");
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument.cast(Mono.class).block().block()).isEqualTo(authentication.getPrincipal());
	}

	@Test
	public void resolveArgumentWhenSpelThenObtainsPrincipal() throws Exception {
		MyUser user = new MyUser(3L);
		MethodParameter parameter = this.spel.arg(Long.class);
		when(authentication.getPrincipal()).thenReturn(user);
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument.block()).isEqualTo(user.getId());
	}

	@Test
	public void resolveArgumentWhenBeanThenObtainsPrincipal() throws Exception {
		MyUser user = new MyUser(3L);
		MethodParameter parameter = this.bean.arg(Long.class);
		when(authentication.getPrincipal()).thenReturn(user);
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
		when(this.beanResolver.resolve(any(), eq("beanName"))).thenReturn(new Bean());

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument.block()).isEqualTo(user.getId());
	}

	@Test
	public void resolveArgumentWhenMetaThenObtainsPrincipal() throws Exception {
		MethodParameter parameter = this.meta.arg(String.class);
		when(authentication.getPrincipal()).thenReturn("user");
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument.block()).isEqualTo("user");
	}

	@Test
	public void resolveArgumentWhenErrorOnInvalidTypeImplicit() throws Exception {
		MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenImplicit").build().arg(Integer.class);
		when(authentication.getPrincipal()).thenReturn("user");
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument.block()).isNull();
	}

	@Test
	public void resolveArgumentWhenErrorOnInvalidTypeExplicitFalse() throws Exception {
		MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitFalse").build().arg(Integer.class);
		when(authentication.getPrincipal()).thenReturn("user");
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThat(argument.block()).isNull();
	}

	@Test
	public void resolveArgumentWhenErrorOnInvalidTypeExplicitTrue() throws Exception {
		MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitTrue").build().arg(Integer.class);
		when(authentication.getPrincipal()).thenReturn("user");
		when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));

		Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);

		assertThatThrownBy(() -> argument.block()).isInstanceOf(ClassCastException.class);
	}

	void authenticationPrincipal(@AuthenticationPrincipal String principal, @AuthenticationPrincipal Mono<String> monoPrincipal) {}

	void authenticationPrincipalNoGeneric(@AuthenticationPrincipal Mono monoPrincipal) {}

	void spel(@AuthenticationPrincipal(expression = "id") Long id) {}

	void bean(@AuthenticationPrincipal(expression = "@beanName.methodName(#this)") Long id) {}

	void meta(@CurrentUser String principal) {}

	void errorOnInvalidTypeWhenImplicit(@AuthenticationPrincipal Integer implicit) {}

	void errorOnInvalidTypeWhenExplicitFalse(@AuthenticationPrincipal(errorOnInvalidType = false) Integer implicit) {}

	void errorOnInvalidTypeWhenExplicitTrue(@AuthenticationPrincipal(errorOnInvalidType = true) Integer implicit) {}

	static class Bean {
		public Long methodName(MyUser user) {
			return user.getId();
		}
	}

	static class MyUser {
		private final Long id;

		MyUser(Long id) {
			this.id = id;
		}

		public Long getId() {
			return id;
		}
	}

	@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
	@Retention(RetentionPolicy.RUNTIME)
	@Documented
	@AuthenticationPrincipal
	public @interface CurrentUser {}
}


text:
import AdminModule from './admin'
import AdminController from './admin.controller';
import AdminComponent from './admin.component';
import AdminTemplate from './admin.html';

describe('Admin', () => {
  let $rootScope, makeController;

  beforeEach(window.module(AdminModule));
  beforeEach(inject((_$rootScope_) => {
    $rootScope = _$rootScope_;
    makeController = () => {
      return new AdminController();
    };
  }));

  describe('Module', () => {
    // top-level specs: i.e., routes, injection, naming
  });

  describe('Controller', () => {
    // controller specs
    it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller
      let controller = makeController();
      expect(controller).to.have.property('name');
    });
  });

  describe('Template', () => {
    // template specs
    // tip: use regex to ensure correct bindings are used e.g., {{  }}
    it('has name in template [REMOVE]', () => {
      expect(AdminTemplate).to.match(/{{\s?\$ctrl\.name\s?}}/g);
    });
  });

  describe('Component', () => {
      // component/directive specs
      let component = AdminComponent;

      it('includes the intended template',() => {
        expect(component.template).to.equal(AdminTemplate);
      });

      it('invokes the right controller', () => {
        expect(component.controller).to.equal(AdminController);
      });
  });
});


text:
Date Range Picker widget for Yii2 framework
=================

## Description

A JavaScript widget for choosing date ranges.
Designed to work with the Bootstrap CSS framework.
For more information please visit [Date Range Picker](http://www.daterangepicker.com/)

## Installation

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

To install, either run

```
$ php composer.phar require conquer/daterangepicker "*"
```
or add

```
"conquer/daterangepicker": "*"
```

to the ```require``` section of your `composer.json` file.

## Usage

```php
use conquer\daterangepicker\DaterangepickerWidget;

$form->field($model, 'range')->widget(
    DaterangepickerWidget::className(),
    [
        'language'=>'ru',
    ]
);
```

## License

**conquer/daterangepicker** is released under the MIT License. See the bundled `LICENSE.md` for details.


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SFA.DAS.PAS.Account.Api.Startup))]

namespace SFA.DAS.PAS.Account.Api
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
use libc::c_int;
use pyport::Py_ssize_t;
use object::*;

extern "C" {
    static mut _Py_EllipsisObject: PyObject;
}

#[inline(always)]
pub unsafe fn Py_Ellipsis() -> *mut PyObject {
    &mut _Py_EllipsisObject
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct PySliceObject {
    #[cfg(py_sys_config="Py_TRACE_REFS")]
    pub _ob_next: *mut PyObject,
    #[cfg(py_sys_config="Py_TRACE_REFS")]
    pub _ob_prev: *mut PyObject,
    pub ob_refcnt: Py_ssize_t,
    pub ob_type: *mut PyTypeObject,
    pub start: *mut PyObject,
    pub stop: *mut PyObject,
    pub step: *mut PyObject
}

extern "C" {
    pub static mut PySlice_Type: PyTypeObject;
    pub static mut PyEllipsis_Type: PyTypeObject;
}

#[inline(always)]
pub unsafe fn PySlice_Check(op: *mut PyObject) -> c_int {
     (Py_TYPE(op) == &mut PySlice_Type) as c_int
}

extern "C" {
    pub fn PySlice_New(start: *mut PyObject, stop: *mut PyObject,
                       step: *mut PyObject) -> *mut PyObject;
    pub fn PySlice_GetIndices(r: *mut PyObject, length: Py_ssize_t,
                              start: *mut Py_ssize_t, stop: *mut Py_ssize_t,
                              step: *mut Py_ssize_t) -> c_int;
    pub fn PySlice_GetIndicesEx(r: *mut PyObject, length: Py_ssize_t,
                                start: *mut Py_ssize_t, stop: *mut Py_ssize_t,
                                step: *mut Py_ssize_t,
                                slicelength: *mut Py_ssize_t)
     -> c_int;
}


text:
package org.hoteia.qalingo.core.pojo.deliverymethod;

public class DeliveryMethodCountyPojo {

	private Long id;
	private String codeCounty;

	public DeliveryMethodCountyPojo() {
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getCodeCounty() {
		return codeCounty;
	}

	public void setCodeCounty(String codeCounty) {
		this.codeCounty = codeCounty;
	}

}


text:
from __future__ import with_statement

import os
import sys
from datetime import datetime
from functools import partial
import time

# workaround on osx, disable kqueue
if sys.platform == "darwin":
    os.environ['EVENT_NOKQUEUE'] = "1"

try:
    import gevent
except ImportError:
    raise RuntimeError("You need gevent installed to use this worker.")
from gevent.pool import Pool
from gevent.server import StreamServer
from gevent import pywsgi

import gunicorn
from gunicorn.workers.async import AsyncWorker

VERSION = "gevent/%s gunicorn/%s" % (gevent.__version__, gunicorn.__version__)

BASE_WSGI_ENV = {
    'GATEWAY_INTERFACE': 'CGI/1.1',
    'SERVER_SOFTWARE': VERSION,
    'SCRIPT_NAME': '',
    'wsgi.version': (1, 0),
    'wsgi.multithread': False,
    'wsgi.multiprocess': False,
    'wsgi.run_once': False
}

class GeventWorker(AsyncWorker):

    server_class = None
    wsgi_handler = None

    @classmethod
    def setup(cls):
        from gevent import monkey
        monkey.noisy = False
        monkey.patch_all()

    def timeout_ctx(self):
        return gevent.Timeout(self.cfg.keepalive, False)

    def run(self):
        servers = []
        ssl_args = {}

        if self.cfg.is_ssl:
            ssl_args = dict(server_side=True,
                    do_handshake_on_connect=False, **self.cfg.ssl_options)

        for s in self.sockets:
            s.setblocking(1)
            pool = Pool(self.worker_connections)
            if self.server_class is not None:
                server = self.server_class(
                    s, application=self.wsgi, spawn=pool, log=self.log,
                    handler_class=self.wsgi_handler, **ssl_args)
            else:
                hfun = partial(self.handle, s)
                server = StreamServer(s, handle=hfun, spawn=pool, **ssl_args)

            server.start()
            servers.append(server)

        pid = os.getpid()
        try:
            while self.alive:
                self.notify()

                if pid == os.getpid() and self.ppid != os.getppid():
                    self.log.info("Parent changed, shutting down: %s", self)
                    break

                gevent.sleep(1.0)

        except KeyboardInterrupt:
            pass

        try:
            # Stop accepting requests
            [server.stop_accepting() for server in servers]

            # Handle current requests until graceful_timeout
            ts = time.time()
            while time.time() - ts <= self.cfg.graceful_timeout:
                accepting = 0
                for server in servers:
                    if server.pool.free_count() != server.pool.size:
                        accepting += 1

                # if no server is accepting a connection, we can exit
                if not accepting:
                    return

                self.notify()
                gevent.sleep(1.0)

            # Force kill all active the handlers
            self.log.warning("Worker graceful timeout (pid:%s)" % self.pid)
            [server.stop(timeout=1) for server in servers]
        except:
            pass

    def handle_request(self, *args):
        try:
            super(GeventWorker, self).handle_request(*args)
        except gevent.GreenletExit:
            pass

    if gevent.version_info[0] == 0:

        def init_process(self):
            #gevent 0.13 and older doesn't reinitialize dns for us after forking
            #here's the workaround
            import gevent.core
            gevent.core.dns_shutdown(fail_requests=1)
            gevent.core.dns_init()
            super(GeventWorker, self).init_process()

class GeventResponse(object):

    status = None
    headers = None
    response_length = None

    def __init__(self, status, headers, clength):
        self.status = status
        self.headers = headers
        self.response_length = clength

class PyWSGIHandler(pywsgi.WSGIHandler):

    def log_request(self):
        start = datetime.fromtimestamp(self.time_start)
        finish = datetime.fromtimestamp(self.time_finish)
        response_time = finish - start
        resp = GeventResponse(self.status, self.response_headers,
                self.response_length)
        req_headers = [h.split(":", 1) for h in self.headers.headers]
        self.server.log.access(resp, req_headers, self.environ, response_time)

    def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env

class PyWSGIServer(pywsgi.WSGIServer):
    base_env = BASE_WSGI_ENV

class GeventPyWSGIWorker(GeventWorker):
    "The Gevent StreamServer based workers."
    server_class = PyWSGIServer
    wsgi_handler = PyWSGIHandler


text:
// Generated by CoffeeScript 1.12.6

/*
 * Command line interface spec suite execution scope parser
 */

(function() {
  'use strict';
  var object;

  object = require('../common/object');

  module.exports = {
    codeModule: function() {
      var codeModule, name, path, ref;
      codeModule = this.item.replace(/\.js$/, '');
      ref = this.modulePaths;
      for (name in ref) {
        path = ref[name];
        if (codeModule === path) {
          return name;
        }
      }
      return false;
    },
    detect: function(item, modulePaths, methodPaths, specPath) {
      var codeModule, folder, method;
      this.item = item;
      this.modulePaths = modulePaths;
      this.methodPaths = methodPaths;
      this.specPath = specPath;
      method = this.method();
      if (method) {
        return method;
      }
      codeModule = this.codeModule();
      if (codeModule) {
        return codeModule;
      }
      folder = this.folder();
      if (folder) {
        return folder;
      }
      return false;
    },
    folder: function() {
      var folder, name, outside, path, ref;
      if (this.specPath.test(this.item)) {
        folder = this.item.replace(this.specPath, '');
        folder = folder.replace(/\/$/, '');
        return folder.split('/').join('.');
      }
      outside = new RegExp("^" + this.item);
      ref = this.modulePaths;
      for (name in ref) {
        path = ref[name];
        if (outside.test(path)) {
          folder = path.replace(outside, '');
          folder = folder.split('/').join('.');
          folder = name.replace("." + folder, '');
          return folder;
        }
      }
      return false;
    },
    key: function(mode, detect) {
      var _, key;
      if (Array.isArray(detect)) {
        key = {
          key: "methods." + detect[0] + "." + mode,
          value: [detect[1]]
        };
        return key;
      }
      return _ = {
        key: mode,
        value: [detect]
      };
    },
    method: function() {
      var codeModule, method;
      if (!this.specPath.test(this.item)) {
        return false;
      }
      method = this.item.replace(this.specPath, '');
      method = method.replace(/\.js$/, '');
      method = method.split('/').join('.');
      method = method.replace(/\.$/, '');
      codeModule = object.match(method, this.methodPaths, true, true);
      if (!codeModule) {
        return false;
      }
      if (!method.replace("" + codeModule, '').length) {
        return codeModule;
      }
      method = method.replace(codeModule + ".", '');
      return [codeModule, method];
    }
  };

}).call(this);


text:
@interface BBALibraryItemTests : XCTestCase{
    BBALibraryItem *item;
}

@end

@implementation BBALibraryItemTests

#pragma mark - Setup/Teardown

- (void) setUp{
    [super setUp];
    item = [BBALibraryItem new];
    BBALinkItem *link1 = [BBALinkItem new];
    link1.rel = @"urn:blinkboxbooks:schema:fullmedia";
    link1.href = @"full link";
    BBALinkItem *link2 = [BBALinkItem new];
    link2.rel = @"urn:blinkboxbooks:schema:mediakey";
    link2.href = @"media key link";
    BBALinkItem *link3 = [BBALinkItem new];
    link3.rel = @"urn:blinkboxbooks:schema:samplemedia";
    link3.href = @"sample link";
    item.links = @[link1, link2, link3];
}

- (void) tearDown{
    item = nil;
    [super tearDown];
}

#pragma mark - Tests

- (void) testInit{
    XCTAssertNotNil(item);
}

- (void) testSampleMediaURLReturnsCorrectValueIfExistInTheLinksArray{
    XCTAssertEqualObjects(item.sampleMediaURL, @"sample link");
}

- (void) testSampleMediaURLReturnsNilValueIfDoesntExistInTheLinksArray{
    item.links = @[];
    XCTAssertNil(item.sampleMediaURL);
}

- (void) testFullMediaURLReturnsCorrectValueIfExistInTheLinksArray{
    XCTAssertEqualObjects(item.fullMediaURL, @"full link");
}

- (void) testFullMediaURLReturnsNilValueIfDoesntExistInTheLinksArray{
    item.links = @[];
    XCTAssertNil(item.fullMediaURL);
}

- (void) testMediaKeyURLReturnsCorrectValueIfExistInTheLinksArray{
    XCTAssertEqualObjects(item.mediaKeyURL, @"media key link");
}

- (void) testMediaKeyURLReturnsNilValueIfDoesntExistInTheLinksArray{
    item.links = @[];
    XCTAssertNil(item.mediaKeyURL);
}

@end


text:
package com.wgh.dao;

import java.sql.*;
import java.util.*;

import com.wgh.actionForm.LessonForm;
import com.wgh.actionForm.QuestionsForm;
import com.wgh.core.ConnDB;

public class StartExamDAO {
	private ConnDB conn=new ConnDB();
	private LessonDAO lessonDAO=new LessonDAO();
    //Ëæ»ú³éÈ¡ÊÔÌâ
    public int randomGetQuestion(int lessonID){
    	int questionsID=0;
    	String sql="SELECT taoTiID FROM (SELECT distinct lessonID,taoTiID from " +
    			"(SELECT lessonId,taoTiID FROM tb_questions GROUP BY taoTiID,lessonID,type)" +
    			" as lessonTaoTi GROUP BY lessonId,taoTiID having count(taoTiID) >1)as temp" +
    			" WHERE lessonID="+lessonID+"";
    	ResultSet rs = conn.executeQuery(sql);
    	int i=0;
        try {
        	rs.last();
        	int recordNum=rs.getRow();
        	rs.first();
        	int[] id=new int[recordNum];
            do {
                id[i]=rs.getInt(1);
                i++;
            }while (rs.next());
            int rand=Math.abs(new Random().nextInt(id.length));
            questionsID=id[rand];
        } catch (Exception ex) {
        	ex.printStackTrace();
        }
    	return questionsID;
    }
    //¸Õ¿ªÊ¼¿¼ÊÔʱ±£´æ¿¼ÊÔ½á¹û
    public int startSaveResult(String studentID,int lessonID){
    	String lesson=((LessonForm)lessonDAO.query(lessonID).get(0)).getName();
    	String sql="INSERT INTO tb_stuResult (stuId,whichLesson,resSingle,resMore) values('"+studentID+"','"+lesson+"',0,0)";
    	System.out.println("¸Õ¿ªÊ¼¿¼ÊÔʱ±£´æ¿¼ÊÔ½á¹ûµÄSQLÓï¾ä£º"+sql);
    	int ret=conn.executeUpdate(sql);
    	return ret;
    }
    //¿¼ÊÔ½áÊøºó±£´æ¿¼ÊÔ½á¹û
    public int saveResult(String studentID,int lessonID,int resSingle,int resMore){
    	String lesson=((LessonForm)lessonDAO.query(lessonID).get(0)).getName();
    	String sql="UPDATE tb_stuResult set resSingle="+resSingle+",resMore="+resMore+" WHERE stuId='"+studentID+"' AND whichLesson='"+lesson+"'";
    	System.out.println(sql);
    	int ret=conn.executeUpdate(sql);
    	return ret;
    }
    public List queryExam(int questionsID,int flag){
    	List questionsList = new ArrayList();
        QuestionsForm questionsForm1 = null;
        String sql="";
        if(flag==0){
            sql = "SELECT * FROM tb_questions WHERE taoTiID="+questionsID+" AND type='µ¥Ñ¡Ìâ'";
        }else{
        	sql = "SELECT * FROM tb_questions WHERE taoTiID="+questionsID+" AND type='¶àÑ¡Ìâ'";
        }
        ResultSet rs = conn.executeQuery(sql);
        String type="";
        int id=0;
        try {
            rs.last();
            int recordNum=rs.getRow();
            rs.first();
            int[] idArr=new int[recordNum];
            for(int i=0;i<recordNum;i++) {
                questionsForm1 = new QuestionsForm();
                id=rs.getInt(1);
                questionsForm1.setID(id);
                questionsForm1.setSubject(rs.getString(2));
                type=rs.getString(3);
                questionsForm1.setType(type);
                questionsForm1.setLessonId(rs.getInt(5));
                questionsForm1.setTaoTiId(rs.getInt(6));
                questionsForm1.setOptionA(rs.getString(7));
                questionsForm1.setOptionB(rs.getString(8));
                questionsForm1.setOptionC(rs.getString(9));
                questionsForm1.setOptionD(rs.getString(10));
                if(type.equals("¶àÑ¡Ìâ")){
                	String[] ans=rs.getString(11).split(",");
                	questionsForm1.setAnswerArr(ans);
                	idArr[i]=id;
                	questionsForm1.setIdArrM(idArr);
                }else{
                	questionsForm1.setAnswer(rs.getString(11));
                	idArr[i]=id;
                	questionsForm1.setIdArrS(idArr);
                }
                questionsForm1.setNote(rs.getString(12));

                questionsList.add(questionsForm1);
                rs.next();
            }
        } catch (Exception e) {
        	e.printStackTrace();			//Êä³öÒì³£ÐÅÏ¢
        }
        return questionsList;
    }
    public String getRightAnswer(int id){
    	String answer="";
    	String sql = "SELECT * FROM tb_questions WHERE id="+id+"";
    	System.out.println("»ñÈ¡ÏÂÕýÈ·´ð°¸Ê±µÄSQLÓï¾ä£º"+sql);
    	ResultSet rs = conn.executeQuery(sql);
        try {
            if (rs.next()) {
                answer=rs.getString(11);
            }
        } catch (Exception ex) {
        	System.out.println("»ñÈ¡ÕýÈ·´ð°¸Ê±²úÉúµÄ´íÎóÐÅÏ¢£º"+ex.getMessage());
        }
    	return answer;
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>首页</title>


text:
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

type IcingaEvent struct {
	Operation  string                 `json:"operation"`
	Name       string                 `json:"name"`
	IcingaType string                 `json:"type"`
	Vars       map[string]interface{} `json:"vars"`
}

func main() {
	router := mux.NewRouter().StrictSlash(true)

	router.HandleFunc("/event", registerEvent).Methods("POST")

	log.Println("Starting to listen")
	loggedRouter := handlers.LoggingHandler(os.Stdout, router)
	log.Fatal(http.ListenAndServe(":8765", loggedRouter))
}

func registerEvent(w http.ResponseWriter, r *http.Request) {
	var event IcingaEvent
	fmt.Printf("%+v\n", r)
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	fmt.Println(string(body))
	if err := json.Unmarshal(body, &event); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422)
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	} else {

		fmt.Printf("%q\n", event)

		w.WriteHeader(http.StatusCreated)
	}
}


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="../../css/main.css" type="text/css" />

    <title>加速度センサー</title>

加速度センサー

        <canvas id="graph" width="380" height="200" style="border: solid 1px #000000;"></canvas>

        <button onclick="demoAcceleration.registerEvent()">開始</button>
        <button onclick="demoAcceleration.unregisterEvent()">停止</button>


text:
<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 2019/1/23
 * Time: 下午 01:07
 */

namespace Exam\Controller;

use Base\Controller\BaseController;
use Base\Document\ExamFile;
use Base\Entity\Exam;
use Exam\Form\ExamForm;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;

class AdminController extends BaseController
{

    public function indexAction()
    {
        $em = $this->getEntityManager();
        $res = $em->getRepository('Base\Entity\Exam')->findAll();

        $viewModel = new ViewModel();
        $viewModel->setVariable('data',$res);
        return $viewModel;
    }

    public function addAction()
    {
        $examForm = new ExamForm('exam_form');
        $em = $this->getEntityManager();
        if ($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();

            $examForm->setData($data);
            if ($examForm->isValid()) {
                /** @var  $user \Base\Entity\User */
                $user = $this->getAuthService()->getIdentity();

                $data2 = $examForm->getData();

                if ($data['id']) {
                    $exam = $em->getRepository('Base\Entity\Exam')->find($data['id']);
                }
                else
                    $exam = new Exam();

                $exam->setSubject($data2['subject']);
                $exam->setCreateTime(new \DateTime());
                $exam->setMemo($data2['memo']);
                $exam->setTeacher($user->getTeacher());

                if ($data2['open_time']) {
                    $exam->setOpenTime(new \DateTime($data2['open_time']));
                }
                if ($data2['close_time']) {
                    $exam->setCloseTime(new \DateTime($data2['close_time']));
                }

                $file = $this->params()->fromFiles();

                if (isset($file['stu_img'])) {
                    $examFile = new ExamFile();
                    $examFile->setName($file['stu_img']['name']);
                    $examFile->setType($file['stu_img']['type']);
                    $examFile->setFile($file['stu_img']['tmp_name']);
                    $dm = $this->getDocumentManager();
                    $dm->persist($examFile);
                    $dm->flush();
                    $mongoId = $examFile->getId();
                    // 測試用
                    $exam->setMemo($mongoId);
                }

                $em->persist($exam);
                $em->flush();
                return $this->redirect()->toUrl('/exam/admin');
            }
        }

        $id = $this->params()->fromQuery('id', 0);
        if ($id) {
            /** @var  $res \Base\Entity\Exam */
            $res = $em->getRepository('Base\Entity\Exam')->find($id);
            if ($res) {
                $examForm->bind($res);
                if ($res->getOpenTime())
                    $examForm->get('open_time')->setValue($res->getOpenTime()->format('Y-m-d H:i'));
                if ($res->getCloseTime())
                    $examForm->get('close_time')->setValue($res->getCloseTime()->format('Y-m-d H:i'));
            }
        }

        $viewModel = new ViewModel();
        $viewModel->setVariable('examForm', $examForm);

        return $viewModel;
    }

    public function deleteAction()
    {
        $id = $this->params()->fromQuery('id');

        $em = $this->getEntityManager();

        $res = $em->getRepository('Base\Entity\Exam')->find($id);

        $jsonModel = new JsonModel();
        if ($res) {
            $em->remove($res);
            $em->flush();
            $jsonModel->setVariable('success', true);
        }

        return $jsonModel;
    }

    public function imgAction()
    {
        $id = $this->params()->fromQuery('id');
        $dm = $this->getDocumentManager();
        /** @var \Zend\Http\Response $tmpRespone */
        $tmpResponse = $this->getResponse();
        $data = $dm->getRepository('Base\Document\ExamFile')->find($id);
        if ($data) {
            $tmpResponse->getHeaders()->addHeaderLine('Content-Type', $data->getType())
                ->addHeaderLine('Content-Disposition', 'attachment; filename="' . $data->getName() . '"')
                ->addHeaderLine('Content-Length', $data->getLength());
            $tmpResponse->setContent($data->getFile()->getBytes());
            return $tmpResponse;
        } else {
            return $tmpResponse->setStatusCode(404);
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;

namespace Context.Interfaces.Content
{
    public interface IContentFile
    {
        IContentItem Item { get; }

        string FileName { get; }

        int Length { get; }

        bool Exists { get; }

        Stream OpenStream();
    }
}


text:
package com.vdesmet.lib.calendar;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.viewpagerindicator.TitlePageIndicator;

import java.util.Calendar;

public class MultiCalendarView extends AbstractCalendarView {

    private boolean mShowIndicator;
    private ViewPager mViewPager;
    private ViewPager.OnPageChangeListener mOnPageChangeListener;
    private MultiCalendarAdapter mAdapter;
    private int mViewPagerPosition = -1;
    private TitlePageIndicator mIndicator;
    private OnCalendarLoadedListener mOnCalendarLoadedListener;

    public MultiCalendarView(final Context context) {
        super(context);
        init();
    }

    public MultiCalendarView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MultiCalendarView(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setOrientation(VERTICAL);

        mShowIndicator = true;
        mIsViewInitialized = false;
        mFirstDayOfWeek = Calendar.MONDAY;
        mLastDayOfWeek = Calendar.SUNDAY;

        // Add ViewPager + TitlePageIndicator
        final ViewPager viewPager = new ViewPager(getContext());
        final MultiCalendarAdapter adapter = new MultiCalendarAdapter(getContext(), this);
        viewPager.setAdapter(adapter);

        final TitlePageIndicator indicator = new TitlePageIndicator(getContext());
        if(mTypeface != null) {
            indicator.setTypeface(mTypeface);
        }
        indicator.setViewPager(viewPager);

        addView(indicator);

        // Add view to layout
        addView(viewPager);

        mAdapter = adapter;
        mViewPager = viewPager;
        mIndicator = indicator;
    }

    public void setIndicatorVisible(boolean visible) {
        this.mShowIndicator = visible;
    }

    @Override
    public void notifyDataSetChanged() {
        if(mAdapter != null) {
            mAdapter.notifyDataSetChanged();
            mViewPager.setAdapter(mAdapter);
            mIndicator.setViewPager(mViewPager);
        }
    }

    @Override
    public TextView getTextViewForDate(final long dayInMillis) {
        // Loop through all children in our ViewPager
        final int childCount = mViewPager.getChildCount();
        for(int i = 0; i < childCount; i++) {
            final View child = mViewPager.getChildAt(i);

            if(child != null && child instanceof ViewGroup) {
                // The CalendarView is the first child in our ViewGroup
                final CalendarView monthView = (CalendarView) ((ViewGroup) child).getChildAt(0);
                if(monthView != null) {
                    // Let the (single) CalendarView find a suitable TextView
                    final TextView result = monthView.getTextViewForDate(dayInMillis);
                    if(result != null) {
                        // If one is found, return it
                        return result;
                    }
                }
            }
        }
        return null;
    }

    public ViewPager getViewPager() {
        return mViewPager;
    }

    @Override
    protected void initView() {
        if(mFirstValidDay != null) {

            // If indicator is visible while it shouldn't, or visa versa
            if(mShowIndicator != (getChildAt(0) == mIndicator)) {
                // Show or hide the view
                if(mShowIndicator) {
                    mIndicator.setVisibility(View.VISIBLE);
                } else {
                    mIndicator.setVisibility(View.GONE);
                }
            }
            if(mOnPageChangeListener != null) {
                mViewPager.setOnPageChangeListener(mOnPageChangeListener);
            }

            if(mViewPagerPosition != -1) {
                // We need to change the ViewPager position
                mViewPager.setCurrentItem(mViewPagerPosition);
                mViewPagerPosition = -1;
            }

            mIsViewInitialized = true;

            if(mOnCalendarLoadedListener != null) {
                mOnCalendarLoadedListener.onCalendarLoaded(this);
            }
        }
    }

    public void setOnPageChangeListener(final ViewPager.OnPageChangeListener onPageChangeListener) {
        if(mViewPager != null) {
            mViewPager.setOnPageChangeListener(onPageChangeListener);
        }
        mOnPageChangeListener = onPageChangeListener;
    }

    public void setOnCalendarLoadedListener(final OnCalendarLoadedListener listener) {
        this.mOnCalendarLoadedListener = listener;
    }

    public void setViewPagerPosition(final int viewPagerPosition) {
        mViewPagerPosition = viewPagerPosition;
    }

    public TitlePageIndicator getIndicator() {
        return mIndicator;
    }
}


text:
var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function ($scope) {
    $scope.phones = [];
    $scope.status = "ok";

    var r = new XMLHttpRequest();
    r.onreadystatechange = function () {
        var DONE = this.DONE || 4;
        if (this.readyState === DONE){
            if (this.status === 200) {
                $scope.phones = JSON.parse(this.responseText);;
                $scope.status = "ok";
            } else {
                $scope.phones = [];
                $scope.status = "error";
            }
        }
    };
    r.open("GET", "phones.json", false);
    r.send();
});


text:
#include "config.h"
#include "PageClientImpl.h"

#include "DrawingAreaProxyImpl.h"
#include "NativeWebKeyboardEvent.h"
#include "NativeWebMouseEvent.h"
#include "NotImplemented.h"
#include "WebContext.h"
#include "WebContextMenuProxyGtk.h"
#include "WebEventFactory.h"
#include "WebKitWebViewBasePrivate.h"
#include "WebPageProxy.h"
#include "WebPopupMenuProxyGtk.h"
#include <WebCore/Cursor.h>
#include <WebCore/EventNames.h>
#include <WebCore/GtkUtilities.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>

using namespace WebCore;

namespace WebKit {

PageClientImpl::PageClientImpl(GtkWidget* viewWidget)
    : m_viewWidget(viewWidget)
{
}

PageClientImpl::~PageClientImpl()
{
}

void PageClientImpl::getEditorCommandsForKeyEvent(const NativeWebKeyboardEvent& event, const AtomicString& eventType, Vector<WTF::String>& commandList)
{
    ASSERT(eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent);

    KeyBindingTranslator::EventType type = eventType == eventNames().keydownEvent ?
        KeyBindingTranslator::KeyDown : KeyBindingTranslator::KeyPress;
    m_keyBindingTranslator.getEditorCommandsForKeyEvent(const_cast<GdkEventKey*>(&event.nativeEvent()->key), type, commandList);
}

// PageClient's pure virtual functions
OwnPtr<DrawingAreaProxy> PageClientImpl::createDrawingAreaProxy()
{
    return createOwned<DrawingAreaProxyImpl>(webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(m_viewWidget)));
}

void PageClientImpl::setViewNeedsDisplay(const WebCore::IntRect& rect)
{
    gtk_widget_queue_draw_area(m_viewWidget, rect.x(), rect.y(), rect.width(), rect.height());
}

void PageClientImpl::displayView()
{
    notImplemented();
}

void PageClientImpl::scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset)
{
    setViewNeedsDisplay(scrollRect);
}

WebCore::IntSize PageClientImpl::viewSize()
{
    if (!gtk_widget_get_realized(m_viewWidget))
        return IntSize();
    GtkAllocation allocation;
    gtk_widget_get_allocation(m_viewWidget, &allocation);
    return IntSize(allocation.width, allocation.height);
}

bool PageClientImpl::isViewWindowActive()
{
    return webkitWebViewBaseIsInWindowActive(WEBKIT_WEB_VIEW_BASE(m_viewWidget));
}

bool PageClientImpl::isViewFocused()
{
    return webkitWebViewBaseIsFocused(WEBKIT_WEB_VIEW_BASE(m_viewWidget));
}

bool PageClientImpl::isViewVisible()
{
    return webkitWebViewBaseIsVisible(WEBKIT_WEB_VIEW_BASE(m_viewWidget));
}

bool PageClientImpl::isViewInWindow()
{
    return webkitWebViewBaseIsInWindow(WEBKIT_WEB_VIEW_BASE(m_viewWidget));
}

void PageClientImpl::PageClientImpl::processDidCrash()
{
    notImplemented();
}

void PageClientImpl::didRelaunchProcess()
{
    notImplemented();
}

void PageClientImpl::takeFocus(bool)
{
    notImplemented();
}

void PageClientImpl::toolTipChanged(const String&, const String& newToolTip)
{
    webkitWebViewBaseSetTooltipText(WEBKIT_WEB_VIEW_BASE(m_viewWidget), newToolTip.utf8().data());
}

void PageClientImpl::setCursor(const Cursor& cursor)
{
    if (!gtk_widget_get_realized(m_viewWidget))
        return;

    // [GTK] Widget::setCursor() gets called frequently
    // http://bugs.webkit.org/show_bug.cgi?id=16388
    // Setting the cursor may be an expensive operation in some backends,
    // so don't re-set the cursor if it's already set to the target value.
    GdkWindow* window = gtk_widget_get_window(m_viewWidget);
    GdkCursor* currentCursor = gdk_window_get_cursor(window);
    GdkCursor* newCursor = cursor.platformCursor().get();
    if (currentCursor != newCursor)
        gdk_window_set_cursor(window, newCursor);
}

void PageClientImpl::setCursorHiddenUntilMouseMoves(bool hiddenUntilMouseMoves)
{
    notImplemented();
}

void PageClientImpl::didChangeViewportProperties(const WebCore::ViewportAttributes&)
{
    notImplemented();
}

void PageClientImpl::registerEditCommand(PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo)
{
    notImplemented();
}

void PageClientImpl::clearAllEditCommands()
{
    notImplemented();
}

bool PageClientImpl::canUndoRedo(WebPageProxy::UndoOrRedo)
{
    notImplemented();
    return false;
}

void PageClientImpl::executeUndoRedo(WebPageProxy::UndoOrRedo)
{
    notImplemented();
}

FloatRect PageClientImpl::convertToDeviceSpace(const FloatRect& viewRect)
{
    notImplemented();
    return viewRect;
}

FloatRect PageClientImpl::convertToUserSpace(const FloatRect& viewRect)
{
    notImplemented();
    return viewRect;
}

IntPoint PageClientImpl::screenToWindow(const IntPoint& point)
{
    IntPoint widgetPositionOnScreen = convertWidgetPointToScreenPoint(m_viewWidget, IntPoint());
    IntPoint result(point);
    result.move(-widgetPositionOnScreen.x(), -widgetPositionOnScreen.y());
    return result;
}

IntRect PageClientImpl::windowToScreen(const IntRect& rect)
{
    return IntRect(convertWidgetPointToScreenPoint(m_viewWidget, rect.location()), rect.size());
}

void PageClientImpl::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool wasEventHandled)
{
    if (wasEventHandled)
        return;
    if (event.isFakeEventForComposition())
        return;

    WebKitWebViewBase* webkitWebViewBase = WEBKIT_WEB_VIEW_BASE(m_viewWidget);
    webkitWebViewBaseForwardNextKeyEvent(webkitWebViewBase);
    gtk_main_do_event(event.nativeEvent());
}

PassRefPtr<WebPopupMenuProxy> PageClientImpl::createPopupMenuProxy(WebPageProxy* page)
{
    return WebPopupMenuProxyGtk::create(m_viewWidget, page);
}

PassRefPtr<WebContextMenuProxy> PageClientImpl::createContextMenuProxy(WebPageProxy* page)
{
    return WebContextMenuProxyGtk::create(m_viewWidget, page);
}

#if ENABLE(INPUT_TYPE_COLOR)
PassRefPtr<WebColorPicker> PageClientImpl::createColorPicker(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&)
{
    notImplemented();
    return 0;
}
#endif

void PageClientImpl::setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate)
{
    notImplemented();
}

#if USE(ACCELERATED_COMPOSITING)
void PageClientImpl::enterAcceleratedCompositingMode(const LayerTreeContext&)
{
    notImplemented();
}

void PageClientImpl::exitAcceleratedCompositingMode()
{
    notImplemented();
}

void PageClientImpl::updateAcceleratedCompositingMode(const LayerTreeContext&)
{
    notImplemented();
}
#endif // USE(ACCELERATED_COMPOSITING)

void PageClientImpl::pageClosed()
{
    notImplemented();
}

void PageClientImpl::preferencesDidChange()
{
    notImplemented();
}

void PageClientImpl::flashBackingStoreUpdates(const Vector<IntRect>&)
{
    notImplemented();
}

void PageClientImpl::updateTextInputState()
{
    webkitWebViewBaseUpdateTextInputState(WEBKIT_WEB_VIEW_BASE(m_viewWidget));
}

void PageClientImpl::startDrag(const WebCore::DragData& dragData, PassRefPtr<ShareableBitmap> dragImage)
{
    webkitWebViewBaseStartDrag(WEBKIT_WEB_VIEW_BASE(m_viewWidget), dragData, dragImage);
}

void PageClientImpl::handleDownloadRequest(DownloadProxy* download)
{
    webkitWebViewBaseHandleDownloadRequest(WEBKIT_WEB_VIEW_BASE(m_viewWidget), download);
}

} // namespace WebKit


text:
Simple Gallery
==============

A Monsta plugin that uses the images in a folder to create galleries/ slideshows.

Visit http://www.mightyhaggis.com/simple-gallery for example and details on how to use the plugin


text:
%
% created April 2, 2018 by Daniel Dolan (Sandia National Laboratories)
%
function dump(object,mode)

switch mode
    case 'create'
        h=uipushtool('Parent',object.ToolBar,...
            'Tag','Dump','ToolTipString','Dump plots',...
            'Cdata',local_graphic('DumpIcon'),'Separator','off',...
            'ClickedCallback',@callback);
        object.ToolButton.Dump=h;
    case 'hide'
        set(object.Button.Dump,'Visible','off');
    case 'show'
        set(object.Button.Dump,'Visible','on');
end

    function callback(varargin)
        location=sprintf('%.0f-',datevec(now));
        location=sprintf('PlotDump_%s',location(1:end-1));
        location=fullfile(pwd,location);
        %
        ha=findobj(object.Handle,'Type','axes','Visible','on');
        ha=ha(end:-1:1);
        for n=1:numel(ha)
            if n == 1
                mkdir(location);
            end
            pos=getpixelposition(ha(n));
            pos(1:2)=0;
            fig=figure('Visible','off','Units','pixels');
            if pos(3) > pos(4)
                fig.PaperOrientation='landscape';
            else
                fig.PaperOrientation='portrait';
            end
            fig.Units=fig.PaperUnits;
            fig.Position=fig.PaperPosition;
            new=copyobj(ha(n),fig);
            set(new,'Units','normalized','OuterPosition',[0 0 1 1]);
            file=fullfile(location,sprintf('plot%d.pdf',n));
            print(fig,'-dpdf',file);
            delete(fig);
        end

    end
end


text:
package edu.isi.karma.mapreduce.driver;

import java.io.IOException;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Mapper;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IdentityJSONMapper extends Mapper<Writable, Text, Text, Text> {
	private static Logger LOG = LoggerFactory.getLogger(IdentityJSONMapper.class);

	@Override
	public void map(Writable key, Text value, Context context) throws IOException, InterruptedException {
		try {
			JSONObject obj = new JSONObject(value.toString());
			if (obj.has("uri")) {
				context.write(new Text(obj.getString("uri")), value);
			}
			else if (obj.has("@id")) {
				context.write(new Text(obj.getString("@id")), value);
			}
			else {
				context.write(new Text(obj.toString()), value);
			}
		}catch(Exception e) {
			LOG.error("something is wrong", e);
		}
	}
}


text:
package com.szlachet.beetle.jwt.filter;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;

/**
 *
 * @author Sebastian Szlachetka
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
@NameBinding
public @interface JwtAuthenticated {

}


text:
package io.skytreasure.kotlingroupchat.chat.ui.widget;

import android.support.annotation.IntDef;
import android.text.TextUtils;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;

import io.skytreasure.kotlingroupchat.chat.model.MessageModel;

/**
 * Created by natuan on 17/01/07.
 * Modified by akash on 02/11/17
 */

public class InfiniteFirebaseArray implements ChildEventListener, ValueEventListener {

    public static final int ADDED = 0;
    public static final int CHANGED = 1;
    public static final int REMOVED = 2;
    public static final int NOTIFY_ALL = 3;

    List<DataSnapshot> tempList = new ArrayList<>();

    @IntDef({ADDED, CHANGED, REMOVED, NOTIFY_ALL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface EventType {
    }

    public interface OnChangedListener {

        void onChanged(@EventType int type, int index, int oldIndex);

        void onCancelled(DatabaseError databaseError);
    }

    private Query mQuery;
    public List<DataSnapshot> mSnapshots = new ArrayList<>();
    private int mIndex = -1;
    private String mNextChildKey = null;
    private String mEndKey;
    private static String startAt;
    private int mNumberPerPage;
    private int mCount;
    private boolean isDuplicateKey;
    private OnChangedListener mListener;

    public InfiniteFirebaseArray(Query ref, int numberPerPage, String startat) {
        mNumberPerPage = numberPerPage;
        startAt = startat;
        initQuery(ref);
    }

    private void initQuery(Query ref) {
        Logger.d("LastChildKey: " + mNextChildKey);
        Logger.d("NumberPerPage: " + mNumberPerPage);
        mQuery = ref.orderByChild("timestamp").startAt(startAt).limitToLast(mNumberPerPage);
        mQuery.addChildEventListener(this);
        mCount = 0;
        tempList.clear();
    }

    private void initNextQuery(Query ref) {
        Logger.d("LastChildKey: " + mNextChildKey);
        Logger.d("NumberPerPage: " + mNumberPerPage);
        ref.orderByChild("timestamp").limitToLast(5)
                .startAt(startAt).endAt(mEndKey).addListenerForSingleValueEvent(this);
        mCount = 0;
        tempList.clear();
    }

    public void cleanup() {
        Logger.enter();
        //mQuery.removeEventListener(this);
        Logger.exit();
    }

    public void more(Query ref) {
        if (/*isHasMore()*/true) {
            initNextQuery(ref);
        }
    }

    public int getCount() {
        return mSnapshots.size();
    }

    public DataSnapshot getItem(int index) {
        return mSnapshots.get(index);
    }

    @Override
    public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
        if (snapshot == null) {
            return;
        }
        mCount++;
        if (mCount == 1) {
            mEndKey = snapshot.getValue(MessageModel.class).getTimestamp();
        }
        mNextChildKey = snapshot.getKey();
        /*if (mCount > mNumberPerPage) {
            return;
        }*/
        if (checkDuplicateKey(mNextChildKey)) {
            isDuplicateKey = true;
            return;
        }
      /*  tempList.clear();
        tempList.add(snapshot);
        //if (mCount == mNumberPerPage) {
        mSnapshots.addAll(0, tempList);
        mListener.onChanged(ADDED, 0, -1);*/
        //}
        //mSnapshots.addAll(0, tempList);
        tempList.clear();
        tempList.add(snapshot);
        int size = mSnapshots.size();
        mSnapshots.addAll(size, tempList);
        notifyChangedListeners(ADDED, mSnapshots.size());
        //notifyChangedListeners(ADDED, 0);

        Logger.d(mIndex + " : " + mNextChildKey);
    }

    private boolean checkDuplicateKey(String nextChildKey) {
        if (mSnapshots.size() > 0) {
            DataSnapshot previousSnapshot = mSnapshots.get(0);
            String previousChildkey = previousSnapshot == null ? "" : previousSnapshot.getKey();
            return (!TextUtils.isEmpty(previousChildkey) && previousChildkey.equals(nextChildKey));
        }
        return false;
    }

    public boolean isHasMore() {
        boolean isHasMore = true;
        if (mCount < mNumberPerPage || isDuplicateKey) {
            isHasMore = false;
        }
        Logger.d("isHasMore: " + isHasMore);
        return isHasMore;
    }

    public void setOnChangedListener(OnChangedListener listener) {
        mListener = listener;
    }

    private void notifyChangedListeners(@EventType int type, int index) {
        notifyChangedListeners(type, index, -1);
    }

    protected void notifyChangedListeners(@EventType int type, int index, int oldIndex) {
        if (mListener != null) {
            mListener.onChanged(type, index, oldIndex);
        }
    }

    protected void notifyCancelledListeners(DatabaseError databaseError) {
        if (mListener != null) {
            mListener.onCancelled(databaseError);
        }
    }

    private int getIndexForKey(String key) {
        int index = 0;
        for (DataSnapshot snapshot : mSnapshots) {
            if (snapshot.getKey().equalsIgnoreCase(key)) {
                return index;
            } else {
                index++;
            }
        }
        return -1;
    }

    @Override
    public void onChildChanged(DataSnapshot snapshot, String s) {
        int index = getIndexForKey(snapshot.getKey());
        if (index != -1) {
            mSnapshots.set(index, snapshot);
            notifyChangedListeners(CHANGED, index);
        }
    }

    @Override
    public void onChildRemoved(DataSnapshot snapshot) {
        int index = getIndexForKey(snapshot.getKey());
        if (index != -1) {
            mSnapshots.remove(index);
            notifyChangedListeners(REMOVED, index);
        }
    }

    @Override
    public void onChildMoved(DataSnapshot snapshot, String previousChildKey) {

    }

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            mCount = 0;

            for (DataSnapshot currentSnap : dataSnapshot.getChildren()) {
                //MessageModel tempModel=dataSnapshot.getChildren().iterator().next().getValue(MessageModel.class);
                if (mCount == 0) {
                    mEndKey = currentSnap.getValue(MessageModel.class).getTimestamp();
                }
                mNextChildKey = currentSnap.getKey();
                if (!checkDuplicateKey(mNextChildKey)) {
                    tempList.add(currentSnap);
                    mIndex++;
                }
                mCount++;
            }
            mSnapshots.addAll(0, tempList);
            mListener.onChanged(NOTIFY_ALL, 0, -1);

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        notifyCancelledListeners(databaseError);
    }
}


text:
<?php

namespace OroCRM\Bundle\MagentoBundle\Form\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;

use Oro\Bundle\IntegrationBundle\Form\Type\ChannelType;
use Oro\Bundle\IntegrationBundle\Manager\TypesRegistry;
use Oro\Bundle\IntegrationBundle\Provider\ConnectorInterface;

use OroCRM\Bundle\MagentoBundle\Provider\ExtensionAwareInterface;

class SoapConnectorsFormSubscriber implements EventSubscriberInterface
{
    /** @var TypesRegistry */
    protected $typeRegistry;

    public function __construct(TypesRegistry $registry)
    {
        $this->typeRegistry = $registry;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            FormEvents::PRE_SET_DATA => 'preSet',
            FormEvents::PRE_SUBMIT   => 'preSubmit'
        ];
    }

    /**
     * Populate websites choices if exist in entity
     *
     * @param FormEvent $event
     */
    public function preSet(FormEvent $event)
    {
        $this->modify($event->getData(), $event->getForm()->getParent());
    }

    /**
     * Pre submit event listener
     * Encrypt passwords and populate if empty
     * Populate websites choices from hidden fields
     *
     * @param FormEvent $event
     */
    public function preSubmit(FormEvent $event)
    {
        $this->modify($event->getData(), $event->getForm()->getParent());
    }

    /**
     * @param array         $data
     * @param FormInterface $form
     */
    protected function modify($data, FormInterface $form)
    {
        if ($this->hasChannelParent($form)) {
            $connectors = $form->getParent()->get('connectors');
            if ($connectors) {
                $config = $connectors->getConfig()->getOptions();
                unset($config['choice_list']);
                unset($config['choices']);
            } else {
                $config = [];
            }

            if (array_key_exists('auto_initialize', $config)) {
                $config['auto_initialize'] = false;
            }

            $allowedTypesChoices = $this->typeRegistry->getAvailableConnectorsTypesChoiceList(
                'magento',
                function (ConnectorInterface $connector) use ($data) {
                    return $connector instanceof ExtensionAwareInterface ? $data : true;
                }
            );

            $form->getParent()
                ->add('connectors', 'choice', array_merge($config, ['choices' => $allowedTypesChoices]));
        }
    }

    /**
     * Check is parent exists and this parent instance of ChannelType
     *
     * @param FormInterface $form
     *
     * @return bool
     */
    private function hasChannelParent(FormInterface $form)
    {
        return (
            $form->getParent()
            && $form->getParent()->getConfig()->getType()->getInnerType() instanceof ChannelType
        );
    }
}


text:
layout: about
title: about
permalink: /
subtitle: Data Scientist | AI Researcher | Full Stack Software Engineer

profile:
  align: right
  image: prof_pic.jpeg
  address: >

555 your office number

123 your address street

Your City, State 12345

news: true  # includes a list of news items
selected_papers: true # includes a list of papers marked as "selected={true}"
social: true  # includes social icons at the bottom of the page
---

Graduate Researcher with experience in modelling and deploying enterprise-level Machine Learning and Deep Learning models. Prabod holds a Bachelor of Science of the Engineering Honours degree specialised in Computer Science and Engineering. Currently, pursuing a PhD degree in Artificial Intelligence at La Trobe University, Australia while employed as a Graduate Researcher.
Working mainly on fields of Business Intelligence, Data Analytics, Natural Language Processing, Time Series Analysis, Machine Vision and Optimization with a proven track record of research publications and machine learning competition winnings.


text:
namespace chrome_common_net {

TEST(UrlUtilTest, AppendQueryParameter) {
  // Appending a name-value pair to a URL without a query component.
  EXPECT_EQ("http://example.com/path?name=value",
            AppendQueryParameter(GURL("http://example.com/path"),
                                 "name", "value").spec());

  // Appending a name-value pair to a URL with a query component.
  // The original component should be preserved, and the new pair should be
  // appended with '&'.
  EXPECT_EQ("http://example.com/path?existing=one&name=value",
            AppendQueryParameter(GURL("http://example.com/path?existing=one"),
                                 "name", "value").spec());

  // Appending a name-value pair with unsafe characters included. The
  // unsafe characters should be escaped.
  EXPECT_EQ("http://example.com/path?existing=one&na+me=v.alue%3D",
            AppendQueryParameter(GURL("http://example.com/path?existing=one"),
                                 "na me", "v.alue=").spec());

}

TEST(UrlUtilTest, AppendOrReplaceQueryParameter) {
  // Appending a name-value pair to a URL without a query component.
  EXPECT_EQ("http://example.com/path?name=value",
            AppendOrReplaceQueryParameter(GURL("http://example.com/path"),
                                 "name", "value").spec());

  // Appending a name-value pair to a URL with a query component.
  // The original component should be preserved, and the new pair should be
  // appended with '&'.
  EXPECT_EQ("http://example.com/path?existing=one&name=value",
      AppendOrReplaceQueryParameter(
          GURL("http://example.com/path?existing=one"),
          "name", "value").spec());

  // Appending a name-value pair with unsafe characters included. The
  // unsafe characters should be escaped.
  EXPECT_EQ("http://example.com/path?existing=one&na+me=v.alue%3D",
      AppendOrReplaceQueryParameter(
          GURL("http://example.com/path?existing=one"),
          "na me", "v.alue=").spec());

  // Replace value of an existing paramater.
  EXPECT_EQ("http://example.com/path?existing=one&name=new",
      AppendOrReplaceQueryParameter(
          GURL("http://example.com/path?existing=one&name=old"),
          "name", "new").spec());

  // Replace a name-value pair with unsafe characters included. The
  // unsafe characters should be escaped.
  EXPECT_EQ("http://example.com/path?na+me=n.ew%3D&existing=one",
      AppendOrReplaceQueryParameter(
          GURL("http://example.com/path?na+me=old&existing=one"),
          "na me", "n.ew=").spec());

  // Replace the value of first parameter with this name only.
  EXPECT_EQ("http://example.com/path?name=new&existing=one&name=old",
      AppendOrReplaceQueryParameter(
          GURL("http://example.com/path?name=old&existing=one&name=old"),
          "name", "new").spec());

  // Preserve the content of the original params regarless of our failure to
  // interpret them correctly.
  EXPECT_EQ("http://example.com/path?bar&name=new&left=&"
            "=right&=&&name=again",
      AppendOrReplaceQueryParameter(
          GURL("http://example.com/path?bar&name=old&left=&"
                "=right&=&&name=again"),
          "name", "new").spec());
}

TEST(BrowserUrlUtilTest, GetValueForKeyInQuery) {
  GURL url("http://example.com/path?name=value&boolParam&"
           "url=http://test.com/q?n1%3Dv1%26n2");
  std::string value;

  // False when getting a non-existent query param.
  EXPECT_FALSE(GetValueForKeyInQuery(url, "non-exist", &value));

  // True when query param exist.
  EXPECT_TRUE(GetValueForKeyInQuery(url, "name", &value));
  EXPECT_EQ("value", value);

  EXPECT_TRUE(GetValueForKeyInQuery(url, "boolParam", &value));
  EXPECT_EQ("", value);

  EXPECT_TRUE(GetValueForKeyInQuery(url, "url", &value));
  EXPECT_EQ("http://test.com/q?n1=v1&n2", value);
}

}  // namespace chrome_common_net.


text:
package com.kopetto.sample.domain.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

/**Base repository, holds mongoTemplate
 *
 */
public class BaseRepositoryImpl{

	@Autowired
	protected MongoTemplate mongoTemplate;

}


text:
<?php

require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/Util/Filter.php';

require_once 'PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php';

PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');

require_once 'PHPUnit/Extensions/Database/Operation/Composite.php';
require_once 'PHPUnit/Extensions/Database/Operation/DeleteAll.php';
require_once 'PHPUnit/Extensions/Database/Operation/Delete.php';
require_once 'PHPUnit/Extensions/Database/Operation/Insert.php';
require_once 'PHPUnit/Extensions/Database/Operation/Null.php';
require_once 'PHPUnit/Extensions/Database/Operation/Update.php';
require_once 'PHPUnit/Extensions/Database/Operation/Truncate.php';

/**
 * A class factory to easily return database operations.
 *
 * @category   Testing
 * @package    PHPUnit
 * @author     Mike Lively <m@digitalsandwich.com>
 * @copyright  2010 Mike Lively <m@digitalsandwich.com>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://www.phpunit.de/
 * @since      Class available since Release 3.2.0
 */
class PHPUnit_Extensions_Database_Operation_Factory
{

    /**
     * Returns a null database operation
     *
     * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation
     */
    public static function NONE()
    {
        return new PHPUnit_Extensions_Database_Operation_Null();
    }

    /**
     * Returns a clean insert database operation. It will remove all contents
     * from the table prior to re-inserting rows.
     *
     * @param bool $cascadeTruncates Set to true to force truncates to cascade on databases that support this.
     * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation
     */
    public static function CLEAN_INSERT($cascadeTruncates = FALSE)
    {
        return new PHPUnit_Extensions_Database_Operation_Composite(array(
            self::TRUNCATE($cascadeTruncates),
            self::INSERT()
        ));
    }

    /**
     * Returns an insert database operation.
     *
     * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation
     */
    public static function INSERT()
    {
        return new PHPUnit_Extensions_Database_Operation_Insert();
    }

    /**
     * Returns a truncate database operation.
     *
     * @param bool $cascadeTruncates Set to true to force truncates to cascade on databases that support this.
     * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation
     */
    public static function TRUNCATE($cascadeTruncates = FALSE)
    {
        $truncate = new PHPUnit_Extensions_Database_Operation_Truncate();
        $truncate->setCascade($cascadeTruncates);

        return $truncate;
    }

    /**
     * Returns a delete database operation.
     *
     * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation
     */
    public static function DELETE()
    {
        return new PHPUnit_Extensions_Database_Operation_Delete();
    }

    /**
     * Returns a delete_all database operation.
     *
     * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation
     */
    public static function DELETE_ALL()
    {
        return new PHPUnit_Extensions_Database_Operation_DeleteAll();
    }

    /**
     * Returns an update database operation.
     *
     * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation
     */
    public static function UPDATE()
    {
        return new PHPUnit_Extensions_Database_Operation_Update();
    }

}
?>