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

    var app = angular.module("FlagQuizApp", []);

    function cropAndMix(arr, size) {
        arr.sort(function(a, b) {
             return Math.random() - 0.5;
        });

        return arr.splice(0, size);
    }

    app.controller("FlagQuizController", [ "$scope", "$http", function($scope, $http) {
        $scope.gamestart = false;
        $scope.selectedCountry = undefined;
        $scope.selectedFlag = undefined;
        $scope.correctAnswers = [];
        $scope.badAnswers = [];
        $scope.allCountries = undefined;
        $scope.halloffame = [];
        $scope.score = 0;

        $http.get("json/all.json").success(function(data, status) {
            $scope.allCountries = data;
            $scope.countries = cropAndMix(data, 5);
            $scope.flags = $scope.countries.slice(0);
            $scope.flags = cropAndMix($scope.flags, 5);
        });

        $scope.setSelectedCountry = function(country) {
            $scope.selectedCountry = country;
        };

        $scope.setSelectedFlag = function(country) {
            $scope.selectedFlag = country;
        };

        $scope.setCountryColor = function(country) {
            if ($scope.correctAnswers.indexOf(country.name) !== -1) {
                return 'btn-success';
            }

            if ($scope.badAnswers.indexOf(country.name) !== -1) {
                return 'btn-danger';
            }

            if ($scope.selectedCountry && $scope.selectedCountry.name == country.name) {
                return 'btn-warning';
            }
            return 'btn-primary';
        };

        $scope.checkIfGameIsOver = function() {
            if ($scope.correctAnswers === undefined || !$scope.badAnswers === undefined || !$scope.countries) return;

            if (($scope.correctAnswers.length + $scope.badAnswers.length) === $scope.countries.length) {
                $scope.gamestart = false;
                $scope.countries = cropAndMix($scope.allCountries, 5);
                $scope.flags = $scope.countries.slice(0);
                $scope.flags = cropAndMix($scope.flags, 5);
                var hof = $scope.halloffame.splice();
                hof.push({ user: $scope.username, score: $scope.score });
                $scope.halloffame = hof;
                $scope.username = undefined;
                $scope.score = 0;
            }
        };

        $scope.setFlagColor = function(country) {
            var code = country['alpha-2'];
            var selected = "";
            if ($scope.selectedFlag && $scope.selectedFlag.name === country.name) {
                selected = " flagSelected";
            }
            return code.toLowerCase() + selected;
        };

        $scope.$watch("selectedFlag", function(country) {
            $scope.checkIfGameIsOver();
            if ($scope.selectedCountry && $scope.selectedFlag) {
                if ($scope.selectedCountry.name === $scope.selectedFlag.name) {
                    $scope.correctAnswers.push($scope.selectedCountry.name);
                    $scope.score++;
                } else {
                    $scope.badAnswers.push($scope.selectedCountry.name);
                    $scope.score--;
                }
                $scope.selectedFlag = undefined;
            }
        });

        $scope.$watch("selectedCountry", function(country) {
            $scope.checkIfGameIsOver();
            if ($scope.selectedCountry && $scope.selectedFlag) {
                if ($scope.selectedCountry.name === $scope.selectedFlag.name) {
                    $scope.correctAnswers.push($scope.selectedCountry.name);
                    $scope.score++;
                } else {
                    $scope.badAnswers.push($scope.selectedCountry.name);
                    $scope.score--;
                }
                $scope.selectedFlag = undefined;
            }
        });
    }]);

}());


text:
import gepify
from . import GepifyTestCase
from flask import url_for, session, g
import spotipy
from urllib import parse
from unittest import mock
from gepify.services import spotify
from gepify.providers import songs
from werkzeug.contrib.cache import SimpleCache
import json
import os
import time

class MockResponse:
    def __init__(self, data, status_code):
        self.text = json.dumps(data)
        self.status_code = status_code

def mocked_spotify_api_post(url, **kwargs):
    data = kwargs.get('data', None)
    headers = kwargs.get('headers', None)

    if url == 'https://accounts.spotify.com/api/token':
        assert 'Authorization' in headers
        assert headers['Authorization'].startswith('Basic')
        assert 'grant_type' in data
        assert data['grant_type'] in ['authorization_code', 'refresh_token']

        if data['grant_type'] == 'authorization_code':
            assert 'code' in data
            assert 'redirect_uri' in data

            return MockResponse({
                'access_token': 'dummy code',
                'refresh_token': 'refresh me',
                'expires_in': 60
            }, 200)
        else:
            assert 'refresh_token' in data
            assert data['refresh_token'] == 'refresh me'

            return MockResponse({
                'access_token': 'new dummy code',
                'refresh_token': 'refresh me again',
                'expires_in': 60
            }, 200)

def mocked_spotify_api_404(*args, **kwargs):
    return MockResponse({}, 404)

def mocked_spotify_api_401(*args, **kwargs):
    return MockResponse({}, 401)

class MockSpotipy:
    def __init__(self, auth=None):
        self.auth = auth

    def me(self):
        return {
            'id': 'test_user'
        }

    def user_playlists(self, username):
        with open('tests/spotify_dump/spotify_user_playlists.json') as f:
            return json.loads(f.read())

    def user_playlist(self, username, playlist_id, fields=None):
        if username == 'test_user' and playlist_id == '1':
            with open('tests/spotify_dump/spotify_user_playlist.json') as f:
                return json.loads(f.read())

    def current_user_saved_albums(self):
        with open('tests/spotify_dump/'
                  'spotify_current_user_saved_albums.json') as f:
            return json.loads(f.read())

    def album(self, album_id):
        if album_id == '0AYlrY39QmCNwR4r1uzlv3':
            with open('tests/spotify_dump/spotify_album.json') as f:
                return json.loads(f.read())

    def next(self, result):
        if result['next'] == 'https://api.spotify.com/v1/users/aplusk' + \
                             '/playlists/5ExcrV72XoJ6aQT8plfau3/' + \
                             'tracks?offset=100&limit=100':
            with open('tests/spotify_dump/spotify_next.json') as f:
                return json.loads(f.read())

class ProfileMixin():
    @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    def login(self, *args):
        login_response = self.client.get(url_for('spotify.login'))
        spotify_redirect = login_response.location
        self.assertTrue(spotify_redirect.startswith(
                            'https://accounts.spotify.com/authorize'))

        params = parse.parse_qs(parse.urlparse(spotify_redirect).query)

        response = self.client.get(url_for(
            'spotify.callback', code='dummy code', state=params['state'][0]
        ))
        self.assertRedirects(response, url_for('spotify.index'))
        return response

    @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    def logout(self, *args):
        logout_response = self.client.get(url_for('spotify.logout'))
        self.assertRedirects(logout_response, url_for('views.index'))
        return logout_response

@mock.patch('requests.post', side_effect=mocked_spotify_api_post)
class SpotifyDecoratorsTestCase(GepifyTestCase, ProfileMixin):
    def test_login_required_decorator(self, *args):
        @self.app.route('/test')
        @spotify.view_decorators.login_required
        def test():
            return 'You should be logged in to read this'

        response = self.client.get('/test')
        self.assertRedirects(response, url_for('spotify.login'))

        login_response = self.login()

        response = self.client.get('/test')
        self.assert200(response)
        self.assertIn(b'You should be logged in to read this', response.data)

        with self.client.session_transaction() as sess:
            sess['spotify_refresh_token'] = 'false token'
            sess['spotify_expires_at'] = -1

        response = self.client.get('/test')
        self.assertEqual(response.status_code, 503)
        self.assertIn(b'There was an error with authenticating', response.data)

        self.logout()

        response = self.client.get('/test')
        self.assertRedirects(response, url_for('spotify.login'))

    def test_login_required_if_spotify_session_has_expired(self, post):
        @self.app.route('/test')
        @spotify.view_decorators.login_required
        def test():
            return 'You should be logged in to read this'

        with self.client as client:
            self.login()

            old_token = session['spotify_access_token']
            old_refresh_token = session['spotify_refresh_token']

            with client.session_transaction() as sess:
                sess['spotify_expires_at'] = -1

            response = self.client.get('/test')
            new_token = session['spotify_access_token']
            new_refresh_token = session['spotify_refresh_token']

            self.assertEqual(old_token, 'dummy code')
            self.assertEqual(old_refresh_token, 'refresh me')
            self.assertEqual(new_token, 'new dummy code')
            self.assertEqual(new_refresh_token, 'refresh me again')

    def test_logout_required_decorator(self, post):
        @self.app.route('/test')
        @spotify.view_decorators.logout_required
        def test():
            return 'You should be logged out to read this'

        response = self.client.get('/test')
        self.assert200(response)
        self.assertIn(b'You should be logged out to read this', response.data)

        login_response = self.login()

        response = self.client.get('/test')
        self.assert403(response)
        self.assertIn(
            b'You need to be logged out to see this page', response.data)

        self.logout()

        response = self.client.get('/test')
        self.assert200(response)
        self.assertIn(b'You should be logged out to read this', response.data)

