text:
<repo_name>Senya10p/php_homework2<file_sep>/inc1.php
<?php

$wether = 'cолнечно';
$temperature = 'тепло ';

?><file_sep>/Readme.txt
ВНИМАНИЕ! Основной файл index.php
Файлы inc1.php, inc2.php, inc2-1.php, inc3.php, inc4.php - это включаемые файлы для задания 3.
Файл functions1.php содержит функцию для задания 4.

		<title>PHP-1</title>

PHP

2 урок

Домашняя работа

1. Напишите программу, которая составит и выведет в браузер таблицу истинности для логических операторов &&, || и xor.

        <?php
        $a1 = false;    //Задаём переменные для первой строки таблиц
        $b1 = false;
        $a2 = true;     //Задаём переменные для второй строки таблиц
        $b2 = false;
        $a3 = false;    //Задаём переменные для третей строки таблиц
        $b3 = true;
        $a4 = true;     //Задаём переменные для четвёртой строки таблиц
        $b4 = true;

        // Затем выводим таблицы истинности. (int) используется для отображения таблиц аналогично таблицам из Википедии, ссылка на которую есть в задании.
        ?>

                        Таблица 1
 (Логическое "И" &&)

 a	 b	 &&

 <?php echo (int)$a1;?>	<?php echo (int)$b1;?>	<?php echo (int)($a1&&$b1);?>

 <?php echo (int)$a2;?>	 <?php echo (int)$b2;?>	<?php echo (int)($a2&&$b2);?>

 <?php echo (int)$a3;?>	 <?php echo (int)$b3;?>	<?php echo (int)($a3&&$b3);?>

 <?php echo (int)$a4;?>	 <?php echo (int)$b4;?>	<?php echo (int)($a4&&$b4);?>

                        Таблица 2
 (Логическое "ИЛИ" ||)

 a	 b	 ||

 <?php echo (int)$a1;?>	<?php echo (int)$b1;?>	<?php echo (int)($a1||$b1);?>

 <?php echo (int)$a2;?>	 <?php echo (int)$b2;?>	<?php echo (int)($a2||$b2);?>

 <?php echo (int)$a3;?>	 <?php echo (int)$b3;?>	<?php echo (int)($a3||$b3);?>

 <?php echo (int)$a4;?>	 <?php echo (int)$b4;?>	<?php echo (int)($a4||$b4);?>

                        Таблица 3
 (Исключающее "ИЛИ" XOR)

 a	 b	xor

 <?php echo (int)$a1;?>	<?php echo (int)$b1;?>	<?php echo (int)($a1 xor $b1);?>

 <?php echo (int)$a2;?>	 <?php echo (int)$b2;?>	<?php echo (int)($a2 xor $b2);?>

 <?php echo (int)$a3;?>	 <?php echo (int)$b3;?>	<?php echo (int)($a3 xor $b3);?>

 <?php echo (int)$a4;?>	 <?php echo (int)$b4;?>	<?php echo (int)($a4 xor $b4);?>

2. Составьте функцию вычисления дискриминанта квадратного уравнения. Покройте ее тестами.
            Используя эту функцию, напишите программу, которая решает квадратное уравнение. Оформите красивый вывод решения.

        <?php

        //Задаём переменные
        $aa = 2;
        $bb = 5;
        $cc = 2;

        //Функция вычисления дискрименанта

        function D($aa, $bb, $cc) {

            return $bb ** 2 - 4 * $aa * $cc;
        }

        $dd = D($aa, $bb, $cc);

        // Тестируем фунцкию дискриминанта
        assert(-3 == D(1, 1, 1));
        assert(0 == D(0, 0, 1));
        assert(0 == D(1, 2, 1));
        assert(9 == D(2, 5, 2));
        assert(0 == D(2, 4, 2));

        ?>

Решаем квадратное уравнение a*x2 + b*x + c = 0

Где a =<?php echo $aa; ?> ; b = <?php echo $bb; ?>; c = <?php echo $cc; ?>

<?php echo $aa; ?> * x2 + <?php echo $bb; ?> * x + <?php echo $cc; ?> = 0

Находим дискриминант (по формуле D = b2 - 4*a*c) : D = <?php echo $dd; ?>

Находим корни квадратного уравнения

        <?php
        if ($dd > 0){

            $xx1 = ((-$bb+sqrt($dd))/2*$aa);
            $xx2 = ((-$bb-sqrt($dd))/2*$aa);
            echo 'Дискриминант больше нуля, значит уравнение имеет два корня:
 1) x1 = '. $xx1 .'
2) x2 = ' . $xx2;
        }
        elseif ($dd == 0){

            $xx1 = ((-$bb+sqrt($dd))/2*$aa);
            echo 'Дискриминант равен нулю, значит уравнение имеет один корень:
 1) x = '. $xx1 ;
        }
        else {
            echo 'Дискриминант меньше нуля, значит уравнение не имеет корней';
        }

        ?>

3. Проведите самостоятельное исследование на тему "Что возвращает оператор include, если его использовать как функцию?".
            Используйте руководство по языку, составьте и приложите примеры, иллюстрирующие ваше исследование.

            Функция принимает аргументы и возвращает результат.
            include как функция в качестве аргумента принимает полное имя файла и возвращает то, что возвращает файл inc2-1.php.
            Пример:

        <?php
        $iinc = include(__DIR__ . '/inc2-1.php');
        echo $iinc;              //Возвращает результат выполнения всего php-кода из файла inc2-1.php
        var_dump($iinc);
        ?>

         include включает и выполняет указанный файл. Когда файл включается, его код наследует ту же область видимости переменных, что и строка, на которой произошло включение.
        Все переменные, доступные во включающем файле, будут доступны во включаемом файле. Но все функции и классы, объявленные во включаемом файле, имеют глобальную обсласть видимости.

        Оператор include возвращает значение False при ошибке и выдаёт предупреждение. Успешное включение, пока это не определено во включаемом файле, возвращают значение 1.

        <?php

        var_dump(include(__DIR__ . '/inc2.php'));
        echo ' Сегодня '.  $wether2 . ' и ' . $temperature2 ;

        ?>

 Если включение происходит внутри функции включающего файла, то весь код, содержащийся во включаемом файле, будет вести себя так, как будто он определён внутри этой функции.
            Исключением являются так называемые волшебные константы (например __DIR__)

 Ещё примеры:

        <?php
            include __DIR__ . '/inc3.php';
            echo ' хорошая погода';

       // Выведет Сегодня хорошая погода
        ?>

 Все функции, определённые во включаемом файле будут доступны, даже если файл не выполняется:

        <?php
        // Файл inc4.php содержит функцию
        include __DIR__ . '/inc4.php';
        func();
        // Выведет Сегодня хорошая погода
        ?>

4. *Составьте функцию, которая на вход будет принимать имя человека, а возвращать его пол, пытаясь угадать по имени (null - если угадать не удалось).
            Вам придется самостоятельно найти нужные вам строковые функции. Начните с написания тестов для функции.

        <?php

        //Задаём имя на русском языке
        $name = 'Сергей'; //имя

        include_once __DIR__ . '/functions1.php'; //подключает файл с функцией определения пола по имени

        echo $name, SN($name);
       //var_dump(SN($name));

        ?>

<file_sep>/index.php

		<title>PHP-1</title>

PHP

2 урок

Домашняя работа

1. Напишите программу, которая составит и выведет в браузер таблицу истинности для логических операторов &&, || и xor.

        <?php
        $a1 = false;    //Задаём переменные для первой строки таблиц
        $b1 = false;
        $a2 = true;     //Задаём переменные для второй строки таблиц
        $b2 = false;
        $a3 = false;    //Задаём переменные для третей строки таблиц
        $b3 = true;
        $a4 = true;     //Задаём переменные для четвёртой строки таблиц
        $b4 = true;

        // Затем выводим таблицы истинности. (int) используется для отображения таблиц аналогично таблицам из Википедии, ссылка на которую есть в задании.
        ?>

                        Таблица 1
 (Логическое "И" &&)

 a	 b	 &&

 <?php echo (int)$a1;?>	<?php echo (int)$b1;?>	<?php echo (int)($a1&&$b1);?>

 <?php echo (int)$a2;?>	 <?php echo (int)$b2;?>	<?php echo (int)($a2&&$b2);?>

 <?php echo (int)$a3;?>	 <?php echo (int)$b3;?>	<?php echo (int)($a3&&$b3);?>

 <?php echo (int)$a4;?>	 <?php echo (int)$b4;?>	<?php echo (int)($a4&&$b4);?>

                        Таблица 2
 (Логическое "ИЛИ" ||)

 a	 b	 ||

 <?php echo (int)$a1;?>	<?php echo (int)$b1;?>	<?php echo (int)($a1||$b1);?>

 <?php echo (int)$a2;?>	 <?php echo (int)$b2;?>	<?php echo (int)($a2||$b2);?>

 <?php echo (int)$a3;?>	 <?php echo (int)$b3;?>	<?php echo (int)($a3||$b3);?>

 <?php echo (int)$a4;?>	 <?php echo (int)$b4;?>	<?php echo (int)($a4||$b4);?>

                        Таблица 3
 (Исключающее "ИЛИ" XOR)

 a	 b	xor

 <?php echo (int)$a1;?>	<?php echo (int)$b1;?>	<?php echo (int)($a1 xor $b1);?>

 <?php echo (int)$a2;?>	 <?php echo (int)$b2;?>	<?php echo (int)($a2 xor $b2);?>

 <?php echo (int)$a3;?>	 <?php echo (int)$b3;?>	<?php echo (int)($a3 xor $b3);?>

 <?php echo (int)$a4;?>	 <?php echo (int)$b4;?>	<?php echo (int)($a4 xor $b4);?>

2. Составьте функцию вычисления дискриминанта квадратного уравнения. Покройте ее тестами.
            Используя эту функцию, напишите программу, которая решает квадратное уравнение. Оформите красивый вывод решения.

        <?php

        //Задаём переменные
        $aa = 2;
        $bb = 5;
        $cc = 2;

        //Функция вычисления дискрименанта

        function D($aa, $bb, $cc) {

            return $bb ** 2 - 4 * $aa * $cc;
        }

        $dd = D($aa, $bb, $cc);

        // Тестируем фунцкию дискриминанта
        assert(-3 == D(1, 1, 1));
        assert(0 == D(0, 0, 1));
        assert(0 == D(1, 2, 1));
        assert(9 == D(2, 5, 2));
        assert(0 == D(2, 4, 2));

        ?>

Решаем квадратное уравнение a*x2 + b*x + c = 0

Где a =<?php echo $aa; ?> ; b = <?php echo $bb; ?>; c = <?php echo $cc; ?>

<?php echo $aa; ?> * x2 + <?php echo $bb; ?> * x + <?php echo $cc; ?> = 0

Находим дискриминант (по формуле D = b2 - 4*a*c) : D = <?php echo $dd; ?>

Находим корни квадратного уравнения

        <?php
        if ($dd > 0){

            $xx1 = ((-$bb+sqrt($dd))/2*$aa);
            $xx2 = ((-$bb-sqrt($dd))/2*$aa);
            echo 'Дискриминант больше нуля, значит уравнение имеет два корня:
 1) x1 = '. $xx1 .'
2) x2 = ' . $xx2;
        }
        elseif ($dd == 0){

            $xx1 = ((-$bb+sqrt($dd))/2*$aa);
            echo 'Дискриминант равен нулю, значит уравнение имеет один корень:
 1) x = '. $xx1 ;
        }
        else {
            echo 'Дискриминант меньше нуля, значит уравнение не имеет корней';
        }

        ?>

