<commit_before>import json
import random

from django.http import HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError
from django.shortcuts import render
from django.utils.html import escape, strip_tags
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name

from web.Language import Language
from web.MetaInfo import MetaInfo
from web.thesaurus_template_generators import generate_language_template

def index(request):
    """
    Renders the home page (/)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    with open("web/thesauruses/meta_info.json", 'r') as meta_file:
        meta_data = meta_file.read()
    meta_info = json.loads(meta_data)
    meta_data_langs = {
        id: {
            "name": lang["name"],
            "versions": ", ".join(lang["versions"])
        }
        for (id, lang) in meta_info["languages"].items()
    }
    random_langs = random.sample(list(meta_data_langs.values()), k=3)

    content = {
        'title': 'Welcome',
        'languages': meta_data_langs,
        'structures': meta_info["structures"],
        'randomLanguages': random_langs,
        'description': 'Code Thesaurus: A polyglot developer reference tool'
    }
    return render(request, 'index.html', content)

def about(request):
    """
    Renders the about page (/about)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    content = {
        'title': 'About',
        'description': 'Code Thesaurus: A polyglot developer reference tool'
    }
    return render(request, 'about.html', content)

def compare(request):
    """
    Renders the page comparing two language structures (/compare)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    lang1_string = escape(strip_tags(request.GET.get('lang1', '')))
    lang2_string = escape(strip_tags(request.GET.get('lang2', '')))
    structure_query_string = escape(strip_tags(request.GET.get('concept', '')))

    errors = []
    if not structure_query_string:
        errors.append("The URL didn't specify a structure/concept to look up.")
    if not lang1_string:
        errors.append("The URL didn't specify a first language to look up.")
    if not lang2_string:
        errors.append("The URL didn't specify a second language to look up.")

    if errors:
        error_page_data = {
            "errors": errors
        }
        response = render(request, 'errormisc.html', error_page_data)

        return HttpResponseNotFound(response)

    try:
        metainfo = MetaInfo()
        meta_structure = metainfo.structure(structure_query_string)
    except (FileNotFoundError):
        error_page_data = {
            "errors": ["The structure/concept isn't valid. Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)

        return HttpResponseNotFound(response)

    try:
        lang1 = Language(
            lang1_string, metainfo.language_friendly_name(lang1_string))
        lang1.load_concepts(meta_structure.key)
    except (FileNotFoundError):
        response = render(request, "error_missing_structure.html", {
            "name": meta_structure.friendly_name,
            "lang": lang1_string,
            "key": meta_structure.key,
            "template": generate_language_template(
                lang1_string,
                meta_structure.key
            )
        })
        return HttpResponseNotFound(response)
    except (KeyError):
        error_page_data = {
            "errors": [f"The first language ({lang1_string}) isn't valid. \
                Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)
        return HttpResponseNotFound(response)

    try:
        lang2 = Language(
            lang2_string, metainfo.language_friendly_name(lang2_string))
        lang2.load_concepts(meta_structure.key)
    except (FileNotFoundError):
        response = render(request, "error_missing_structure.html", {
            "name": meta_structure.friendly_name,
            "lang": lang2_string,
            "key": meta_structure.key,
            "template": generate_language_template(
                lang2_string,
                meta_structure.key
            )
        })
        return HttpResponseNotFound(response)
    except (KeyError):
        error_page_data = {
            "errors": [f"The second language ({lang2_string}) isn't valid. \
                Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)
        return HttpResponseNotFound(response)

    both_categories = []

    for (category_key, category) in meta_structure.categories.items():
        concepts = [concept_comparision(id, name, lang1, lang2)
                    for (id, name) in category.items()]

        both_categories.append({
            "id": category_key,
            "concepts": concepts
        })

    response = {
        "title": "Comparing " + lang1.friendly_name + " and " + lang2.friendly_name,
        "concept": meta_structure.key,
        "concept_friendly_name": meta_structure.friendly_name,
        "lang1": lang1.key,
        "lang2": lang2.key,
        "lang1_friendlyname": lang1.friendly_name,
        "lang2_friendlyname": lang2.friendly_name,
        "categories": both_categories,
        "description": f"Code Thesaurus: Comparing {lang1.friendly_name} and {lang2.friendly_name}"
    }

    return render(request, 'compare.html', response)

def reference(request):
    """
    Renders the page showing one language structure for reference (/reference)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    lang_string = escape(strip_tags(request.GET.get('lang', '')))
    structure_query_string = escape(strip_tags(request.GET.get('concept', '')))

    errors = []
    if not structure_query_string:
        errors.append("The URL didn't specify a structure/concept to look up.")
    if not lang_string:
        errors.append("Thr URL didn't specify a language to look up.")
    if errors:
        error_page_data = {
            "errors": errors
        }
        response = render(request, 'errormisc.html', error_page_data)

        return HttpResponseNotFound(response)

    try:
        metainfo = MetaInfo()
        meta_structure = metainfo.structure(structure_query_string)
    except (FileNotFoundError):
        error_page_data = {
            "errors": ["The structure/concept isn't valid. Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)

        return HttpResponseNotFound(response)

    try:
        lang = Language(
            lang_string, metainfo.language_friendly_name(lang_string))
        lang.load_concepts(meta_structure.key)
    except (FileNotFoundError):
        ctx = {
            "name": meta_structure.friendly_name,
            "lang": lang_string,
            "key": meta_structure.key,
            "template": generate_language_template(
                lang_string,
                meta_structure.key
            )
        }
        response = render(request, "error_missing_structure.html", ctx)
        return HttpResponseNotFound(response)
    except (KeyError):
        error_page_data = {
            "errors": [f"The language ({lang_string}) isn't valid. \
                        Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)
        return HttpResponseNotFound(response)

    categories = []

    for (category_key, category) in meta_structure.categories.items():
        concepts = [concept_reference(id, name, lang)
                    for (id, name) in category.items()]
        categories.append({
            "id": category_key,
            "concepts": meta_structure.categories[category_key]
        })

    response = {
        "title": "Reference for " + lang.key,
        "concept": meta_structure.key,
        "concept_friendly_name": meta_structure.friendly_name,
        "lang": lang.key,
        "lang_friendlyname": lang.friendly_name,
        "categories": categories,
        "description": "Code Thesaurus: Reference for " + lang.key
    }

    return render(request, 'reference.html', response)

# pylint: disable=unused-argument
def error_handler_400_bad_request(request, exception):
    """
    Renders the page for a generic client error (HTTP 400)
    :param request: HttpRequest object
    :param exception: details about the exception
    :return: HttpResponse object with rendered object of the page
    """
    response = render(request, 'error400.html')
    return HttpResponseBadRequest(response)

# pylint: disable=unused-argument
def error_handler_403_forbidden(request, exception):
    """
    Renders the page for a forbidden error (HTTP 403)
    :param request: HttpRequest object
    :param exception: details about the exception
    :return: HttpResponse object with rendered object of the page
    """
    response = render(request, 'error403.html')
    return HttpResponseForbidden(response)

# pylint: disable=unused-argument
def error_handler_404_not_found(request, exception):
    """
    Renders the page for a file not found error (HTTP 404)
    :param request: HttpRequest object
    :param exception: details about the exception
    :return: HttpResponse object with rendered object of the page
    """
    response = render(request, 'error404.html')
    return HttpResponseNotFound(response)

def error_handler_500_server_error(request):
    """
    Renders the page for a generic server error (HTTP 500)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    response = render(request, 'error500.html')
    return HttpResponseServerError(response)

# Helper functions
def format_code_for_display(concept_key, lang):
    """
    Returns the formatted HTML formatted syntax-highlighted text for a concept key (from a meta language file) and a language
    :param concept_key: name of the key to format
    :param lang: language to format it (in meta language/syntax highlighter format)
    :return: string with code with applied HTML formatting
    """
    if lang.concept_unknown(concept_key) or lang.concept_code(concept_key) is None:
        return "Unknown"
    if lang.concept_implemented(concept_key):
        return highlight(
            lang.concept_code(concept_key),
            get_lexer_by_name(lang.key, startinline=True),
            HtmlFormatter()
        )
    return None

def format_comment_for_display(concept_key, lang):
    """
    Returns the formatted HTML formatted comment text for a concept key (from a meta language file) and a language
    :param concept_key: the concept key located in the meta language JSON file
    :param lang: the ID of the language to fetch concept key from
    :return: formatted HTML for the comment
    """
    if not lang.concept_implemented(concept_key) and lang.concept_comment(concept_key) == "":
        return "Not Implemented In This Language"
    return lang.concept_comment(concept_key)

def concept_comparision(id, name, lang1, lang2):
    """
    Generates the comparision object of a single concept
    :param id: id of the concept
    :param name: name of the concept
    :param lang1: first language to compare
    :param lang2: other language to compare
    :return: string with code with applied HTML formatting
    """
    return {
        "id": id,
        "name": name,
        "code1": format_code_for_display(id, lang1),
        "code2": format_code_for_display(id, lang2),
        "comment1": format_comment_for_display(id, lang1),
        "comment2": format_comment_for_display(id, lang2)
    }

def concept_reference(id, name, lang):
    """
    Generates the reference object of a single concept
    :param id: id of the concept
    :param name: name of the concept
    :param lang: language to get the reference for
    :return: string with code with applied HTML formatting
    """
    return {
        "id": id,
        "name": name,
        "code": format_code_for_display(id, lang),
        "comment": format_comment_for_display(id, lang)
    }
<commit_msg>Fix passing correct concepts on reference page<commit_after>import json
import random

from django.http import HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError
from django.shortcuts import render
from django.utils.html import escape, strip_tags
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name

from web.Language import Language
from web.MetaInfo import MetaInfo
from web.thesaurus_template_generators import generate_language_template

def index(request):
    """
    Renders the home page (/)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    with open("web/thesauruses/meta_info.json", 'r') as meta_file:
        meta_data = meta_file.read()
    meta_info = json.loads(meta_data)
    meta_data_langs = {
        id: {
            "name": lang["name"],
            "versions": ", ".join(lang["versions"])
        }
        for (id, lang) in meta_info["languages"].items()
    }
    random_langs = random.sample(list(meta_data_langs.values()), k=3)

    content = {
        'title': 'Welcome',
        'languages': meta_data_langs,
        'structures': meta_info["structures"],
        'randomLanguages': random_langs,
        'description': 'Code Thesaurus: A polyglot developer reference tool'
    }
    return render(request, 'index.html', content)

def about(request):
    """
    Renders the about page (/about)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    content = {
        'title': 'About',
        'description': 'Code Thesaurus: A polyglot developer reference tool'
    }
    return render(request, 'about.html', content)

def compare(request):
    """
    Renders the page comparing two language structures (/compare)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    lang1_string = escape(strip_tags(request.GET.get('lang1', '')))
    lang2_string = escape(strip_tags(request.GET.get('lang2', '')))
    structure_query_string = escape(strip_tags(request.GET.get('concept', '')))

    errors = []
    if not structure_query_string:
        errors.append("The URL didn't specify a structure/concept to look up.")
    if not lang1_string:
        errors.append("The URL didn't specify a first language to look up.")
    if not lang2_string:
        errors.append("The URL didn't specify a second language to look up.")

    if errors:
        error_page_data = {
            "errors": errors
        }
        response = render(request, 'errormisc.html', error_page_data)

        return HttpResponseNotFound(response)

    try:
        metainfo = MetaInfo()
        meta_structure = metainfo.structure(structure_query_string)
    except (FileNotFoundError):
        error_page_data = {
            "errors": ["The structure/concept isn't valid. Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)

        return HttpResponseNotFound(response)

    try:
        lang1 = Language(
            lang1_string, metainfo.language_friendly_name(lang1_string))
        lang1.load_concepts(meta_structure.key)
    except (FileNotFoundError):
        response = render(request, "error_missing_structure.html", {
            "name": meta_structure.friendly_name,
            "lang": lang1_string,
            "key": meta_structure.key,
            "template": generate_language_template(
                lang1_string,
                meta_structure.key
            )
        })
        return HttpResponseNotFound(response)
    except (KeyError):
        error_page_data = {
            "errors": [f"The first language ({lang1_string}) isn't valid. \
                Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)
        return HttpResponseNotFound(response)

    try:
        lang2 = Language(
            lang2_string, metainfo.language_friendly_name(lang2_string))
        lang2.load_concepts(meta_structure.key)
    except (FileNotFoundError):
        response = render(request, "error_missing_structure.html", {
            "name": meta_structure.friendly_name,
            "lang": lang2_string,
            "key": meta_structure.key,
            "template": generate_language_template(
                lang2_string,
                meta_structure.key
            )
        })
        return HttpResponseNotFound(response)
    except (KeyError):
        error_page_data = {
            "errors": [f"The second language ({lang2_string}) isn't valid. \
                Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)
        return HttpResponseNotFound(response)

    both_categories = []

    for (category_key, category) in meta_structure.categories.items():
        concepts = [concept_comparision(id, name, lang1, lang2)
                    for (id, name) in category.items()]

        both_categories.append({
            "id": category_key,
            "concepts": concepts
        })

    response = {
        "title": "Comparing " + lang1.friendly_name + " and " + lang2.friendly_name,
        "concept": meta_structure.key,
        "concept_friendly_name": meta_structure.friendly_name,
        "lang1": lang1.key,
        "lang2": lang2.key,
        "lang1_friendlyname": lang1.friendly_name,
        "lang2_friendlyname": lang2.friendly_name,
        "categories": both_categories,
        "description": f"Code Thesaurus: Comparing {lang1.friendly_name} and {lang2.friendly_name}"
    }

    return render(request, 'compare.html', response)

def reference(request):
    """
    Renders the page showing one language structure for reference (/reference)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    lang_string = escape(strip_tags(request.GET.get('lang', '')))
    structure_query_string = escape(strip_tags(request.GET.get('concept', '')))

    errors = []
    if not structure_query_string:
        errors.append("The URL didn't specify a structure/concept to look up.")
    if not lang_string:
        errors.append("Thr URL didn't specify a language to look up.")
    if errors:
        error_page_data = {
            "errors": errors
        }
        response = render(request, 'errormisc.html', error_page_data)

        return HttpResponseNotFound(response)

    try:
        metainfo = MetaInfo()
        meta_structure = metainfo.structure(structure_query_string)
    except (FileNotFoundError):
        error_page_data = {
            "errors": ["The structure/concept isn't valid. Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)

        return HttpResponseNotFound(response)

    try:
        lang = Language(
            lang_string, metainfo.language_friendly_name(lang_string))
        lang.load_concepts(meta_structure.key)
    except (FileNotFoundError):
        ctx = {
            "name": meta_structure.friendly_name,
            "lang": lang_string,
            "key": meta_structure.key,
            "template": generate_language_template(
                lang_string,
                meta_structure.key
            )
        }
        response = render(request, "error_missing_structure.html", ctx)
        return HttpResponseNotFound(response)
    except (KeyError):
        error_page_data = {
            "errors": [f"The language ({lang_string}) isn't valid. \
                        Double-check your URL and try again."]
        }
        response = render(request, "errormisc.html", error_page_data)
        return HttpResponseNotFound(response)

    categories = []

    for (category_key, category) in meta_structure.categories.items():
        concepts = [concept_reference(id, name, lang)
                    for (id, name) in category.items()]
        categories.append({
            "id": category_key,
            "concepts": concepts
        })

    response = {
        "title": "Reference for " + lang.key,
        "concept": meta_structure.key,
        "concept_friendly_name": meta_structure.friendly_name,
        "lang": lang.key,
        "lang_friendlyname": lang.friendly_name,
        "categories": categories,
        "description": "Code Thesaurus: Reference for " + lang.key
    }

    return render(request, 'reference.html', response)

# pylint: disable=unused-argument
def error_handler_400_bad_request(request, exception):
    """
    Renders the page for a generic client error (HTTP 400)
    :param request: HttpRequest object
    :param exception: details about the exception
    :return: HttpResponse object with rendered object of the page
    """
    response = render(request, 'error400.html')
    return HttpResponseBadRequest(response)

# pylint: disable=unused-argument
def error_handler_403_forbidden(request, exception):
    """
    Renders the page for a forbidden error (HTTP 403)
    :param request: HttpRequest object
    :param exception: details about the exception
    :return: HttpResponse object with rendered object of the page
    """
    response = render(request, 'error403.html')
    return HttpResponseForbidden(response)

# pylint: disable=unused-argument
def error_handler_404_not_found(request, exception):
    """
    Renders the page for a file not found error (HTTP 404)
    :param request: HttpRequest object
    :param exception: details about the exception
    :return: HttpResponse object with rendered object of the page
    """
    response = render(request, 'error404.html')
    return HttpResponseNotFound(response)

def error_handler_500_server_error(request):
    """
    Renders the page for a generic server error (HTTP 500)
    :param request: HttpRequest object
    :return: HttpResponse object with rendered object of the page
    """
    response = render(request, 'error500.html')
    return HttpResponseServerError(response)

# Helper functions
def format_code_for_display(concept_key, lang):
    """
    Returns the formatted HTML formatted syntax-highlighted text for a concept key (from a meta language file) and a language
    :param concept_key: name of the key to format
    :param lang: language to format it (in meta language/syntax highlighter format)
    :return: string with code with applied HTML formatting
    """
    if lang.concept_unknown(concept_key) or lang.concept_code(concept_key) is None:
        return "Unknown"
    if lang.concept_implemented(concept_key):
        return highlight(
            lang.concept_code(concept_key),
            get_lexer_by_name(lang.key, startinline=True),
            HtmlFormatter()
        )
    return None

def format_comment_for_display(concept_key, lang):
    """
    Returns the formatted HTML formatted comment text for a concept key (from a meta language file) and a language
    :param concept_key: the concept key located in the meta language JSON file
    :param lang: the ID of the language to fetch concept key from
    :return: formatted HTML for the comment
    """
    if not lang.concept_implemented(concept_key) and lang.concept_comment(concept_key) == "":
        return "Not Implemented In This Language"
    return lang.concept_comment(concept_key)

def concept_comparision(id, name, lang1, lang2):
    """
    Generates the comparision object of a single concept
    :param id: id of the concept
    :param name: name of the concept
    :param lang1: first language to compare
    :param lang2: other language to compare
    :return: string with code with applied HTML formatting
    """
    return {
        "id": id,
        "name": name,
        "code1": format_code_for_display(id, lang1),
        "code2": format_code_for_display(id, lang2),
        "comment1": format_comment_for_display(id, lang1),
        "comment2": format_comment_for_display(id, lang2)
    }

def concept_reference(id, name, lang):
    """
    Generates the reference object of a single concept
    :param id: id of the concept
    :param name: name of the concept
    :param lang: language to get the reference for
    :return: string with code with applied HTML formatting
    """
    return {
        "id": id,
        "name": name,
        "code": format_code_for_display(id, lang),
        "comment": format_comment_for_display(id, lang)
    }
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import requests
from flask import (render_template as _render_template, url_for,
                   redirect, request)

from . import app

# Templating

def render_template(filename, **kwargs):
    template_folder = app.template_folder
    template_folder = template_folder.replace(app.config['ROOT_DIR'], '')

    kwargs['github_url'] = app.config['GITHUB_URL'].format(
        template_folder=template_folder.strip('/'),
        filename=filename
    )
    return _render_template(filename, **kwargs)

@app.context_processor
def inject_context():
    return {
        'debug': app.debug,
        'url': request.url,
    }

# Regular views

@app.route('/')
def index():
    context = {
        'pyvec_account_url': app.config['PYVEC_ACCOUNT_URL'],
    }
    return render_template('index.html', **context)

@app.route('/index-en.html')
def index_en():
    return render_template('index-en.html')

@app.route('/zapojse')
def get_involved():
    board_id = app.config['TRELLO_BOARD_ID']
    url = 'https://trello.com/1/boards/{}/lists?cards=open'.format(board_id)

    resp = requests.get(url)
    trello_board = resp.json()

    context = {
        'trello_board': [sort_by_votes(l) for l in trello_board],
        'trello_board_url': 'https://trello.com/b/{}/'.format(board_id),
        'pyvec_account_url': app.config['PYVEC_ACCOUNT_URL'],
    }
    return render_template('get_involved.html', **context)

def sort_by_votes(trello_list):
    def card_key(card):
        return card['badges']['votes']

    cards = sorted(trello_list['cards'], key=card_key, reverse=True)
    trello_list['cards'] = cards
    return trello_list

# Legacy redirects

@app.route('/index.html')
def index_legacy():
    return redirect(url_for('index'), code=301)

@app.route('/english.html')
def index_en_legacy():
    return redirect(url_for('index_en'), code=301)
<commit_msg>Raising exceptions for failed requests.<commit_after># -*- coding: utf-8 -*-

import requests
from flask import (render_template as _render_template, url_for,
                   redirect, request)

from . import app

# Templating

def render_template(filename, **kwargs):
    template_folder = app.template_folder
    template_folder = template_folder.replace(app.config['ROOT_DIR'], '')

    kwargs['github_url'] = app.config['GITHUB_URL'].format(
        template_folder=template_folder.strip('/'),
        filename=filename
    )
    return _render_template(filename, **kwargs)

@app.context_processor
def inject_context():
    return {
        'debug': app.debug,
        'url': request.url,
    }

# Regular views

@app.route('/')
def index():
    context = {
        'pyvec_account_url': app.config['PYVEC_ACCOUNT_URL'],
    }
    return render_template('index.html', **context)

@app.route('/index-en.html')
def index_en():
    return render_template('index-en.html')

@app.route('/zapojse')
def get_involved():
    board_id = app.config['TRELLO_BOARD_ID']
    url = 'https://trello.com/1/boards/{}/lists?cards=open'.format(board_id)

    resp = requests.get(url)
    resp.raise_for_status()  # TODO better error handling
    trello_board = resp.json()

    context = {
        'trello_board': [sort_by_votes(l) for l in trello_board],
        'trello_board_url': 'https://trello.com/b/{}/'.format(board_id),
        'pyvec_account_url': app.config['PYVEC_ACCOUNT_URL'],
    }
    return render_template('get_involved.html', **context)

def sort_by_votes(trello_list):
    def card_key(card):
        return card['badges']['votes']

    cards = sorted(trello_list['cards'], key=card_key, reverse=True)
    trello_list['cards'] = cards
    return trello_list

# Legacy redirects

@app.route('/index.html')
def index_legacy():
    return redirect(url_for('index'), code=301)

@app.route('/english.html')
def index_en_legacy():
    return redirect(url_for('index_en'), code=301)
<|endoftext|>


<commit_before>from flask import current_app as app, render_template, request, redirect, abort, jsonify, json as json_mod, url_for, session

from CTFd.utils import ctftime, authed, unix_time, get_kpm, can_view_challenges
from CTFd.models import db, Challenges, Files, Solves, WrongKeys, Keys

import time
import re
import logging

def init_challenges(app):
    @app.route('/challenges', methods=['GET'])
    def challenges():
        if not ctftime():
            return redirect('/')
        if can_view_challenges():
            return render_template('chals.html')
        else:
            return redirect(url_for('login', next="challenges"))

    @app.route('/chals', methods=['GET'])
    def chals():
        if not ctftime():
            return redirect('/')
        if can_view_challenges():
            chals = Challenges.query.add_columns('id', 'name', 'value', 'description', 'category').order_by(Challenges.value).all()

            json = {'game':[]}
            for x in chals:
                files = [ str(f.location) for f in Files.query.filter_by(chal=x.id).all() ]
                json['game'].append({'id':x[1], 'name':x[2], 'value':x[3], 'description':x[4], 'category':x[5], 'files':files})

            db.session.close()
            return jsonify(json)
        else:
            db.session.close()
            return redirect('/login')

    @app.route('/chals/solves')
    def chals_per_solves():
        if can_view_challenges():
            solves = Solves.query.add_columns(db.func.count(Solves.chalid)).group_by(Solves.chalid).all()
            json = {}
            for chal, count in solves:
                json[chal.chal.name] = count
            return jsonify(json)
        return redirect(url_for('login', next="/chals/solves"))

    @app.route('/solves')
    @app.route('/solves/<teamid>')
    def solves(teamid=None):
        if teamid is None:
            if authed():
                solves = Solves.query.filter_by(teamid=session['id']).all()
            else:
                abort(401)
        else:
            solves = Solves.query.filter_by(teamid=teamid).all()
        db.session.close()
        json = {'solves':[]}
        for x in solves:
            json['solves'].append({'id':x.id, 'chal':x.chal.name, 'chalid':x.chalid,'team':x.teamid, 'value': x.chal.value, 'category':x.chal.category, 'time':unix_time(x.date)})
        return jsonify(json)

    @app.route('/fails/<teamid>', methods=['GET'])
    def fails(teamid):
        fails = WrongKeys.query.filter_by(team=teamid).count()
        solves = Solves.query.filter_by(teamid=teamid).count()
        db.session.close()
        json = {'fails':str(fails), 'solves': str(solves)}
        return jsonify(json)

    @app.route('/chal/<chalid>/solves', methods=['GET'])
    def who_solved(chalid):
        solves = Solves.query.filter_by(chalid=chalid)
        json = {'teams':[]}
        for solve in solves:
            json['teams'].append({'id':solve.team.id, 'name':solve.team.name, 'date':solve.date})
        return jsonify(json)

    @app.route('/chal/<chalid>', methods=['POST'])
    def chal(chalid):
        if not ctftime():
            return redirect('/')
        if authed():
            logger = logging.getLogger('keys')
            data = (time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'), request.form['key'].encode('utf-8'), get_kpm(session['id']))
            print "[{0}] {1} submitted {2} with kpm {3}".format(*data)
            if get_kpm(session['id']) > 10:
                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
                logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
                return "3" # Submitting too fast
            solves = Solves.query.filter_by(teamid=session['id'], chalid=chalid).first()
            if not solves:
                keys = Keys.query.filter_by(chal=chalid).all()
                key = request.form['key'].strip().lower()
                for x in keys:
                    if x.key_type == 0: #static key
                        if x.flag.strip().lower() == key:
                            solve = Solves(chalid=chalid, teamid=session['id'], ip=request.remote_addr)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                            logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                            return "1" # key was correct
                    elif x.key_type == 1: #regex
                        res = re.match(str(x), key, re.IGNORECASE)
                        if res and res.group() == key:
                            solve = Solves(chalid=chalid, teamid=session['id'], ip=request.remote_addr)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                            logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                            return "1" # key was correct

                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
                logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
                return '0' # key was wrong
            else:
                logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
                return "2" # challenge was already solved
        else:
            return "-1"
<commit_msg>Allowing admins to preview challenge board<commit_after>from flask import current_app as app, render_template, request, redirect, abort, jsonify, json as json_mod, url_for, session

from CTFd.utils import ctftime, authed, unix_time, get_kpm, can_view_challenges, is_admin
from CTFd.models import db, Challenges, Files, Solves, WrongKeys, Keys

import time
import re
import logging

def init_challenges(app):
    @app.route('/challenges', methods=['GET'])
    def challenges():
        if not is_admin() and not ctftime():
            return redirect('/')
        if can_view_challenges():
            return render_template('chals.html')
        else:
            return redirect(url_for('login', next="challenges"))

    @app.route('/chals', methods=['GET'])
    def chals():
        if not is_admin() and not ctftime():
            return redirect('/')
        if can_view_challenges():
            chals = Challenges.query.add_columns('id', 'name', 'value', 'description', 'category').order_by(Challenges.value).all()

            json = {'game':[]}
            for x in chals:
                files = [ str(f.location) for f in Files.query.filter_by(chal=x.id).all() ]
                json['game'].append({'id':x[1], 'name':x[2], 'value':x[3], 'description':x[4], 'category':x[5], 'files':files})

            db.session.close()
            return jsonify(json)
        else:
            db.session.close()
            return redirect('/login')

    @app.route('/chals/solves')
    def chals_per_solves():
        if can_view_challenges():
            solves = Solves.query.add_columns(db.func.count(Solves.chalid)).group_by(Solves.chalid).all()
            json = {}
            for chal, count in solves:
                json[chal.chal.name] = count
            return jsonify(json)
        return redirect(url_for('login', next="/chals/solves"))

    @app.route('/solves')
    @app.route('/solves/<teamid>')
    def solves(teamid=None):
        if teamid is None:
            if authed():
                solves = Solves.query.filter_by(teamid=session['id']).all()
            else:
                abort(401)
        else:
            solves = Solves.query.filter_by(teamid=teamid).all()
        db.session.close()
        json = {'solves':[]}
        for x in solves:
            json['solves'].append({'id':x.id, 'chal':x.chal.name, 'chalid':x.chalid,'team':x.teamid, 'value': x.chal.value, 'category':x.chal.category, 'time':unix_time(x.date)})
        return jsonify(json)

    @app.route('/fails/<teamid>', methods=['GET'])
    def fails(teamid):
        fails = WrongKeys.query.filter_by(team=teamid).count()
        solves = Solves.query.filter_by(teamid=teamid).count()
        db.session.close()
        json = {'fails':str(fails), 'solves': str(solves)}
        return jsonify(json)

    @app.route('/chal/<chalid>/solves', methods=['GET'])
    def who_solved(chalid):
        solves = Solves.query.filter_by(chalid=chalid)
        json = {'teams':[]}
        for solve in solves:
            json['teams'].append({'id':solve.team.id, 'name':solve.team.name, 'date':solve.date})
        return jsonify(json)

    @app.route('/chal/<chalid>', methods=['POST'])
    def chal(chalid):
        if not ctftime():
            return redirect('/')
        if authed():
            logger = logging.getLogger('keys')
            data = (time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'), request.form['key'].encode('utf-8'), get_kpm(session['id']))
            print "[{0}] {1} submitted {2} with kpm {3}".format(*data)
            if get_kpm(session['id']) > 10:
                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
                logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
                return "3" # Submitting too fast
            solves = Solves.query.filter_by(teamid=session['id'], chalid=chalid).first()
            if not solves:
                keys = Keys.query.filter_by(chal=chalid).all()
                key = request.form['key'].strip().lower()
                for x in keys:
                    if x.key_type == 0: #static key
                        if x.flag.strip().lower() == key:
                            solve = Solves(chalid=chalid, teamid=session['id'], ip=request.remote_addr)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                            logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                            return "1" # key was correct
                    elif x.key_type == 1: #regex
                        res = re.match(str(x), key, re.IGNORECASE)
                        if res and res.group() == key:
                            solve = Solves(chalid=chalid, teamid=session['id'], ip=request.remote_addr)
                            db.session.add(solve)
                            db.session.commit()
                            db.session.close()
                            logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
                            return "1" # key was correct

                wrong = WrongKeys(session['id'], chalid, request.form['key'])
                db.session.add(wrong)
                db.session.commit()
                db.session.close()
                logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
                return '0' # key was wrong
            else:
                logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
                return "2" # challenge was already solved
        else:
            return "-1"
<|endoftext|>


<commit_before>################################################################################
# Config file providing some global used variables (e.g. paths)
#
# Author: Daniel Kocher
################################################################################

import os
import errno

# def of dirs, files and constants
def init ():
  global data_dir
  global src_dir
  global images_dir
  global scaler_dir
  global kmeanspp_dir
  global splits_dir
  global classifiers_dir
  global scenes_dir
  global filepaths
  global splits_per_attribute
  global train_test_sizes
  global train_test_labels
  global scale_size
  global class_count
  global scene_train_ratio

  data_dir = '/home/seniix/github/advanced-image-processing-and-computer-vision-ps/data/'
  src_dir = '/home/seniix/github/advanced-image-processing-and-computer-vision-ps/src/'
  images_dir = data_dir + 'images/'
  scaler_dir = src_dir + 'scaler/'
  kmeanspp_dir = src_dir + 'kmeanspp/'
  splits_dir = data_dir + 'splits/'
  classifiers_dir = src_dir + 'classifiers/'
  scenes_dir = data_dir + 'scenes/'

  filepaths = {
    'attributes' : data_dir + 'SUN_attributes.txt',
    'votes' : data_dir + 'SUN_attribute_votes.txt',
    'images' : data_dir + 'SUN_images.txt',
    'k-means++' : kmeanspp_dir + 'kmeanspp.p',
    'scaler' : scaler_dir + 'scaler.p'
  }

  # 1 = positive sample, 0 = negative sample
  train_test_sizes = {
    'asymmetric' : { 'train' : [ 150, 150 ] , 'test' : [ 50, 50 ] },
    #'asymmetric' : { 'train' : [ 6, 6 ], 'test' : [ 2, 2 ] },
    'symmetric' : { 'train' : [ 150, 150 ], 'test' : [ 150, 150 ] }
  }

  # initialize labels (1 = positive sample, 0 = negative sample)
  train_test_labels = {
    'asymmetric' : {
      'train' : [],
      'test' : []
    },
    'symmetric' : {
      'train' : [],
      'test' : []
    }
  }
  label = 1
  for i in range(0, 2):
    for split in ['asymmetric', 'symmetric']:
      for t in ['train', 'test']:
        train_test_labels[split][t].extend(
          [ label for j in range(0, train_test_sizes[split][t][i]) ]
        )
    label = 0

  splits_per_attribute = 10
  scale_size = 256
  class_count = 512
  scene_train_ratio = 80 # percent

# check stati of dirs and files
def check_settings ():
  # required
  if not os.path.isdir(data_dir):
    raise NameError('Data directory \"' + data_dir + '\" does not exist.')

  # required
  if not os.path.isdir(images_dir):
    raise NameError('Images directory \"' + images_dir +
      '\" does not exist.'
    )

  # required
  if not os.path.isdir(scenes_dir):
    raise NameError('Scenes directory \"' + scenes_dir +
      '\" does not exist.'
    )

  # required
  if not os.path.isfile(filepaths['attributes']):
    raise NameError('Attributes file \"' + filepaths['attributes'] +
      '\" does not exists.'
    )

  # required
  if not os.path.isfile(filepaths['votes']):
    raise NameError('Attribute votes file \"' + filepaths['votes'] +
      '\" does not exists.'
    )

  # required
  if not os.path.isfile(filepaths['images']):
    raise NameError('Images file \"' + filepaths['images'] +
      '\" does not exists.'
    )

  # optional (directory is created if it does not exist)
  try:
    os.makedirs(scaler_dir)
  except OSError as ose:
    if ose.errno != errno.EEXIST:
      raise

  # optional (directory is created if it does not exist)
  try:
    os.makedirs(kmeanspp_dir)
  except OSError as ose:
    if ose.errno != errno.EEXIST:
      raise

  # optional (directory is created if it does not exist)
  try:
    os.makedirs(classifiers_dir)
  except OSError as ose:
    if ose.errno != errno.EEXIST:
      raise

# print dir and file settings
def print_settings ():
  print('[SETTINGS] Settings:')
  print('[SETTINGS]  * data directory:          {}'.format(data_dir))
  print('[SETTINGS]  * source directory:        {}'.format(src_dir))
  print('[SETTINGS]  * images directory:        {}'.format(images_dir))
  print('[SETTINGS]  * scaler directory:        {}'.format(scaler_dir))
  print('[SETTINGS]  * k-means++ directory:     {}'.format(kmeanspp_dir))
  print('[SETTINGS]  * splits directory:        {}'.format(splits_dir))
  print('[SETTINGS]  * classifiers directory:   {}'.format(classifiers_dir))
  print('[SETTINGS]  * attributes file:         {}'.format(filepaths['attributes']))
  print('[SETTINGS]  * attribute votes file:    {}'.format(filepaths['votes']))
  print('[SETTINGS]  * images file:             {}'.format(filepaths['images']))
  print('[SETTINGS]  * scaler file:             {}'.format(filepaths['scaler']))
  print('[SETTINGS]  * k-means++ file:          {}'.format(filepaths['k-means++']))
  print('[SETTINGS]  * asymmetric (train/test): {}/{}'.format(
    train_test_sizes['asymmetric']['train'][0] + train_test_sizes['asymmetric']['train'][1],
    train_test_sizes['asymmetric']['test'][0] + train_test_sizes['asymmetric']['test'][1],
  ))
  print('[SETTINGS]  * symmetric (train/test):  {}/{}'.format(
    train_test_sizes['symmetric']['train'][0] + train_test_sizes['symmetric']['train'][1],
    train_test_sizes['symmetric']['test'][0] + train_test_sizes['symmetric']['test'][1],
  ))
  print('[SETTINGS]  * splits per attribute:    {}'.format(splits_per_attribute))
  print('[SETTINGS]  * scaling to:              {}x{}'.format(
    scale_size, scale_size
  ))
  print('[SETTINGS]  * number of classes:       {}'.format(class_count))
<commit_msg>Add unbalanced asymmetric splits and balanced symmetric splits<commit_after>################################################################################
# Config file providing some global used variables (e.g. paths)
#
# Author: Daniel Kocher
################################################################################

import os
import errno

# def of dirs, files and constants
def init ():
  global data_dir
  global src_dir
  global images_dir
  global scaler_dir
  global kmeanspp_dir
  global splits_dir
  global classifiers_dir
  global scenes_dir
  global filepaths
  global splits_per_attribute
  global train_test_sizes
  global train_test_labels
  global scale_size
  global class_count
  global scene_train_ratio

  data_dir = '/home/seniix/github/advanced-image-processing-and-computer-vision-ps/data/'
  src_dir = '/home/seniix/github/advanced-image-processing-and-computer-vision-ps/src/'
  images_dir = data_dir + 'images/'
  scaler_dir = src_dir + 'scaler/'
  kmeanspp_dir = src_dir + 'kmeanspp/'
  splits_dir = data_dir + 'splits/'
  classifiers_dir = src_dir + 'classifiers/'
  scenes_dir = data_dir + 'scenes/'

  filepaths = {
    'attributes' : data_dir + 'SUN_attributes.txt',
    'votes' : data_dir + 'SUN_attribute_votes.txt',
    'images' : data_dir + 'SUN_images.txt',
    'k-means++' : kmeanspp_dir + 'kmeanspp.p',
    'scaler' : scaler_dir + 'scaler.p'
  }

  # 1 = positive sample, 0 = negative sample
  # Entries:
  #  1. asymmetric, sets balanced (50% negative samples, 50% positive samples)
  #  2. asymmetric, sets unbalanced (95% negative samples, 5% positive samples)
  #  3. symmetric, sets unbalanced (95% negative samples, 5% positive samples)
  #  4. symmetric, sets balanced (50% negative samples, 50% positive samples)
  train_test_sizes = {
    'asymmetric' : { 'train' : [ 150, 150 ] , 'test' : [ 50, 50 ] },
    #'asymmetric' : { 'train' : [ 450, 24 ], 'test' : [ 150, 8 ] },
    'symmetric' : { 'train' : [ 500, 25 ], 'test' : [ 500, 25 ] }
    #'symmetric' : { 'train' : [ 150, 150 ], 'test' : [ 150, 150] }
  }

  # initialize labels (1 = positive sample, 0 = negative sample)
  train_test_labels = {
    'asymmetric' : {
      'train' : [],
      'test' : []
    },
    'symmetric' : {
      'train' : [],
      'test' : []
    }
  }
  label = 1
  for i in range(0, 2):
    for split in ['asymmetric', 'symmetric']:
      for t in ['train', 'test']:
        train_test_labels[split][t].extend(
          [ label for j in range(0, train_test_sizes[split][t][i]) ]
        )
    label = 0

  splits_per_attribute = 10
  scale_size = 256
  class_count = 512
  scene_train_ratio = 80 # percent

# check stati of dirs and files
def check_settings ():
  # required
  if not os.path.isdir(data_dir):
    raise NameError('Data directory \"' + data_dir + '\" does not exist.')

  # required
  if not os.path.isdir(images_dir):
    raise NameError('Images directory \"' + images_dir +
      '\" does not exist.'
    )

  # required
  if not os.path.isdir(scenes_dir):
    raise NameError('Scenes directory \"' + scenes_dir +
      '\" does not exist.'
    )

  # required
  if not os.path.isfile(filepaths['attributes']):
    raise NameError('Attributes file \"' + filepaths['attributes'] +
      '\" does not exists.'
    )

  # required
  if not os.path.isfile(filepaths['votes']):
    raise NameError('Attribute votes file \"' + filepaths['votes'] +
      '\" does not exists.'
    )

  # required
  if not os.path.isfile(filepaths['images']):
    raise NameError('Images file \"' + filepaths['images'] +
      '\" does not exists.'
    )

  # optional (directory is created if it does not exist)
  try:
    os.makedirs(scaler_dir)
  except OSError as ose:
    if ose.errno != errno.EEXIST:
      raise

  # optional (directory is created if it does not exist)
  try:
    os.makedirs(kmeanspp_dir)
  except OSError as ose:
    if ose.errno != errno.EEXIST:
      raise

  # optional (directory is created if it does not exist)
  try:
    os.makedirs(classifiers_dir)
  except OSError as ose:
    if ose.errno != errno.EEXIST:
      raise

# print dir and file settings
def print_settings ():
  print('[SETTINGS] Settings:')
  print('[SETTINGS]  * data directory:          {}'.format(data_dir))
  print('[SETTINGS]  * source directory:        {}'.format(src_dir))
  print('[SETTINGS]  * images directory:        {}'.format(images_dir))
  print('[SETTINGS]  * scaler directory:        {}'.format(scaler_dir))
  print('[SETTINGS]  * k-means++ directory:     {}'.format(kmeanspp_dir))
  print('[SETTINGS]  * splits directory:        {}'.format(splits_dir))
  print('[SETTINGS]  * classifiers directory:   {}'.format(classifiers_dir))
  print('[SETTINGS]  * attributes file:         {}'.format(filepaths['attributes']))
  print('[SETTINGS]  * attribute votes file:    {}'.format(filepaths['votes']))
  print('[SETTINGS]  * images file:             {}'.format(filepaths['images']))
  print('[SETTINGS]  * scaler file:             {}'.format(filepaths['scaler']))
  print('[SETTINGS]  * k-means++ file:          {}'.format(filepaths['k-means++']))
  print('[SETTINGS]  * asymmetric (train/test): {}/{}'.format(
    train_test_sizes['asymmetric']['train'][0] + train_test_sizes['asymmetric']['train'][1],
    train_test_sizes['asymmetric']['test'][0] + train_test_sizes['asymmetric']['test'][1],
  ))
  print('[SETTINGS]  * symmetric (train/test):  {}/{}'.format(
    train_test_sizes['symmetric']['train'][0] + train_test_sizes['symmetric']['train'][1],
    train_test_sizes['symmetric']['test'][0] + train_test_sizes['symmetric']['test'][1],
  ))
  print('[SETTINGS]  * splits per attribute:    {}'.format(splits_per_attribute))
  print('[SETTINGS]  * scaling to:              {}x{}'.format(
    scale_size, scale_size
  ))
  print('[SETTINGS]  * number of classes:       {}'.format(class_count))
<|endoftext|>


<commit_before>from selenium import webdriver
from pandas import DataFrame
import csv
import time
import sys
import getopt

# load test data
inputfile = str(sys.argv[1])
with open(inputfile, 'rb') as f:
	reader = csv.reader(f)
	testbot_raw = list(reader)

testbot = sorted(testbot_raw, key=lambda testbot_raw: testbot_raw[2])
df = DataFrame(testbot, columns = testbot[len(testbot)-1])
# set test sample ec url
preurl = "http://etusaasentry.com:8099/test_entry.html"
url = "http://etusaas.com:8099/test.html"
# launch browsers for each uid
driver = {}
k = 0
ssid = df.ssid.unique()
while k < len(ssid)-1:
	key = ssid[k]
	value = webdriver.PhantomJS()
	#value = webdriver.Firefox()
	driver[key] = value
	driver[key].delete_all_cookies()
	k += 1

# send actions from testbot
for k in range(len(df)-1):
	driver[df.ssid[k]].get(preurl)
	driver[df.ssid[k]].find_element_by_link_text('TEST').click()
	driver[df.ssid[k]].find_element_by_id('agroup').send_keys("etusolution")
	driver[df.ssid[k]].find_element_by_id('acid').send_keys("etusolutionrec")
	driver[df.ssid[k]].find_element_by_id('auid').send_keys(df.uid[k])
	if df.lo[k] == '0':
		driver[df.ssid[k]].find_element_by_id('auid').send_keys("")
		pass
	driver[df.ssid[k]].find_element_by_id('aact').send_keys(df.act[k])
	driver[df.ssid[k]].find_element_by_id('acat').send_keys(df.cat[k])
	driver[df.ssid[k]].find_element_by_id('apid').send_keys(df.pid[k])
	driver[df.ssid[k]].find_element_by_id('apcat').send_keys(df.pcat[k])
	driver[df.ssid[k]].find_element_by_id('apaypid').send_keys(df.paypid[k])
	driver[df.ssid[k]].find_element_by_id('aunit_price').send_keys(df.unit_price[k])
	#driver[df.ssid[k]].find_element_by_id('apmk').send_keys(df.pmk[k])
	driver[df.ssid[k]].find_element_by_id('aqty').send_keys(df.qty[k])
	driver[df.ssid[k]].find_element_by_id('aeturec').send_keys(df.eturec[k])
	driver[df.ssid[k]].find_element_by_id('aoid').send_keys(df.oid[k])
	driver[df.ssid[k]].find_element_by_id('aercamp').send_keys(df.ERCAMP[k])
	driver[df.ssid[k]].find_element_by_id('aerad').send_keys(df.ERAD[k])
	driver[df.ssid[k]].find_element_by_id('custom-click').click()
	if df.flag[k] == '1':
		driver[df.ssid[k]].switch_to.frame(driver[df.ssid[k]].find_element_by_tag_name("iframe"))
		driver[df.ssid[k]].delete_all_cookies()
		driver[df.ssid[k]].switch_to.default_content()
		driver[df.ssid[k]].delete_all_cookies()
		pass

for k in range(len(ssid)-1):
	#driver[ssid[k]].switch_to.frame(driver[ssid[k]].find_element_by_tag_name("iframe"))
	driver[ssid[k]].delete_all_cookies()
	#driver[df.ssid[k]].switch_to.default_content()
	driver[ssid[k]].quit()
<commit_msg>try firefox to resolve session/cookie issue<commit_after>from selenium import webdriver
from pandas import DataFrame
import csv
import time
import sys
import getopt

# load test data
inputfile = str(sys.argv[1])
with open(inputfile, 'rb') as f:
	reader = csv.reader(f)
	testbot_raw = list(reader)

testbot = sorted(testbot_raw, key=lambda testbot_raw: testbot_raw[2])
df = DataFrame(testbot, columns = testbot[len(testbot)-1])
# set test sample ec url
preurl = "http://etusaasentry.com:8099/test_entry.html"
url = "http://etusaas.com:8099/test.html"
# launch browsers for each uid
driver = {}
k = 0
ssid = df.ssid.unique()
while k < len(ssid)-1:
	key = ssid[k]
	#value = webdriver.PhantomJS()
	value = webdriver.Firefox()
	driver[key] = value
	driver[key].delete_all_cookies()
	k += 1

# send actions from testbot
for k in range(len(df)-1):
	driver[df.ssid[k]].get(preurl)
	driver[df.ssid[k]].find_element_by_link_text('TEST').click()
	driver[df.ssid[k]].find_element_by_id('agroup').send_keys("etusolution")
	driver[df.ssid[k]].find_element_by_id('acid').send_keys("etusolutionrec")
	driver[df.ssid[k]].find_element_by_id('auid').send_keys(df.uid[k])
	if df.lo[k] == '0':
		driver[df.ssid[k]].find_element_by_id('auid').send_keys("")
		pass
	driver[df.ssid[k]].find_element_by_id('aact').send_keys(df.act[k])
	driver[df.ssid[k]].find_element_by_id('acat').send_keys(df.cat[k])
	driver[df.ssid[k]].find_element_by_id('apid').send_keys(df.pid[k])
	driver[df.ssid[k]].find_element_by_id('apcat').send_keys(df.pcat[k])
	driver[df.ssid[k]].find_element_by_id('apaypid').send_keys(df.paypid[k])
	driver[df.ssid[k]].find_element_by_id('aunit_price').send_keys(df.unit_price[k])
	#driver[df.ssid[k]].find_element_by_id('apmk').send_keys(df.pmk[k])
	driver[df.ssid[k]].find_element_by_id('aqty').send_keys(df.qty[k])
	driver[df.ssid[k]].find_element_by_id('aeturec').send_keys(df.eturec[k])
	driver[df.ssid[k]].find_element_by_id('aoid').send_keys(df.oid[k])
	driver[df.ssid[k]].find_element_by_id('aercamp').send_keys(df.ERCAMP[k])
	driver[df.ssid[k]].find_element_by_id('aerad').send_keys(df.ERAD[k])
	driver[df.ssid[k]].find_element_by_id('custom-click').click()
	#if df.flag[k] == '1':
	#	driver[df.ssid[k]].switch_to.frame(driver[df.ssid[k]].find_element_by_tag_name("iframe"))
	#	driver[df.ssid[k]].delete_all_cookies()
	#	driver[df.ssid[k]].switch_to.default_content()
	#	driver[df.ssid[k]].delete_all_cookies()
	#	pass

for k in range(len(ssid)-1):
	#driver[ssid[k]].switch_to.frame(driver[ssid[k]].find_element_by_tag_name("iframe"))
	driver[ssid[k]].delete_all_cookies()
	#driver[ssid[k]].switch_to.default_content()
	driver[ssid[k]].quit()
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Karl Mikaelsson <derfian@lysator.liu.se>
#
# 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.

import socket
import json
import random
import xml.etree.ElementTree as ElementTree
import requests
import StringIO
import httplib

CRA_SSDP_MGRP = '239.255.255.250'
CRA_SSDP_PORT = 1900
CRA_SSDP_GROUP = (CRA_SSDP_MGRP, CRA_SSDP_PORT)

CRA_SSDP_MX = 5      # Request timeout, seconds
CRA_SSDP_ST = 'urn:schemas-sony-com:service:ScalarWebAPI:1'
CRA_SSDP_MSG = "\r\n".join([
    'M-SEARCH * HTTP/1.1',
    'HOST: {h}:{p}',
    'MAN: "ssdp:discover"',
    'ST: {st}',
    'MX: 3',
    '',
    ''])

ALL = ['CameraRemoteError',
       'CameraRemoteServerError',
       'CameraRemoteAPI',
       'discover']

class SSDPResponse(object):
    class _FakeSocket(StringIO.StringIO):
        def makefile(self, *args, **kw):
            return self
    def __init__(self, response):
        r = httplib.HTTPResponse(self._FakeSocket(response))
        r.begin()
        self.location = r.getheader("location")
        self.usn = r.getheader("usn")
        self.st = r.getheader("st")
        try:
            self.cache = r.getheader("cache-control").split("=")[1]
        except:
            self.cache = None
    def __repr__(self):
        return "<SSDPResponse({location}, {st}, {usn})>".format(**self.__dict__)

class CameraRemoteError(Exception):
    """ Generic exception from within CameraRemoteAPI """
    pass

class CameraRemoteRPCError(CameraRemoteError):
    """ The API call failed. """
    pass

class CameraRemoteAPI:
    urls = {}
    _json_headers = {'Content-Type': "application/json",}
    trace = False

    def __init__(self, ddxml):
        """Initialize the CameraRemoteAPI Object with a device description XML
        file. FIXME: Reconsider this approach"""
        _x = ElementTree.fromstring(ddxml)

        ns = "urn:schemas-sony-com:av"

        for service in _x.findall('.//{%(ns)s}X_ScalarWebAPI_ServiceList/{%(ns)s}X_ScalarWebAPI_Service' % locals()):
            servicetype = service.find('{%(ns)s}X_ScalarWebAPI_ServiceType' % locals()).text
            serviceurl = service.find('{%(ns)s}X_ScalarWebAPI_ActionList_URL' % locals()).text
            self.urls[servicetype] = serviceurl + '/' + servicetype

    def _apicall(self, endpoint, **params):
        """ Perform an actual API call. """

        if not 'id' in params:
            params['id'] = random.randint(1, 0x7FFFFFF)

        if not endpoint in self.urls:
            raise CameraRemoteError("Unknown endpoint %r" % endpoint)

        if self.trace:
            print self.urls[endpoint], "<-", params

        r = requests.post(self.urls[endpoint], data=json.dumps(params), headers=self._json_headers)
        j = r.json()
        r.close()

        if self.trace:
            print self.urls[endpoint], "->", j

        # FIXME: Long exposures may signal errors while they're
        # processing. Look into that.
        if 'error' in j:
            raise CameraRemoteRPCError({'code': j['error'][0],
                                        'message': j['error'][1]})
        return j

    # Implement methods here:
    def getVersions(self):
        resp = self._apicall('camera',
                             method='getVersions',
                             params=[],
                             version='1.0')
        return resp['result'][0]

    def setShootMode(self, shootmode):
        resp = self._apicall('camera',
                             method="setShootMode",
                             params=[shootmode],
                             version="1.0")
        return

    def getShootMode(self):
        resp = self._apicall('camera',
                             method="getShootMode",
                             params=[],
                             version="1.0")
        return resp['result'][0]

    def getSupportedShootMode(self):
        resp = self._apicall('camera',
                             method="getSupportedShootMode",
                             params=[],
                             version="1.0")
        return resp['result']

    def getAvailableShootMode(self):
        resp = self._apicall('camera',
                             method="getAvailableShootMode",
                             params=[],
                             version="1.0")
        return resp['result']

    def actTakePicture(self):
        resp = self._apicall('camera',
                             method='actTakePicture',
                             params=[],
                             version='1.0')
        return resp['result'][0]

    def awaitTakePicture(self):
        resp = self._apicall('camera',
                             method='awaitTakePicture',
                             params=[],
                             version='1.0')
        return resp['result'][0]

    def startContShooting(self):
        resp = self._apicall('camera',
                             method='startContShooting',
                             params=[],
                             version='1.0')
        return

    def stopContShooting(self):
        raise NotImplemented

    def startMovieRec(self):
        raise NotImplemented

    def stopMovieRec(self):
        raise NotImplemented

    def startAudioRec(self):
        raise NotImplemented

    def stopAudioRec(self):
        raise NotImplemented

    def startIntervalStillRec(self):
        raise NotImplemented

    def stopIntervalStillRec(self):
        raise NotImplemented

    def startLiveview(self):
        raise NotImplemented

    def stopLiveview(self):
        raise NotImplemented

    def startLiveviewWithSize(self):
        raise NotImplemented

    def getLiveviewSize(self):
        raise NotImplemented

    def getSupportedLiveviewSize(self):
        raise NotImplemented

    def getAvailableLiveviewSize(self):
        raise NotImplemented

    def setLiveviewFrameInfo(self):
        raise NotImplemented

    def getLiveviewFrameInfo(self):
        raise NotImplemented

    def actZoom(self):
        raise NotImplemented

    def setZoomSetting(self):
        raise NotImplemented

    def getZoomSetting(self):
        raise NotImplemented

    def getSupportedZoomSetting(self):
        raise NotImplemented

    def getAvailableZoomSetting(self):
        raise NotImplemented

    def actHalfPressShutter(self):
        raise NotImplemented

    def cancelHalfPressShutter(self):
        raise NotImplemented

    def setTouchAFPosition(self):
        raise NotImplemented

    def getTouchAFPosition(self):
        raise NotImplemented

    def cancelTouchAFPosition(self):
        raise NotImplemented

    def actTrackingFocus(self):
        raise NotImplemented

    def cancelTrackingFocus(self):
        raise NotImplemented

    def setTrackingFocus(self):
        raise NotImplemented

    def getTrackingFocus(self):
        raise NotImplemented

    def getSupportedTrackingFocus(self):
        raise NotImplemented

    def getAvailableTrackingFocus(self):
        raise NotImplemented

    def setContShootingMode(self):
        raise NotImplemented

    def getContShootingMode(self):
        raise NotImplemented

    def getSupportedContShootingMode(self):
        raise NotImplemented

    def getAvailableContShootingMode(self):
        raise NotImplemented

    def setContShootingSpeed(self):
        raise NotImplemented

    def getContShootingSpeed(self):
        raise NotImplemented

    def getSupportedContShootingSpeed(self):
        raise NotImplemented

    def getAvailableContShootingSpeed(self):
        raise NotImplemented

    def setSelfTimer(self):
        raise NotImplemented

    def getSelfTimer(self):
        raise NotImplemented

    def getSupportedSelfTimer(self):
        raise NotImplemented

    def getAvailableSelfTimer(self):
        raise NotImplemented

    def setExposureMode(self):
        raise NotImplemented

    def getExposureMode(self):
        raise NotImplemented

    def getSupportedExposureMode(self):
        raise NotImplemented

    def getAvailableExposureMode(self):
        raise NotImplemented

    def setFocusMode(self):
        raise NotImplemented

    def getFocusMode(self):
        raise NotImplemented

    def getSupportedFocusMode(self):
        raise NotImplemented

    def getAvailableFocusMode(self):
        raise NotImplemented

    def getExposureCompensation(self):
        raise NotImplemented

    def setExposureCompensation(self):
        raise NotImplemented

    def getSupportedExposureCompensation(self):
        raise NotImplemented

    def getAvailableExposureCompensation(self):
        raise NotImplemented

    def setFNumber(self):
        raise NotImplemented

    def getFNumber(self):
        raise NotImplemented

    def getSupportedFNumber(self):
        raise NotImplemented

    def getAvailableFNumber(self):
        raise NotImplemented

    def setShutterSpeed(self):
        raise NotImplemented

    def getShutterSpeed(self):
        raise NotImplemented

    def getSupportedShutterSpeed(self):
        raise NotImplemented

    def getAvailableShutterSpeed(self):
        raise NotImplemented

    def setIsoSpeedRate(self):
        raise NotImplemented

    def getIsoSpeedRate(self):
        raise NotImplemented

    def getSupportedIsoSpeedRate(self):
        raise NotImplemented

    def getAvailableIsoSpeedRate(self):
        raise NotImplemented

    def setWhiteBalance(self):
        raise NotImplemented

    def getWhiteBalance(self):
        raise NotImplemented

    def getSupportedWhiteBalance(self):
        raise NotImplemented

    def getAvailableWhiteBalance(self):
        raise NotImplemented

    def setProgramShift(self):
        raise NotImplemented

    def getSupportedProgramShift(self):
        raise NotImplemented

    def setFlashMode(self):
        raise NotImplemented

    def getFlashMode(self):
        raise NotImplemented

    def getSupportedFlashMode(self):
        raise NotImplemented

    def getAvailableFlashMode(self):
        raise NotImplemented

    def setStillSize(self):
        raise NotImplemented

    def getStillSize(self):
        raise NotImplemented

    def getSupportedStillSize(self):
        raise NotImplemented

    def getAvailableStillSize(self):
        raise NotImplemented

    def setStillQuality(self):
        raise NotImplemented

    def getStillQuality(self):
        raise NotImplemented

    def getSupportedStillQuality(self):
        raise NotImplemented

    def getAvailableStillQuality(self):
        raise NotImplemented

    def setPostviewImageSize(self):
        raise NotImplemented

    def getPostviewImageSize(self):
        raise NotImplemented

    def getSupportedPostviewImageSize(self):
        raise NotImplemented

    def getAvailablePostviewImageSize(self):
        raise NotImplemented

    def setMovieFileFormat(self):
        raise NotImplemented

    def getMovieFileFormat(self):
        raise NotImplemented

    def getSupportedMovieFileFormat(self):
        raise NotImplemented

    def getAvailableMovieFileFormat(self):
        raise NotImplemented

    def setMovieQuality(self):
        raise NotImplemented

    def getMovieQuality(self):
        raise NotImplemented

    def getSupportedMovieQuality(self):
        raise NotImplemented

    def getAvailableMovieQuality(self):
        raise NotImplemented

    def setSteadyMode(self):
        raise NotImplemented

    def getSteadyMode(self):
        raise NotImplemented

    def getSupportedSteadyMode(self):
        raise NotImplemented

    def getAvailableSteadyMode(self):
        raise NotImplemented

    def setViewAngle(self):
        raise NotImplemented

    def getViewAngle(self):
        raise NotImplemented

    def getSupportedViewAngle(self):
        raise NotImplemented

    def getAvailableViewAngle(self):
        raise NotImplemented

    def setSceneSelection(self):
        raise NotImplemented

    def getSceneSelection(self):
        raise NotImplemented

    def getSupportedSceneSelection(self):
        raise NotImplemented

    def getAvailableSceneSelection(self):
        raise NotImplemented

    def setColorSetting(self):
        raise NotImplemented

    def getColorSetting(self):
        raise NotImplemented

    def getSupportedColorSetting(self):
        raise NotImplemented

    def getAvailableColorSetting(self):
        raise NotImplemented

    def setIntervalTime(self):
        raise NotImplemented

    def getIntervalTime(self):
        raise NotImplemented

    def getSupportedIntervalTime(self):
        raise NotImplemented

    def getAvailableIntervalTime(self):
        raise NotImplemented

    def setFlipSetting(self):
        raise NotImplemented

    def getFlipSetting(self):
        raise NotImplemented

    def getSupportedFlipSetting(self):
        raise NotImplemented

    def getAvailableFlipSetting(self):
        raise NotImplemented

    def setTvColorSystem(self):
        raise NotImplemented

    def getTvColorSystem(self):
        raise NotImplemented

    def getSupportedTvColorSystem(self):
        raise NotImplemented

    def getAvailableTvColorSystem(self):
        raise NotImplemented

    def startRecMode(self):
        raise NotImplemented

    def stopRecMode(self):
        raise NotImplemented

    def setCameraFunction(self):
        raise NotImplemented

    def getCameraFunction(self):
        raise NotImplemented

    def getSupportedCameraFunction(self):
        raise NotImplemented

    def getAvailableCameraFunction(self):
        raise NotImplemented

    def getSchemeList(self):
        raise NotImplemented

    def getSourceList(self):
        raise NotImplemented

    def getContentCount(self):
        raise NotImplemented

    def getContentList(self):
        raise NotImplemented

    def setStreamingContent(self):
        raise NotImplemented

    def startStreaming(self):
        raise NotImplemented

    def pauseStreaming(self):
        raise NotImplemented

    def seekStreamingPosition(self):
        raise NotImplemented

    def stopStreaming(self):
        raise NotImplemented

    def requestToNotifyStreamingStatus(self):
        raise NotImplemented

    def deleteContent(self):
        raise NotImplemented

    def setInfraredRemoteControl(self):
        raise NotImplemented

    def getInfraredRemoteControl(self):
        raise NotImplemented

    def getSupportedInfraredControl(self):
        raise NotImplemented

    def getAvailableInfraredControl(self):
        raise NotImplemented

    def setAutoPowerOff(self):
        raise NotImplemented

    def getAutoPowerOff(self):
        raise NotImplemented

    def getSupportedAutoPowerOff(self):
        raise NotImplemented

    def getAvailableAutoPowerOff(self):
        raise NotImplemented

    def setBeepMode(self):
        raise NotImplemented

    def getBeepMode(self):
        raise NotImplemented

    def getSupportedBeepMode(self):
        raise NotImplemented

    def getAvailableBeepMode(self):
        raise NotImplemented

    def setCurrentTime(self):
        raise NotImplemented

    def getStorageInformation(self):
        raise NotImplemented

    def getEvent(self):
        raise NotImplemented

    def getEvent(self):
        raise NotImplemented

    def getEvent(self):
        raise NotImplemented

    def getAvailableApiList(self):
        raise NotImplemented

    def getApplicationInfo(self):
        raise NotImplemented

    def getMethodTypes(self):
        raise NotImplemented

def discover():
    resp = __msearch()
    _ddurl = resp.location

    _ddr = requests.get(_ddurl)
    if _ddr.status_code != 200:
        raise CameraRemoteError("Failed to get Device Description from %s" % _ddurl)

    return CameraRemoteAPI(_ddr.text)

def __msearch(st=CRA_SSDP_ST):
    """Send a M-SEARCH * HTTP/1.1 request and return the response"""
    sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sender.setsockopt(socket.IPPROTO_IP,
                      socket.IP_MULTICAST_TTL,
                      1)
    # FIXME: Need to figure out which interface is the right one if
    # there are more than one. This is wrong.
    sender.setsockopt(socket.SOL_IP,
                      socket.IP_MULTICAST_IF,
                      socket.inet_pton(socket.AF_INET,
                                       '192.168.122.173'))
    sender.setsockopt(socket.SOL_IP,
                      socket.IP_MULTICAST_LOOP,
                      1)
    sender.sendto(CRA_SSDP_MSG.format(h=CRA_SSDP_MGRP,
                                      p=CRA_SSDP_PORT,
                                      st=st),
                  CRA_SSDP_GROUP)
    responses = {}

    _msg, _from = sender.recvfrom(1024)
    r = SSDPResponse(_msg)

    if sender:
        sender.close()

    return r
<commit_msg>Implement stopContShooting API call<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Karl Mikaelsson <derfian@lysator.liu.se>
#
# 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.

import socket
import json
import random
import xml.etree.ElementTree as ElementTree
import requests
import StringIO
import httplib

CRA_SSDP_MGRP = '239.255.255.250'
CRA_SSDP_PORT = 1900
CRA_SSDP_GROUP = (CRA_SSDP_MGRP, CRA_SSDP_PORT)

CRA_SSDP_MX = 5      # Request timeout, seconds
CRA_SSDP_ST = 'urn:schemas-sony-com:service:ScalarWebAPI:1'
CRA_SSDP_MSG = "\r\n".join([
    'M-SEARCH * HTTP/1.1',
    'HOST: {h}:{p}',
    'MAN: "ssdp:discover"',
    'ST: {st}',
    'MX: 3',
    '',
    ''])

ALL = ['CameraRemoteError',
       'CameraRemoteServerError',
       'CameraRemoteAPI',
       'discover']

class SSDPResponse(object):
    class _FakeSocket(StringIO.StringIO):
        def makefile(self, *args, **kw):
            return self
    def __init__(self, response):
        r = httplib.HTTPResponse(self._FakeSocket(response))
        r.begin()
        self.location = r.getheader("location")
        self.usn = r.getheader("usn")
        self.st = r.getheader("st")
        try:
            self.cache = r.getheader("cache-control").split("=")[1]
        except:
            self.cache = None
    def __repr__(self):
        return "<SSDPResponse({location}, {st}, {usn})>".format(**self.__dict__)

class CameraRemoteError(Exception):
    """ Generic exception from within CameraRemoteAPI """
    pass

class CameraRemoteRPCError(CameraRemoteError):
    """ The API call failed. """
    pass

class CameraRemoteAPI:
    urls = {}
    _json_headers = {'Content-Type': "application/json",}
    trace = False

    def __init__(self, ddxml):
        """Initialize the CameraRemoteAPI Object with a device description XML
        file. FIXME: Reconsider this approach"""
        _x = ElementTree.fromstring(ddxml)

        ns = "urn:schemas-sony-com:av"

        for service in _x.findall('.//{%(ns)s}X_ScalarWebAPI_ServiceList/{%(ns)s}X_ScalarWebAPI_Service' % locals()):
            servicetype = service.find('{%(ns)s}X_ScalarWebAPI_ServiceType' % locals()).text
            serviceurl = service.find('{%(ns)s}X_ScalarWebAPI_ActionList_URL' % locals()).text
            self.urls[servicetype] = serviceurl + '/' + servicetype

    def _apicall(self, endpoint, **params):
        """ Perform an actual API call. """

        if not 'id' in params:
            params['id'] = random.randint(1, 0x7FFFFFF)

        if not endpoint in self.urls:
            raise CameraRemoteError("Unknown endpoint %r" % endpoint)

        if self.trace:
            print self.urls[endpoint], "<-", params

        r = requests.post(self.urls[endpoint], data=json.dumps(params), headers=self._json_headers)
        j = r.json()
        r.close()

        if self.trace:
            print self.urls[endpoint], "->", j

        # FIXME: Long exposures may signal errors while they're
        # processing. Look into that.
        if 'error' in j:
            raise CameraRemoteRPCError({'code': j['error'][0],
                                        'message': j['error'][1]})
        return j

    # Implement methods here:
    def getVersions(self):
        resp = self._apicall('camera',
                             method='getVersions',
                             params=[],
                             version='1.0')
        return resp['result'][0]

    def setShootMode(self, shootmode):
        resp = self._apicall('camera',
                             method="setShootMode",
                             params=[shootmode],
                             version="1.0")
        return

    def getShootMode(self):
        resp = self._apicall('camera',
                             method="getShootMode",
                             params=[],
                             version="1.0")
        return resp['result'][0]

    def getSupportedShootMode(self):
        resp = self._apicall('camera',
                             method="getSupportedShootMode",
                             params=[],
                             version="1.0")
        return resp['result']

    def getAvailableShootMode(self):
        resp = self._apicall('camera',
                             method="getAvailableShootMode",
                             params=[],
                             version="1.0")
        return resp['result']

    def actTakePicture(self):
        resp = self._apicall('camera',
                             method='actTakePicture',
                             params=[],
                             version='1.0')
        return resp['result'][0]

    def awaitTakePicture(self):
        resp = self._apicall('camera',
                             method='awaitTakePicture',
                             params=[],
                             version='1.0')
        return resp['result'][0]

    def startContShooting(self):
        resp = self._apicall('camera',
                             method='startContShooting',
                             params=[],
                             version='1.0')
        return

    def stopContShooting(self):
        resp = self._apicall('camera',
                             method='stopContShooting',
                             params=[],
                             version='1.0')
        return

    def startMovieRec(self):
        raise NotImplemented

    def stopMovieRec(self):
        raise NotImplemented

    def startAudioRec(self):
        raise NotImplemented

    def stopAudioRec(self):
        raise NotImplemented

    def startIntervalStillRec(self):
        raise NotImplemented

    def stopIntervalStillRec(self):
        raise NotImplemented

    def startLiveview(self):
        raise NotImplemented

    def stopLiveview(self):
        raise NotImplemented

    def startLiveviewWithSize(self):
        raise NotImplemented

    def getLiveviewSize(self):
        raise NotImplemented

    def getSupportedLiveviewSize(self):
        raise NotImplemented

    def getAvailableLiveviewSize(self):
        raise NotImplemented

    def setLiveviewFrameInfo(self):
        raise NotImplemented

    def getLiveviewFrameInfo(self):
        raise NotImplemented

    def actZoom(self):
        raise NotImplemented

    def setZoomSetting(self):
        raise NotImplemented

    def getZoomSetting(self):
        raise NotImplemented

    def getSupportedZoomSetting(self):
        raise NotImplemented

    def getAvailableZoomSetting(self):
        raise NotImplemented

    def actHalfPressShutter(self):
        raise NotImplemented

    def cancelHalfPressShutter(self):
        raise NotImplemented

    def setTouchAFPosition(self):
        raise NotImplemented

    def getTouchAFPosition(self):
        raise NotImplemented

    def cancelTouchAFPosition(self):
        raise NotImplemented

    def actTrackingFocus(self):
        raise NotImplemented

    def cancelTrackingFocus(self):
        raise NotImplemented

    def setTrackingFocus(self):
        raise NotImplemented

    def getTrackingFocus(self):
        raise NotImplemented

    def getSupportedTrackingFocus(self):
        raise NotImplemented

    def getAvailableTrackingFocus(self):
        raise NotImplemented

    def setContShootingMode(self):
        raise NotImplemented

    def getContShootingMode(self):
        raise NotImplemented

    def getSupportedContShootingMode(self):
        raise NotImplemented

    def getAvailableContShootingMode(self):
        raise NotImplemented

    def setContShootingSpeed(self):
        raise NotImplemented

    def getContShootingSpeed(self):
        raise NotImplemented

    def getSupportedContShootingSpeed(self):
        raise NotImplemented

    def getAvailableContShootingSpeed(self):
        raise NotImplemented

    def setSelfTimer(self):
        raise NotImplemented

    def getSelfTimer(self):
        raise NotImplemented

    def getSupportedSelfTimer(self):
        raise NotImplemented

    def getAvailableSelfTimer(self):
        raise NotImplemented

    def setExposureMode(self):
        raise NotImplemented

    def getExposureMode(self):
        raise NotImplemented

    def getSupportedExposureMode(self):
        raise NotImplemented

    def getAvailableExposureMode(self):
        raise NotImplemented

    def setFocusMode(self):
        raise NotImplemented

    def getFocusMode(self):
        raise NotImplemented

    def getSupportedFocusMode(self):
        raise NotImplemented

    def getAvailableFocusMode(self):
        raise NotImplemented

    def getExposureCompensation(self):
        raise NotImplemented

    def setExposureCompensation(self):
        raise NotImplemented

    def getSupportedExposureCompensation(self):
        raise NotImplemented

    def getAvailableExposureCompensation(self):
        raise NotImplemented

    def setFNumber(self):
        raise NotImplemented

    def getFNumber(self):
        raise NotImplemented

    def getSupportedFNumber(self):
        raise NotImplemented

    def getAvailableFNumber(self):
        raise NotImplemented

    def setShutterSpeed(self):
        raise NotImplemented

    def getShutterSpeed(self):
        raise NotImplemented

    def getSupportedShutterSpeed(self):
        raise NotImplemented

    def getAvailableShutterSpeed(self):
        raise NotImplemented

    def setIsoSpeedRate(self):
        raise NotImplemented

    def getIsoSpeedRate(self):
        raise NotImplemented

    def getSupportedIsoSpeedRate(self):
        raise NotImplemented

    def getAvailableIsoSpeedRate(self):
        raise NotImplemented

    def setWhiteBalance(self):
        raise NotImplemented

    def getWhiteBalance(self):
        raise NotImplemented

    def getSupportedWhiteBalance(self):
        raise NotImplemented

    def getAvailableWhiteBalance(self):
        raise NotImplemented

    def setProgramShift(self):
        raise NotImplemented

    def getSupportedProgramShift(self):
        raise NotImplemented

    def setFlashMode(self):
        raise NotImplemented

    def getFlashMode(self):
        raise NotImplemented

    def getSupportedFlashMode(self):
        raise NotImplemented

    def getAvailableFlashMode(self):
        raise NotImplemented

    def setStillSize(self):
        raise NotImplemented

    def getStillSize(self):
        raise NotImplemented

    def getSupportedStillSize(self):
        raise NotImplemented

    def getAvailableStillSize(self):
        raise NotImplemented

    def setStillQuality(self):
        raise NotImplemented

    def getStillQuality(self):
        raise NotImplemented

    def getSupportedStillQuality(self):
        raise NotImplemented

    def getAvailableStillQuality(self):
        raise NotImplemented

    def setPostviewImageSize(self):
        raise NotImplemented

    def getPostviewImageSize(self):
        raise NotImplemented

    def getSupportedPostviewImageSize(self):
        raise NotImplemented

    def getAvailablePostviewImageSize(self):
        raise NotImplemented

    def setMovieFileFormat(self):
        raise NotImplemented

    def getMovieFileFormat(self):
        raise NotImplemented

    def getSupportedMovieFileFormat(self):
        raise NotImplemented

    def getAvailableMovieFileFormat(self):
        raise NotImplemented

    def setMovieQuality(self):
        raise NotImplemented

    def getMovieQuality(self):
        raise NotImplemented

    def getSupportedMovieQuality(self):
        raise NotImplemented

    def getAvailableMovieQuality(self):
        raise NotImplemented

    def setSteadyMode(self):
        raise NotImplemented

    def getSteadyMode(self):
        raise NotImplemented

    def getSupportedSteadyMode(self):
        raise NotImplemented

    def getAvailableSteadyMode(self):
        raise NotImplemented

    def setViewAngle(self):
        raise NotImplemented

    def getViewAngle(self):
        raise NotImplemented

    def getSupportedViewAngle(self):
        raise NotImplemented

    def getAvailableViewAngle(self):
        raise NotImplemented

    def setSceneSelection(self):
        raise NotImplemented

    def getSceneSelection(self):
        raise NotImplemented

    def getSupportedSceneSelection(self):
        raise NotImplemented

    def getAvailableSceneSelection(self):
        raise NotImplemented

    def setColorSetting(self):
        raise NotImplemented

    def getColorSetting(self):
        raise NotImplemented

    def getSupportedColorSetting(self):
        raise NotImplemented

    def getAvailableColorSetting(self):
        raise NotImplemented

    def setIntervalTime(self):
        raise NotImplemented

    def getIntervalTime(self):
        raise NotImplemented

    def getSupportedIntervalTime(self):
        raise NotImplemented

    def getAvailableIntervalTime(self):
        raise NotImplemented

    def setFlipSetting(self):
        raise NotImplemented

    def getFlipSetting(self):
        raise NotImplemented

    def getSupportedFlipSetting(self):
        raise NotImplemented

    def getAvailableFlipSetting(self):
        raise NotImplemented

    def setTvColorSystem(self):
        raise NotImplemented

    def getTvColorSystem(self):
        raise NotImplemented

    def getSupportedTvColorSystem(self):
        raise NotImplemented

    def getAvailableTvColorSystem(self):
        raise NotImplemented

    def startRecMode(self):
        raise NotImplemented

    def stopRecMode(self):
        raise NotImplemented

    def setCameraFunction(self):
        raise NotImplemented

    def getCameraFunction(self):
        raise NotImplemented

    def getSupportedCameraFunction(self):
        raise NotImplemented

    def getAvailableCameraFunction(self):
        raise NotImplemented

    def getSchemeList(self):
        raise NotImplemented

    def getSourceList(self):
        raise NotImplemented

    def getContentCount(self):
        raise NotImplemented

    def getContentList(self):
        raise NotImplemented

    def setStreamingContent(self):
        raise NotImplemented

    def startStreaming(self):
        raise NotImplemented

    def pauseStreaming(self):
        raise NotImplemented

    def seekStreamingPosition(self):
        raise NotImplemented

    def stopStreaming(self):
        raise NotImplemented

    def requestToNotifyStreamingStatus(self):
        raise NotImplemented

    def deleteContent(self):
        raise NotImplemented

    def setInfraredRemoteControl(self):
        raise NotImplemented

    def getInfraredRemoteControl(self):
        raise NotImplemented

    def getSupportedInfraredControl(self):
        raise NotImplemented

    def getAvailableInfraredControl(self):
        raise NotImplemented

    def setAutoPowerOff(self):
        raise NotImplemented

    def getAutoPowerOff(self):
        raise NotImplemented

    def getSupportedAutoPowerOff(self):
        raise NotImplemented

    def getAvailableAutoPowerOff(self):
        raise NotImplemented

    def setBeepMode(self):
        raise NotImplemented

    def getBeepMode(self):
        raise NotImplemented

    def getSupportedBeepMode(self):
        raise NotImplemented

    def getAvailableBeepMode(self):
        raise NotImplemented

    def setCurrentTime(self):
        raise NotImplemented

    def getStorageInformation(self):
        raise NotImplemented

    def getEvent(self):
        raise NotImplemented

    def getEvent(self):
        raise NotImplemented

    def getEvent(self):
        raise NotImplemented

    def getAvailableApiList(self):
        raise NotImplemented

    def getApplicationInfo(self):
        raise NotImplemented

    def getMethodTypes(self):
        raise NotImplemented

def discover():
    resp = __msearch()
    _ddurl = resp.location

    _ddr = requests.get(_ddurl)
    if _ddr.status_code != 200:
        raise CameraRemoteError("Failed to get Device Description from %s" % _ddurl)

    return CameraRemoteAPI(_ddr.text)

def __msearch(st=CRA_SSDP_ST):
    """Send a M-SEARCH * HTTP/1.1 request and return the response"""
    sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sender.setsockopt(socket.IPPROTO_IP,
                      socket.IP_MULTICAST_TTL,
                      1)
    # FIXME: Need to figure out which interface is the right one if
    # there are more than one. This is wrong.
    sender.setsockopt(socket.SOL_IP,
                      socket.IP_MULTICAST_IF,
                      socket.inet_pton(socket.AF_INET,
                                       '192.168.122.173'))
    sender.setsockopt(socket.SOL_IP,
                      socket.IP_MULTICAST_LOOP,
                      1)
    sender.sendto(CRA_SSDP_MSG.format(h=CRA_SSDP_MGRP,
                                      p=CRA_SSDP_PORT,
                                      st=st),
                  CRA_SSDP_GROUP)
    responses = {}

    _msg, _from = sender.recvfrom(1024)
    r = SSDPResponse(_msg)

    if sender:
        sender.close()

    return r
<|endoftext|>


<commit_before>
{
  'variables': {
      'node_mapnik_sources': [
          "src/node_mapnik.cpp",
          "src/mapnik_map.cpp",
          "src/mapnik_color.cpp",
          "src/mapnik_geometry.cpp",
          "src/mapnik_feature.cpp",
          "src/mapnik_image.cpp",
          "src/mapnik_image_view.cpp",
          "src/mapnik_grid.cpp",
          "src/mapnik_grid_view.cpp",
          "src/mapnik_js_datasource.cpp",
          "src/mapnik_memory_datasource.cpp",
          "src/mapnik_palette.cpp",
          "src/mapnik_projection.cpp",
          "src/mapnik_layer.cpp",
          "src/mapnik_datasource.cpp",
          "src/mapnik_featureset.cpp",
          "src/mapnik_expression.cpp"
      ],
      'node_root': '/opt/node-v6.1',
      'node_root_win': 'c:\\node',
      'deps_root_win': 'c:\\dev2'
  },
  'targets': [
    {
      'target_name': '_mapnik',
      'product_name': '_mapnik',
      'type': 'loadable_module',
      'product_prefix': '',
      'product_extension':'node',
      'sources': [
        '<@(node_mapnik_sources)',
      ],
      'defines': [
        'PLATFORM="<(OS)"',
        'HAVE_JPEG',
        'MAPNIK_THREADSAFE',
        'HAVE_LIBXML2',
        'LIBTOOL_SUPPORTS_ADVISE',
      ],
      'conditions': [
        [ 'OS=="mac"', {
          'libraries': [
            '-lmapnik',
            '-undefined dynamic_lookup'
          ],
          'include_dirs': [
             'src/',
             '<@(node_root)/include/node',
             '<@(node_root)/include',
             '/opt/boost-48/include',
             '/usr/local/Cellar/icu4c/4.8.1.1/include',
             '/usr/X11/include/freetype2',
             '/usr/X11/include',
          ],
          'defines': [
            #'HAVE_CAIRO',
            '_LARGEFILE_SOURCE',
            '_FILE_OFFSET_BITS=64',
          ],
        }],
        [ 'OS=="win"', {
          'defines': [
            'HAVE_CAIRO',
            'PLATFORM="win32"',
            '_LARGEFILE_SOURCE',
            '_FILE_OFFSET_BITS=64',
            '_WINDOWS',
            '__WINDOWS__', # ltdl
            'BUILDING_NODE_EXTENSION'
          ],
          'libraries': [
              'mapnik2.lib',
              'node.lib',
              'icuuc.lib',
              'libboost_regex-vc100-mt-1_48.lib',
          ],
          'include_dirs': [
             'c:\\mapnik-2.0\\include',
             '<@(deps_root_win)\\freetype',
             '<@(deps_root_win)\\freetype\\include',
             '<@(deps_root_win)\\cairo\\src',
             '<@(deps_root_win)\\cairomm',
             '<@(deps_root_win)\\libsigc++',
             '<@(deps_root_win)\\boost-vc100\\include\\boost-1_48',
             '<@(node_root_win)\\deps\\v8\\include',
             '<@(node_root_win)\\src',
             '<@(node_root_win)\\deps\\uv\\include',
             '<@(deps_root_win)\\proj\\src',
             '<@(deps_root_win)\\icu\\include',
             '<@(deps_root_win)\\mapnik-packaging\\windows\\ltdl',
          ],
          'msvs_settings': {
            'VCLinkerTool': {
              'AdditionalOptions': [
                # https://github.com/mapnik/node-mapnik/issues/74
                '/FORCE:MULTIPLE'
              ],
              'AdditionalLibraryDirectories': [
                '<@(node_root_win)\\Release\\lib',
                '<@(node_root_win)\\Release',
                '<@(deps_root_win)\\mapnik-packaging\\windows\\build\\src\\msvc-10.0\\release\\threading-multi',
                '<@(deps_root_win)\\boost-vc100\\lib',
                '<@(deps_root_win)\\icu\\lib',
              ],
            },
          },
        },
      ],
      ]
    },
  ],
}<commit_msg>link to mapnik not mapnik2<commit_after>
{
  'variables': {
      'node_mapnik_sources': [
          "src/node_mapnik.cpp",
          "src/mapnik_map.cpp",
          "src/mapnik_color.cpp",
          "src/mapnik_geometry.cpp",
          "src/mapnik_feature.cpp",
          "src/mapnik_image.cpp",
          "src/mapnik_image_view.cpp",
          "src/mapnik_grid.cpp",
          "src/mapnik_grid_view.cpp",
          "src/mapnik_js_datasource.cpp",
          "src/mapnik_memory_datasource.cpp",
          "src/mapnik_palette.cpp",
          "src/mapnik_projection.cpp",
          "src/mapnik_layer.cpp",
          "src/mapnik_datasource.cpp",
          "src/mapnik_featureset.cpp",
          "src/mapnik_expression.cpp"
      ],
      'node_root': '/opt/node-v6.1',
      'node_root_win': 'c:\\node',
      'deps_root_win': 'c:\\dev2'
  },
  'targets': [
    {
      'target_name': '_mapnik',
      'product_name': '_mapnik',
      'type': 'loadable_module',
      'product_prefix': '',
      'product_extension':'node',
      'sources': [
        '<@(node_mapnik_sources)',
      ],
      'defines': [
        'PLATFORM="<(OS)"',
        'HAVE_JPEG',
        'MAPNIK_THREADSAFE',
        'HAVE_LIBXML2',
        'LIBTOOL_SUPPORTS_ADVISE',
      ],
      'conditions': [
        [ 'OS=="mac"', {
          'libraries': [
            '-lmapnik',
            '-undefined dynamic_lookup'
          ],
          'include_dirs': [
             'src/',
             '<@(node_root)/include/node',
             '<@(node_root)/include',
             '/opt/boost-48/include',
             '/usr/local/Cellar/icu4c/4.8.1.1/include',
             '/usr/X11/include/freetype2',
             '/usr/X11/include',
          ],
          'defines': [
            #'HAVE_CAIRO',
            '_LARGEFILE_SOURCE',
            '_FILE_OFFSET_BITS=64',
          ],
        }],
        [ 'OS=="win"', {
          'defines': [
            'HAVE_CAIRO',
            'PLATFORM="win32"',
            '_LARGEFILE_SOURCE',
            '_FILE_OFFSET_BITS=64',
            '_WINDOWS',
            '__WINDOWS__', # ltdl
            'BUILDING_NODE_EXTENSION'
          ],
          'libraries': [
              'mapnik.lib',
              'node.lib',
              'icuuc.lib',
              'libboost_regex-vc100-mt-1_48.lib',
          ],
          'include_dirs': [
             'c:\\mapnik-2.0\\include',
             '<@(deps_root_win)\\freetype',
             '<@(deps_root_win)\\freetype\\include',
             '<@(deps_root_win)\\cairo\\src',
             '<@(deps_root_win)\\cairomm',
             '<@(deps_root_win)\\libsigc++',
             '<@(deps_root_win)\\boost-vc100\\include\\boost-1_48',
             '<@(node_root_win)\\deps\\v8\\include',
             '<@(node_root_win)\\src',
             '<@(node_root_win)\\deps\\uv\\include',
             '<@(deps_root_win)\\proj\\src',
             '<@(deps_root_win)\\icu\\include',
             '<@(deps_root_win)\\mapnik-packaging\\windows\\ltdl',
          ],
          'msvs_settings': {
            'VCLinkerTool': {
              'AdditionalOptions': [
                # https://github.com/mapnik/node-mapnik/issues/74
                '/FORCE:MULTIPLE'
              ],
              'AdditionalLibraryDirectories': [
                '<@(node_root_win)\\Release\\lib',
                '<@(node_root_win)\\Release',
                '<@(deps_root_win)\\mapnik-packaging\\windows\\build\\src\\msvc-10.0\\release\\threading-multi',
                '<@(deps_root_win)\\boost-vc100\\lib',
                '<@(deps_root_win)\\icu\\lib',
              ],
            },
          },
        },
      ],
      ]
    },
  ],
}<|endoftext|>