class SpotifyModelsTestCase(GepifyTestCase):
    def setUp(self):
        g.spotipy = MockSpotipy()
        songs.cache = SimpleCache()

    def tearDown(self):
        g.spotipy = None

    @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    def test_get_access_token_from_code(self, post):
        token_data =spotify.models.get_access_token_from_code('some code')
        self.assertEqual(post.call_count, 1)
        self.assertEqual(token_data['access_token'], 'dummy code')
        self.assertEqual(token_data['refresh_token'], 'refresh me')
        self.assertEqual(token_data['expires_in'], 60)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    def test_get_access_token_from_refresh_token(self, post):
        token_data = spotify.models.get_access_token_from_refresh_token(
                'refresh me')
        self.assertEqual(post.call_count, 1)
        self.assertEqual(token_data['access_token'], 'new dummy code')
        self.assertEqual(token_data['refresh_token'], 'refresh me again')
        self.assertEqual(token_data['expires_in'], 60)

    def test_save_token_data_in_session(self):
        token_data = {
            'access_token': 'access token',
            'refresh_token': 'refresh token',
            'expires_in': 60
        }
        spotify.models.save_token_data_in_session(token_data)
        self.assertEqual(session['spotify_access_token'], 'access token')
        self.assertEqual(session['spotify_refresh_token'], 'refresh token')
        self.assertEqual(session['spotify_expires_at'], int(time.time()) + 60)

    # @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    # def test_request_access_token_with_refresh_token_request(self, post):
    #     payload = {
    #         'grant_type': 'refresh_token',
    #         'refresh_token': 'refresh me'
    #     }

    #     with self.client.session_transaction() as sess:
    #         sess['spotify_access_token'] = 'some random test token'
    #         sess['spotify_refresh_token'] = 'some random refresh token'
    #     self.assertNotIn('spotify_expires_at', session)
    #     spotify.models.request_access_token(payload)
    #     self.assertEqual(post.call_count, 1)
    #     self.assertEqual(session['spotify_access_token'], 'new dummy code')
    #     self.assertEqual(session['spotify_refresh_token'], 'refresh me again')
    #     self.assertIn('spotify_expires_at', session)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_404)
    def test_get_access_token_from_code_with_error(self, post):
        with self.assertRaisesRegex(
                RuntimeError, 'Could not get authentication token'):
            spotify.models.get_access_token_from_code('code')

    @mock.patch('requests.post', side_effect=mocked_spotify_api_404)
    def test_get_access_token_from_refresh_token_with_error(self, post):
        with self.assertRaisesRegex(
                RuntimeError, 'Could not get authentication token'):
            spotify.models.get_access_token_from_refresh_token('token')

    def test_get_username(self):
        self.assertEqual(spotify.models.get_username(), 'test_user')
        self.assertEqual(spotify.models.get_username(), 'test_user')

    def test_get_song_name(self):
        track = {
            'artists': [{'name': 'Artist 1'}, {'name': 'Artist 2'}],
            'name': 'Track name'
        }
        self.assertEqual(spotify.models.get_song_name(track),
                         'Artist 1 & Artist 2 - Track name')

    def test_get_playlists(self):
        playlists = spotify.models.get_playlists()
        self.assertEqual(len(playlists), 25)
        self.assertEqual(playlists[0]['name'], 'Starred')
        self.assertEqual(playlists[-1]['name'], 'Bozdugan')

    def test__get_playlist(self):
        playlist = spotify.models._get_playlist('test_user', '1')
        self.assertEqual(playlist['name'], 'Starred')
        self.assertIsNone(playlist['description'])
        self.assertIn('image', playlist)
        self.assertEqual(playlist['id'], 'test_user:1')
        self.assertEqual(len(playlist['tracks']), 200)

    def test__get_album(self):
        album = spotify.models._get_album('0AYlrY39QmCNwR4r1uzlv3')
        self.assertEqual(album['name'], 'Bozdugan')
        self.assertEqual(album['id'], 'album:0AYlrY39QmCNwR4r1uzlv3')
        self.assertIn('image', album)
        self.assertEqual(len(album['tracks']), 13)

    @mock.patch('gepify.providers.songs.get_song',
                side_effect=lambda song_name: {'name': song_name})
    def test_get_playlist_without_keeping_song_names(self, get_song):
        playlist = spotify.models.get_playlist('test_user:1')
        self.assertEqual(playlist['id'], 'test_user:1')
        self.assertIsNone(playlist['description'])
        self.assertEqual(playlist['name'], 'Starred')
        self.assertEqual(len(playlist['tracks']), 200)
        self.assertEqual(get_song.call_count, len(playlist['tracks']))
        self.assertEqual(playlist['tracks'][25]['name'],
                         'Leona Lewis - Bleeding Love')
        self.assertEqual(playlist['tracks'][42]['name'],
                         'The National - Anyone's Ghost')

        get_song.reset_mock()
        playlist = spotify.models.get_playlist('album:0AYlrY39QmCNwR4r1uzlv3')
        self.assertEqual(playlist['name'], 'Bozdugan')
        self.assertEqual(playlist['id'], 'album:0AYlrY39QmCNwR4r1uzlv3')
        self.assertEqual(len(playlist['tracks']), 13)
        self.assertEqual(get_song.call_count, len(playlist['tracks']))

class SpotifyViewsTestCase(GepifyTestCase, ProfileMixin):
    def setUp(self):
        songs.cache = SimpleCache()

    @classmethod
    def tearDownClass(cls):
        if os.path.isfile('test song.mp3'):
            os.remove('test song.mp3')

        if os.path.isfile('playlist.zip'):
            os.remove('playlist.zip')

    def test_index_if_not_logged_in(self):
        response = self.client.get(url_for('spotify.index'))
        self.assertRedirects(response, url_for('spotify.login'))

    @mock.patch('spotipy.Spotify', side_effect=MockSpotipy)
    def test_index_if_logged_in(self, *args):
        self.login()
        response = self.client.get(url_for('spotify.index'))
        self.assert200(response)
        self.assertIn(b'Bozdugan', response.data)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    def test_login(self, *args):
        response = self.client.get(url_for('spotify.login'))
        self.assertTrue(response.location.startswith(
                        'https://accounts.spotify.com/authorize/'))
        self.login()
        response = self.client.get(url_for('spotify.login'))
        self.assertIn(b'You need to be logged out to see this page',
                      response.data)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    def test_login_callback(self, post, *args):
        response = self.client.get(
            url_for('spotify.callback', error='access_denied'))
        self.assertEqual(response.status_code, 503)
        self.assertIn(b'There was an error while trying to authenticate you.'
                      b'Please, try again.', response.data)
        self.assertEqual(post.call_count, 0)

        with self.client.session_transaction() as sess:
            sess['spotify_auth_state'] = 'some state'

        response = self.client.get(
            url_for('spotify.callback', state='other state', code='123'))
        self.assertEqual(response.status_code, 503)
        self.assertIn(b'There was an error while trying to authenticate you.'
                      b'Please, try again.', response.data)
        self.assertEqual(post.call_count, 0)

        response = self.client.get(
            url_for('spotify.callback', state='some state', code='123'))
        self.assertRedirects(response, url_for('spotify.index'))
        self.assertEqual(post.call_count, 1)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_404)
    def test_login_callback_with_spotify_error(self, post, *args):
        with self.client.session_transaction() as sess:
            sess['spotify_auth_state'] = 'some state'
        response = self.client.get(
            url_for('spotify.callback', state='some state', code='123'))
        self.assertEqual(response.status_code, 503)
        self.assertIn(b'There was an error while trying to authenticate you.'
                      b'Please, try again.', response.data)
        self.assertEqual(post.call_count, 1)

    @mock.patch('spotipy.Spotify', side_effect=MockSpotipy)
    def test_logout(self, Spotify):
        response = self.client.get(url_for('spotify.logout'))
        self.assertRedirects(response, url_for('views.index'))
        response = self.client.get(url_for('spotify.index'))
        self.assertRedirects(response, url_for('spotify.login'))
        self.login()
        response = self.client.get(url_for('spotify.index'))
        self.assert200(response)
        response = self.client.get(url_for('spotify.logout'))
        self.assertRedirects(response, url_for('views.index'))
        response = self.client.get(url_for('spotify.index'))
        self.assertRedirects(response, url_for('spotify.login'))

    @mock.patch('spotipy.Spotify', side_effect=MockSpotipy)
    @mock.patch('gepify.providers.songs.get_song',
                side_effect=lambda song_name: {'name': song_name, 'files': {}})
    def test_get_playlist(self, get_song, Spotify):
        self.login()
        response = self.client.get(
            url_for('spotify.playlist', id='test_user:1'))
        self.assert200(response)
        self.assertIn(b'Use Somebody', response.data)

    def test_download_song_in_unsupported_format(self, *args):
        self.login()
        response = self.client.get(
            url_for('spotify.download_song',
                    song_name='test song', format='wav'))
        self.assertEqual(response.status_code, 400)
        self.assertIn(b'Unsupported format', response.data)

    def test_download_song_with_unsupported_provider(self, *args):
        self.login()
        response = self.client.get(
            url_for('spotify.download_song',
                    song_name='song with / / slashes /',
                    format='mp3', provider='zamunda'))
        self.assertEqual(response.status_code, 400)
        self.assertIn(b'Unsupported provider', response.data)

    @mock.patch('gepify.providers.songs.has_song_format',
                side_effect=lambda song, format: False)
    @mock.patch('gepify.providers.songs.download_song.delay',
                side_effect=lambda *args, **kwargs: None)
    def test_download_song_if_song_is_missing(self, *args):
        self.login()
        response = self.client.get(
            url_for('spotify.download_song',
                    song_name='test song', format='mp3'))
        self.assert200(response)
        self.assertIn(b'Your song has started downloading.', response.data)

    @mock.patch('gepify.providers.songs.has_song_format',
                side_effect=lambda song, format: True)
    @mock.patch('gepify.providers.songs.get_song',
                side_effect=lambda song: {
                    'name': song, 'files': {'mp3': os.getcwd() + '/' + song + '.mp3'}})
    def test_download_song_if_song_is_not_missing(self, *args):
        with open('test song.mp3', 'w+') as f:
            f.write('some data')

        self.login()
        response = self.client.get(
            url_for('spotify.download_song',
                    song_name='test song', format='mp3'))
        self.assert200(response)
        self.assertEqual(b'some data', response.data)
        self.assertTrue(response.content_type.startswith('audio'))
        response.close()

    def test_download_playlist_with_wrong_post_data(self, *args):
        self.login()
        response = self.client.post(url_for('spotify.download_playlist'))
        self.assertEqual(response.status_code, 400)
        response = self.client.post(url_for('spotify.download_playlist'),
                                    data={'format': 'mp3'})
        self.assertEqual(response.status_code, 400)

        response = self.client.post(
            url_for('spotify.download_playlist'),
            data={'playlist_id': 'test_user:some id', 'format': 'wav'})
        self.assertEqual(response.status_code, 400)
        self.assertIn(b'Unsupported format', response.data)

        response = self.client.post(
            url_for('spotify.download_playlist'),
            data={'playlist_id': 'test_user:some id', 'provider': 'zamunda'})
        self.assertEqual(response.status_code, 400)
        self.assertIn(b'Unsupported provider', response.data)

    @mock.patch('gepify.providers.playlists.has_playlist',
                side_effect=lambda *args: False)
    @mock.patch('gepify.providers.playlists.download_playlist.delay')
    @mock.patch('spotipy.Spotify', side_effect=MockSpotipy)
    def test_download_playlist_if_playlist_is_missing(self, *args):
        self.login()
        response = self.client.post(
            url_for('spotify.download_playlist'),
            data={'playlist_id': 'test_user:1', 'format': 'mp3'})
        self.assert200(response)
        self.assertIn(b'Your playlist is getting downloaded', response.data)

    @mock.patch('gepify.providers.playlists.has_playlist',
                side_effect=lambda *args: True)
    @mock.patch('gepify.providers.playlists.get_playlist',
                side_effect=lambda *args: {
                    'path': os.getcwd() + '/playlist.zip',
                    'checksum': '89c2226a90943679844cdc71693bc543'})
    @mock.patch('spotipy.Spotify', side_effect=MockSpotipy)
    def test_download_playlist_if_playlist_is_not_missing(self, *args):
        with open('playlist.zip', 'w+') as f:
            f.write('some data')

        self.login()
        response = self.client.post(
            url_for('spotify.download_playlist'),
            data={'playlist_id': 'test_user:1', 'format': 'mp3'})
        self.assert200(response)
        self.assertEqual(b'some data', response.data)
        self.assertEqual(response.content_type, 'application/zip')
        response.close()

    @mock.patch('gepify.providers.playlists.has_playlist',
                side_effect=lambda *args: True)
    @mock.patch('gepify.providers.playlists.get_playlist',
                side_effect=lambda *args: {
                    'path': 'playlist.zip',
                    'checksum': 'old checkum'})
    @mock.patch('gepify.providers.playlists.download_playlist.delay')
    @mock.patch('spotipy.Spotify', side_effect=MockSpotipy)
    def test_download_playlist_if_playlist_has_changed(self, *args):
        self.login()
        response = self.client.post(
            url_for('spotify.download_playlist'),
            data={'playlist_id': 'test_user:1', 'format': 'mp3'})
        self.assert200(response)
        self.assertIn(b'Your playlist is getting downloaded', response.data)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    def test_get_access_token_success(self, post):
        response = self.client.get(
            '/spotify/get_access_token/code'
        )
        self.assertEqual(post.call_count, 1)
        self.assert200(response)
        self.assertIn(b'dummy code', response.data)
        self.assertIn(b'refresh me', response.data)
        self.assertIn(b'60', response.data)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_404)
    def test_get_access_token_error(self, post):
        response = self.client.get(
            '/spotify/get_access_token/code'
        )
        self.assertEqual(post.call_count, 1)
        self.assertEqual(response.status_code, 401)
        self.assertIn(b'There was an error while trying to authenticate you.'
                      b'Please, try again.', response.data)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_post)
    def test_refresh_access_token_success(self, post):
        response = self.client.get(
            '/spotify/refresh_access_token/refresh me'
        )
        self.assertEqual(post.call_count, 1)
        self.assert200(response)
        self.assertIn(b'new dummy code', response.data)
        self.assertIn(b'refresh me again', response.data)
        self.assertIn(b'60', response.data)

    @mock.patch('requests.post', side_effect=mocked_spotify_api_401)
    def test_refresh_access_token_error(self, post):
        response = self.client.get(
            '/spotify/refresh_access_token/refresh me'
        )
        self.assertEqual(post.call_count, 1)
        self.assertEqual(response.status_code, 401)
        self.assertIn(b'Unable to refresh token.', response.data)

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}