3. Проведите самостоятельное исследование на тему "Что возвращает оператор include, если его использовать как функцию?".
            Используйте руководство по языку, составьте и приложите примеры, иллюстрирующие ваше исследование.

            Функция принимает аргументы и возвращает результат.
            include как функция в качестве аргумента принимает полное имя файла и возвращает то, что возвращает файл inc2-1.php.
            Пример:

        <?php
        $iinc = include(__DIR__ . '/inc2-1.php');
        echo $iinc;              //Возвращает результат выполнения всего php-кода из файла inc2-1.php
        var_dump($iinc);
        ?>

         include включает и выполняет указанный файл. Когда файл включается, его код наследует ту же область видимости переменных, что и строка, на которой произошло включение.
        Все переменные, доступные во включающем файле, будут доступны во включаемом файле. Но все функции и классы, объявленные во включаемом файле, имеют глобальную обсласть видимости.

        Оператор include возвращает значение False при ошибке и выдаёт предупреждение. Успешное включение, пока это не определено во включаемом файле, возвращают значение 1.

        <?php

        var_dump(include(__DIR__ . '/inc2.php'));
        echo ' Сегодня '.  $wether2 . ' и ' . $temperature2 ;

        ?>

 Если включение происходит внутри функции включающего файла, то весь код, содержащийся во включаемом файле, будет вести себя так, как будто он определён внутри этой функции.
            Исключением являются так называемые волшебные константы (например __DIR__)

 Ещё примеры:

        <?php
            include __DIR__ . '/inc3.php';
            echo ' хорошая погода';

       // Выведет Сегодня хорошая погода
        ?>

 Все функции, определённые во включаемом файле будут доступны, даже если файл не выполняется:

        <?php
        // Файл inc4.php содержит функцию
        include __DIR__ . '/inc4.php';
        func();
        // Выведет Сегодня хорошая погода
        ?>

4. *Составьте функцию, которая на вход будет принимать имя человека, а возвращать его пол, пытаясь угадать по имени (null - если угадать не удалось).
            Вам придется самостоятельно найти нужные вам строковые функции. Начните с написания тестов для функции.

        <?php

        //Задаём имя на русском языке
        $name = 'Сергей'; //имя

        include_once __DIR__ . '/functions1.php'; //подключает файл с функцией определения пола по имени

        echo $name, SN($name);
       //var_dump(SN($name));

        ?>

<file_sep>/inc2-1.php
<?php

return  42 + 24;
?><file_sep>/inc3.php
<?php

    echo 'Сегодня';
    return;

?><file_sep>/inc2.php
<?php

$wether2 = 'cолнечно';
$temperature2 = 'тепло ';

?><file_sep>/inc4.php
<?php
return;
function func(){
    echo 'Сегодня плохая погода';
}
?><file_sep>/functions1.php
<?php
function SN($name)
{
    $pop = substr($name, -2); //Возвращает последнюю букву от имени

    $male = ' пол мужской';
    $female = ' пол женский';

    if ($name == 'Никита' || $name == 'Илья' || $name == 'Петя' || $name == 'Ваня') {    //Добавляем исключения
        return $male;
    }else {

        //выполняется сравнение последней буквы имени и определения пола
        switch ($pop) {
            case 'б':
                return $male;
                break;
            case 'в':
                return $male;
                break;
            case 'г':
                return $male;
                break;
            case 'д':
                return $male;
                break;
            case 'ж':
                return $male;
                break;
            case 'з':
                return $male;
                break;
            case 'й':
                return $male;
                break;
            case 'к':
                return $male;
                break;
            case 'л':
                return $male;
                break;
            case 'м':
                return $male;
                break;
            case 'н':
                return $male;
                break;
            case 'п':
                return $male;
                break;
            case 'р':
                return $male;
                break;
            case 'с':
                return $male;
                break;
            case 'т':
                return $male;
                break;
            case 'ф':
                return $male;
                break;
            case 'х':
                return $male;
                break;
            case 'ц':
                return $male;
                break;
            case 'ч':
                return $male;
                break;
            case 'ш':
                return $male;
                break;
            case 'щ':
                return $male;
                break;
            case 'а':
                return $female;
                break;
            case 'я':
                return $female;
                break;
            case 'ь':
                return $female;
                break;

            default:
                return null;

        }
    }
}

// Тестируем функцию
 assert( null == SN('Анэ'));
 assert( ' пол мужской' == SN('Илья'));
 assert( ' пол мужской' == SN('Сергей'));
 assert( ' пол мужской' == SN('Василий'));
 assert( ' пол женский' == SN('Дарья'));
 assert( ' пол женский' == SN('Мария'));
 assert( ' пол мужской' == SN('Иван'));
 assert( ' пол женский' == SN('Ассоль'));
 assert( ' пол женский' == SN('Любовь'));

languages: Text PHP

repo_language: Text


text:
<repo_name>Sam-Weiner/Module_13<file_sep>/README.md
# Venture Capital Opportunities with Deep Neural Networks

## Summary
This is a project to assess funding applications from startups to see if success could be predicted.
Preprocessing necessitated OneHotEncoding to make all the variables usable by the neural network.
The model was tweaked to try and increase the accuracy metrics.
The trained models are then saved as h5 files.

## Preprocessing

Preprocessing is an important facet of machine learning with neural networks.

One Hot Encoding creates additional columns in the testing and training data corresponding to data not represented by integers or floats.
All the data needs to be numeric in order for machine learning to be able to use the data.

branch_name: refs/heads/main

repo_language: Markdown


text:
<file_sep>from django.apps import AppConfig

class LogoConfig(AppConfig):
    name = 'logo'
<file_sep>web: gunicorn calibre.wsgi --log-file -

branch_name: refs/heads/master

languages: Procfile Python

repo_language: Procfile

repo_name: Jerryraoul/calibre


text:
<repo_name>kintesh/slides<file_sep>/README.md
# slides [![Build Status](https://travis-ci.org/kintesh/slides.svg?branch=master)](https://travis-ci.org/kintesh/slides)
A tool to make and present HTML5 slides. Supports mathematical equations using MathJax.