{% load i18n %}

{% block title %}
{% trans "Change Password" %}
{% endblock title %}

{% block content %}

{% trans "Change Password" %}

        {% for error in form.non_field_errors %}

{{ error }}

        {% endfor %}
        <form class="form-horizontal" method="post" action="{% url 'auth_set_password' token %}">
            {% csrf_token %}
            {% for field in form %}
            {% if field.label != 'Old password' and token %}

                {{ field.label }}

                    {{ field }}

                        {{ field.errors }}

            {% endif %}
            {% endfor %}

                <input type="submit" class="btn btn-primary" value="{% trans "Change password" %}" />

        </form>

{% endblock content %}


text:
import sys, glob
sys.path.append('gen-py.twisted')
sys.path.insert(0, glob.glob('../../lib/py/build/lib.*')[0])

from tutorial import Calculator
from tutorial.ttypes import *

from shared.ttypes import SharedStruct

from zope.interface import implements
from twisted.internet import reactor

from thrift.transport import TTwisted
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

class CalculatorHandler:
  implements(Calculator.Iface)
  def __init__(self):
    self.log = {}

  def ping(self):
    print 'ping()'

  def add(self, n1, n2):
    print 'add(%d,%d)' % (n1, n2)
    return n1+n2

  def calculate(self, logid, work):
    print 'calculate(%d, %r)' % (logid, work)

    if work.op == Operation.ADD:
      val = work.num1 + work.num2
    elif work.op == Operation.SUBTRACT:
      val = work.num1 - work.num2
    elif work.op == Operation.MULTIPLY:
      val = work.num1 * work.num2
    elif work.op == Operation.DIVIDE:
      if work.num2 == 0:
        x = InvalidOperation()
        x.what = work.op
        x.why = 'Cannot divide by 0'
        raise x
      val = work.num1 / work.num2
    else:
      x = InvalidOperation()
      x.what = work.op
      x.why = 'Invalid operation'
      raise x

    log = SharedStruct()
    log.key = logid
    log.value = '%d' % (val)
    self.log[logid] = log

    return val

  def getStruct(self, key):
    print 'getStruct(%d)' % (key)
    return self.log[key]

  def zip(self):
    print 'zip()'

if __name__ == '__main__':
    handler = CalculatorHandler()
    processor = Calculator.Processor(handler)
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = reactor.listenTCP(9090,
                TTwisted.ThriftServerFactory(processor,
                pfactory), interface="127.0.0.1")
    reactor.run()


text:
import Slider from 'antd/lib/slider';
export default Slider;


text:
use crate::{chunk_request::GetChunkRequest, chunk_response::GetChunkResponse, counters};
use async_trait::async_trait;
use channel::{diem_channel, message_queues::QueueStyle};
use diem_types::PeerId;
use network::{
    error::NetworkError,
    peer_manager::{ConnectionRequestSender, PeerManagerRequestSender},
    protocols::network::{
        AppConfig, ApplicationNetworkSender, NetworkEvents, NetworkSender, NewNetworkSender,
        RpcError,
    },
    ProtocolId,
};
use serde::{Deserialize, Serialize};
use std::time::Duration;

const STATE_SYNC_MAX_BUFFER_SIZE: usize = 1;

/// State sync network messages
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum StateSyncMessage {
    GetChunkRequest(Box<GetChunkRequest>),
    GetChunkResponse(Box<GetChunkResponse>),
}

/// The interface from Network to StateSync layer.
///
/// `StateSyncEvents` is a `Stream` of `PeerManagerNotification` where the
/// raw `Bytes` direct-send messages are deserialized into `StateSyncMessage`
/// types. `StateSyncEvents` is a thin wrapper around a
/// `channel::Receiver<PeerManagerNotification>`.
pub type StateSyncEvents = NetworkEvents<StateSyncMessage>;

/// The interface from StateSync to Networking layer.
///
/// This is a thin wrapper around a `NetworkSender<StateSyncMessage>`, so it
/// is easy to clone and send off to a separate task. For example, the rpc
/// requests return Futures that encapsulate the whole flow, from sending the
/// request to remote, to finally receiving the response and deserializing. It
/// therefore makes the most sense to make the rpc call on a separate async task,
/// which requires the `StateSyncSender` to be `Clone` and `Send`.
#[derive(Clone)]
pub struct StateSyncSender {
    inner: NetworkSender<StateSyncMessage>,
}

impl NewNetworkSender for StateSyncSender {
    fn new(
        peer_mgr_reqs_tx: PeerManagerRequestSender,
        connection_reqs_tx: ConnectionRequestSender,
    ) -> Self {
        Self {
            inner: NetworkSender::new(peer_mgr_reqs_tx, connection_reqs_tx),
        }
    }
}

#[async_trait]
impl ApplicationNetworkSender<StateSyncMessage> for StateSyncSender {
    fn send_to(&self, recipient: PeerId, message: StateSyncMessage) -> Result<(), NetworkError> {
        let protocol = ProtocolId::StateSyncDirectSend;
        self.inner.send_to(recipient, protocol, message)
    }

    async fn send_rpc(
        &self,
        _recipient: PeerId,
        _req_msg: StateSyncMessage,
        _timeout: Duration,
    ) -> Result<StateSyncMessage, RpcError> {
        unimplemented!()
    }
}

/// Configuration for the network endpoints to support state sync.
pub fn network_endpoint_config() -> AppConfig {
    AppConfig::p2p(
        [ProtocolId::StateSyncDirectSend],
        diem_channel::Config::new(STATE_SYNC_MAX_BUFFER_SIZE)
            .queue_style(QueueStyle::LIFO)
            .counters(&counters::PENDING_STATE_SYNC_NETWORK_EVENTS),
    )
}


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

    <!--
        Licensed to the Apache Software Foundation (ASF) under one or more
        contributor license agreements.  See the NOTICE file distributed with
        this work for additional information regarding copyright ownership.
        The ASF licenses this file to You 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.
    -->

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.brooklyn.clocker</groupId>
        <artifactId>brooklyn-clocker-parent</artifactId>
        <version>1.1.0-SNAPSHOT</version>
    </parent>

    <artifactId>brooklyn-clocker-features</artifactId>

    <packaging>feature</packaging>

    <name>Clocker Karaf Features</name>
    <description>Clocker features for Karaf deployment.</description>

    <dependencies>
        <dependency>
            <groupId>org.apache.karaf</groupId>
            <artifactId>apache-karaf</artifactId>
            <type>zip</type>
            <version>${karaf.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- same as in brooklyn-clocker-dist -->
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>brooklyn-clocker-extras</artifactId>
            <version>${project.parent.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>brooklyn-clocker-patches</artifactId>
            <version>${project.parent.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>brooklyn-clocker-docker</artifactId>
            <version>${project.parent.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>brooklyn-clocker-mesos</artifactId>
            <version>${project.parent.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>brooklyn-clocker-jsgui</artifactId>
            <version>${project.parent.version}</version>
            <type>war</type>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>brooklyn-clocker-console</artifactId>
            <version>${project.parent.version}</version>
            <type>war</type>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.karaf.tooling</groupId>
                    <artifactId>karaf-maven-plugin</artifactId>
                    <version>4.0.4</version>
                    <extensions>true</extensions>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.karaf.tooling</groupId>
                <artifactId>karaf-maven-plugin</artifactId>
                <configuration>
                    <startLevel>50</startLevel>
                    <aggregateFeatures>false</aggregateFeatures>
                    <addBundlesToPrimaryFeature>false</addBundlesToPrimaryFeature>
                    <checkDependencyChange>false</checkDependencyChange>
                    <failOnDependencyChange>false</failOnDependencyChange>
                    <logDependencyChanges>false</logDependencyChanges>
                    <overwriteChangedDependencies>true</overwriteChangedDependencies>
                    <!-- for karaf:verify -->
                    <descriptors>
                        <descriptor>file:${project.build.directory}/feature/feature.xml</descriptor>
                    </descriptors>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>validation</id>
            <activation>
                <property>
                    <name>validateFeatures</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.karaf.tooling</groupId>
                        <artifactId>karaf-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>validate-features</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
package org.servicelayer.access;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.servicelayer.factory.MyBatisConnectionFactory;
import org.servicelayer.models.ReprocessRecipeDomain;

public class ReprocessCaller {

	private static SqlSession session = null;

	static{
		session = MyBatisConnectionFactory.getSqlSessionFactory().openSession();
	}
//	Reprocessor
//	getByTypeIdList
//	getByNameList
	public static List<ReprocessRecipeDomain> getRecipesFromNames(List<String> nameList){
		List<ReprocessRecipeDomain> result
			= session.selectList("Reprocessor.getByNameList", nameList);
		return result;
	}

	public static List<ReprocessRecipeDomain> getRecipesFromTypeIDs(List<Integer> idList){
		List<ReprocessRecipeDomain> result
			= session.selectList("Reprocessor.getByNameList", idList);
		return result;
	}

}


text:
@interface NSObject (ZZAlertView) <UIAlertViewDelegate>
- (void)showAlertViewWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitle:(NSString *)otherButtonTitle complete:(void(^)(NSInteger buttonIndex))complete;

- (void)showAlertViewWithMessage:(NSString *)message complete:(void(^)(NSInteger buttonIndex))complete;
- (void)showAlertViewWithMessage:(NSString *)message;

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
- (void)showAlertViewWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle complete:(void(^)(NSInteger buttonIndex))complete otherButtonTitles:(NSArray *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions.");
#endif

@end


text:
""" Recursion into other modules.

"""

from logging import debug, warning

from nuitka import ModuleRegistry, Options
from nuitka.freezer.BytecodeModuleFreezer import isFrozenModule
from nuitka.importing import ImportCache, Importing, StandardLibrary
from nuitka.tree.SourceReading import readSourceCodeFromFilename
from nuitka.utils import Utils

def recurseTo(module_package, module_filename, module_relpath, module_kind,
             reason):
    from nuitka.tree import Building

    if not ImportCache.isImportedModuleByPath(module_relpath):
        module, source_ref, source_filename = Building.decideModuleTree(
            filename = module_filename,
            package  = module_package,
            is_top   = False,
            is_main  = False,
            is_shlib = module_kind == "shlib"
        )

        # Check if the module name is known. In order to avoid duplicates,
        # learn the new filename, and continue build if its not.
        if not ImportCache.isImportedModuleByName(module.getFullName()):
            debug(
                "Recurse to import '%s' from %s. (%s)",
                module.getFullName(),
                module_relpath,
                reason
            )

            if module_kind == "py" and source_filename is not None:
                try:
                    Building.createModuleTree(
                        module      = module,
                        source_ref  = source_ref,
                        source_code = readSourceCodeFromFilename(
                            module_name     = module.getFullName(),
                            source_filename = source_filename
                        ),
                        is_main     = False
                    )
                except (SyntaxError, IndentationError) as e:
                    if module_filename not in Importing.warned_about:
                        Importing.warned_about.add(module_filename)

                        warning(
                            """\
Cannot recurse to import module '%s' (%s) because of '%s'""",
                            module_relpath,
                            module_filename,
                            e.__class__.__name__
                        )

                    return None, False

            ImportCache.addImportedModule(
                module_relpath,
                module
            )

            is_added = True
        else:
            ImportCache.addImportedModule(
                module_relpath,
                ImportCache.getImportedModuleByName(module.getFullName())
            )

            module = ImportCache.getImportedModuleByName(
                module.getFullName()
            )

            is_added = False

        assert not module_relpath.endswith("/__init__.py"), module

        return module, is_added
    else:
        return ImportCache.getImportedModuleByPath(module_relpath), False

def decideRecursion(module_filename, module_name, module_package,
                    module_kind):
    # Many branches, which make decisions immediately, by returning
    # pylint: disable=R0911,R0912

    if module_kind == "shlib":
        if Options.isStandaloneMode():
            return True, "Shared library for inclusion."
        else:
            return False, "Shared library cannot be inspected."

    if module_package is None:
        full_name = module_name
    else:
        full_name = module_package + '.' + module_name

    if isFrozenModule(full_name):
        return False, "Module is frozen."

    no_case_modules = Options.getShallFollowInNoCase()

    for no_case_module in no_case_modules:
        if full_name == no_case_module:
            return (
                False,
                "Module listed explicitly to not recurse to."
            )

        if full_name.startswith(no_case_module + '.'):
            return (
                False,
                "Module in package listed explicitly to not recurse to."
            )

    any_case_modules = Options.getShallFollowModules()

    for any_case_module in any_case_modules:
        if full_name == any_case_module:
            return (
                True,
                "Module listed explicitly to recurse to."
            )

        if full_name.startswith(any_case_module + '.'):
            return (
                True,
                "Module in package listed explicitly to recurse to."
            )

    if Options.shallFollowNoImports():
        return (
            False,
            "Requested to not recurse at all."
        )

    if StandardLibrary.isStandardLibraryPath(module_filename):
        return (
            Options.shallFollowStandardLibrary(),
            "Requested to %srecurse to standard library." % (
                "" if Options.shallFollowStandardLibrary() else "not "
            )
        )

    if Options.shallFollowAllImports():
        return (
            True,
            "Requested to recurse to all non-standard library modules."
        )

    # Means, we were not given instructions how to handle things.
    return (
        None,
        "Default behavior, not recursing without request."
    )

def considerFilename(module_filename, module_package):
    assert module_package is None or \
           ( type(module_package) is str and module_package != "" )

    module_filename = Utils.normpath(module_filename)

    if Utils.isDir(module_filename):
        module_filename = Utils.abspath(module_filename)

        module_name = Utils.basename(module_filename)
        module_relpath = Utils.relpath(module_filename)

        return module_filename, module_relpath, module_name
    elif module_filename.endswith(".py"):
        module_name = Utils.basename(module_filename)[:-3]
        module_relpath = Utils.relpath(module_filename)

        return module_filename, module_relpath, module_name
    else:
        return None

def isSameModulePath(path1, path2):
    if Utils.basename(path1) == "__init__.py":
        path1 = Utils.dirname(path1)
    if Utils.basename(path2) == "__init__.py":
        path2 = Utils.dirname(path2)

    return Utils.abspath(path1) == Utils.abspath(path2)

def _checkPluginPath(plugin_filename, module_package):
    # Many branches, for the decision is very complex, pylint: disable=R0912

    debug(
        "Checking detail plug-in path '%s' '%s':",
        plugin_filename,
        module_package
    )

    plugin_info = considerFilename(
        module_package  = module_package,
        module_filename = plugin_filename
    )

    if plugin_info is not None:
        module, is_added = recurseTo(
            module_filename = plugin_info[0],
            module_relpath  = plugin_info[1],
            module_package  = module_package,
            module_kind     = "py",
            reason          = "Lives in plug-in directory."
        )

        if module:
            if not is_added:
                warning(
                    "Recursed to %s '%s' at '%s' twice.",
                    "package" if module.isPythonPackage() else "module",
                    module.getName(),
                    plugin_info[0]
                )

                if not isSameModulePath(module.getFilename(), plugin_info[0]):
                    warning(
                        "Duplicate ignored '%s'.",
                        plugin_info[1]
                    )

                    return

            debug(
                "Recursed to %s %s %s",
                module.getName(),
                module.getPackage(),
                module
            )

            if module.isPythonPackage():
                package_filename = module.getFilename()

                if Utils.isDir(package_filename):
                    # Must be a namespace package.
                    assert Utils.python_version >= 330

                    package_dir = package_filename

                    # Only include it, if it contains actual modules, which will
                    # recurse to this one and find it again.
                    useful = False
                else:
                    package_dir = Utils.dirname(package_filename)

                    # Real packages will always be included.
                    useful = True

                debug(
                    "Package directory %s",
                    package_dir
                )

                for sub_path, sub_filename in Utils.listDir(package_dir):
                    if sub_filename in ("__init__.py", "__pycache__"):
                        continue

                    assert sub_path != plugin_filename

                    if Importing.isPackageDir(sub_path) or \
                       sub_path.endswith(".py"):
                        _checkPluginPath(sub_path, module.getFullName())
            else:
                # Modules should always be included.
                useful = True

            if useful:
                ModuleRegistry.addRootModule(module)

        else:
            warning("Failed to include module from '%s'.", plugin_info[0])

def checkPluginPath(plugin_filename, module_package):
    debug(
        "Checking top level plug-in path %s %s",
        plugin_filename,
        module_package
    )

    plugin_info = considerFilename(
        module_package  = module_package,
        module_filename = plugin_filename
    )

    if plugin_info is not None:
        # File or package makes a difference, handle that
        if Utils.isFile(plugin_info[0]) or \
           Importing.isPackageDir(plugin_info[0]):
            _checkPluginPath(plugin_filename, module_package)
        elif Utils.isDir(plugin_info[0]):
            for sub_path, sub_filename in Utils.listDir(plugin_info[0]):
                assert sub_filename != "__init__.py"

                if Importing.isPackageDir(sub_path) or \
                   sub_path.endswith(".py"):
                    _checkPluginPath(sub_path, None)
        else:
            warning("Failed to include module from '%s'.", plugin_info[0])
    else:
        warning("Failed to recurse to directory '%s'.", plugin_filename)

def checkPluginFilenamePattern(pattern):
    import sys, glob

    debug(
        "Checking plug-in pattern '%s':",
        pattern,
    )

    if Utils.isDir(pattern):
        sys.exit("Error, pattern cannot be a directory name.")

    found = False

    for filename in glob.iglob(pattern):
        if filename.endswith(".pyc"):
            continue

        if not Utils.isFile(filename):
            continue

        found = True
        _checkPluginPath(filename, None)

    if not found:
        warning("Didn't match any files against pattern '%s'." % pattern)


text:
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
EventBoard::Application.initialize!


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bol. Micol. , Valparaíso 3(3): 202 (1988)

#### Original name
Uromyces traucoensis Monteal. & Oehrens

### Remarks
null


text:
    <waltz-measurable-rating-panel measurables="$ctrl.measurables"
                                   ratings="$ctrl.ratings"
                                   rating-scheme-items="$ctrl.ratingSchemeItems">
    </waltz-measurable-rating-panel>

    <waltz-markdown class="text-muted small"
                    text="$ctrl.measurableCategory.description">
    </waltz-markdown>


text:
var f = R.pipe(Math.pow, R.negate, R.inc);

f(3, 4); // -(3^4) + 1

//  parseJson :: String -> Maybe *
//  get :: String -> Object -> Maybe *

//  getStateCode :: Maybe String -> Maybe String
var getStateCode = R.pipeK(
  parseJson,
  get("user"),
  get("address"),
  get("state"),
  R.compose(Maybe.of, R.toUpper)
);

getStateCode('{"user":{"address":{"state":"ny"}}}');
//=> Just('NY')
getStateCode("[Invalid JSON]");
//=> Nothing()

//  followersForUser :: String -> Promise [User]
var followersForUser = R.pipeP(db.getUserById, db.getFollowers);


text:
set -e

# give up after two minutes
TIMEOUT=120

#
# functions
#

. /usr/share/one/supervisor/scripts/lib/functions.sh

#
# run service
#

for envfile in \
    /etc/default/supervisor/oneflow \
    ;
do
    if [ -f "$envfile" ] ; then
        . "$envfile"
    fi
done

if [ -f /var/lib/one/.one/oneflow_auth ] ; then
    msg "Found oneflow_auth - we can start service"
else
    msg "No oneflow_auth - wait for oned to create it..."
    if ! wait_for_file /var/lib/one/.one/oneflow_auth ; then
        err "Timeout!"
        exit 1
    fi
    msg "File created - continue"
fi

msg "Rotate log to start with an empty one"
/usr/sbin/logrotate -s /var/lib/one/.logrotate.status \
    -f /etc/logrotate.d/opennebula-flow || true

msg "Service started!"
exec /usr/bin/ruby /usr/lib/one/oneflow/oneflow-server.rb


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy Fit
 *
 * DEVICE: GT-S5670
 * MODEL: GT-S5670
 */
final class gt2ds5670_gt2ds5670 {
    public static final String DATA = "Samsung|Galaxy Fit|";
}


text:
package com.enetwiz.hibernateusage;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author Mariusz G <mg@netwiz.pl>
 */
@Entity
@Table(name = "entities")
public class ExampleEntity {

    @Id
    @GeneratedValue
    private int id = 0;

    @Column(nullable = false, length = 50)
    private String label = null;

    public int getId() {
        return id;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String pLabel) {
        label = pLabel;
    }

}


text:
<?php

/* @gantry-admin/pages/configurations/page/atoms.html.twig */
class __TwigTemplate_99c5758753f04c76da6096c42af899d1f8008be55314aba70bc07c29dda05a56 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "

    ";
        // line 2
        echo twig_escape_filter($this->env, $this->env->getExtension('Gantry\Component\Twig\TwigExtension')->transFilter("GANTRY5_PLATFORM_ATOMS"), "html", null, true);
        echo "

";
        // line 7
        $context['_parent'] = $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["atoms"]) ? $context["atoms"] : null));
        foreach ($context['_seq'] as $context["atom"] => $context["label"]) {
            // line 8
            echo "
env, $context["atom"], "html", null, true);
            echo "\"
            data-atom-picked=\"";
            // line 9
            echo twig_escape_filter($this->env, twig_jsonencode_filter(array("title" => $context["label"], "type" => $context["atom"], "attributes" => $this->getAttribute($this->getAttribute((isset($context["gantry"]) ? $context["gantry"] : null), "config", array()), "get", array(0 => ("particles." . $context["atom"])), "method"))), "html_attr");
            echo "\"
        >

            ";
            // line 12
            echo twig_escape_filter($this->env, $context["label"], "html", null, true);
            echo "
            env, $this->getAttribute((isset($context["gantry"]) ? $context["gantry"] : null), "route", array(0 => "configurations", 1 => (isset($context["page_id"]) ? $context["page_id"] : null), 2 => "page", 3 => "atoms", 4 => $context["atom"]), "method"));
            echo "\" class=\"atom-settings config-cog\">
                env, $this->env->getExtension('Gantry\Component\Twig\TwigExtension')->transFilter("GANTRY5_PLATFORM_ATOMS_CONFIGURE_SETTINGS"), "html", null, true);
            echo "\" class=\"fa fa-cog\">

";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['atom'], $context['label'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 18
        echo "

        ";
        // line 21
        $context["list"] = ((($this->getAttribute((isset($context["data"]) ? $context["data"] : null), "get", array(0 => "page.head.atoms"), "method", true, true) &&  !(null === $this->getAttribute((isset($context["data"]) ? $context["data"] : null), "get", array(0 => "page.head.atoms"), "method")))) ? ($this->getAttribute((isset($context["data"]) ? $context["data"] : null), "get", array(0 => "page.head.atoms"), "method")) : ($this->getAttribute((isset($context["defaults"]) ? $context["defaults"] : null), "get", array(0 => "page.head.atoms"), "method")));
        // line 22
        echo "        ";
        if ((isset($context["list"]) ? $context["list"] : null)) {
            // line 23
            echo "
";
            // line 24
            $context['_parent'] = $context;
            $context['_seq'] = twig_ensure_traversable((isset($context["list"]) ? $context["list"] : null));
            foreach ($context['_seq'] as $context["_key"] => $context["atom"]) {
                // line 25
                $context["classes"] = ((($this->getAttribute($this->getAttribute($context["atom"], "attributes", array()), "enabled", array())) ? ("") : ("atom-disabled")) . (($this->getAttribute($this->getAttribute($context["atom"], "inherit", array()), "outline", array())) ? (" g-inheriting") : ("")));
                // line 26
                echo "                    ";
                $context["inheriting"] = (($this->getAttribute($this->getAttribute($context["atom"], "inherit", array()), "outline", array())) ? (((((((" g-inheriting=\"\" data-tip=\"" . $this->env->getExtension('Gantry\Component\Twig\TwigExtension')->transFilter("GANTRY5_PLATFORM_INHERITING_FROM_X", (("" . $this->getAttribute($this->getAttribute(                // line 27
(isset($context["gantry"]) ? $context["gantry"] : null), "outlines", array()), "title", array(0 => $this->getAttribute($this->getAttribute($context["atom"], "inherit", array()), "outline", array())), "method")) . ""))) . "
ID: ") . $this->getAttribute($this->getAttribute($context["atom"], "inherit", array()), "atom", array())) . "
Replace: ") . twig_join_filter($this->getAttribute($this->getAttribute($context["atom"], "inherit", array()), "include", array()), ", ")) . "\"")) : (""));
                // line 28
                echo "                    ";
                $context["title"] = (($this->getAttribute($this->getAttribute($context["atom"], "attributes", array()), "enabled", array())) ? ("") : (((" title=\"" . $this->env->getExtension('Gantry\Component\Twig\TwigExtension')->transFilter("GANTRY5_PLATFORM_ATOMS_DISABLED_DESC")) . "\"")));
                // line 29
                echo "
env, twig_jsonencode_filter($context["atom"]), "html_attr");
                echo "\"";
                echo (((isset($context["classes"]) ? $context["classes"] : null)) ? (((" class=\"" . trim((isset($context["classes"]) ? $context["classes"] : null))) . "\"")) : (""));
                echo (isset($context["inheriting"]) ? $context["inheriting"] : null);
                echo (isset($context["title"]) ? $context["title"] : null);
                echo " data-atom-type=\"";
                echo twig_escape_filter($this->env, $this->getAttribute($context["atom"], "type", array()), "html", null, true);
                echo "\">

                        ";
                // line 31
                echo twig_escape_filter($this->env, $this->getAttribute($context["atom"], "title", array()), "html", null, true);
                echo "
                        env, $this->getAttribute((isset($context["gantry"]) ? $context["gantry"] : null), "route", array(0 => "configurations", 1 => (isset($context["page_id"]) ? $context["page_id"] : null), 2 => "page", 3 => "atoms", 4 => $this->getAttribute($context["atom"], "type", array())), "method"), "html", null, true);
                echo "\" class=\"atom-settings config-cog\">

";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['atom'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 37
            echo "

        ";
        } else {
            // line 39
            echo "

        ";
        }
        // line 41
        echo "
        ";
        // line 42
        if ((isset($context["overrideable"]) ? $context["overrideable"] : null)) {
            // line 43
            echo "            ";
            $context["prefix"] = "page.head.";
            // line 44
            echo "            ";
            $this->loadTemplate("forms/override.html.twig", "@gantry-admin/pages/configurations/page/atoms.html.twig", 44)->display(array_merge($context, array("scope" => (isset($context["prefix"]) ? $context["prefix"] : null), "name" => "atoms", "has_value" =>  !(null === $this->getAttribute((isset($context["data"]) ? $context["data"] : null), "get", array(0 => ((isset($context["prefix"]) ? $context["prefix"] : null) . "atoms")), "method")), "field" => array("label" => "Enabled of the field Atoms"))));
            // line 45
            echo "        ";
        }
        // line 46
        echo "

    ";
        // line 49
        echo "    ";
        if ((( !(null === (isset($context["atoms_deprecated"]) ? $context["atoms_deprecated"] : null)) && twig_length_filter($this->env, (isset($context["atoms_deprecated"]) ? $context["atoms_deprecated"] : null))) && $this->getAttribute((isset($context["data"]) ? $context["data"] : null), "get", array(0 => "page.head.atoms"), "method"))) {
            // line 50
            echo "
";
            echo twig_escape_filter($this->env, $this->env->getExtension('Gantry\Component\Twig\TwigExtension')->transFilter("GANTRY5_PLATFORM_ATOMS_DEPRECATED_MESSAGE"), "html", null, true);
            echo "

    ";
        }
        // line 52
        echo "

×
";
        // line 53
        echo twig_escape_filter($this->env, $this->env->getExtension('Gantry\Component\Twig\TwigExtension')->transFilter("GANTRY5_PLATFORM_DROP_DELETE"), "html", null, true);
        echo "

    ";
        // line 55
        echo "
";
    }

    public function getTemplateName()
    {
        return "@gantry-admin/pages/configurations/page/atoms.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  157 => 55,  153 => 53,  150 => 52,  144 => 50,  141 => 49,  137 => 46,  134 => 45,  131 => 44,  128 => 43,  126 => 42,  123 => 41,  119 => 39,  115 => 37,  105 => 32,  101 => 31,  89 => 29,  86 => 28,  84 => 27,  82 => 26,  80 => 25,  76 => 24,  74 => 23,  71 => 22,  69 => 21,  64 => 18,  55 => 14,  51 => 13,  47 => 12,  41 => 9,  36 => 8,  32 => 7,  28 => 5,  22 => 2,  19 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("", "@gantry-admin/pages/configurations/page/atoms.html.twig", "/var/www/html/grav/user/plugins/gantry5/admin/templates/pages/configurations/page/atoms.html.twig");
    }
}


text:
This library contains native implementation of [RELP protocol](http://www.rsyslog.com/doc/relp.html) in ruby with TLS support. At the moment only server-side
is properly implemented and (to some extent) tested.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'relp'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install relp

## Usage

### Server

To run server just create instance of `Relp::RelpServer.new(port, callback, host, tls_context, logger)`
and then call method run on instance of server e.g. `server.run`

`port`

  * This is a required setting.
  * Value type is number
  * There is no default value for this setting.
  * Sets on which port you want to listen for incoming RELP connections

`callback`
  * This is a required setting.
  * Method you want to be executed upon successfully accepted message, it has only one :string parameter, which is message itself.

`host`
  * This is a required setting.
  * Value type is string
  * Default value is "0.0.0.0' to bind any address
  * Specifies address you want to bind to, use "0.0.0.0" to bind to any address

`tls_context`
  * Value type is SSL_context_object = OpenSSL::SSL::SSLContext.new See -> OpenSSL homepage
  * If is not set - server runs without TLS or SSL encryption
  * Example of TLS/SSL context object:
  ```ruby
      sslContext = OpenSSL::SSL::SSLContext.new
      sslContext.cert = OpenSSL::X509::Certificate.new(File.open("path/to/certificate/cert.pem"))
      sslContext.key = OpenSSL::PKey::RSA.new(File.open("path/to/key/key.pem"))
      sslContext.ca_file = 'path/to/certificate/authority/ca.pem'
      sslContext.verify_mode = OpenSSL::SSL::VERIFY_PEER #only if you want verify peer
  ```

`logger`

  * This is optional setting
  * Value type is logger object
  * If is not set - default is `Logger.new(STDOUT)` with all levels of logging

#### Important Methods
  * `run` Start connecting clients
  *  `server_shutdown` Close connection to all clients and shutdown server

### Client

Coming soon.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`.
## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ViaQ/Relp.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
import AnalyzerResult from '../analyzer-result';
import TextProcessor from '../text-processor';
import textStatistics from 'text-statistics';
import readTime from 'read-time';
import roundTo from 'round-to';

export default class StatisticsAnalyzer {
  analyze(str) {
    const result = new AnalyzerResult();

    const text = TextProcessor.markdownToText(str);

    const stats = textStatistics(text || ' ');
    const statsFullTextContent = textStatistics(str || ' ');

    const addMessage = (messageType, numericValue) => {
      result.addMessage(messageType, roundTo(numericValue, 2));
    };

    //
    // General statistics
    //

    addMessage('statistics-text-length', statsFullTextContent.textLength());
    addMessage('statistics-letter-count', stats.letterCount());
    addMessage('statistics-sentence-count', stats.sentenceCount());
    addMessage('statistics-word-count', stats.wordCount());
    addMessage('statistics-average-words-per-sentence', stats.averageWordsPerSentence());
    addMessage('statistics-average-syllables-per-word', stats.averageSyllablesPerWord());
    addMessage('statistics-words-with-three-syllables', stats.wordsWithThreeSyllables());
    addMessage('statistics-percentage-words-with-three-syllables', stats.percentageWordsWithThreeSyllables());

    //
    // Readability
    //

    // https://en.wikipedia.org/wiki/Flesch–Kincaid_readability_tests
    addMessage('statistics-flesch-kincaid-reading-ease', stats.fleschKincaidReadingEase());
    addMessage('statistics-flesch-kincaid-grade-level', stats.fleschKincaidGradeLevel());

    // https://en.wikipedia.org/wiki/Gunning_fog_index
    addMessage('statistics-gunning-fog-score', stats.gunningFogScore());

    // https://en.wikipedia.org/wiki/Coleman%E2%80%93Liau_index
    addMessage('statistics-coleman-liau-index', stats.colemanLiauIndex());

    // https://en.wikipedia.org/wiki/SMOG
    addMessage('statistics-smog-index', stats.smogIndex());

    // https://en.wikipedia.org/wiki/Automated_readability_index
    addMessage('statistics-automated-readability-index', stats.automatedReadabilityIndex());

    //
    // Estimated read time
    //

    const readTimeResult = readTime(text);

    result.addMessage('statistics-estimated-read-time', readTimeResult.text);
    result.addMessage('statistics-estimated-read-time-minutes', readTimeResult.m);

    return result;
  }
}


text:
@implementation CheckoutInputTableViewCell

- (void)awakeFromNib
{
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
@end


text:
using DragonSpark.Model.Selection;
using DragonSpark.Runtime.Activation;
using System;

namespace DragonSpark.Runtime.Invocation;

sealed class Stripe<TIn, TOut> : ISelect<TIn, TOut>, IActivateUsing<Func<TIn, TOut>> where TIn : notnull
{
	readonly static Func<TIn, object> Lock = Locks<TIn>.Default.Get;

	readonly Func<TIn, object> _lock;
	readonly Func<TIn, TOut>   _source;

	public Stripe(Func<TIn, TOut> source) : this(Lock, source) {}

	public Stripe(Func<TIn, object> @lock, Func<TIn, TOut> source)
	{
		_lock   = @lock;
		_source = source;
	}

	public TOut Get(TIn parameter)
	{
		lock (_lock(parameter))
		{
			return _source(parameter);
		}
	}
}


text:
@interface DPPlainColorViewController : DPBaseViewController <DPDrawerControllerChild,
DPDrawerControllerPresenting>

@property (nonatomic, weak) DPDrawerViewController *drawer;

@end


text:
package com.amazonaws.services.opsworks.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.opsworks.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * RaidArrayMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RaidArrayMarshaller {

    private static final MarshallingInfo<String> RAIDARRAYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RaidArrayId").build();
    private static final MarshallingInfo<String> INSTANCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InstanceId").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();
    private static final MarshallingInfo<Integer> RAIDLEVEL_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RaidLevel").build();
    private static final MarshallingInfo<Integer> NUMBEROFDISKS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NumberOfDisks").build();
    private static final MarshallingInfo<Integer> SIZE_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Size").build();
    private static final MarshallingInfo<String> DEVICE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Device").build();
    private static final MarshallingInfo<String> MOUNTPOINT_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MountPoint").build();
    private static final MarshallingInfo<String> AVAILABILITYZONE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AvailabilityZone").build();
    private static final MarshallingInfo<String> CREATEDAT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("CreatedAt").build();
    private static final MarshallingInfo<String> STACKID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("StackId").build();
    private static final MarshallingInfo<String> VOLUMETYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("VolumeType").build();
    private static final MarshallingInfo<Integer> IOPS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Iops").build();

    private static final RaidArrayMarshaller instance = new RaidArrayMarshaller();

    public static RaidArrayMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(RaidArray raidArray, ProtocolMarshaller protocolMarshaller) {

        if (raidArray == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(raidArray.getRaidArrayId(), RAIDARRAYID_BINDING);
            protocolMarshaller.marshall(raidArray.getInstanceId(), INSTANCEID_BINDING);
            protocolMarshaller.marshall(raidArray.getName(), NAME_BINDING);
            protocolMarshaller.marshall(raidArray.getRaidLevel(), RAIDLEVEL_BINDING);
            protocolMarshaller.marshall(raidArray.getNumberOfDisks(), NUMBEROFDISKS_BINDING);
            protocolMarshaller.marshall(raidArray.getSize(), SIZE_BINDING);
            protocolMarshaller.marshall(raidArray.getDevice(), DEVICE_BINDING);
            protocolMarshaller.marshall(raidArray.getMountPoint(), MOUNTPOINT_BINDING);
            protocolMarshaller.marshall(raidArray.getAvailabilityZone(), AVAILABILITYZONE_BINDING);
            protocolMarshaller.marshall(raidArray.getCreatedAt(), CREATEDAT_BINDING);
            protocolMarshaller.marshall(raidArray.getStackId(), STACKID_BINDING);
            protocolMarshaller.marshall(raidArray.getVolumeType(), VOLUMETYPE_BINDING);
            protocolMarshaller.marshall(raidArray.getIops(), IOPS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
require_relative './jamespath/tokenizer'
require_relative './jamespath/parser'
require_relative './jamespath/vm'
require_relative './jamespath/version'

# {include:file:README.md}
module Jamespath
  module_function

  # Searches an object with a given JMESpath expression.
  #
  # @param query [String] the expression to search for.
  # @param object [Object] an object to search for the expression in.
  # @return [Object] the object, or list of objects, that match the expression.
  # @return [nil] if no objects matched the expression
  # @example Searching an object
  #   Jamespath.search('foo.bar', foo: {bar: 'result'}) #=> 'result'
  def search(query, object)
    compile(query).search(object)
  end

  # Compiles an expression that can be {VM#search searched}.
  #
  # @param query [String] the expression to search for.
  # @return [VM] a virtual machine object that can interpret the expression.
  # @see VM#search
  # @example Compiling an expression
  #   expr = Jamespath.compile('foo.bar')
  #   expr.search(foo: {bar: 'result1'}) #=> 'result1'
  #   expr.search(foo: {bar: 'result2'}) #=> 'result2'
  def compile(query)
    VM.new(Parser.new.parse(query))
  end
end


text:
#include <iostream>		// for console output
#include <opencv2\features2d\features2d.hpp>
#include "CameraPoseEstimator.h"
#include "CameraPoseEstimator1.h"
#include "DepthToPointTranslator.h"
#include "DepthToPointTranslator1.h"
#include "RGBDMerger1.h"

RGBDMerger1::RGBDMerger1(void)
{
	this->poseEstimator = new CameraPoseEstimator1();
	this->d2pTranslator = new DepthToPointTranslator1();
	this->detector = new DenseFeatureDetector(1.f, 1, 0.1f, 1);
	this->extractor = new ORB();
	//this->matcher = new BFMatcher(NORM_HAMMING, true);
	this->matcher = new ocl::BruteForceMatcher_OCL_base(
		ocl::BruteForceMatcher_OCL_base::HammingDist);	// no cross-checking
}

RGBDMerger1::~RGBDMerger1(void)
{
	delete this->poseEstimator;
	delete this->d2pTranslator;
	delete this->detector;
	delete this->extractor;
	delete this->matcher;
}

Mat RGBDMerger1::merge(const vector<Mat>& images, const vector<Mat>& depthMaps,
	const vector<Mat>& confidenceMaps, const Mat& calibrationMatrix)
{
	assert(images.size() > 1);

	cout << "RGBDMerger::merge(): 1) estimate camera poses" << endl;
	// 1) estimate camera poses
	poseEstimator->estimateCameraPoses(images, calibrationMatrix);

	cout << "RGBDMerger::merge(): 2) triangulate points" << endl;
	// 2) triangulate points
	vector<Mat> partialReconstructions = vector<Mat>(depthMaps.size());
	for (int i = 0; i < depthMaps.size(); i++)
	{
		partialReconstructions.at(i) = d2pTranslator->translateDepthToPoints(
			depthMaps.at(i), calibrationMatrix, poseEstimator->rotations.at(i),
			poseEstimator->translations.at(i));
	}

	cout << "RGBDMerger::merge(): 3) find redundancies" << endl;
	// 3) find redundancies
	vector<vector<KeyPoint>> keyPoints;
	vector<Mat> descriptors;
	vector<DMatch> matches;
	vector<vector<DMatch>> matches12, matches21;

	Mat mask = Mat(images.at(0).size(), CV_8SC1, Scalar::all(0));
	rectangle(mask, Point(32, 32), Point(images.at(0).size().width - 31,
		images.at(0).size().height - 31), Scalar::all(255), CV_FILLED);
	vector<Mat> masks = vector<Mat>(images.size());
	for (int i = 0; i < masks.size(); i++)
		mask.copyTo(masks[i]);

	// prepare images for feature detection and descriptor extraction
	vector<Mat> bwImages = vector<Mat>(images.size());
	for (int i = 0; i < images.size(); i++)
	{
		cvtColor(images.at(i), bwImages.at(i), CV_RGB2GRAY);
		bwImages.at(i).convertTo(bwImages.at(i), CV_8UC1, 255);
	}

	detector->detect(bwImages, keyPoints);
	extractor->compute(bwImages, keyPoints, descriptors);

	// upload descriptors to GPU
	vector<oclMat> oclDescriptors = vector<oclMat>(descriptors.size());
	for (int i = 0; i < descriptors.size(); i++)
		oclDescriptors.at(i) = oclMat(descriptors.at(i));
	oclMat queryDescriptors;

	//Mat queryDescriptors;
	int matchIndex, imgIdx1, imgIdx2;
	DMatch match, match12, match21;
	Point2f pt1, pt2;
	float confidence1, confidence2;
	for (imgIdx1 = images.size() - 1; imgIdx1 >= 0 ; imgIdx1--)
	for (imgIdx2 = 0; imgIdx2 < imgIdx1; imgIdx2++)
	{
		//queryDescriptors = oclDescriptors.at(imgIdx1);
		//oclDescriptors.pop_back();
		//queryDescriptors = descriptors.at(i);
		//descriptors.pop_back();

		//matcher->clear();
		//matcher->add(oclDescriptors);
		//matcher->add(descriptors);

		//matcher->match(queryDescriptors, matches);

		matcher->match(oclDescriptors.at(imgIdx1), oclDescriptors.at(imgIdx2),
			matches);

		/*
		matcher->knnMatch(oclDescriptors.at(imgIdx1), oclDescriptors.at(imgIdx2),
			matches12, 2);
		matcher->knnMatch(oclDescriptors.at(imgIdx2), oclDescriptors.at(imgIdx1),
			matches21, 2);
		const float distanceThreshold = 0.75;			// TODO constant
		*/

		for (matchIndex = 0; matchIndex < matches.size(); matchIndex++)
		{
			match12 = matches.at(matchIndex);
			//match12 = matches12.at(matchIndex).at(0);
			//match21 = matches21.at(match12.trainIdx).at(0);

			/*
			// cross-check and symmetric ratio test
			if (!(match21.trainIdx == match12.queryIdx &&
				matches12.at(matchIndex).at(0).distance / matches12.at(matchIndex).at(1).distance < distanceThreshold &&
				matches21.at(matchIndex).at(0).distance / matches21.at(matchIndex).at(1).distance < distanceThreshold))

				continue;
			*/

			pt1 = keyPoints.at(imgIdx1).at(match12.queryIdx).pt;
			pt2 = keyPoints.at(imgIdx2).at(match12.trainIdx).pt;

			confidence1 = confidenceMaps.at(imgIdx1).at<float>(pt1);
			confidence2 = confidenceMaps.at(imgIdx2).at<float>(pt2);

			if (confidence1 < confidence2)
				masks.at(imgIdx1).at<uchar>(pt1) = 0;
			else
				masks.at(imgIdx2).at<uchar>(pt2) = 0;
		}
	}

	cout << "RGBDMerger::merge(): 4) merge partial reconstructions" << endl;
	// 4) merge partial reconstructions
	Mat completeReconstruction = Mat();//partialReconstructions.at(0).clone();
	Mat luminanceMap = Mat();//images.at(0).clone();
	for (int i = 0; i < partialReconstructions.size(); i++)
	{
		// handle redundant points
		partialReconstructions.at(i).setTo(Scalar::all(0), masks.at(i) - 255);	// flip binary mask

		// join partial models
		completeReconstruction.push_back(partialReconstructions.at(i));
		luminanceMap.push_back(images.at(i));
	}

	this->pointCloud = completeReconstruction;
	this->pointColors = luminanceMap;

	return completeReconstruction;
}


text:
(function (){
    function blah (month,year) {
                 return new Date(year, month, 0).getDate();
    }
    function DatePanelViewModel(){
        // The data here is system generated
        // ensure that the system clock is uptodate

	var self = this;
	self.selectedDay = ko.observable();
        self.daysInMonth = function (month,year){
	    var dt = new Date();
	    console.log(dt.getMonth());

	    self.month = month || dt.getMonth()+1;
	    console.log("The current month is "+ month);
	    self.year = year || dt.getYear();
            return new Date(self.year, self.month, 0).getDate();
	},
	self.init = function (){
            self.noofdays= self.daysInMonth();
            console.log(self.noofdays);
            self.days= ko.observableArray();
            for (var i=1; i<= self.noofdays; i++){
		var eff = self.randomEfficiencyForTheDay();

                self.days.push({day: i, cop: eff});
            }
	},
	self.selectDate = function (day, e){
	    self.showData(self.year,self.month,day.day);
	    console.log(e);
	    $(self.selected).css('background-color',"transparent");
	    $(e.target).css('background-color',"yellow");
	    self.selected = e.target;
	},
	self.randomEfficiencyForTheDay = function (){
	   return Math.random(.1);
	},
	self.copColor = ko.computed(function (){
	// returns the color as per the efficiency level;
		return self.cop;
	},this );

	self.showData = function (y,m,d){
	    // Will check for existing data, and will fetch if it's not there
	    //
	    console.log("year"+y+" month"+m+" day"+d);

	    // And pass it to the appropriate viewmodel.
	},
	self.logMouseOver = function (d,e){

	    $(e.target).css("background-color","blue");
	    console.log(d.cop);
	},
	self.logMouseOut = function (d,e){
	    if (e.target == self.selected){
	        $(e.target).css("background-color", "yellow");

	    }
	    else {
	         $(e.target).css("background-color", "transparent");

	    }

	},
        this.init();
    }
    ko.applyBindings(
        new DatePanelViewModel()
      );

})();


text:
package org.apache.poi.hsmf.model;

import java.io.IOException;

import org.apache.poi.hsmf.MAPIMessage;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
import org.apache.poi.POIDataSamples;

import junit.framework.TestCase;

/**
 * Tests to verify that the library can read blank msg files.
 *
 * @author Travis Ferguson
 *
 */
public final class TestBlankFileRead extends TestCase {
	private MAPIMessage mapiMessage;

	/**
	 * Initialize this test, load up the blank.msg mapi message.
	 */
	public TestBlankFileRead() throws IOException {
        POIDataSamples samples = POIDataSamples.getHSMFInstance();
		this.mapiMessage = new MAPIMessage(samples.openResourceAsStream("blank.msg"));
	}

	/**
	 * Check if we can read the body of the blank message, we expect "".
	 */
	public void testReadBody() {
		try {
			mapiMessage.getTextBody();
		} catch(ChunkNotFoundException exp) {
			return;
		}

		TestCase.fail("Should have thrown a ChunkNotFoundException but didn't");
	}

	/**
	 * Test to see if we can read the CC Chunk.
	 */
	public void testReadDisplayCC() throws ChunkNotFoundException {
		String obtained = mapiMessage.getDisplayCC();
		String expected = "";

		TestCase.assertEquals(expected, obtained);
	}

	/**
	 * Test to see if we can read the CC Chunk.
	 */
	public void testReadDisplayTo() throws ChunkNotFoundException {
		String obtained = mapiMessage.getDisplayTo();
		String expected = "";

		TestCase.assertEquals(expected, obtained);
	}

	/**
	 * Test to see if we can read the FROM Chunk.
	 */
	public void testReadDisplayFrom() {
		try {
			mapiMessage.getDisplayFrom();
		} catch(ChunkNotFoundException exp) {
			return;
		}

		TestCase.fail("Should have thrown a ChunkNotFoundException but didn't");
	}

	/**
	 * Test to see if we can read the CC Chunk.
	 */
	public void testReadDisplayBCC() throws ChunkNotFoundException {
		String obtained = mapiMessage.getDisplayBCC();
		String expected = "";

		TestCase.assertEquals(expected, obtained);
	}

	/**
	 * Check if we can read the subject line of the blank message, we expect ""
	 */
	public void testReadSubject() throws Exception {
		String obtained = mapiMessage.getSubject();
		TestCase.assertEquals("", obtained);
	}

	/**
	 * Check if we can read the subject line of the blank message, we expect ""
	 */
	public void testReadConversationTopic() {
		try {
			mapiMessage.getConversationTopic();
		} catch(ChunkNotFoundException exp) {
			return;
		}
		TestCase.fail("We shouldn't have a ConversationTopic node on the blank.msg file.");
	}

}


text:
package org.apache.commons.configuration2.builder;

import javax.sql.DataSource;

/**
 *

 * A specialized parameters object for database configurations.
 *

 *

 * This class has properties for defining the database structures the
 * configuration operates on.
 *

 *

 * This class is not thread-safe. It is intended that an instance is constructed
 * and initialized by a single thread during configuration of a
 * {@code ConfigurationBuilder}.
 *

 *
 * @version $Id$
 * @since 2.0
 */
public class DatabaseBuilderParametersImpl extends BasicBuilderParameters
        implements DatabaseBuilderProperties<DatabaseBuilderParametersImpl>
{
    /** Constant for the data source property. */
    private static final String PROP_DATA_SOURCE = "dataSource";

    /** Constant for the table property. */
    private static final String PROP_TABLE = "table";

    /** Constant for the key column property. */
    private static final String PROP_KEY_COLUMN = "keyColumn";

    /** Constant for the value column property. */
    private static final String PROP_VALUE_COLUMN = "valueColumn";

    /** Constant for the configuration name column property. */
    private static final String PROP_CONFIG_NAME_COLUMN =
            "configurationNameColumn";

    /** Constant for the configuration name property. */
    private static final String PROP_CONFIG_NAME = "configurationName";

    /** Constant for the auto commit property. */
    private static final String PROP_AUTO_COMMIT = "autoCommit";

    @Override
    public DatabaseBuilderParametersImpl setDataSource(DataSource src)
    {
        storeProperty(PROP_DATA_SOURCE, src);
        return this;
    }

    @Override
    public DatabaseBuilderParametersImpl setTable(String tname)
    {
        storeProperty(PROP_TABLE, tname);
        return this;
    }

    @Override
    public DatabaseBuilderParametersImpl setKeyColumn(String name)
    {
        storeProperty(PROP_KEY_COLUMN, name);
        return this;
    }

    @Override
    public DatabaseBuilderParametersImpl setValueColumn(String name)
    {
        storeProperty(PROP_VALUE_COLUMN, name);
        return this;
    }

    @Override
    public DatabaseBuilderParametersImpl setConfigurationNameColumn(String name)
    {
        storeProperty(PROP_CONFIG_NAME_COLUMN, name);
        return this;
    }

    @Override
    public DatabaseBuilderParametersImpl setConfigurationName(String name)
    {
        storeProperty(PROP_CONFIG_NAME, name);
        return this;
    }

    @Override
    public DatabaseBuilderParametersImpl setAutoCommit(boolean f)
    {
        storeProperty(PROP_AUTO_COMMIT, Boolean.valueOf(f));
        return this;
    }
}


text:
namespace i2p
{
namespace api
{
	void InitI2P (int argc, char* argv[], const char * appName)
	{
		i2p::util::filesystem::SetAppName (appName);
		i2p::util::config::OptionParser(argc, argv);
		i2p::context.Init ();
	}

	void StartI2P (std::ostream * logStream)
	{
		if (logStream)
			StartLog (logStream);
		else
			StartLog (i2p::util::filesystem::GetAppName () + ".log");
		i2p::data::netdb.Start();
		LogPrint("NetDB started");
		i2p::transport::transports.Start();
		LogPrint("Transports started");
		i2p::tunnel::tunnels.Start();
		LogPrint("Tunnels started");
	}

	void StopI2P ()
	{
		LogPrint("Shutdown started.");
		i2p::tunnel::tunnels.Stop();
		LogPrint("Tunnels stopped");
		i2p::transport::transports.Stop();
		LogPrint("Transports stopped");
		i2p::data::netdb.Stop();
		LogPrint("NetDB stopped");
		StopLog ();
	}

	i2p::client::ClientDestination * CreateLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic,
		const std::map<std::string, std::string> * params)
	{
		auto localDestination = new i2p::client::ClientDestination (keys, isPublic, params);
		localDestination->Start ();
		return localDestination;
	}

	i2p::client::ClientDestination * CreateLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType,
		const std::map<std::string, std::string> * params)
	{
		i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType);
		auto localDestination = new i2p::client::ClientDestination (keys, isPublic, params);
		localDestination->Start ();
		return localDestination;
	}

	void DestroyLocalDestination (i2p::client::ClientDestination * dest)
	{
		if (dest)
		{
			dest->Stop ();
			delete dest;
		}
	}

	void RequestLeaseSet (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote)
	{
		if (dest)
			dest->RequestDestination (remote);
	}

	std::shared_ptr<i2p::stream::Stream> CreateStream (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote)
	{
		if (!dest) return nullptr;
		auto leaseSet = dest->FindLeaseSet (remote);
		if (leaseSet)
		{
			auto stream = dest->CreateStream (leaseSet);
			stream->Send (nullptr, 0); // connect
			return stream;
		}
		else
		{
			RequestLeaseSet (dest, remote);
			return nullptr;
		}
	}

	void AcceptStream (i2p::client::ClientDestination * dest, const i2p::stream::StreamingDestination::Acceptor& acceptor)
	{
		if (dest)
			dest->AcceptStreams (acceptor);
	}

	void DestroyStream (std::shared_ptr<i2p::stream::Stream> stream)
	{
		if (stream)
			stream->Close ();
	}
}
}


text:
var crypto = require("crypto");

// load common module
exports = module.exports = require('./cs2a.js');

// prefer compiled versions

try {
  if(process.env.PURE == 'true') throw new Error("pure requested");
  var ecc = require("ecc");
}catch(E){
  var ecc = require("ecc-jsbn")
}

var forge = require("node-forge");
try {
  if(process.env.PURE == 'true') throw new Error("pure requested");
  var ursa = require("ursa");
}catch(E){
}

// load node-specific crypto methods
exports.crypt(ecc,forge);

// replace these when compiled ursa works and forge won't be used
if(ursa)
{
  exports.generate = function(cb)
  {
    var kpair = ursa.generatePrivateKey();
    var key = str2der(kpair.toPublicPem("utf8"));
    var secret = str2der(kpair.toPrivatePem("utf8"));
    cb(null,{key:key,secret:secret});
  }

  exports.loadkey = function(id, key, secret)
  {
    // TODO, figure out why ursa is rejecting valid pub keys, workaround is using forge
    var pkf = forge.pki.publicKeyFromAsn1(forge.asn1.fromDer(key.toString("binary")));     var pem = forge.pki.publicKeyToPem(pkf);
    var pk = ursa.coercePublicKey(pem);
//    var pk = ursa.coercePublicKey(der2pem(key,"PUBLIC"));
    if(!pk) return true;
    if(pk.getModulus().length != 256) return true;
    id.encrypt = function(buf){
      return pk.encrypt(buf, undefined, undefined, ursa.RSA_PKCS1_OAEP_PADDING);
    };
    id.verify = function(a,b){
      return pk.hashAndVerify("sha256", a, b);
    };
    if(secret)
    {
      var sk = ursa.coercePrivateKey(der2pem(secret,"RSA PRIVATE"));
      id.sign = function(buf){
        return sk.hashAndSign("sha256", buf);
      };
      id.decrypt = function(buf){
        return sk.decrypt(buf, undefined, undefined, ursa.RSA_PKCS1_OAEP_PADDING);
      };
    }
    return undefined;
  }
}

// ursa is not very flexible!

var PEM_REGEX = /^(-----BEGIN (.*) KEY-----\r?\n([\/+=a-zA-Z0-9\r\n]*)\r?\n-----END \2 KEY-----\r?\n)/m;
function str2der(str)
{
  var r = PEM_REGEX.exec(str);
  var b64 = r ? r[3] : str;
  return new Buffer(b64, "base64");
}
function der2pem(der,type)
{
  if(!der || !Buffer.isBuffer(der)) return false;
  var b64 = der.toString("base64");
  if(!b64) return false;
  b64 = b64.match(/.{1,64}/g).join("\n");
  return "-----BEGIN "+type+" KEY-----\n"+b64+"\n-----END "+type+" KEY-----\n";
}


text:
package org.atomify.model;

import java.net.URI;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;

import org.jbasics.xml.XmlStylesheetLinks;
import org.jbasics.xml.types.XmlStylesheetProcessInstruction;
import org.xml.sax.SAXException;

public class AtomDocumentSerializer {
	private final String encoding;

	public AtomDocumentSerializer() {
		this("UTF-8");
	}

	public AtomDocumentSerializer(String encoding) {
		this.encoding = AtomContractConstraint.mustNotBeEmptyString(encoding, "encoding");
	}

	public void serialize(AtomDocument document, Result result) {
		serialize(document, result, null);
	}

	protected void serialize(AtomDocument document, Result result, Templates templates) {
		AtomContractConstraint.notNull("document", document);
		AtomContractConstraint.notNull("result", result);
		try {
			SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
			TransformerHandler handler = templates == null ? factory.newTransformerHandler() : factory.newTransformerHandler(templates);
			Transformer serializer = handler.getTransformer();
			serializer.setOutputProperty(OutputKeys.METHOD, "xml");
			serializer.setOutputProperty(OutputKeys.ENCODING, this.encoding);
			serializer.setOutputProperty(OutputKeys.INDENT, "yes");
			serializer.setOutputProperty(OutputKeys.VERSION, "1.0");
			serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
			handler.setResult(result);
			if (document instanceof XmlStylesheetLinks) {
				for (XmlStylesheetProcessInstruction stylesheet : ((XmlStylesheetLinks) document).getStylesheetLinks()) {
					stylesheet.serialize(handler, null);
				}
			}
			handler.startDocument();
			document.serialize(handler, null);
			handler.endDocument();
		} catch (SAXException e) {
			RuntimeException er = new RuntimeException("[" + e.getClass().getSimpleName() + "] " + e.getMessage(), e);
			er.setStackTrace(e.getStackTrace());
			throw er;
		} catch (TransformerConfigurationException e) {
			RuntimeException er = new RuntimeException("[" + e.getClass().getSimpleName() + "] " + e.getMessage(), e);
			er.setStackTrace(e.getStackTrace());
			throw er;
		}
	}
}


text:
function floodfill(input)
  local size, grid, fillparams = {}, {}, {}

  local function parseInput(input)
    local nline = 0
    for line in input:gmatch("[^\n]+") do --break at \n
      nline = nline + 1
      if nline == 1 then
        for item in line:gmatch("[^ ]+") do -- break at space
          table.insert(size, tonumber(item))
        end
      end
      if nline > size[2]+1 then
        for item in line:gmatch("[^ ]+") do -- break at space
          table.insert(fillparams, item)
        end
      elseif nline ~= 1 then
        table.insert(grid, {})
        for char in line:gmatch(".") do
          table.insert(grid[nline-1], char)
        end
      end
    end
  end
  parseInput(input)

  local dirs = { --adjacency (contiguousness) is not valid diagonally
    U = { 0, -1 },
    R = { 1, 0 },
    D = { 0, 1 },
    L = { -1, 0 }
  }

  --note to self, co-ords are x, y but grid is [y][x] indexed.
  local start = { tonumber(fillparams[1])+1, tonumber(fillparams[2])+1 } --add 1 due to lua's 1-indexed tables
  local oldchar = grid[start[2]][start[1]]

  local checkAdjacent = function (x, y)
    --check every direction
    local to_fill = {}
    for _, dir in pairs(dirs) do
      local ax, ay = x + dir[1], y + dir[2]
      --extension (wrapping) - manually wrap the values in the edge cases...
      if ax < 1 then ax = ax + size[1] end --add the width to get to the other side!
      if ax > size[1] then ax = ax - size[1] end --subtract the width
      if ay < 1 then ay = ay + size[2] end --add the height
      if ay > size[2] then ay = ay - size[2] end --subtract the height
      --end of extension

      --theoretically with the extension we shouldn't need to nil test for out of bounds...
      if grid[ay] then
        if grid[ay][ax] then
          if grid[ay][ax] == oldchar then
            table.insert(to_fill, { ax, ay })
          end
        end
      end
    end
    return to_fill
  end

  local fill --need to pre-declare for local recursion
  fill = function (x, y)
    grid[y][x] = fillparams[3] --first change this char
    --then any adjacent ones that qualify, recursively ;)
    for _, coords in ipairs(checkAdjacent(x, y)) do
      fill(coords[1], coords[2])
    end
  end

  -- GO!
  fill(start[1], start[2])

  --now get the grid table back to a string for output
  local result = {}
  for _, line in ipairs(grid) do
    table.insert(result, table.concat(line))
  end
  return table.concat(result, "\n")
end

local inputs = {
  [[
9 9
\/\/\/\.\
/./..././
\.\.\.\.\
/.../.../
\/\/\/\/\
/.../.../
\.\.\.\.\
/./..././
\/\/\/\.\
1 7 #]]
}

for _, v in ipairs(inputs) do
  print(floodfill(v))
end