This module provides CLI for making slides. A GUI app can be found here
[https://github.com/kintesh/slides-app] (https://github.com/kintesh/slides-app)

# Demo
Check out sample slides produced by this app [over here.](https://slides.kinte.sh/sample.html)

#Installation

This tool requires Node.js. Download and install latest version of Node.js for your platform from
[nodejs.org] (https://nodejs.org/download/)

Run the following command to install latest version of slides.

    $ npm install -g https://github.com/kintesh/slides/tarball/master

Note: You may need to run this command with sudo (i.e. `$ sudo npm install -g https://github.com/kintesh/slides/tarball/master`).

#Usage

Default output for offline presentation:

    $ slides /path/to/source

Single file output for online presentation (requires internet connection when presenting):

    $ slides -o /path/to/source

#Writing slides

Slides uses markdown at its core to render HTML with few additional formatting.

##Comments

Comments are written between `/*` and `*/` tags. The comments will be removed when translating the slides and will not be included in the produced slides.

##Properties

The properties are used for generating title slide and setting up meta tags of the output HTML file. Therefore it is recommended to specify all properties when writing slides. The properties must be defined at top of a document and fore the first slide.
The following properties are available:

    title:      sets slides title
    sub_title:  sets slides subtitle/topic
    author:     author
    date:       date

##Title slide

The title slides is automatically generated based on the specified properties.

##Slide
Each slide must begin with `====` (four equals symbols) and also end with `====` (four equals symbols). Any content between these tags will be put under one slide.

    ====

    slide contents goes here...

    ====

##Styling slides
The default css style of any slide can be overridden. To do this, place any css styles between `[[` and `]]` tags. The properties tag must go immediately after the begin slide tag `====`. For example:

    ====
    [[background-color:aquamarine; color:black]]

    slide contents.....

    ====

##Paragraphs

Writing paragraphs does not require any syntax. Paragraphs are written simply writing one or more consecutive lines of text.

    ====

    Writing paragraphs does not require any syntax. Paragraphs are
    written simply writing one or more consecutive lines of text.

    This is a 2nd paragraph.
    ====

##Headers
HTML headers 1 to 6 are written using hash characters at the start of the line. The number of hash characters represents the header level.

    ====

    # H1 header
    ## H2 header
    ### H3 header
    #### H4 header
    ##### H5 header
    ###### H6 header

    ====

##Text formatting and alignment

The following text formatting are provided using various tags.

  * \*Italic text\* results in *Italic text*
  * \*\*bold text\*\* results in **bold text**
  * \`monospace text\` results in `monospace text`
  * -> align center  <- results the text being aligned to the center of a slide

##Escape tags

When writing slides, use `\\` followed a tag to escape it. For example \\\`foo\\\`, \\\*bar\\\* results in \`foo\`, \*bar\*

##Blockquotes

Blockquotes are written using right angle character `>`.

    ====
    > Block quotes are
    > written like so.
    >
    > They can span multiple paragraphs,
    > if you like.
    ====

##Lists

Lists are written using asterisks or numbers. Note that (not considering the asterisk) the actual text content starts at 4-columns in.

    ====
    Itemized lists look like:
    [[reveal:true]]
      * this one
      * that one
      * the other one

    Here's a numbered list:
    [[reveal:true]]
     1. first item
     2. second item
     3. third item
    ====

##Writing maths

Slides supports rendering math equations both inline and block. Inline maths should be written between `\$` and `\$` tags. Block maths should be written between  `\$\$` and `\$\$` tags.

    ====
    [[background-color:cadetblue; color:black]]
    # ->Mass–energy equivalence<-

    The equivalence of energy $E$ and mass $m$ is reliant on the speed
    of light $c$ and is described by the famous equation:

    $$ E = mc^2 $$

    ====

##Content properties

Similar to styling slides, properties of its content can also be set and/or overridden. Again the properties must go between `[[` and `]]` tags. Unlike styling slides, the content property must go before the content.

Besides standard css styles, slides provides following custom properties:

    property : value
    ---------------------------------------
    reveal   : true | false
    anim     : dropDown | slideInLeft

##Code Blocks

Pre-formatted code blocks are written by indenting every line of the block by at least 4 spaces or 1 tab.

     ====
     Soup algorithm:
         find wooden spoon
         uncover pot
         stir
         cover pot
         balance wooden spoon precariously on pot handle
         wait 10 minutes
         goto first step (or shut off burner when done)
    Do not bump wooden spoon or it will fall.
    ====

##Links

Links are written like so:

    ====
    This project can be found on [Github](https://github.com/kintesh/slides).

    [<NAME>](https://kinte.sh).
    ====

##Images

Images are inserted like so:

    ====
    ![Alt text](/path/to/img.jpg)
    ![Alt text](/path/to/img.jpg "Optional title")
    ====

##Tables

Tables are written by formatting it as shown below.

    ====
    # Table

    |size | material   |  color
    |---- | ---------- | -----------
    |9    |leather     |  brown
    |10   |hemp canvas |  natural
    |11   |glass       |  transparent

    # Advanced table
    |keyword  | text
    |-------- | -----------------------
    |red      | Sunsets, apples, and
    |         | other red or reddish
    |         | things.
    |green    | Leaves, grass, frogs
    |         | and other things it's
    |         | not easy being.

    ====

#Presenting slides

When presenting use following keyboard shortcuts to interact with slides:

    key                     | result
    ------------------------------------------------------
    Arrow Left, Arrow Down  | Next slide
    Arrow Right, Arrow UP   | Previous slide
    F, f, Return/Enter      | Toggle full screen
    C, c                    | Open presentation console
    H, h                    | Show help menu

#Example

    /*
     * Created by kintesh on 28/01/15.
     */

    title: Sample Slides
    sub_title: Sample slides showing various features.
    author: Kintesh
    date: 28/01/2015

    /* slide 1 */
    ====
    # ->Headers<-

    # H1 header
    [[color:red]]
    ## H2 header
    [[reveal:true; color:red; anim:dropDown]]
    ### H3 header
    [[reveal:true; color:coral; anim:slideInLeft]]
    #### H4 header
    [[reveal:true]]
    ##### H5 header
    [[reveal:true]]
    ###### H6 header
    ====

    /* slide 2 */
    ====
    [[background-color:cadetblue; color:black]]
    # ->Text<-

    Paragraphs are separated by a blank line.

    This is the 2nd paragraph. Text styles *Italic*, **bold**, `monospace` and ~~Strikethrough~~.

    And note that you can backslash-escape any punctuation characters
    which you wish to be displayed literally, ex.: \`foo\`, \*bar\*, etc.

    > Block quotes are
    > written like so.
    >
    > They can span multiple paragraphs,
    > if you like.
    ====

    /* slide 3 */
    ====
    [[background-color:indianred; color:black]]
    # ->Lists<-

    Itemized lists look like:
    [[reveal:true]]
      * this one
      * that one
      * the other one

    Here's a numbered list:
    [[reveal:true]]
     1. first item
     2. second item
     3. third item

    Note: that --- not considering the asterisk --- the actual text content starts at 4-columns in.
    ====

    /* slide 4 */
    ====
    [[background-color:indianred; color:black]]
    # ->Lists (2)<-

    Now a nested list:
    [[reveal:true; anim:slideInLeft]]
     1. First, get these ingredients:

          * carrots
          * celery
          * lentils

     2. Boil some water.

     3. Dump everything in the pot and follow
        this algorithm:

            find wooden spoon
            uncover pot
            stir
            cover pot
            balance wooden spoon precariously on pot handle
            wait 10 minutes
            goto first step (or shut off burner when done)

        Do not bump wooden spoon or it will fall.

    Notice again how text always lines up on 4-space indents (including
    that last line which continues item 3 above).
    ====

    /* slide 5 */
    ====
    # ->Tables<-

    Tables can look like this:

    |size | material   |  color
    |---- | ---------- | -----------
    |9    |leather     |  brown
    |10   |hemp canvas |  natural
    |11   |glass       |  transparent

    Table: Shoes, their sizes, and what they're made of

    (The above is the caption for the table.) Pandoc also supports
    multi-line tables:

    |keyword  | text
    |-------- | -----------------------
    |red      | Sunsets, apples, and
    |         | other red or reddish
    |         | things.
    |green    | Leaves, grass, frogs
    |         | and other things it's
    |         | not easy being.
    ====

    /* slide 6 */
    ====
    # ->Maths<-

    Inline math equations go in like so: $ \omega = d\phi / dt $. Display
    math should get its own line and be put in in double-dollarsigns:

    Maxwell's equations:
    $$ \nabla \cdot \vec{E} = \frac{\rho}{\epsilon_0} $$
    $$ \nabla \cdot \vec{B} = 0 \nonumber $$
    $$ \nabla \times \vec{E} = - \frac{\partial B}{\partial t} \nonumber $$
    $$ \nabla \times \vec{B} = \mu_{0}\vec{J} + \mu_{0}\epsilon_{0}\frac{\partial E}{\partial t} $$

    And note that you can backslash-escape any punctuation characters
    which you wish to be displayed literally, ex.: \`foo\`, \*bar\*, etc.

    [[reveal:true]]
      * $ E = mc^2 $
      * $ \cos (2\theta) = \cos^2 \theta - \sin^2 \theta $
      * $ c = \pm\sqrt{a^2 + b^2} $
      * the other one
    ====

    /* slide 7 */
    ====
    # -> Image <-

    The Claws of the Dragon, Senja, Norway.

    [[reveal:true; anim:slideInLeft; width:75%]]
    ![Alt text](http://35photo.ru/photos_series/574/574181.jpg)

    [Open in maps](https://www.google.com/maps/place/Devil%27s+Jaw,+Berg,+Norway/@69.528935,17.3400671,5584a,20y,180h,40.7t/data=!3m1!1e3!4m2!3m1!1s0x45dcabd272fb1e17:0x864a1f90f2fc2f90)
    ====

#Licence

Copyright 2015 <NAME>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.<file_sep>/lib/slides.js
/**
 * Created by kintesh on 28/01/15.
 */
;(function(){
    var constants = require("./constants"),
        translator = require("./translator"),
        async = require("async");

    function slides(source, callback) {
        async.waterfall([
            function(callback) {
                translator(source, callback)
            }
        ], function(err, res) {
            if(err == null) {
                res.offline = constants.temp_html(constants.temp_offline(res.properties),res.html);
                res.online = constants.temp_html(constants.temp_online(res.properties),res.html);
            }
            callback(err, res);
        });
    }

    module.exports = slides;

})();<file_sep>/lib/constants.js
/**
 * Created by kintesh on 28/01/15.
 */
;(function(){

    /**
     * Basic constants
     * @type {string}
     */
    exports.frame_separator = "====";
    exports.math_type_inline = 0;
    exports.math_type_block = 1;
    exports.math_marker = function(number) {
        return "%{MATH"+number+"}";
    };
    exports.math_replace = "%{MATH}";

    /**
     * Regular expressions.
     */
    exports.regex_comments = /(\/\*([^*]|[\r\n]|(\*+([^\*/]|[\r\n])))*\*+\/)/g;
    exports.regex_lines = /\r\n|\r|\n/m;
    exports.regex_properties = /([\w]+):\s*(.*)\s*/m;
    exports.regex_frame = /={4}[^=]((?:[^=\\]|\\.|={0,3}[^=])*)={4}/g;
    exports.regex_maths = /(\$(?!\$)((?:[^$\\]|\\.)*)\$(?!\$))|(\$\$((?:[^\$\\]|\\.)*)\$\$)/g;
    exports.regex_frameProperties = /^\[\[([\w\d %#;:,-]+)]]/m;
    exports.regex_controlElemBlock = /\[\[([\w\d %#;:,-]+)]]/g;
    exports.regex_controlElemProp = /\s*([\w-]+)\s*:\s*([\w\d#%-]+)\s*/g;
    exports.regex_controlElemClass = /class="controlElem"/g;
    exports.regex_alignCenter = /(?:->)([\S\s]*)(?:<-)/m;

    /**
     * HTML Templates.
     */
    exports.temp_html = function(head, body) {
        return "<!DOCTYPE html>\n\n\n"+head+"\n\n\n"+body+"\n";
    };
    exports.temp_offline = function(properties) {
        return this.temp_meta(properties) +
            "<link rel=\"stylesheet\" href=\"./slides_assets/css/fonts.css\">\n" +
            "<link rel=\"stylesheet\" href=\"./slides_assets/css/slides.css\">\n" +
            "<link rel=\"stylesheet\" href=\"./slides_assets/css/slides-print.css\" media=\"print\"/>\n" +
            "<link rel=\"stylesheet\" href=\"./slides_assets/css/style.css\"/>\n" +
            "<link rel=\"stylesheet\" href=\"./slides_assets/css/animations.css\"/>\n" +
            "<link rel=\"stylesheet\" href=\"./slides_assets/css/font-awesome.css\">\n" +
            "\n" +
            "\n" +
            "\n";
    };
    exports.temp_online = function(properties) {
        return this.temp_meta(properties) +
            "<link rel=\"stylesheet\" href=\"https://slides.kinte.sh/slides_assets/css/fonts.css\">\n" +
            "<link rel=\"stylesheet\" href=\"https://slides.kinte.sh/slides_assets/css/slides.css\">\n" +
            "<link rel=\"stylesheet\" href=\"https://slides.kinte.sh/slides_assets/css/slides-print.css\" media=\"print\"/>\n" +
            "<link rel=\"stylesheet\" href=\"https://slides.kinte.sh/slides_assets/css/style.css\"/>\n" +
            "<link rel=\"stylesheet\" href=\"https://slides.kinte.sh/slides_assets/css/animations.css\"/>\n" +
            "<link rel=\"stylesheet\" href=\"https://slides.kinte.sh/slides_assets/css/font-awesome.css\">\n" +
            "\n" +
            "\n" +
            "\n";
    };
    exports.temp_meta = function(properties) {
        return (properties["title"] != undefined ? "<title>" + properties["title"] + "</title>\n" : "<title>Slides</title>\n") +
            ("<meta charset=\"UTF-8\">\n") +
            (properties["sub_title"] != undefined ? "<meta name=\"description\" content=\""+properties["sub_title"]+"\">\n" : "") +
            (properties["author"] != undefined ? "<meta name=\"author\" content=\""+properties["author"]+"\">\n" : "");
    };
    exports.temp_controlElem = function(props) {
        return "
"+props+"
";
    };
    exports.temp_slide = function(content, frameProps) {
        if(frameProps != undefined) {
            return "
\n"+content+"\n
\n";
        } else {
            return "
\n" + content + "\n
\n";
        }
    };
    exports.temp_title = function(title) {
        return "

"+title+"

";
    };
    exports.temp_subTitle = function(subTitle) {
        return "

"+subTitle+"

";
    };
    exports.temp_author = function(author) {
        return "
"+author+"
";
    };
    exports.temp_date = function(date) {
        return "
"+date+"
";
    };
    exports.temp_inlineMath = function(math) {
        return "\\("+math+"\\)";
    };
    exports.temp_blockMath = function(math) {
        return "
\\("+math+"\\)
";
    };
    exports.tmp_alignMiddle = function(content) {
        return "
<divc class=\"middle_container\">\n" + content + "\n

\n";
    };

    /**
     * Make all properties constant
     */
    (function() {
        Object.getOwnPropertyNames(exports).map(function(name) {
            var descriptor = Object.getOwnPropertyDescriptor(exports, name);
            descriptor.writable = false;
            descriptor.configurable = false;
            Object.defineProperty(exports, name, descriptor);
        });
    }).call();

})();<file_sep>/index.js
/**
 * Created by kintesh on 28/01/15.
 */
module.exports = require('./lib/slides');<file_sep>/bin/slides
#!/usr/bin/env node
/**
 * Created by kintesh on 08/02/15.
 */

if (!module.parent) {
    process.title = "slides";
    main(process.argv.slice(), function(err, code) {
        if (err) throw err;
        return process.exit(code || 0);
    });
} else {
    module.exports = main;
}

function main(argv) {

    var program = require("commander"),
        slides = require("../"),
        path = require("path"),
        fs = require("fs"),
        fsx = require("fs-extra"),
        async = require("async");

    program
        .version("1.0.0")
        .usage("[options] [source file]")
        .option("-o, --online", "Single file output for online presentation " +
                "(requires internet connection during presentation)")
        .option("-v, --verbose", "Print verbose output on console")
        .parse(process.argv);

    if(argv.length <= 2) {
        return program.help();
    } else {
        var pwd = process.cwd(),
            inFile = path.join(pwd, argv[argv.length-1]),
            outFile = path.join(pwd, "slides_"+argv[argv.length-1]+".html"),
            assetsDir = path.join(path.dirname(__dirname), "assets"),
            source,
            output,
            startTime = Date.now();

        async.waterfall([
            function(callback) {
                if (program.verbose) console.log("Reading file from: " + inFile);
                fs.readFile(inFile, "utf8", callback);
            },
            function(data, callback) {
                if (program.verbose) console.log("Making slides...");
                slides(data, callback);
            },
            function(result, callback) {
                if (program.verbose) console.log("Saving to : " + outFile);
                if(program.online) {
                    fs.writeFile(outFile, result.online, "utf8", callback);
                } else {
                    fs.writeFile(outFile, result.offline, "utf8", callback);
                }
            },
            function(callback) {
                if(!program.online) {
                    if (program.verbose) console.log("Assets copied to : " + path.join(pwd, "slides_assets"));
                    fsx.copy(assetsDir, path.join(pwd, "slides_assets"), callback);
                } else {
                    callback();
                }
            }
        ], function(err) {
            if(err == null) {
                if (program.verbose) console.log("DONE! " + (Date.now() - startTime) +"ms");
            }
        });
    }
}

languages: Markdown JavaScript

repo_name: kintesh/slides


text:
<repo_name>esanchezm/xmpp-muc-bot<file_sep>/poll.py
#!/usr/bin/env python
import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

def init_database():
        db = sqlite3.connect("polls.db")
        db.cursor().execute("CREATE TABLE IF NOT EXISTS polls (id INTEGER PRIMARY KEY, question TEXT, status INT DEFAULT 1, author TEXT, UNIQUE(question))")
        db.cursor().execute("CREATE TABLE IF NOT EXISTS votes ( id INTEGER PRIMARY KEY, voter TEXT DEFAULT NULL, vote INTEGER, msg TEXT DEFAULT NULL, poll_id INTEGER, FOREIGN KEY(poll_id) REFERENCES polls(id), UNIQUE(voter, poll_id))")
        db.close()

class PollFactory:
    @staticmethod
    def get_db():
        """Get a db connection. Caller MUST close it"""
        pollsdb = sqlite3.connect("polls.db")
        pollsdb.row_factory = dict_factory
        return pollsdb

    @staticmethod
    def get_active_poll():
        """Get the current active poll"""
        pollsdb = PollFactory.get_db()
        c = pollsdb.cursor()
        c.execute("SELECT id FROM polls WHERE status = 1 LIMIT 1")
        row = c.fetchone()
        c.close()
        pollsdb.close()
        if row is None:
            poll = None
        else:
            poll = Poll(row["id"])
        return poll

    @staticmethod
    def get_poll(poll_id):
        """Get a poll by using a poll id"""
        pollsdb = PollFactory.get_db()
        c = pollsdb.cursor()
        try:
            c.execute("SELECT id FROM polls WHERE id = ? LIMIT 1", (str(int(poll_id))))
        except ValueError, e:
            c.close()
            pollsdb.close()
            raise PollException('Invalid poll id: '+poll_id)
        row = c.fetchone()
        c.close()
        pollsdb.close()
        poll = Poll(row['id'])
        return poll

    @staticmethod
    def get_polls():
        """Get all the polls"""
        pollsdb = PollFactory.get_db()
        c = pollsdb.cursor()
        c.execute("SELECT id FROM polls WHERE status = 0 ORDER BY id")
        rows = c.fetchall()
        c.close()
        pollsdb.close()
        polls = []
        for row in rows:
            poll = Poll(row['id'])
            polls.append(poll)
        return polls

class BaseTable(object):
    def __init__(self, table):
        self.table = str(table)
        self.pollsdb = PollFactory.get_db()

    def __del__(self):
        self.pollsdb.close()

    def __fetch(self, instance_id):
        c = self.pollsdb.cursor()
        c.execute("SELECT * FROM "+self.table+" WHERE id = ? LIMIT 1", (str(instance_id)))
        row = c.fetchone()
        self.__init_attrs(row)
        c.close()

    def __init_attrs(self, attrs):
        for field in self.__dict__.iteritems():
            if field[1] is None:
                try:
                    self.__dict__[field[0]] = attrs[field[0]]
                except TypeError:
                    pass

class Poll(BaseTable):

    def __init__(self, poll_id = None):
        self.id       = None
        self.question = None
        self.author   = None
        self.status   = None
        super(Poll, self).__init__('polls')
        if poll_id is not None:
            self._BaseTable__fetch(poll_id)

    def new(self, question, author):
        """Creates a new poll"""
        attrs = {}
        attrs["question"] = question
        attrs["author"]   = author
        self.__create_poll(attrs)

    def __create_poll(self, attrs):
        c = self.pollsdb.cursor()
        try:
            c.execute("INSERT INTO polls (question, status, author) VALUES(?, 1, ?)",\
                      (attrs["question"], attrs["author"]))
        except sqlite3.IntegrityError:
            self.pollsdb.rollback()
            c.close()
            raise PollException('Duplicated poll')
        self.pollsdb.commit()
        poll_id = c.lastrowid
        c.close()
        self._BaseTable__fetch(poll_id)

    def close(self):
        """Close the poll"""
        c = self.pollsdb.cursor()
        c.execute("UPDATE polls SET status = 0 WHERE id = ?",\
                  (str(self.id)))
        self.pollsdb.commit()
        c.close()
        self.status = 0

    def vote(self, voter, vote_value, msg = None):
        """Vote"""
        vote = VoteFactory.new_vote(self.id)
        vote.new(voter, vote_value, msg)

    def get_votes(self):
        """Get all the votes on a poll"""
        c = VoteFactory.get_db().cursor()

        c.execute("SELECT id FROM votes WHERE poll_id = ?", (str(self.id)))
        rows = c.fetchall()
        votes = []
        for row in rows:
            vote = Vote(self.id, row['id'])
            votes.append(vote)
        c.close()
        return votes

class VoteFactory:
    @staticmethod
    def get_db():
        """Get a db connection. Caller MUST close it"""
        pollsdb = sqlite3.connect("polls.db")
        pollsdb.row_factory = dict_factory
        pollsdb.cursor().execute("CREATE TABLE IF NOT EXISTS votes ( id INTEGER PRIMARY KEY, voter TEXT DEFAULT NULL, vote INTEGER, msg TEXT DEFAULT NULL, poll_id INTEGER, FOREIGN KEY(poll_id) REFERENCES polls(id), UNIQUE(voter, poll_id))")
        return pollsdb

    @staticmethod
    def new_vote(poll_id):
        """Creates a new vote on a poll"""
        return Vote(poll_id, None)

class Vote(BaseTable):
    def __init__(self, poll_id, vote_id = None):
        self.id      = None
        self.voter   = None
        self.vote    = None
        self.msg     = None
        self.poll_id = poll_id
        super(Vote, self).__init__('votes')
        if vote_id is not None:
            self._BaseTable__fetch(vote_id)

    def __str__(self):
        if self.vote is None:
            return "undefined"
        if self.vote == 0:
            return "no"
        if self.vote == 1:
            return "yes"

        return "WTF!" # Should not happen...

    def new(self, author, vote, msg = None):
        """Creates a new vote"""
        attrs = {}
        attrs["poll_id"] = self.poll_id
        attrs["voter"]   = author
        attrs["vote"]    = vote
        attrs["msg"]     = msg
        self.__create_vote(attrs)

    def __create_vote(self, attrs):
        c = self.pollsdb.cursor()
        try:
            c.execute("INSERT INTO votes (voter, vote, msg, poll_id) VALUES(?, ?, ?, ?)",\
                      (attrs["voter"], attrs["vote"], attrs["msg"], attrs["poll_id"]))
        except sqlite3.IntegrityError, e:
            self.pollsdb.rollback()
            c.close()
            raise PollException('Duplicated vote')
        self.pollsdb.commit()
        vote_id = c.lastrowid
        c.close()
        self._BaseTable__fetch(vote_id)

class PollException(Exception):
    """Poll exception class"""
    pass
<file_sep>/start.sh
cd /home/punchagan/childrens-park/
if [ `ps -ef|grep chatroom|grep -v grep|wc -l` -lt 1 ]; then
    echo "Bot not running, Starting ..."
    /usr/bin/nohup ./vir-santa/bin/python chatroom.py >> /home/punchagan/childrens-park/nohup.out &
elif [ `tail -1 nohup.out|grep -c -E "(WARNING - could not connect to server - aborting)|(Disconnected from server)"` -gt 0 ]; then
    pid=`ps -ef|grep chatroom|head -1|tr -s " "|cut -d " " -f 2`
    echo "killing bot:" $pid
    kill -9 $pid
    sleep 60
    /usr/bin/nohup ./vir-santa/bin/python chatroom.py >> /home/punchagan/childrens-park/nohup.out &
else
    echo "Bot running..." > /dev/null
fi
<file_sep>/README.org
* Description
  This is a Jabber/Gtalk bot written using the python-jabberbot
  library.  This bot is written to behave like a chatroom, where all
  the messages are sent to all the subscribed users.

* Usage

  + Depends: python-jabberbot, xmpppy

  + You are required to have a file settings.py with the variables, JID,
    PASSWORD, CHANNEL, RES

  + To add new users, the admin can either add them manually to a USERS
    dict in a state.py file, or they can be invited and then added.

* Bugs/Issues

  + *Known Issue*: Google doesn't allow sending and receiving more than
    50 messages in a period of 12.5 seconds.  This is a big problem if
    you have even three or four members in the channel.  Use jabber.org
    for hosting the bot, instead.

  + Report other bugs/issues at [[https://github.com/punchagan/childrens-park/issues][GitHub]]

* TO-DO/Ideas
  1. Private Messaging
     For instance, @ringo blah blah, should be shown only to ringo,
     nobody else.

  2. Translation
     te2hi or te2en bot for translation help

  3. Reminders
     For instance -- ,setreminder 2011/04/15 20:00 Priya's
     Treat This should keep reminding at pre-set intervals before the
     event.

  4. Score bot
     We should be able to keep track of scores for various objects,
     using object-name++ and object-name--

  5. Replace regex
     s/old_word/new_word should do the replacements
<file_sep>/chatroom.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# A portion of this code is from the code of JabberBot copyrighted by
# <NAME> the copyright of which is included below.
# JabberBot: A simple jabber/xmpp bot framework
#
# Copyright (c) 2007-2011 <NAME> <thp.io/about>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Commentary:
#
# This bot is written to behave like a chatroom, where all the
# messages are sent to all the users subscribed to this bot.
#
# You are required to have a file settings.py with the variables,
# JID, PASSWORD, CHANNEL, RES
#
# Depends: python-jabberbot, xmpppy
#

from jabberbot import JabberBot, botcmd

import xmpp
import collections
import threading
import time
import logging
import traceback
import codecs
from datetime import timedelta, datetime
from textwrap import dedent

import re, os, sys
import urllib2, urllib
import simplejson
from subprocess import Popen, PIPE, call

import meme
import poll
import handy

try:
    from BeautifulSoup import BeautifulSoup
    import gdata.youtube.service
except:
    print "Some features will not work, unless you have BeautifulSoup and gdata"

class ChatRoomJabberBot(JabberBot):
    """A bot based on JabberBot and broadcast example given in there."""

    def __init__( self, jid, password, res = None):
        super( ChatRoomJabberBot, self).__init__( jid, password, res)
        # create console handler
        chandler = logging.StreamHandler()
        # create formatter
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        # add formatter to handler
        chandler.setFormatter(formatter)
        # add handler to logger
        self.log.addHandler(chandler)
        # set level to INFO
        self.log.setLevel(logging.INFO)

        self.ops = {
            '++' : (re.compile(r'([a-zA-Z0-9]+)\+\+'), lambda x: x + 1, 'w00t!') ,
            '--' : (re.compile(r'([a-zA-Z0-9]+)--'), lambda x: x - 1, 'ouch!'),
            }

        try:
            from state import MINILOGMAX
            self.MINILOGMAX = int(MINILOGMAX)
        except Exception, e:
            self.log.exception(e)
            self.MINILOGMAX=5

        self.sub_expression = re.compile(r"s/([a-zA-Z0-9-_\s]+)/([a-zA-Z0-9-_\s]+)/")
        # for s/// expresions
        self.mini_log = {}
        self.users = self.get_users()
        self.invited = self.get_invited()
        self.ideas = self.get_ideas()
        self.words = self.get_words()
        poll.init_database()
        self.started = time.time()
        self.message_queue = []
        self.thread_killed = False

    def connect(self):
        if not self.conn:
            conn = xmpp.Client(self.jid.getDomain(), debug = ['always'])

            if self.jid.getDomain() == 'gmail.com':
                conres = conn.connect(server=('talk.google.com', 5222))
            else:
                conres = conn.connect()

            if not conres:
                self.log.error('unable to connect to server %s.' % self.jid.getDomain())
                return None
            if conres<>'tls':
                self.log.warning('unable to establish secure connection - TLS failed!')
            else:
                self.log.info('Connected to server')

            authres = conn.auth(self.jid.getNode(), self._JabberBot__password, self.res)
            if not authres:
                self.log.error('unable to authorize with server.')
                self.attempt_reconnect()

            if authres<>'sasl':
                self.log.warning("unable to perform SASL auth os %s. Old authentication method used!" % self.jid.getDomain())

            conn.sendInitPresence()
            self.conn = conn
            self.roster = self.conn.Roster.getRoster()
            self.log.info('*** roster ***')
            for contact in self.roster.getItems():
                self.log.info('  %s' % contact)
            self.log.info('*** roster ***')
            self.conn.RegisterHandler('message', self.callback_message)
            self.conn.RegisterDisconnectHandler(self.attempt_reconnect)
            self.conn.UnregisterDisconnectHandler(conn.DisconnectHandler)
            self._JabberBot__set_status(self.get_topic())

        return self.conn

    def save_state(self):
        f = open('state.py', 'w')
        f.write('# -*- coding: utf-8 -*-\n\n')
        f.write('MINILOGMAX = %d\n\n' % self.MINILOGMAX)
        self.save_users(f)
        self.save_invited(f)
        self.save_topic(f)
        self.save_ideas(f)
        self.save_words(f)
        f.close()

    def get_users(self):
        try:
            from state import USERS
            users = USERS
            for user in users:
                users[user] = users[user].decode('utf-8')
            self.log.info("Obtained user data")
        except:
            users = {}
            self.log.info("No existing user data")
        return users

    def save_users(self, file):
        try:
            file.write('USERS = {\n')
            for u in self.users:
                file.write("'%s': '%s',\n"
                           %(u.encode('utf-8'),
                             self.users[u].encode('utf-8')))
            file.write('}\n\n')
            self.log.info("Saved user data")
        except:
            self.log.info("Couldn't save user data")

    def get_words(self):
        try:
            from state import WORDS
            words = WORDS
            for word in words:
                words[word] = int(words[word])
            self.log.info("Obtained word")
        except:
            words = {}
            self.log.info("No existing words")
        return words

    def save_words(self, file):
        try:
            file.write('WORDS = {\n')
            for word in self.words:
                file.write("'%s': '%d',\n"
                           %(word.encode('utf-8'),
                             int(self.words[word])))
            file.write('}\n\n')
            self.log.info("Saved words")
        except:
            self.log.info("Couldn't save words")

    def get_invited(self):
        try:
            from state import INVITED
            invited = INVITED
            for user in invited:
                invited[user] = invited[user].decode('utf-8')
            self.log.info("Obtained invited user data")
        except:
            invited = {}
            self.log.info("No existing invited users")
        return invited

    def save_invited(self, file):
        try:
            file.write('INVITED = {\n')
            for u in self.invited:
                file.write("'%s': '%s',\n" %(u, self.invited[u].encode('utf-8')))
            file.write('}\n\n')
            self.log.info("Saved invited user data")
        except:
            self.log.info("Couldn't save invited user data")

    def get_topic(self):
        try:
            from state import TOPIC
            TOPIC = TOPIC.decode('utf-8')
            return TOPIC
        except:
            return ''

    def save_topic(self, file):
        try:
            file.write('TOPIC = """%s"""\n\n' %(self._JabberBot__status.encode('utf-8')))
        except:
            return ''

    def get_ideas(self):
        try:
            from state import IDEAS
            ideas = [idea.decode('utf-8') for idea in IDEAS]
        except:
            ideas = []
        return ideas

    def save_ideas(self, file):
        try:
            file.write('IDEAS = [\n')
            for u in self.ideas:
                file.write('"""%s""",\n' % (u.encode('utf-8')))
            file.write(']\n\n')
        except:
            self.log.info("Couldn't save ideas")

    def shutdown(self):
        self.save_state()

    def attempt_reconnect(self):
        self.log.info('Restarting...')
        self.log.info('Pulling changes from GitHub...')
        call(["git", "pull"])
        os.execl('/usr/bin/nohup', sys.executable, sys.executable,
                 os.path.abspath(__file__))

    def get_sender_username(self, mess):
        """Extract the sender's user name (along with domain) from a message."""
        jid = mess.getFrom()
        typ = mess.getType()
        username = jid.getNode()
        domain = jid.getDomain()
        if typ == "chat":
            return "%s@%s" %(username, domain)
        else:
            return ""

    def unknown_command(self, mess, cmd, args):
        user = self.get_sender_username(mess)
        if user in self.users:
            self.message_queue.append('[%s]: %s %s' % (self.users[user], cmd, args))
            self.log.info("%s sent: %s %s" %(user, cmd, args))
        return ''

    def callback_message( self, conn, mess):
        """Messages sent to the bot will arrive here. Command handling + routing is done in this function."""

        jid      = mess.getFrom()
        props    = mess.getProperties()
        text     = mess.getBody()
        username = self.get_sender_username(mess)

        if username not in self.users.keys() + self.invited.keys():
            self.log.info("Ignored message from %s." % username)
            return

        self.log.debug("*** props = %s" % props)
        self.log.debug("*** jid = %s" % jid)
        self.log.debug("*** username = %s" % username)
        self.log.debug("*** type = %s" % type)
        self.log.debug("*** text = %s" % text)

        # Ignore messages from before we joined
        if xmpp.NS_DELAY in props: return

        # If a message format is not supported (eg. encrypted), txt will be None
        if not text: return

        # Remember the last-talked-in thread for replies
        self._JabberBot__threads[jid] = mess.getThread()

        if ' ' in text:
            command, args = text.split(' ', 1)
        else:
            command, args = text, ''
        cmd = command
        self.log.debug("*** cmd = %s" % cmd)

        # parse operators, commands, etc and if not, dump the message to the chat
        if self.apply_operator(mess, args):
            return

        if self.replace_text(username, mess):
            return

        if self.commands.has_key(cmd) and cmd != 'help':
            try:
                reply = self.commands[cmd](mess, args)
            except Exception, e:
                reply = traceback.format_exc(e)
                self.log.exception('An error happened while processing a message ("%s") from %s: %s"' % (text, jid, reply))
        else:
            # In private chat, it's okay for the bot to always respond.
            # In group chat, the bot should silently ignore commands it
            # doesn't understand or aren't handled by unknown_command().
            default_reply = 'Unknown command: "%s". Type "help" for available commands.<b>blubb!</b>' % cmd
            if type == "groupchat": default_reply = None
            reply = self.unknown_command( mess, cmd, args)
            if reply is None:
                reply = default_reply

        if reply:
            self.send_simple_reply(mess,reply)

        self.log_to_mini_log(username, text)

    def log_to_mini_log(self, username, text):
        # mini_log for s///
        mini_log = None
        try:
            mini_log = self.mini_log[username]
        except KeyError:
            try:
                mini_log = collections.deque([],self.MINILOGMAX)
            except TypeError:
                mini_log = collections.deque()
            self.mini_log[username] = mini_log
        mini_log.append(text)
        self.log.info("mini_log: %s" % (mini_log))

    def replace_text(self, username, mess):
        text = mess.getBody()
        if not self.sub_expression.match(text):
            return False

        match = self.sub_expression.match(text).group(1)
        replace = self.sub_expression.match(text).group(2)
        try:
        	mini_log = self.mini_log[username]
        	for phrase in mini_log:
        	    if match in phrase:
        	        new_phrase = phrase.replace(match,replace)
        	        self.message_queue.append('_%s meant %s_' %(self.users[username], new_phrase))
                        self.mini_log[username].append(new_phrase)
                        return True
        except KeyError:
            # no mini_log, we create it on the 1st phrase
            pass
        # nothing found, inform
        reply = "No message found that matches that pattern."
        self.send_simple_reply(mess,reply)
        return True

    @botcmd(name=',restart')
    def restart(self, mess, args):
        """Restart the bot. Use resource name as PASSWORD.

        To avoid accidental restarts, resource name is used as argument.
        """
        user = self.get_sender_username(mess)

        if user in self.users and args.strip() == self.res:
            self.message_queue.append('_%s restarted me! brb!_'
                                       %(self.users[user]))
            self.log.info( '%s is restarting me.' % user)
            self.shutdown()
            self.idle_proc()
            self.conn.sendPresence(typ='unavailable')
            self.attempt_reconnect()

    @botcmd(name=',subscribe')
    def subscribe( self, mess, args):
        """Subscribe to the broadcast list"""
        user = self.get_sender_username(mess)
        if user in self.users:
            return 'You are already subscribed.'
        else:
            self.users[user] = user
            self.invited.pop(user)
            self.message_queue.append('_%s has joined the channel_' % user)
            self.log.info('%s subscribed to the broadcast.' % user)
            self.save_state()
            return 'You are now subscribed.'

    @botcmd(name=',unsubscribe')
    def unsubscribe( self, mess, args):
        """Unsubscribe from the broadcast list"""
        user = self.get_sender_username(mess)
        if not user in self.users:
            return 'You are not subscribed!'
        else:
            user = self.users.pop(user)
            self.message_queue.append('_%s has left the channel_' % user)
            self.log.info( '%s unsubscribed from the broadcast.' % user)
            self.save_state()
            return 'You are now unsubscribed.'

    @botcmd(name=',alias')
    def alias( self, mess, args):
        """Change your nick"""
        user = self.get_sender_username(mess)
        args = args.strip().replace(' ', '_')
        if user in self.users:
            if 0 < len(args) < 24 and args not in self.users.values():
                self.message_queue.append('_%s is now known as %s_' %(self.users[user], args))
                self.users[user] = args
                self.log.info( '%s changed alias.' % user)
                self.log.info('%s' %self.users)
                self.save_state()
                return 'You are now known as %s' % args
            else:
                return 'Nick already taken, or too short/long. 1-24 chars allowed.'

    def apply_operator(self, mess, args):
        """w00ts"""
        msg = '_%s: %s [%s now at %d]_'
        user = self.get_sender_username(mess)
        text = mess.getBody()
        for op in self.ops:
            (regex, func, string) = self.ops[op]
            match = regex.match(text)
            if match is not None:
                if match.group(1) in self.words:
                    counter = self.words[match.group(1)]
                    counter = func(counter)
                    self.words[match.group(1)] = counter
                    self.message_queue.append(msg %(self.users[user], match.group(0), string, counter))
                else:
                    counter = 0
                    counter = func(counter)
                    self.words[match.group(1)] = counter
                    self.message_queue.append(msg %(self.users[user], match.group(0), string, counter))
                return True
        return False

    @botcmd(name=',topic')
    def topic( self, mess, args):
        """Change the topic/status"""
        user = self.get_sender_username(mess)
        if user in self.users:
            self._JabberBot__set_status(args)
            self.message_queue.append('_%s changed topic to %s_' %(self.users[user], args))
            self.log.info( '%s changed topic.' % user)
            self.save_state()

    @botcmd(name=',handy')
    def handy( self, mess, args):
        user = self.get_sender_username(mess)
        handy_link = args.split(' ')[0]
        if handy_link in ('help', '', None):
            keys = handy.handy_links.keys()
            return "usage: ,handy link where link is %s" % keys
        else:
            try:
                self.message_queue.append('_%s shares %s _' % (self.users[user], handy.handy_links[handy_link]))
            except:
                return 'could not find link'

    @botcmd(name=',meme')
    def meme( self, mess, args):
        """Create a meme, for the lulz"""
        user = self.get_sender_username(mess)
        if user in self.users:
            try:
                meme_id = args.split(' ')[0]
                if meme_id in ('help', '', None):
                    memes = meme.list_memes()
                    help_msg = "usage: ,meme meme 'top text' 'button text' where meme is %s" % memes
                    return help_msg

                parsed = args.split('\'')
                (top, button) = (parsed[1], parsed[3])
                meme_url = meme.create_meme(meme_id, top, button)
                self.message_queue.append('_%s created a meme %s _' %(self.users[user], meme_url))
                self.log.info( '%s created a meme, for the lulz' % user)

            except Exception:
                self.log.info( '%s tried to create a meme, but failed' % user)

    @botcmd(name=',list')
    def list( self, mess, args):
        """List all the members of the list"""
        user = self.get_sender_username(mess)
        args = args.replace(' ', '_')
        if user in self.users:
            user_list = 'All these users are subscribed - \n'
            user_list += '\n'.join(['%s :: %s' %(u, self.users[u]) for u in sorted(self.users)])
            if self.invited.keys():
                user_list += '\n The following users are invited - \n'
                user_list += '\n'.join(self.invited.keys())
            self.log.info( '%s checks list of users.' % user)
            return user_list

    @botcmd(name=',me')
    def myself(self, mess, args):
        """Send message in third person"""
        user = self.get_sender_username(mess)
        if user in self.users:
            self.message_queue.append('_%s %s_' % (self.users[user], args))
            self.log.info( '%s says %s in third person.' % (user, args))

    @botcmd(name=',invite')
    def invite(self, mess, args):
        """Invite a person to join the room. Works only if the person has added the bot as a friend, as of now."""
        user = self.get_sender_username(mess)
        if user in self.users:
            self.send(args, '%s invited you to join %s. Say ",help" to see how to join.' % (user, CHANNEL))
            self.invited['%s@%s' %(xmpp.JID(args).getNode(), xmpp.JID(args).getDomain())] = ''
            self.log.info( '%s invited %s.' % (user, args))
            self.save_state()
            self.message_queue.append('_%s invited %s_' % (self.users[user], args))

    @botcmd(name=',ideas')
    def ideas(self, mess, args):
        """Maintain a list of ideas/items. Use ,ideas help."""
        user = self.get_sender_username(mess)
        if user in self.users:
            if args.startswith('show'):
                txt = '\n_%s is ideating_\n' % (self.users[user])
                for i, idea in enumerate(self.ideas):
                    txt += '_%s - %s_\n' % (i, idea)
                self.message_queue.append(txt)
            elif args.startswith('add'):
                text = ' '.join(args.split()[1:]).strip()
                if text == '':
                    return "Sorry. Cannot add empty idea."
                self.ideas.append(text)
                self.save_state()
                self.message_queue.append('_%s added "%s" as an idea_' % (self.users[user], text))
            elif args.startswith('del'):
                try:
                    num = int(args.split()[1])
                    if num in range(len(self.ideas)):
                        self.message_queue.append('_%s deleted "%s" from ideas_' % (self.users[user], self.ideas[num]))
                        del self.ideas[num]
                        self.save_state()
                except:
                    return "Invalid option to delete."
            elif args.startswith('edit'):
                try:
                    num = int(args.split()[1])
                    if num in range(len(self.ideas)):
                        txt = ' '.join(args.split()[2:]).strip()
                        if txt == '':
                            return "Sorry. Cannot add empty idea."
                        self.message_queue.append('_%s changed idea %s to %s_' % (self.users[user], num, txt))
                        self.ideas[num] = txt
                        self.save_state()
                except:
                    return "Invalid option to edit."
            elif not args:
                return '\n'.join(['_%s - %s_' %(i,t) for i,t in enumerate(self.ideas)])
            else:
                return """add - Adds a new idea
                del n - Deletes n^{th} idea
                edit n txt - Replace n^{th} idea with 'txt'
                show - Show ideas in chatroom
                no arguments - Show ideas to you"""

    @botcmd(name=',whois')
    def whois( self, mess, args):
        """Check who has a particular nick"""
        user = self.get_sender_username(mess)
        args = args.strip().replace(' ', '_')
        if user in self.users:
            self.log.info('%s queried whois %s.' % (user, args))
            if args in self.users.values():
                return filter(lambda u: self.users[u] == args, self.users)[0]
            else:
                return 'Nobody!'

    @botcmd(name=',uptime')
    def uptime(self, mess, args):
        """Check the uptime of the bot."""
        user = self.get_sender_username(mess)
        if user in self.users:
            t = datetime.fromtimestamp(time.time()) - \
                   datetime.fromtimestamp(self.started)
            hours = t.seconds/3600
            mins = (t.seconds/60)%60
            secs = t.seconds%60
            self.log.info('%s queried uptime.' % (user))
            self.message_queue.append("Harbouring conversations, and what's more, memories, relentlessly since %s day(s) %s hour(s) %s min(s) and %s sec(s) for %s & friends" % (t.days, hours, mins, secs, self.users[user]))

    @botcmd(name=',yt')
    def youtube_fetch(self, mess, args):
        """Fetch the top-most result from YouTube"""
        user = self.get_sender_username(mess)
        if user in self.users:
            self.log.info('%s queried %s from Youtube.' % (user, args))
            yt_service = gdata.youtube.service.YouTubeService()
            query = gdata.youtube.service.YouTubeVideoQuery()
            query.racy = 'include'
            query.orderby = 'relevance'
            query.max_results = 1
            query.vq = args

            feed = yt_service.YouTubeQuery(query)
            self.message_queue.append('%s searched for %s ...' %(self.users[user], args))

            for entry in feed.entry:
                self.message_queue.append('... and here you go -- %s' % entry.GetHtmlLink().href)

    @botcmd(name=',g')
    def google_fetch(self, mess, args):
        """Fetch the top-most result from Google"""
        user = self.get_sender_username(mess)
        if user in self.users:
            self.log.info('%s queried %s from Google.' % (user, args))
            query = urllib.urlencode({'q' : args})
            url = 'http://ajax.googleapis.com/ajax/' + \
                  'services/search/web?v=1.0&%s' % (query)
            results = urllib.urlopen(url)
            json = simplejson.loads(results.read())
            self.message_queue.append('%s googled for %s ... and here you go'
                                      %(self.users[user], args))
            try:
                top = json['responseData']['results'][0]
                self.message_queue.append('%s -- %s' %(top['title'], top['url']))
            except:
                self.message_queue.append('%s' % "Oops! Nothing found!")

    @botcmd(name=',sc')
    def soundcloud_fetch(self, mess, args):
        """Fetch the top-most result from Google for site: soundcloud.com"""
        user = self.get_sender_username(mess)
        if user in self.users:
            self.log.info('%s queried %s from Google.' % (user, args))
            query = urllib.urlencode({'q' : "site:soundcloud.com " + args})
            url = 'http://ajax.googleapis.com/ajax/' + \
                  'services/search/web?v=1.0&%s' % (query)
            results = urllib.urlopen(url)
            json = simplejson.loads(results.read())
            top = json['responseData']['results'][0]
            self.message_queue.append('%s googled for %s ... and here you go'
                                      %(self.users[user], args))
            self.message_queue.append('%s -- %s' %(top['title'], top['url']))

    @botcmd(name=",stats")
    def stats(self, mess, args):
        "Simple statistics with message count for each user."
        user = self.get_sender_username(mess)
        self.log.info('Starting analysis... %s requested' % user)
        stats_th = threading.Thread(target=self.analyze_logs)
        stats_th.start()
        return 'Starting analysis... will take a while!'

    def analyze_logs(self):
        self.log.info('Starting analysis...')
        logs = Popen(["grep", "sent:", "nohup.out"], stdout=PIPE)
        logs = logs.stdout
        people = {}
        for line in logs:
            log = line.strip().split()
            if not log or len(log) < 10:
                continue
            person = log[7]
            if '@' in person:
                person = person.split('@')[0]
            message = ' '.join(log[9:])
            if person not in people:
                people[person] = [message]
            else:
                people[person].append(message)
        stats = ["%-15s -- %s" %(dude, len(people[dude])) for dude in people]
        stats = sorted(stats, key=lambda x: int(x.split()[2]), reverse=True)
        stats = ["%-15s -- %s" %("Name", "Message count")] + stats

        stats = 'the stats ...\n' + '\n'.join(stats) + '\n'

        self.log.info('Sending analyzed info')
        self.message_queue.append(stats)

    @botcmd(name=',see')
    def bot_see(self, mess, args):
        """ Look at bot's attributes.

        May not be a good idea to allow use for all users, but for
        now, I don't care."""
        try:
            return "%s is %s" % (args, bc.__getattribute__(args))
        except AttributeError:
            return "No such attribute"

    @botcmd(name=',help')
    def help_alias(self, mess, args):
        """An alias to help command."""
        return self.help(mess,args)

    def highlight_name(self, msg, user):
        """Emphasizes your name, when sent in a message.
        """
        nick = self.users[user]
        msg = re.sub("((\s)%s(\s))|(\A%s(\s))|((\s)%s\Z)" %(nick, nick, nick),
                     " *%s* " %nick, msg)

        return msg

    @botcmd(name=',polls')
    def cmd_polls(self, mess, args):
        '"/polls" List all the finished polls'
        polls = poll.PollFactory.get_polls()
        if len(polls) == 0:
            return "There are no finished polls. You can create one using ,poll question"
        polls_str = ""
        user = self.get_sender_username(mess)
        for iter_poll in polls:
            polls_str += "\n* Poll: #%d (%s): %s" % (iter_poll.id, user, iter_poll.question)
        return polls_str

    @botcmd(name=',pollresults')
    def cmd_pollresults(self, mess, args):
        '"/pollresults" Get the results of a given poll. Syntax: /pollresults poll_id '

        msg = mess.getBody()
        if len(msg.split(' ')) == 1:
            return 'It works like /poll poll_id'

        try:
            poll_id = msg.split(' ')[1]
            poll_ = poll.PollFactory.get_poll(poll_id)
        except poll.PollException, e:
            reply = e.message
            self.log.exception(reply)
            return reply

        votes = poll_.get_votes()
        self.print_votes(votes)

    def print_votes(self, votes):
        if len(votes):
            yes = 0
            no = 0
            total = len(votes)
            for vote in votes:
                yes += vote.vote
                user = self.users[vote.voter]
                self.message_queue.append('%s voted %s %s\n' % (user, str(vote), vote.msg if vote.msg else ""))

            no = abs(total - yes)
            self.message_queue.append('Total votes: %d\nYes: %d\nNo: %d' % (total, yes, no))
        else:
            self.message_queue.append('There were no votes')

    @botcmd(name=',poll')
    def cmd_poll(self, mess, args):
        '"/poll" Init a poll. Syntax: /poll question'
        who = self.get_sender_username(mess)
        msg = mess.getBody()
        if len(msg.split(' ')) == 1:
            return 'It works like ,poll question'

        active_poll = poll.PollFactory.get_active_poll()
        if active_poll is not None:
            user = self.users[active_poll.author]
            return "There is a running poll:\nAuthor: %s\nQuestion: %s\nAuthor must close it using ,endpoll before starting another" % (user, active_poll.question)
        currentpoll = poll.Poll()
        try:
            polltxt = ' '.join(msg.split(' ')[1:])
            currentpoll.new(polltxt, who)
        except poll.PollException, e:
            reply = e.message
            self.log.exception(reply)
            return reply

        self.message_queue.append('%s has a question for you:\n----\n%s\n----\nPlease vote using /vote <0|1> [reason]' % (who, msg))

    @botcmd(name=',endpoll')
    def cmd_endpoll(self, mess, args):
        '"/endpoll" Finish a poll.'

        active_poll = poll.PollFactory.get_active_poll()
        who = self.get_sender_username(mess)
        if active_poll is None:
            return "There is no running poll."

        if active_poll.author != who:
            return "The running poll is not yours. Author: %s\nAsk him to close the vote using /endpoll" % poll.author

        self.message_queue.append('%s has closed the poll: "%s"\nResults:' % (self.users[who], active_poll.question))
        votes = active_poll.get_votes()
        self.print_votes(votes)
        active_poll.close()

    @botcmd(name=',vote')
    def cmd_vote(self, mess, args):
        '",vote" Init a poll. Syntax: ,vote <0|1> [reason]'
        who = self.get_sender_username(mess)
        msg = mess.getBody()
        comment = None
        if msg.strip().lower() == "":
            return 'It works like ,vote <0|1> [reason]'

        active_poll = poll.PollFactory.get_active_poll()
        if active_poll is None:
            return "There is no running poll."

        try:
            response = msg.split(" ")[1]
            vote = int(response)
            if vote not in [0, 1]:
                raise ValueError('Invalid vote')
        except ValueError:
            return "You can only vote 0 or 1 and you voted: %s" % response

        try:
            comment = " ".join(msg.split(' ')[2:])
        except IndexError:
            pass #comment = None
        try:
            active_poll.vote(who, vote, comment)
        except poll.PollException, e:
            reply = e.message
            self.log.exception(reply)
            return reply

        reply = 'Your vote has been registered. Wait for poll ending to show final results'
        self.send_simple_reply(mess,reply)
        self.message_queue.append('%s has voted' % who)

    def chunk_message(self, user, msg):
        LIM_LEN = 512
        if len(msg) <= LIM_LEN:
            self.send(user, msg)
        else:
            idx = (msg.rfind('\n', 0, LIM_LEN) + 1) or (msg.rfind(' ', 0, LIM_LEN) + 1)
            if not idx:
                idx = LIM_LEN
            self.send(user, msg[:idx])
            time.sleep(0.1)
            self.chunk_message(user, msg[idx:])

    def idle_proc( self):
        if not len(self.message_queue):
            return

        # copy the message queue, then empty it
        messages = self.message_queue
        self.message_queue = []

        for message in messages:
            if len(self.users):
                self.log.info('sending "%s" to %d user(s).' % ( message, len(self.users), ))
            for user in self.users:
                if not message.startswith("[%s]:" % self.users[user]):
                    self.chunk_message(user,
                                       self.highlight_name(message, user))

    def thread_proc( self):
        while not self.thread_killed:
            self.message_queue.append('')
            for i in range(300):
                time.sleep(1)
                if self.thread_killed:
                    return

if __name__ == "__main__":
    PATH = os.path.dirname(os.path.abspath(__file__))
    sys.path = [PATH] + sys.path

    from settings import *

    bc = ChatRoomJabberBot(JID, PASSWORD, RES)

    th = threading.Thread(target = bc.thread_proc)
    bc.serve_forever(connect_callback = lambda: th.start())
    bc.thread_killed = True

<file_sep>/meme.py
#!/usr/bin/env python
import sys, re
from pyquery import PyQuery

memes = {
    'fry'          : { 'generatorID': 305,   'imageID' : 84688 },
    'raptor'       : { 'generatorID': 17,    'imageID' : 984 },
    'toad'         : { 'generatorID': 3,     'imageID' : 203 },
    'foreveralone' : { 'generatorID': 116,   'imageID' : 142442 },
    'yuno'         : { 'generatorID': 2,     'imageID' : 166088 },
    'penguin'      : { 'generatorID': 29,    'imageID' : 983 },
    'pedobear'     : { 'generatorID': 235,   'imageID' : 564288 },
    'trollface'    : { 'generatorID': 26298, 'imageID' : 1182094 },
    'yaoming'      : { 'generatorID': 1610,  'imageID' : 458071 },
    'kid'          : { 'generatorID': 121,   'imageID' : 1031 },
    'yodawg'       : { 'generatorID': 79,    'imageID' : 108785 },
    'awyeah'       : { 'generatorID': 211112,'imageID' : 1778013 },
    'chicken'      : { 'generatorID': 747,   'imageID' : 473733 }
    }

GENURL = 'http://memegenerator.net/create/instance'
def create_meme(meme, t0, t1):
    data = {
       'languageCode': 'es',
       'text0': t0,
       'text1': t1
    }

    if not meme in memes:
        return 'Not Found'

    data = dict(data.items() + memes[meme].items())

    try:
        pq = PyQuery(url=GENURL, data=data, method='post')
    except Exception, e:
        return 'Error %s' % e
    s = str(pq)
    # <img src="http://d.images.memegenerator.net/instances/400x/xxxxxx.jpg
    regex = re.compile("http://[\w\.]+.memegenerator.net/instances/400x/\d+.jpg")
    match = regex.search(s)
    if match is None:
        return 'Error'
    else:
        return match.group(0)

def list_memes():
    l = []
    list = ''
    for m in memes:
        l.append(m)
    l.sort()
    for i in l:
        list += i + ', '
    return list[:-2]

if __name__ == '__main__':
    if len(sys.argv) != 4:
        print('Usage meme text0 text1')
        sys.exit(1)
    print "creating: %s %s %s" % (sys.argv[1], sys.argv[2], sys.argv[3])
    print create_meme(sys.argv[1], sys.argv[2], sys.argv[3])
<file_sep>/handy.py
#!/usr/bin/env python

# please consider uploading the link to imgur before
handy_links = {
    'haters'     : 'http://i.imgur.com/DmgKb.jpg',
    'haterz'     : 'http://i.imgur.com/LGOwa.gif',
    'palomitas'  : 'http://i.imgur.com/M33BF.gif',
    'pics'       : 'http://i.imgur.com/UdXdM.jpg',
    'megusta'    : 'http://i.imgur.com/ibzJX.jpg',
    'yaoming'    : 'http://i.imgur.com/AwWvY.png',
    'trollface'  : 'http://i.imgur.com/Njy8l.png',
    'sfuck'      : 'http://i.imgur.com/sXtZc.jpg',
    'goback'     : 'http://i.imgur.com/pLQUU.gif',
    'dealwithit' : 'http://i.imgur.com/G7f9J.gif',
    'likeigive'  : 'http://i.imgur.com/6kO74.gif',
    'mindblown'  : 'http://i.imgur.com/fbelJ.gif',
    'clap'       : 'http://i.imgur.com/1WypN.gif',
    'truestory'  : 'http://i.imgur.com/51Ekh.png',
    'laugh'      : 'http://i.imgur.com/JFbhu.gif',
    'rolleyes'   : 'http://i.imgur.com/RqtZe.gif',
    'fuckthis'   : 'http://i.imgur.com/Bsfnw.gif',
    'fuckevery'  : 'http://i.imgur.com/yScef.jpg',
    'fuckdapol'  : 'http://i.imgur.com/6UpBV.png',
    'lol'        : 'http://i.imgur.com/LFguu.gif',
    'wrong'      : 'http://i.imgur.com/TBL3j.gif',
    'coolstory'  : 'http://i.imgur.com/iVLKt.gif',
    'f7u12'      : 'http://i.imgur.com/U8jcB.gif',
    'facepalm'   : 'http://i.imgur.com/6eKQz.gif',
    'party'      : 'http://i.imgur.com/yq9A0.gif',
    'rickroll'   : 'http://i.imgur.com/UR1x2.gif',
    'punch'      : 'http://i.imgur.com/dEhlI.gif',
    'orly'       : 'http://i.imgur.com/HX9Tt.gif',
    'wtf'        : 'http://i.imgur.com/ZlC7s.gif',
    'onoudidnt'  : 'http://i.imgur.com/1mUDX.gif',
    'challenge'  : 'http://i.imgur.com/02HJ9.png',
    'shark'      : 'http://i.imgur.com/7fsza.png',
    'trap'       : 'http://i.imgur.com/NcCIw.jpg',
    'notsure'    : 'http://i.imgur.com/WH4mO.gif',
    'rolfmao'    : 'http://i.imgur.com/VlOTd.gif',
    'orly'       : 'http://i.imgur.com/wdlmj.gif',
    'cry'        : 'http://i.imgur.com/SlOFG.gif',
    'disapprove' : 'http://i.imgur.com/3QAmc.gif',
    'tldr'       : 'http://i.imgur.com/mOH78.gif',
    'disgonbgud' : 'http://i.imgur.com/sbk60.gif',
    'rushitting' : 'http://i.imgur.com/8MwwZ.gif',
    'iseewhat'   : 'http://i.imgur.com/IEUCH.jpg',
    'regret'     : 'http://i.imgur.com/7yw6D.gif'
}

languages: Org Shell Python

repo_language: Org

repo_name: esanchezm/xmpp-muc-bot


text:
<file_sep>// import Vue from 'vue'
// import Vuex from 'vuex'

// //1.安装插件
// Vue.use(Vuex)

// //2.创建store对象
// const store = new Vuex.Store({
//   state: {
//     cartList: []
//   },
//   //修改store里的东西都需要经过mutations
//   mutations: {
//     addCart(state, payload) {

//       //数组find()方法
//       // let oldProduct = state.cartList.find(item => item.id === payload.iid)
//       let oldProduct = state.cartList.find(function (item) {
//         return item.iid === payload.iid
//       })

//       if (oldProduct) {
//         oldProduct.count += 1;
//       } else {
//         payload.count = 1;
//         // payload.checked = true;
//         state.cartList.push(payload)
//       }
//       // state.cartList.push(payload)
//       // console.log(payload);
//     }
//   }
// })

// //3.挂载
// export default store<file_sep>import { request } from "./request";

export function getHomeMutidata() {
  return request({
    // url: '/recommend',
    url: '/home/multidata',

  })
}

export function getHomeGoods(type, page) {
  return request({
    url: '/home/data',
    params: {
      type,
      page
    }
  })

}
// function test() {
//   const names = ['lcy', '111 ']
// }

// let totalNums = []

// const nums = [20, 11, 22]
// const nums = [20, 11, 333]

// totalNums = nums

repo_language: JavaScript


text:
<file_sep># MachineLearningAlgorithm-Mini-Project
Model on Breast Cancer

The models are followings:
-Decision Trees Classifier
-K-Nearest Neighbours Classifier
-Logistic Regression Classifier
-Naïve Bayes Classifier
-Random Forest Classifier
-SVM Classifier
-XGBoost Classifier

## Breast Cancer Wisconsin (Diagnostic) Data Set
This is the dataset I used for developing our classification model, the dataset description is followings:

Data Set Characteristics:  Multivariate

Number of Instances: 569

Area: Life

Attribute Characteristics:  Real

Number of Attributes: 32

Date Donated: 1995-11-01

Associated Tasks: Classification

Missing Values? : No

workflow used in a developing model are followings:
- Import required libraries
- Step 1 - Dataset Selection
- Step 2 - Data Normlization
- Step 3 - Train and Test Split
- Step 4 - Algorithem Selection
- Step 5 - Model Evalution (Training)
- Step 5 - Model Evalution (Testing)

Evaluation Matrix Used

- Accuracy
- Sensitivity/Recall
- Specificity
- Precision
- F-Score
- Mens Squre Error
- Root Mens Squre Error
- ROC_AUC scores (Plot)


text:
<file_sep>
Welcome to Home!

{{>weather}}<file_sep># Node-with-express
看《Node与Express开发》时敲的,感觉这是一本很适合对Node.js和express有初步了解新手书。

用的模板引擎是handlebars<file_sep>
about cky travel

你未来的一天：

{{fortune}}

联系我<file_sep>var fortunes = [
  "中彩票",
  "免费吃蛋糕",
  "糟糕的一天",
  "上班迟到",
  "被夸奖",
];

exports.getFortune = function(){
    var idx = Math.floor(Math.random() * fortunes.length);
    return fortunes[idx];
};<file_sep>
welcome to cky travel

languages: Handlebars Markdown JavaScript

repo_language: Handlebars


text:
<repo_name>alivin/blog<file_sep>/app/views/articles/_feed.html.erb
<% @articles.each do |article| %>

      <%= article.title %>
      <%= article.content %>
      <%= image_tag article.avatar.url if article.avatar? %>

<% end%>
<file_sep>/app/views/articles/_form.html.erb
<%= form_for @article, :html => { :multipart => true } do |f| %>

      <%= f.label :title %>
      <%= f.text_field :title, class: "title" %>

      <%= f.label :content %>
      <%= f.cktext_area :content %>

      <%= f.file_field :avatar, accept: 'image/jpeg image/gif image/png' %>
      <%= f.hidden_field :avatar_cache %>

      <%= f.submit "Post", class: "btn" %>

<% end %><file_sep>/app/views/static_pages/home.html.erb
<%= provide(:title, 'Home') %>

  <% @articles.each do |article| %>

<%= link_to article.title, article %>

            <%= article.content.html_safe %>

  <% end %>

<file_sep>/app/views/layouts/_footer.html.erb

copied from jumbotron for studies.<%= link_to "write a new blog", new_article_path if logged_in? && yield(:title) == "Home" %>

<file_sep>/app/views/articles/show.html.erb
<% provide(:title, @article.title) %>

<%= link_to @article.title %>

<%= @article.created_at.strftime("%d %b %Y") %>

    <%= @article.content.html_safe %>

      <%= image_tag @article.avatar.url if @article.avatar? %>

<file_sep>/app/views/articles/manage.html.erb
<% provide(:title, 'Manage') %>

id	title	settings

  <% @articles.each do |article| %>

    <%= article.id %>
    <%= article.title %>

      <%= link_to "show", article %>
      <%= link_to "edit", edit_article_path(article) %>
      <%= link_to "delete", article, method: :delete, data: { confirm: "You sure?" } %>

  <% end %>

<file_sep>/app/views/articles/index.html.erb
<% provide(:title, 'articles - alivin') %>
<%= paginate @articles %>

  <% @articles.each do |article| %>

<%= link_to article.title, article %>

Text contains presences the text.

  <% end %>

<file_sep>/app/views/static_pages/about.html.erb
<%= provide(:title, 'About') %>

Alivin's Blog

just a blog development

<%= link_to "write a blog", new_article_path %>

Sign up now

<file_sep>/app/views/layouts/_nav.html.erb

  <%= link_to "文字", articles_path %>
  <%= link_to "关于", about_path %>
  <%= link_to "联系我", contact_path %>
  <%= link_to "Feed", feed_path %>
  <%= link_to "GitHub", "https://github.com/alivin" %>

<file_sep>/README.md
== README

envorinment

ruby '2.0.0p598'
rails '4.1.8

Please feel free to use a different markup language if you do not plan to run
<tt>rake doc:app</tt>.
<file_sep>/app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
  def home
    @articles = Article.limit(5)
  end

  def help
  end

  def contact
  end

  def feed
  end
end
<file_sep>/app/views/users/show.html.erb

<%= notice %>

  Name:
  <%= @user.name %>

  Email:
  <%= @user.email %>

  Avatar:
  <%= image_tag(@user.avatar) %>

<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>

<%= link_to "manage my blog", manage_path %>

languages: HTML+ERB Markdown Ruby

repo_language: HTML+ERB

repo_name: alivin/blog


text:
<file_sep># spectre

`timescale 1ns / 1ps

module modified( clk_in);//tag, index,
 reg[15:0]T;
 //reg [11:0]T[15:4];
 reg [4:0]location;
 reg[6:0]out_cache;
 reg y;
 reg [27:1]z;
 reg[3:0] temp;
 reg[11:0] intermediate;
 reg cache_hit;
 reg[11:0]tag[15:0];
 reg[6:0]data[15:0];
  input clk_in;
  wire clk, clk_100M;
 wire[4:0]X;
 reg[3:0]index;
 reg[4:0]w;
 reg[4:0] store[25:0];
 reg[15:0] A[26:1];
 reg [6:0] main[26:1];
 parameter size=15;
 integer i=1;
 initial begin
   store[0]=5'b00001;
	store[1]=5'b00010;
   store[2]=5'b00011;
	store[3]=5'b00100;
	store[4]=5'b00101;
   store[5]=5'b00110;
	store[6]=5'b00111;
	store[7]=5'b01000;
	store[8]=5'b01001;
	store[9]=5'b01010;
   store[10]=5'b01011;
   store[11]=5'b01100;
   store[12]=5'b01101;
   store[13]=5'b01110;
	store[14]=5'b01111;
	store[15]=5'b10000;
   store[16]=5'b10001;
	store[17]=5'b10010;
	store[18]=5'b10011;
	store[19]=5'b10100;
	store[20]=5'b10101;
	store[21]=5'b10110;
	store[22]=5'b10111;
	store[23]=5'b11000;
	store[24]=5'b11001;
	store[25]=5'b11010;
end
initial begin
		// Initialize Inputs
	//VICTIM MEMORY
    A[1]=16'b1000000000000001;
	A[2]=16'b1100000000000010;
    A[3]=16'b1110000000000011;
    A[4]=16'b1111000000000100;
    A[5]=16'b1111100000000101;
    A[6]=16'b1111110000000110;
    A[7]=16'b1111000000000111;
    A[8]=16'b1111100000001000;
    A[9]=16'b1111111111111001;
    A[10]=16'b1111111000001010;
    A[11]=16'b1111111000001011;
    A[12]=16'b1111111100001100;
	A[13]=16'b1111111110001101;
	A[14]=16'b1111111111001110;
	A[15]=16'b1111111111101111;
	A[16]=16'b0000000000110000;
	A[17]=16'b0000000001110001;
    A[18]=16'b0000000011110010;
	A[19]=16'b000000111110011;
	A[20]=16'b1000001111110100;
    A[21]=16'b0000001111110101;
	A[22]=16'b0000011111110110;
	A[23]=16'b0000111111110111;
	A[24]=16'b0001111111111000;
	A[25]=16'b0011111111111001;
	A[26]=16'b0111111111111010;
	end
	initial begin
	//FORBIDDEN DATA
	main[1]=7'b1100001;//a
	main[2]=7'b1100010;//b
	main[3]=7'b1100011;//c
	main[4]=7'b1100100;//d
	main[5]=7'b1100101;//e
	main[6]=7'b1100110;//f
	main[7]=7'b1100111;//g
	main[8]=7'b1101000;//h
	main[9]=7'b1101001;//i
	main[10]=7'b1101010;//j
	main[11]=7'b1101011;//k
	main[12]=7'b1101100;//l
	main[13]=7'b1101101;//m
	main[14]=7'b1101110;//n
	main[15]=7'b1101111;//o
	main[16]=7'b1110000;//p
	main[17]=7'b1110001;//q
	main[18]=7'b1110010;//r
	main[19]=7'b1110011;//s
	main[20]=7'b1110100;//t
	main[21]=7'b1110101;//u
	main[22]=7'b1110110;//v
	main[23]=7'b1110111;//w
	main[24]=7'b1111000;//x
	main[25]=7'b1111001;//y
	main[26]=7'b1111010;//z
	end
always @(posedge clk)
begin

	  w=store[{X[4],X[3],X[2],X[1],X[0]}];
  T=A[{w[4],w[3],w[2],w[1],w[0]}];
		   if(X<size)
	 y=1'b1;//input is correct
	  else
	   y=1'b0;//input is malicious
end
 always @(posedge clk)
 begin
  index=T[3:0];
  T[15:4]=T[15:4];
end
always @(posedge clk)
begin
  case(index)
4'b0000:

begin
	tag[0]=T[15:4];
	data[0]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b0001:
begin
	tag[1]=T[15:4];
	data[1]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b0010:
begin
	tag[2]=T[15:4];
	data[2]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b0011:
begin
	tag[3]=T[15:4];
	data[3]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b0100:
begin

	tag[4]=T[15:4];
	data[4]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b0101:
begin
	tag[5]=T[15:4];
	data[5]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b0110:
begin
	tag[6]=T[15:4];
	data[6]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b0111:
begin
	tag[7]=T[15:4];
	data[7]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b1000:
begin
	tag[8]=T[15:4];
	data[8]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b1001:
begin
	tag[9]=T[15:4];
	data[9]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b1010:
begin
	tag[10]=T[15:4];
	data[10]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b1011:
begin
	tag[11]=T[15:4];
	data[11]=main[{T[4],T[3],T[2],T[1],T[0]}];
	tag[10]=12'b0;
end
4'b1100:
begin
	tag[12]=T[15:4];
	data[12]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b1101:
begin
	tag[13]=T[15:4];
	data[13]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b1110:
begin
	tag[14]=T[15:4];
	data[14]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
4'b1111:
begin
	tag[15]=T[15:4];
	data[15]=main[{T[4],T[3],T[2],T[1],T[0]}];
end
  endcase
 end

 initial begin
	z=27'b0;
 end

always @(posedge clk)
 begin
if(i>=1 && i<27)
begin
	temp=A[i][3:0];
	intermediate=A[i][15:4];
if(tag[temp]==intermediate)
	begin
	cache_hit=1'b1;
	location=store[i-1];
	z[i-1]<=1'b1;
	out_cache=main[i];
	error(i-1);
	i<=i+1;
	end
else
	begin
	z[i-1]<=1'b0;
	cache_hit=1'b0;
	i<=i+1;
	end
end
else if(i>=27)
	begin
	cache_hit=1'b0;
	i<=1'b1;
	z<=27'b00000000000000000000000000;

//	//flushing the data
//	tag[0]<=12'b0;
//	tag[1]<=12'b0;
//	tag[2]<=12'b0;
//	tag[3]<=12'b0;
//	tag[4]<=12'b0;
//	tag[5]<=12'b0;
//	tag[6]<=12'b0;
//	tag[7]<=12'b0;
//	tag[8]<=12'b0;
//	tag[9]<=12'b0;
//	tag[10]<=12'b0;
//	tag[11]<=12'b0;
//	tag[12]<=12'b0;
//	tag[13]<=12'b0;
//	tag[14]<=12'b0;
//	tag[15]<=12'b0;

    data[0]<=7'b0;
    data[1]<=7'b0;
    data[2]<=7'b0;
    data[3]<=7'b0;
    data[4]<=7'b0;
    data[5]<=7'b0;
    data[6]<=7'b0;
    data[7]<=7'b0;
    data[8]<=7'b0;
    data[9]<=7'b0;
    data[10]<=7'b0;
    data[11]<=7'b0;
    data[12]<=7'b0;
    data[13]<=7'b0;
    data[14]<=7'b0;
    data[15]<=7'b0;
    end
end

 task error;
	  input integer s;
 $display("Hit at location:%d",s);
 endtask

 vio_0 modified_vio (
   .clk(clk_100M),                // input wire clk
   .probe_in0(T),    // input wire [15 : 0] probe_in0
   .probe_in1(y),    // input wire [0 : 0] probe_in1
   .probe_in2(w),    // input wire [4 : 0] probe_in2
   .probe_in3(z),    // input wire [26 : 0] probe_in3
   .probe_in4(index),    // input wire [3 : 0] probe_in4
   .probe_in5(temp),    // input wire [3 : 0] probe_in5
   .probe_in6(intermediate),    // input wire [11 : 0] probe_in6
   .probe_in7(cache_hit),    // input wire [0 : 0] probe_in7
   .probe_in8(out_cache),    // input wire [6 : 0] probe_in8
   .probe_in9(location),    // input wire [4 : 0] probe_in9
   .probe_out0(X)  // output wire [4 : 0] probe_out0
 );

 ila_0 modified_ila (
     .clk(clk_100M), // input wire clk

     .probe0(clk), // input wire [0:0]  probe0
     .probe1(X), // input wire [4:0]  probe1
     .probe2(T), // input wire [15:0]  probe2
     .probe3(y), // input wire [0:0]  probe3
     .probe4(w), // input wire [4:0]  probe4
     .probe5(z), // input wire [26:0]  probe5
     .probe6(index), // input wire [3:0]  probe6
     .probe7(temp), // input wire [3:0]  probe7
     .probe8(intermediate), // input wire [11:0]  probe8
     .probe9(cache_hit), // input wire [0:0]  probe9
     .probe10(out_cache), // input wire [6:0]  probe10
     .probe11(location) // input wire [4:0]  probe11
 );

  clk_wiz_0 clocling_wiz
   (
    // Clock out ports
    .clk_out1(clk_100M),     // output clk_out1
    .clk_out2(clk),     // output clk_out2
   // Clock in ports
    .clk_in1(clk_in));

endmodule

repo_name: pavanyerukula/spectre


text:
<file_sep># Demo
Demo for checking

repo_name: govindnarute/Demo