text:
import json
import os

from golem.core import test_data
from golem.core import test

class TestSaveCSVTestData:

    def test_save_csv_data(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        input_test_data = [{'key1': 'value1', 'key2': 'value2'},
                           {'key1': 'value3', 'key2': 'value4'}]
        test_data.save_csv_test_data(project, test_name, input_test_data)
        with open(test_data.csv_file_path(project, test_name)) as f:
            result = f.read()
            expected = ('key1,key2\n'
                        'value1,value2\n'
                        'value3,value4\n')
            assert result == expected

    def test_save_csv_data_empty_data(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        input_test_data = []
        test_data.save_csv_test_data(project, test_name, input_test_data)
        assert not os.path.isfile(test_data.csv_file_path(project, test_name))

    def test_save_csv_data_empty_data_file_exists(self, project_class, test_utils):
        """csv file is removed when data is empty"""
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        input_test_data = []
        data_path = test_data.csv_file_path(project, test_name)
        open(data_path, 'w+').close()
        test_data.save_csv_test_data(project, test_name, input_test_data)
        assert not os.path.isfile(data_path)

    def test_save_csv_data_special_cases(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        input_test_data = [{'key1': 'string with spaces'},
                           {'key1': 'string "with" quotes'},
                           {'key1': 'string \'with\' quotes'},
                           {'key1': '"quoted_string"'},
                           {'key1': '\'quoted_string\''}]
        test_data.save_csv_test_data(project, test_name, input_test_data)
        with open(test_data.csv_file_path(project, test_name)) as f:
            result = f.read()
            expected = ('key1\n'
                        'string with spaces\n'
                        '"string ""with"" quotes"\n'
                        'string \'with\' quotes\n'
                        '"""quoted_string"""\n'
                        '\'quoted_string\'\n')
            assert result == expected

class TestGetCSVTestData:

    def test_get_csv_test_data(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        input = 'key1,key2\nvalue1,value2\nvalue3,value4\n'
        with open(test_data.csv_file_path(project, test_name), 'w+') as f:
            f.write(input)
        result = test_data.get_csv_test_data(project, test_name)
        expected = [{'key1': 'value1', 'key2': 'value2'},
                    {'key1': 'value3', 'key2': 'value4'}]
        assert result == expected

    def test_get_csv_test_data_no_file(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        result = test_data.get_csv_test_data(project, test_name)
        assert result == []

    def test_get_csv_test_data_special_cases(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        input = ('key1\n'
                 'string with spaces\n'
                 '"string ""with"" quotes"\n'
                 'string \'with\' quotes\n'
                 '"""quoted_string"""\n'
                 '\'quoted_string\'\n')
        with open(test_data.csv_file_path(project, test_name), 'w+') as f:
            f.write(input)
        result = test_data.get_csv_test_data(project, test_name)
        expected = [{'key1': 'string with spaces'},
                    {'key1': 'string "with" quotes'},
                    {'key1': 'string \'with\' quotes'},
                    {'key1': '"quoted_string"'},
                    {'key1': '\'quoted_string\''}]
        assert result == expected

class TestSaveJsonTestData:

    def test_save_json_data(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        json_data_str = '[{"foo": "bar"}]'
        test_data.save_json_test_data(project, test_name, json_data_str)
        json_data = test_data.get_json_test_data(project, test_name)
        assert json_data == [{'foo': 'bar'}]

    def test_save_json_data_empty_data(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        test_data.save_csv_test_data(project, test_name, '')
        assert not os.path.isfile(test_data.json_file_path(project, test_name))

    def test_save_json_data_invalid_json(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        json_data_str = '[{"foo": "bar"]'
        test_data.save_json_test_data(project, test_name, json_data_str)
        assert not os.path.isfile(test_data.json_file_path(project, test_name))

class TestGetJsonTestData:

    def test_get_json_data_is_dict(self, project_class, test_utils):
        """json dict is return as a list of dict"""
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        json_data_str = '{"foo": "bar"}'
        test_data.save_json_test_data(project, test_name, json_data_str)
        json_data = test_data.get_json_test_data(project, test_name)
        assert json_data == [{'foo': 'bar'}]

    def test_get_json_data_list_of_dicts(self, project_class, test_utils):
        """json dict is return as a list of dict"""
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        json_data_str = '[{"foo": "bar"}, {"foo": "etc"}]'
        test_data.save_json_test_data(project, test_name, json_data_str)
        json_data = test_data.get_json_test_data(project, test_name)
        assert json_data == [{'foo': 'bar'}, {'foo': 'etc'}]

    def test_get_json_data_list_of_not_dicts(self, project_class, test_utils):
        """an element in the list is not a dict"""
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        json_data_str = '[{"foo": "bar"}, "not a dict"]'
        test_data.save_json_test_data(project, test_name, json_data_str)
        json_data = test_data.get_json_test_data(project, test_name)
        assert json_data == []

    def test_get_json_data_not_list_not_dict(self, project_class, test_utils):
        """not a list and not a dict"""
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        json_data_str = '"not a dict"'
        test_data.save_json_test_data(project, test_name, json_data_str)
        json_data = test_data.get_json_test_data(project, test_name)
        assert json_data == []

class TestGetJsonTestDataAsString:

    def test_get_json_data_as_string(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        json_data_str = '{"foo": "bar"}'
        test_data.save_json_test_data(project, test_name, json_data_str)
        json_data = test_data.get_json_test_data_as_string(project, test_name)
        assert json_data == '{"foo": "bar"}'

    def test_get_json_data_as_string_no_file(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.random_string()
        json_data = test_data.get_json_test_data_as_string(project, test_name)
        assert json_data == ''

class TestValidateInternalData:

    def test_validate_internal_data(self):
        result = test_data.validate_internal_data('data = [{"foo": "bar"}]')
        assert result == []

    def test_validate_internal_data_invalid(self):
        result = test_data.validate_internal_data('data = [{"foo": "bar"]')
        assert '^\nSyntaxError:' in result[0]
        assert len(result) == 1

class TestGetInternalTestDataAsString:

    def test_get_internal_data_as_string(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        test_content = ("data = [\n"
                        "    {'key1': 'a'},\n"
                        "    {'key1': 'b'},\n"
                        "]\n"
                        "def test(data):\n"
                        "    pass\n")
        with open(test.Test(project, test_name).path, 'w+') as f:
            f.write(test_content)
        data_str = test_data.get_internal_test_data_as_string(project, test_name)
        assert data_str == ("data = [\n"
                            "    {\n"
                            "        'key1': 'a',\n"
                            "    },\n"
                            "    {\n"
                            "        'key1': 'b',\n"
                            "    },\n"
                            "]\n")

    def test_get_internal_data_as_string_no_data_var(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        test_content = ("def test(data):\n"
                        "    pass\n")
        with open(test.Test(project, test_name).path, 'w+') as f:
            f.write(test_content)
        data_str = test_data.get_internal_test_data_as_string(project, test_name)
        assert data_str == ''

class TestGetInternalTestData:

    def test_get_internal_data(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        test_content = ("data = [\n"
                        "    {'key1': 'a'},\n"
                        "    {'key1': 'b'},\n"
                        "]\n"
                        "def test(data):\n"
                        "    pass\n")
        with open(test.Test(project, test_name).path, 'w+') as f:
            f.write(test_content)
        data = test_data.get_internal_test_data(project, test_name)
        assert data == [{'key1': 'a'}, {'key1': 'b'}]

    def test_get_internal_data_is_dict(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        test_content = ("data = {'key1': 'a'}\n"
                        "def test(data):\n"
                        "    pass\n")
        with open(test.Test(project, test_name).path, 'w+') as f:
            f.write(test_content)
        data = test_data.get_internal_test_data(project, test_name)
        assert data == [{'key1': 'a'}]

    def test_get_internal_data_not_dict_not_list_of_dicts(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        test_content = ("data = 'key1'\n"
                        "def test(data):\n"
                        "    pass\n")
        with open(test.Test(project, test_name).path, 'w+') as f:
            f.write(test_content)
        data = test_data.get_internal_test_data(project, test_name)
        assert data == []

class TestGetTestData:

    def test_get_test_data(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        csv_data = [{'a': ' b'}]
        json_data = '[{"c": "d"}]'
        test_data.save_csv_test_data(project, test_name, csv_data)
        test_data.save_json_test_data(project, test_name, json_data)
        test_content = "data = {'e': 'f'}"
        with open(test.Test(project, test_name).path, 'w+') as f:
            f.write(test_content)
        data = test_data.get_test_data(project, test_name)
        expected = {
            'csv': csv_data,
            'json': json_data,
            'internal': "data = {\n    'e': 'f',\n}"
        }
        assert data == expected

class TestGetParsedTestData:

    def test_get_test_data__csv_and_json(self, project_class, test_utils):
        """Only csv is returned"""
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        csv_data = [{'a': ' b'}]
        json_data = '[{"c": "d"}]'
        test_data.save_csv_test_data(project, test_name, csv_data)
        test_data.save_json_test_data(project, test_name, json_data)
        data = test_data.get_parsed_test_data(project, test_name)
        assert data == csv_data

    def test_get_test_data__json_and_internal(self, project_class, test_utils):
        """Only json is returned"""
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        json_data = '[{"c": "d"}]'
        test_data.save_json_test_data(project, test_name, json_data)
        test_content = "data = {'e': 'f'}"
        with open(test.Test(project, test_name).path, 'w+') as f:
            f.write(test_content)
        data = test_data.get_parsed_test_data(project, test_name)
        assert data == json.loads(json_data)
        # remove json data, internal data is now returned
        test_data.remove_json_data_if_present(project, test_name)
        data = test_data.get_parsed_test_data(project, test_name)
        assert data == [{'e': 'f'}]

    def test_get_test_data__no_data(self, project_class, test_utils):
        _, project = project_class.activate()
        test_name = test_utils.create_random_test(project)
        data = test_data.get_parsed_test_data(project, test_name)
        assert data == [{}]


text:
Airports in JavaScript.

![Test Suite](./images/test-suite.png)

redpajama_set_name: RedPajamaGithub


text:
OC.L10N.register(
    "templateeditor",
    {
    "Could not load template" : "Tidak dapat memuat templat",
    "Saved" : "Disimpan",
    "Reset" : "Atur Ulang",
    "Sharing email (HTML)" : "Berbagi email (HTML)",
    "Sharing email (plain text fallback)" : "Berbagi email (teks biasa)",
    "Lost password mail" : "Kehilangan sandi email",
    "New user email (HTML)" : "Email pengguna baru (HTML)",
    "New user email (plain text fallback)" : "Email pengguna baru (teks biasa)",
    "Activity notification mail" : "Email pemberitahuan aktivitas",
    "Mail Templates" : "Templat Email",
    "Theme" : "Tema",
    "Template" : "Templat",
    "Please choose a template" : "Pilih sebuah templat",
    "Save" : "Simpan"
},
"nplurals=1; plural=0;");


text:
This scene shows a basic implementation of "custom deferred lights" - i.e.
it shows how command buffers can be used to implement custom lights that
compute scene illumination in deferred shading.

The idea is: after regular deferred shading light pass is done,
draw a sphere for each custom light, with a shader that computes illumination
and adds it to the lighting buffer.

Note: this is small example code, and not a production-ready custom light system!

In this example, each custom light has a CustomLight.cs script attached; two kinds of
custom lights are implemented:

* Sphere: similar to a point light, but with an actual "area light size".
* Tube: a cylinder-shaped light, has a lengh along X axis and cylinder radius (size).

The shader to compute illumination is CustomLightShader.shader, and uses "closest point"
approximations Brian Karis' SIGGRAPH 2013 course
(http://blog.selfshadow.com/publications/s2013-shading-course/).

CustomLightRenderer.cs is a script that should be assigned to some "always visible"
object (e.g. ground). When that object becomes visible by any camera, it will add
command buffers with all the lights to that camera. This way this works for scene view
cameras too, but is not an ideal setup for a proper custom light system.

Caveats: for simplicity reasons, the example code does a not-too-efficient
rendering of light shapes. Would be more efficient to use stencil marking as in typical
deferred shading; here we just render the sphere backfaces with depth testing off.


text:
// The MIT License (MIT)
//
// Copyright (c) 2013 Florida International University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//  FingerprintObject.m
//  Mobile Clinic
//
//  Created by sebastian a zanlongo on 4/7/13.
//

#import "FingerprintObject.h"
#import "PatientObjectProtocol.h"

@implementation FingerprintObject

+(id)sharedClass{

    return [[FingerprintObject alloc]init];
}
- (id)init
{
    self = [super init];

    if (self) {
        enrolledFingers = [[NSMutableArray alloc]init];
    }

    return self;
}

- (id)initWithEnrolledFingers:(NSArray *)enrolled {
    self = [super init];
    if (self) {
    if (enrolled) {
         enrolledFingers = [NSArray arrayWithArray:enrolled];
    }else{
        enrolledFingers = [[NSMutableArray alloc]init];
    }
    }
    return self;

}

/** Serializes a PBBiometryFinger object to a string. */
-(NSString*) serializeFinger: (PBBiometryFinger*) finger
{
    NSString* serializedFinger = [NSString stringWithFormat:@"%09d_%02d", finger.user.id_, finger.position];

    return serializedFinger;
}

/** Serializes a PBBiometryTemplateType value to a string. */
-(NSString*) serializeTemplateType: (PBBiometryTemplateType) templateType
{
    NSString* serializedTemplateType = [NSString stringWithFormat:@"%09d", templateType];

    return serializedTemplateType;
}

-(BOOL) insertTemplate: (PBBiometryTemplate*) template_
             forFinger: (PBBiometryFinger*) finger
{
    NSMutableDictionary* attributes = [[NSMutableDictionary alloc] init];

    NSData* templateData = [[NSData alloc] initWithBytes:template_.data length:template_.dataSize];

    //[attributes setObject:[self serializeFinger:finger] forKey:SERIALIZEDFINGER];

    [attributes setObject:[NSNumber numberWithInt:template_.templateType] forKey:TEMPLATETYPE];
    [attributes setObject:templateData forKey:FINGERDATA];
    [attributes setObject:[NSNumber numberWithInt:template_.dataSize] forKey:DATASIZE];
    [attributes setObject:[NSNumber numberWithInt:finger.user.id_] forKey:USERID];
    [attributes setObject:[NSNumber numberWithInt:finger.position] forKey:FINGERPOSITION];

    if (!enrolledFingers) {
        enrolledFingers = [[NSMutableArray alloc]initWithObjects:attributes, nil];
    }else{
    [enrolledFingers addObject:attributes];
    }

     [self performSelectorOnMainThread:@selector(SendNotification) withObject:nil waitUntilDone:NO];

    return YES;
}

-(void)SendNotification{
     [[NSNotificationCenter defaultCenter]postNotificationName:@"fingerprintRegistered" object:enrolledFingers.lastObject];
}

-(PBBiometryTemplateType) getTemplateTypeFromString: (NSString*)templateTypeString
{
    if ((templateTypeString == nil) || [templateTypeString isEqualToString:@""]) {
        /* Undefined template type, use default. */
        return PBBiometryTemplateTypeISOCompactCard;
    }
    else {
        return [templateTypeString integerValue];
    }
}

-(PBBiometryTemplate*) getTemplateForFinger: (PBBiometryFinger*) finger
{
    BOOL fingerIsRegistered = [self templateIsEnrolledForFinger:finger];

    if (fingerIsRegistered) {

        NSArray * array = [enrolledFingers filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%K == %@ && %K == %@", USERID, [NSNumber numberWithInt:finger.user.id_],FINGERPOSITION,[NSNumber numberWithInt:finger.position]]];

            NSDictionary * theFinger = array.lastObject;

            return [[PBBiometryTemplate alloc] initWithData:(uint8_t*)[[theFinger objectForKey:FINGERDATA] bytes] andDataSize:[[theFinger objectForKey:DATASIZE]intValue] andTemplateType:[[theFinger objectForKey:TEMPLATETYPE] intValue]];

    } else {
            return nil;
        }

}

-(BOOL) deleteTemplateForFinger: (PBBiometryFinger*) finger
{
    return YES;
}

+(NSMutableDictionary *)findPatientFromArrayOfPatients:(NSArray *)allPatients withFinger:(PBBiometryFinger *)finger{

    NSArray * array = [allPatients filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%K==%@ && %K == %@", USERID, [NSNumber numberWithInt:finger.user.id_],FINGERPOSITION,[NSNumber numberWithInt:finger.position]]];

    if (array.count  == 1 ) {
        return array.lastObject;
    }

    return nil;

}

-(BOOL) templateIsEnrolledForFinger:(PBBiometryFinger *)finger
{

    NSArray * array = [enrolledFingers filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%K==%@ && %K == %@", USERID, [NSNumber numberWithInt:finger.user.id_],FINGERPOSITION,[NSNumber numberWithInt:finger.position]]];

        if (array.count  == 1 ) {
            return YES;
        }

    return NO;
}

-(NSArray*) getEnrolledFingers
{
    NSMutableArray* allFingers = [[NSMutableArray alloc]initWithCapacity:enrolledFingers.count];

    for (NSDictionary* finger in enrolledFingers) {
        if ([finger objectForKey:USERID] == nil) {
            continue;
        }
        PBBiometryFinger* theFinger = [[PBBiometryFinger alloc]initWithPosition:[[finger objectForKey:FINGERPOSITION]intValue] andUserId:(uint32_t)[[finger objectForKey:USERID]intValue]];

        [allFingers addObject:theFinger];
    }

    return allFingers;
}

@end


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Runtime.Serialization;
using System.ComponentModel.DataAnnotations;
using System.Web.Script.Serialization;

namespace CitySurfing.Domain.Models
{
    [DataContract]
    public sealed class User : IdentityUser
    {
        public User()
        {
            UserName = Email;
        }

        [DataMember]
        public override string Id { get; set; }

        [DataMember]
        [Required]
        [EmailAddress]
        public override string Email { get; set; }

        [DataMember]
        [Required]
        public string FullName { get; set; }

        [DataMember]
        public string About { get; set; }

        [DataMember]
        public override string PhoneNumber { get; set; }

        [ScriptIgnore]
        public ICollection<Applyment> Applyments { get; set; } = new HashSet<Applyment>();

        public ICollection<Job> Jobs { get; set; } = new HashSet<Job>();

        public ICollection<Skill> Skills { get; set; } = new HashSet<Skill>();
    }
}


text:
package org.springframework.boot.web.servlet;

import java.util.EventListener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

/**
 * Tests for {@link ServletListenerRegistrationBean}.
 *
 * @author Dave Syer
 */
public class ServletListenerRegistrationBeanTests {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Mock
	private ServletContextListener listener;

	@Mock
	private ServletContext servletContext;

	@Before
	public void setupMocks() {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void startupWithDefaults() throws Exception {
		ServletListenerRegistrationBean<ServletContextListener> bean = new ServletListenerRegistrationBean<>(
				this.listener);
		bean.onStartup(this.servletContext);
		verify(this.servletContext).addListener(this.listener);
	}

	@Test
	public void disable() throws Exception {
		ServletListenerRegistrationBean<ServletContextListener> bean = new ServletListenerRegistrationBean<>(
				this.listener);
		bean.setEnabled(false);
		bean.onStartup(this.servletContext);
		verify(this.servletContext, times(0))
				.addListener(any(ServletContextListener.class));
	}

	@Test
	public void cannotRegisterUnsupportedType() throws Exception {
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("Listener is not of a supported type");
		new ServletListenerRegistrationBean<EventListener>(new EventListener() {
		});
	}

}


text:
package it.poliba.sisinflab.simlib.datamodel.abstat;

import it.poliba.sisinflab.simlib.datamodel.Arrow;
import it.poliba.sisinflab.simlib.datamodel.Node;
import it.poliba.sisinflab.simlib.datamodel.abstat.api.*;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * Created by giorgio on 12/05/16.
 */
public class AbstatNode extends Node {

    private int frequency = -1;

    protected AbstatNode(String id, AbstatGraph graphRef) {
        super(id, graphRef);
        this.frequency = graphRef.getResourceOccurrence(id);
    }

    protected AbstatNode(String id, AbstatGraph graphRef, int frequency) {
        super(id, graphRef);
        this.frequency = frequency;
    }

    @Override
    public HashMap<Arrow, HashSet<Node>> getArrows(){
        if(arrows.size() == 0) {
            HashMap<Arrow, HashSet<Node>> nodeArrows = new HashMap<>();
            AbstatGraph abstatGraph = (AbstatGraph) graphRef;
            List<AKP> akpListOut = abstatGraph.getAkps(abstatGraph.getGraphURI(), id, null, null, null, String.valueOf(Integer.MAX_VALUE), null);
            List<AKP> akpListIn = abstatGraph.getAkps(abstatGraph.getGraphURI(), null, null, id, null, String.valueOf(Integer.MAX_VALUE), null);

            for(AKP akp : akpListOut){
                String pred = akp.getPredValue();
                String obj = akp.getObjValue();

                abstatGraph.createNode(pred, akp.getPredFrequencyValue());
                abstatGraph.createNode(obj, akp.getObjFrequencyValue());

                AbstatNode property = (AbstatNode) abstatGraph.getNode(akp.getPredValue());
                AbstatNode object = (AbstatNode) abstatGraph.getNode(akp.getObjValue());

                AbstatArrow abstatArrow = (AbstatArrow) abstatGraph.createArrow(property, Arrow.DIR_OUT, akp.getAkpFrequencyValue());
                if(!nodeArrows.containsKey(abstatArrow)){
                    nodeArrows.put(abstatArrow, new HashSet<>());
                }
                nodeArrows.get(abstatArrow).add(object);
            }

            for(AKP akp : akpListIn){
                String pred = akp.getPredValue();
                String subj = akp.getSubjValue();

                abstatGraph.createNode(pred, akp.getPredFrequencyValue());
                abstatGraph.createNode(subj, akp.getSubjFrequencyValue());

                AbstatNode property = (AbstatNode) abstatGraph.getNode(akp.getPredValue());
                AbstatNode subject = (AbstatNode) abstatGraph.getNode(akp.getSubjValue());

                AbstatArrow abstatArrow = (AbstatArrow) abstatGraph.createArrow(property, Arrow.DIR_IN, akp.getAkpFrequencyValue());
                if(!nodeArrows.containsKey(abstatArrow)){
                    nodeArrows.put(abstatArrow, new HashSet<>());
                }
                nodeArrows.get(abstatArrow).add(subject);
            }
            arrows = nodeArrows;
        }
        return arrows;

    }

    public int getFrequency() {
        return frequency;
    }

    public void setFrequency(int frequency) {
        this.frequency = frequency;
    }
}


text:
package org.apache.hadoop.fs.s3a;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AnonymousAWSCredentials;
import com.amazonaws.auth.AWSCredentials;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

/**
 * AnonymousAWSCredentialsProvider supports anonymous access to AWS services
 * through the AWS SDK.  AWS requests will not be signed.  This is not suitable
 * for most cases, because allowing anonymous access to an S3 bucket compromises
 * security.  This can be useful for accessing public data sets without
 * requiring AWS credentials.
 *
 * Please note that users may reference this class name from configuration
 * property fs.s3a.aws.credentials.provider.  Therefore, changing the class name
 * would be a backward-incompatible change.
 *
 * @deprecated This class will be replaced by one that implements AWS SDK V2's AwsCredentialProvider
 * as part of upgrading S3A to SDK V2. See HADOOP-18073.
 */
@InterfaceAudience.Private
@InterfaceStability.Stable
@Deprecated
public class AnonymousAWSCredentialsProvider implements AWSCredentialsProvider {

  public static final String NAME
      = "org.apache.hadoop.fs.s3a.AnonymousAWSCredentialsProvider";

  public AWSCredentials getCredentials() {
    return new AnonymousAWSCredentials();
  }

  public void refresh() {}

  @Override
  public String toString() {
    return getClass().getSimpleName();
  }

}


text:
#include <folly/experimental/io/AsyncIO.h>

#include <cerrno>
#include <ostream>
#include <stdexcept>
#include <string>

#include <boost/intrusive/parent_from_member.hpp>
#include <fmt/ostream.h>
#include <glog/logging.h>

#include <folly/Exception.h>
#include <folly/Likely.h>
#include <folly/String.h>
#include <folly/portability/Unistd.h>
#include <folly/small_vector.h>

#if __has_include(<libaio.h>)

// debugging helpers
namespace {
#define X(c) \
  case c:    \
    return #c

const char* iocbCmdToString(short int cmd_short) {
  auto cmd = static_cast<io_iocb_cmd>(cmd_short);
  switch (cmd) {
    X(IO_CMD_PREAD);
    X(IO_CMD_PWRITE);
    X(IO_CMD_FSYNC);
    X(IO_CMD_FDSYNC);
    X(IO_CMD_POLL);
    X(IO_CMD_NOOP);
    X(IO_CMD_PREADV);
    X(IO_CMD_PWRITEV);
  };
  return "<INVALID io_iocb_cmd>";
}

#undef X

void toStream(std::ostream& os, const iocb& cb) {
  fmt::print(
      os,
      "data={}, key={}, opcode={}, reqprio={}, fd={}, f={}, ",
      cb.data,
      cb.key,
      iocbCmdToString(cb.aio_lio_opcode),
      cb.aio_reqprio,
      cb.aio_fildes,
      folly::AsyncBaseOp::fd2name(cb.aio_fildes));

  switch (cb.aio_lio_opcode) {
    case IO_CMD_PREAD:
    case IO_CMD_PWRITE:
      fmt::print(
          os,
          "buf={}, offset={}, nbytes={}, ",
          cb.u.c.buf,
          cb.u.c.offset,
          cb.u.c.nbytes);
      break;
    default:
      os << "[TODO: write debug string for "
         << iocbCmdToString(cb.aio_lio_opcode) << "] ";
      break;
  }
}

} // namespace

namespace folly {

AsyncIOOp::AsyncIOOp(NotificationCallback cb) : AsyncBaseOp(std::move(cb)) {
  memset(&iocb_, 0, sizeof(iocb_));
}

void AsyncIOOp::reset(NotificationCallback cb) {
  CHECK_NE(state_, State::PENDING);
  cb_ = std::move(cb);
  state_ = State::UNINITIALIZED;
  result_ = -EINVAL;
  memset(&iocb_, 0, sizeof(iocb_));
}

AsyncIOOp::~AsyncIOOp() = default;

void AsyncIOOp::pread(int fd, void* buf, size_t size, off_t start) {
  init();
  io_prep_pread(&iocb_, fd, buf, size, start);
}

void AsyncIOOp::preadv(int fd, const iovec* iov, int iovcnt, off_t start) {
  init();
  io_prep_preadv(&iocb_, fd, iov, iovcnt, start);
}

void AsyncIOOp::pwrite(int fd, const void* buf, size_t size, off_t start) {
  init();
  io_prep_pwrite(&iocb_, fd, const_cast<void*>(buf), size, start);
}

void AsyncIOOp::pwritev(int fd, const iovec* iov, int iovcnt, off_t start) {
  init();
  io_prep_pwritev(&iocb_, fd, iov, iovcnt, start);
}

void AsyncIOOp::toStream(std::ostream& os) const {
  os << "{" << state_ << ", ";

  if (state_ != AsyncBaseOp::State::UNINITIALIZED) {
    ::toStream(os, iocb_);
  }

  if (state_ == AsyncBaseOp::State::COMPLETED) {
    os << "result=" << result_;
    if (result_ < 0) {
      os << " (" << errnoStr(-result_) << ')';
    }
    os << ", ";
  }

  os << "}";
}

std::ostream& operator<<(std::ostream& os, const AsyncIOOp& op) {
  op.toStream(os);
  return os;
}

AsyncIO::AsyncIO(size_t capacity, PollMode pollMode)
    : AsyncBase(capacity, pollMode) {}

AsyncIO::~AsyncIO() {
  CHECK_EQ(pending_, 0);
  if (ctx_) {
    int rc = io_queue_release(ctx_);
    CHECK_EQ(rc, 0) << "io_queue_release: " << errnoStr(-rc);
  }
}

void AsyncIO::initializeContext() {
  if (!init_.load(std::memory_order_acquire)) {
    std::lock_guard<std::mutex> lock(initMutex_);
    if (!init_.load(std::memory_order_relaxed)) {
      int rc = io_queue_init(capacity_, &ctx_);
      // returns negative errno
      if (rc == -EAGAIN) {
        long aio_nr, aio_max;
        std::unique_ptr<FILE, int (*)(FILE*)> fp(
            fopen("/proc/sys/fs/aio-nr", "r"), fclose);
        PCHECK(fp);
        CHECK_EQ(fscanf(fp.get(), "%ld", &aio_nr), 1);

        std::unique_ptr<FILE, int (*)(FILE*)> aio_max_fp(
            fopen("/proc/sys/fs/aio-max-nr", "r"), fclose);
        PCHECK(aio_max_fp);
        CHECK_EQ(fscanf(aio_max_fp.get(), "%ld", &aio_max), 1);

        LOG(ERROR) << "No resources for requested capacity of " << capacity_;
        LOG(ERROR) << "aio_nr " << aio_nr << ", aio_max_nr " << aio_max;
      }

      checkKernelError(rc, "AsyncIO: io_queue_init failed");
      DCHECK(ctx_);
      init_.store(true, std::memory_order_release);
    }
  }
}

int AsyncIO::submitOne(AsyncBase::Op* op) {
  // -1 return here will trigger throw if op isn't an AsyncIOOp
  AsyncIOOp* aop = op->getAsyncIOOp();

  if (!aop) {
    return -1;
  }

  iocb* cb = &aop->iocb_;
  cb->data = nullptr; // unused
  if (pollFd_ != -1) {
    io_set_eventfd(cb, pollFd_);
  }

  return io_submit(ctx_, 1, &cb);
}

int AsyncIO::submitRange(Range<AsyncBase::Op**> ops) {
  std::vector<iocb*> vec;
  vec.reserve(ops.size());
  for (auto& op : ops) {
    AsyncIOOp* aop = op->getAsyncIOOp();
    if (!aop) {
      continue;
    }

    iocb* cb = &aop->iocb_;
    cb->data = nullptr; // unused
    if (pollFd_ != -1) {
      io_set_eventfd(cb, pollFd_);
    }

    vec.push_back(cb);
  }

  return vec.size() ? io_submit(ctx_, vec.size(), vec.data()) : -1;
}

Range<AsyncBase::Op**> AsyncIO::doWait(
    WaitType type,
    size_t minRequests,
    size_t maxRequests,
    std::vector<AsyncBase::Op*>& result) {
  size_t constexpr kNumInlineRequests = 16;
  folly::small_vector<io_event, kNumInlineRequests> events(maxRequests);

  // Unfortunately, Linux AIO doesn't implement io_cancel, so even for
  // WaitType::CANCEL we have to wait for IO completion.
  size_t count = 0;
  do {
    int ret;
    do {
      // GOTCHA: io_getevents() may returns less than min_nr results if
      // interrupted after some events have been read (if before, -EINTR
      // is returned).
      ret = io_getevents(
          ctx_,
          minRequests - count,
          maxRequests - count,
          events.data() + count,
          /* timeout */ nullptr); // wait forever
    } while (ret == -EINTR);
    // Check as may not be able to recover without leaking events.
    CHECK_GE(ret, 0) << "AsyncIO: io_getevents failed with error "
                     << errnoStr(-ret);
    count += ret;
  } while (count < minRequests);
  DCHECK_LE(count, maxRequests);

  result.clear();
  for (size_t i = 0; i < count; ++i) {
    CHECK(events[i].obj);
    Op* op = boost::intrusive::get_parent_from_member(
        events[i].obj, &AsyncIOOp::iocb_);
    decrementPending();
    switch (type) {
      case WaitType::COMPLETE:
        complete(op, events[i].res);
        break;
      case WaitType::CANCEL:
        cancel(op);
        break;
    }
    result.push_back(op);
  }

  return range(result);
}

} // namespace folly

#endif


text:
<?php
/****************************************************************************/
/* ATutor																	*/
/****************************************************************************/
/* Copyright (c) 2002-2010                                                  */
/* Inclusive Design Institute                                               */
/* http://atutor.ca															*/
/*																			*/
/* This program is free software. You can redistribute it and/or			*/
/* modify it under the terms of the GNU General Public License				*/
/* as published by the Free Software Foundation.							*/
/****************************************************************************/
// $Id$
/*
 * Get the latest updates of this module
 * @return list of news, [timestamp]=>
 */

 //
 //exit;

function reading_list_news() {
global $enrolled_courses, $system_courses;
	$news = array();
    if(isset($enrolled_courses)){
	$sql = "SELECT * FROM %sreading_list R INNER JOIN %sexternal_resources E ON E.resource_id = R.resource_id WHERE R.course_id in %s ORDER BY R.reading_id DESC";
	$rows_resources = queryDB($sql, array(TABLE_PREFIX, TABLE_PREFIX, $enrolled_courses));

	if(count($rows_resources) > 0){
	    foreach($rows_resources as $row){
			$news[] = array('time'=>$row['date_end'],
							'object'=>$row,
							'alt'=>_AT('reading_list'),
							'course'=>$system_courses[$row['course_id']]['title'],
							'thumb'=>'images/home-reading_list_sm.png',
							'link'=>' SUBLINK_TEXT_LEN ? ' title="'.$row['title'].'"' : '') .'>'.
									validate_length($row['title'], SUBLINK_TEXT_LEN, VALIDATE_LENGTH_FOR_DISPLAY) .'');
		}
	}
	return $news;
	}
}
?>


text:
module.exports = function(url, loader) {
  var request = new XMLHttpRequest();

  request.open('GET', url, true);
  request.responseType = 'text';

  request.addEventListener('progress', function(e) {
    var percent = e.loaded / e.total;
    loader.progress(percent);
  });

  request.onload = function() {
    if (request.status !== 200) {
      return loader.error(url);
    }

    var data = JSON.parse(this.response);
    loader.done(data);
  };
  request.send();
};


text:
package org.motechproject.tasks.domain.mds.channel.builder;

import org.motechproject.tasks.contract.EventParameterRequest;
import org.motechproject.tasks.domain.enums.ParameterType;
import org.motechproject.tasks.domain.mds.channel.EventParameter;

/**
 * Provides methods for constructing event parameters.
 */
public class EventParameterBuilder {

    private String displayName;

    private String eventKey;

    private ParameterType parameterType;

    public EventParameterBuilder setDisplayName(String displayName) {
        this.displayName = displayName;
        return this;
    }

    public EventParameterBuilder setEventKey(String eventKey) {
        this.eventKey = eventKey;
        return this;
    }

    public EventParameterBuilder setParameterType(String type) {
        this.parameterType = ParameterType.fromString(type);
        return this;
    }

    /**
     * Builds an object of {@link EventParameter} class.
     *
     * @return the created instance
     */
    public EventParameter build() {
        return new EventParameter(displayName, eventKey, parameterType);
    }

    /**
     * Creates a builder, which allows building event parameters based on the given {@code eventParameterRequest}.
     *
     * @param eventParameterRequest  the event parameter request
     * @return the created builder
     */
    public static EventParameterBuilder fromEventParameterRequest(EventParameterRequest eventParameterRequest) {
        return new EventParameterBuilder()
                .setDisplayName(eventParameterRequest.getDisplayName())
                .setEventKey(eventParameterRequest.getEventKey())
                .setParameterType(eventParameterRequest.getType());
    }
}


text:
""" Optimizations of the expression tree representation for better CSE
opportunities.
"""

from sympy.core.basic import Basic
from sympy.core.operations import AssocOp
from sympy.utilities.iterables import preorder_traversal

from sympy import Add, Mul

def assumed(e, name):
    """ Return True if the given assumption is true about the sympy expression.

    Examples
    --------
    >>> from sympy import symbols
    >>> from sympy.simplify.cse_opts import assumed
    >>> from sympy.abc import x, y
    >>> assumed(x+y, 'is_Add')
    True
    >>> assumed(x+y, 'is_Mul')
    False

    """
    return getattr(e, name, False)

class Sub(AssocOp):
    """ Stub of a Sub operator to replace Add(x, Mul(NegativeOne(-1), y)).
    """
    __slots__ = []
    is_Add = False
    is_Sub = True

    def _eval_subs(self, old, new):
        if self==old:
            return new
        else:
            return self.__class__(*[s._eval_subs(old, new) for s in self.args ])

def sub_pre(e):
    """ Replace Add(x, Mul(NegativeOne(-1), y)) with Sub(x, y).
    """
    replacements = []
    for node in preorder_traversal(e):
        if assumed(node, 'is_Add'):
            positives = []
            negatives = []
            for arg in node.args:
                if (assumed(arg, 'is_Mul') and
                    assumed(arg.args[0], 'is_number') and
                    assumed(arg.args[0], 'is_negative')):
                    negatives.append(Mul(-arg.args[0], *arg.args[1:]))
                else:
                    positives.append(arg)
            if len(negatives) > 0:
                replacement = Sub(Add(*positives), Add(*negatives))
                replacements.append((node, replacement))
    for node, replacement in replacements:
        e = e.subs(node, replacement)

    return e

def sub_post(e):
    """ Replace Sub(x,y) with the canonical form Add(x, Mul(NegativeOne(-1), y)).
    """
    replacements = []
    for node in preorder_traversal(e):
        if assumed(node, 'is_Sub'):
            replacements.append((node, Add(node.args[0], Mul(-1, node.args[1]))))
    for node, replacement in replacements:
        e = e.subs(node, replacement)

    return e

default_optimizations = [
    (sub_pre, sub_post),
]


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/font-awesome.min.css">

           <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic,700italic' rel='stylesheet' type='text/css'>

Concerts

Reviews

About Us

FAQ

Wilco Announces a New Album and Summer Tour

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.

Newsletter Signup

                        <form class="newsletter-signup">
                            <input type="text">
                            <input type="submit" class="btn" value="Sign Up">
                        </form>

Upcoming Concerts

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.

                        See All

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet.

                        See All

 Recent news & reviews

News

Arcade Fire Drops Hints About a New Side Project in a Recent Interview - What Will It Be?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.

News

Our Roundup of 2015's Top Summer Festivals & Free Shows

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.

News

Laura Marling and Johnny Flynn are Teaming Up Again - Will it be an Albumn or a Single?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.

Review

Mumford and Sons New Album "Wilder Minds" - Oh Yes! or Oh No?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.

Review

Jose Gonzalez's New Albumn "Vestiges & Claws" - Hit or Miss?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.

News

The National Surprises Us with a New Single - Will a New Albumn Follow?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.


text:
package eu.celarcloud.cloud_is.visualizationTool.servlet.pages;

import java.io.IOException;
import java.net.URI;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

// TODO: Auto-generated Javadoc
/**
 * Servlet implementation class DeplInfo.
 */
public class DeplInfo extends HttpServlet {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

    /**
	 * Instantiates a new depl info.
	 *
	 * @see HttpServlet#HttpServlet()
	 */
    public DeplInfo() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
	 * Do request.
	 *
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @throws ServletException
	 *             the servlet exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
    private void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String appID, versID, deplID;

    	appID = request.getParameter("appID") == null ? "" : request.getParameter("appID");
    	versID = request.getParameter("versID") == null ? "" : request.getParameter("versID");
    	deplID = request.getParameter("deplID") == null ? "" : request.getParameter("deplID");

    	// Build the rest client
    	ClientResponse restResponse;
    	MultivaluedMap<String, String> queryParams;
    	String isserver = (String) getServletContext().getAttribute("isserver");
    	URI uri = UriBuilder.fromUri( isserver + "/rest/").build();
		Client client = Client.create();
		WebResource service = client.resource(uri);

    	// Issue the request
		// TODO enclose to try / catch, in order to avoid error when the is-core service is not available.
		//restResponse = service.path("application/"+appID+"/"+versID+"/"+deplID).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    	//String deploymentInfo = restResponse.getEntity(String.class);

    	// Inject the obtained info to request object
    	// in order for jsp page to get the info

		RequestDispatcher dispatcher;
    	if(request.getParameter("tab") != null && request.getParameter("tab").equals("analysis"))
    	{
    		dispatcher = request.getRequestDispatcher("/hPages/deployment-analysis.jsp");
    	}
    	else
    	{
    		dispatcher = request.getRequestDispatcher("/hPages/deployment-live.jsp");
    	}
    	dispatcher.forward(request, response);
	}

	/**
	 * Do get.
	 *
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @throws ServletException
	 *             the servlet exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doRequest(request, response);
	}

	/**
	 * Do post.
	 *
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @throws ServletException
	 *             the servlet exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doRequest(request, response);
	}

}


text:
package org.springframework.boot.actuate.autoconfigure.observation.web.servlet;

import java.util.Collections;
import java.util.EnumSet;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.observation.tck.TestObservationRegistry;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.test.MetricsRun;
import org.springframework.boot.actuate.autoconfigure.metrics.web.TestController;
import org.springframework.boot.actuate.autoconfigure.observation.ObservationAutoConfiguration;
import org.springframework.boot.actuate.metrics.web.servlet.DefaultWebMvcTagsProvider;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTagsContributor;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTagsProvider;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.test.context.assertj.AssertableWebApplicationContext;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.observation.DefaultServerRequestObservationConvention;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.filter.ServerHttpObservationFilter;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Tests for {@link WebMvcObservationAutoConfiguration}.
 *
 * @author Andy Wilkinson
 * @author Dmytro Nosan
 * @author Tadaya Tsuyukubo
 * @author Madhura Bhave
 * @author Chanhyeong LEE
 */
@ExtendWith(OutputCaptureExtension.class)
@SuppressWarnings("removal")
class WebMvcObservationAutoConfigurationTests {

	private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
			.with(MetricsRun.simple()).withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class))
			.withConfiguration(AutoConfigurations.of(WebMvcObservationAutoConfiguration.class));

	@Test
	void backsOffWhenMeterRegistryIsMissing() {
		new WebApplicationContextRunner()
				.withConfiguration(AutoConfigurations.of(WebMvcObservationAutoConfiguration.class))
				.run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class));
	}

	@Test
	void definesFilterWhenRegistryIsPresent() {
		this.contextRunner.run((context) -> {
			assertThat(context).doesNotHaveBean(DefaultWebMvcTagsProvider.class);
			assertThat(context).hasSingleBean(FilterRegistrationBean.class);
			assertThat(context.getBean(FilterRegistrationBean.class).getFilter())
					.isInstanceOf(ServerHttpObservationFilter.class);
		});
	}

	@Test
	void adapterConventionWhenTagsProviderPresent() {
		this.contextRunner.withUserConfiguration(TagsProviderConfiguration.class)
				.run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter())
						.extracting("observationConvention")
						.isInstanceOf(ServerRequestObservationConventionAdapter.class));
	}

	@Test
	void customConventionWhenPresent() {
		this.contextRunner.withUserConfiguration(CustomConventionConfiguration.class)
				.run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter())
						.extracting("observationConvention").isInstanceOf(CustomConvention.class));
	}

	@Test
	void filterRegistrationHasExpectedDispatcherTypesAndOrder() {
		this.contextRunner.run((context) -> {
			FilterRegistrationBean<?> registration = context.getBean(FilterRegistrationBean.class);
			assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes",
					EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
			assertThat(registration.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE + 1);
		});
	}

	@Test
	void filterRegistrationBacksOffWithAnotherServerHttpObservationFilterRegistration() {
		this.contextRunner.withUserConfiguration(TestServerHttpObservationFilterRegistrationConfiguration.class)
				.run((context) -> {
					assertThat(context).hasSingleBean(FilterRegistrationBean.class);
					assertThat(context.getBean(FilterRegistrationBean.class))
							.isSameAs(context.getBean("testServerHttpObservationFilter"));
				});
	}

	@Test
	void filterRegistrationBacksOffWithAnotherServerHttpObservationFilter() {
		this.contextRunner.withUserConfiguration(TestServerHttpObservationFilterConfiguration.class)
				.run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class)
						.hasSingleBean(ServerHttpObservationFilter.class));
	}

	@Test
	void filterRegistrationDoesNotBackOffWithOtherFilterRegistration() {
		this.contextRunner.withUserConfiguration(TestFilterRegistrationConfiguration.class)
				.run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcObservationFilter"));
	}

	@Test
	void filterRegistrationDoesNotBackOffWithOtherFilter() {
		this.contextRunner.withUserConfiguration(TestFilterConfiguration.class)
				.run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcObservationFilter"));
	}

	@Test
	void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) {
		this.contextRunner.withUserConfiguration(TestController.class)
				.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
						ObservationAutoConfiguration.class, WebMvcAutoConfiguration.class))
				.withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> {
					MeterRegistry registry = getInitializedMeterRegistry(context);
					assertThat(registry.get("http.server.requests").meters().size()).isLessThanOrEqualTo(2);
					assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'");
				});
	}

	@Test
	@Deprecated(since = "3.0.0", forRemoval = true)
	void afterMaxUrisReachedFurtherUrisAreDeniedWhenUsingCustomMetricName(CapturedOutput output) {
		this.contextRunner.withUserConfiguration(TestController.class)
				.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
						ObservationAutoConfiguration.class, WebMvcAutoConfiguration.class))
				.withPropertyValues("management.metrics.web.server.max-uri-tags=2",
						"management.metrics.web.server.request.metric-name=my.http.server.requests")
				.run((context) -> {
					MeterRegistry registry = getInitializedMeterRegistry(context);
					assertThat(registry.get("my.http.server.requests").meters().size()).isLessThanOrEqualTo(2);
					assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'");
				});
	}

	@Test
	void afterMaxUrisReachedFurtherUrisAreDeniedWhenUsingCustomObservationName(CapturedOutput output) {
		this.contextRunner.withUserConfiguration(TestController.class)
				.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
						ObservationAutoConfiguration.class, WebMvcAutoConfiguration.class))
				.withPropertyValues("management.metrics.web.server.max-uri-tags=2",
						"management.observations.http.server.requests.name=my.http.server.requests")
				.run((context) -> {
					MeterRegistry registry = getInitializedMeterRegistry(context);
					assertThat(registry.get("my.http.server.requests").meters().size()).isLessThanOrEqualTo(2);
					assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'");
				});
	}

	@Test
	void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) {
		this.contextRunner.withUserConfiguration(TestController.class)
				.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
						ObservationAutoConfiguration.class, WebMvcAutoConfiguration.class))
				.withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> {
					MeterRegistry registry = getInitializedMeterRegistry(context);
					assertThat(registry.get("http.server.requests").meters()).hasSize(3);
					assertThat(output)
							.doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'");
				});
	}

	@Test
	void whenTagContributorsAreDefinedThenTagsProviderUsesThem() {
		this.contextRunner.withUserConfiguration(TagsContributorsConfiguration.class)
				.run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter())
						.extracting("observationConvention")
						.isInstanceOf(ServerRequestObservationConventionAdapter.class));
	}

	private MeterRegistry getInitializedMeterRegistry(AssertableWebApplicationContext context) throws Exception {
		return getInitializedMeterRegistry(context, "/test0", "/test1", "/test2");
	}

	private MeterRegistry getInitializedMeterRegistry(AssertableWebApplicationContext context, String... urls)
			throws Exception {
		assertThat(context).hasSingleBean(FilterRegistrationBean.class);
		Filter filter = context.getBean(FilterRegistrationBean.class).getFilter();
		assertThat(filter).isInstanceOf(ServerHttpObservationFilter.class);
		MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(filter).build();
		for (String url : urls) {
			mockMvc.perform(MockMvcRequestBuilders.get(url)).andExpect(status().isOk());
		}
		return context.getBean(MeterRegistry.class);
	}

	@Configuration(proxyBeanMethods = false)
	static class TagsProviderConfiguration {

		@Bean
		TestWebMvcTagsProvider tagsProvider() {
			return new TestWebMvcTagsProvider();
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class TagsContributorsConfiguration {

		@Bean
		WebMvcTagsContributor tagContributorOne() {
			return mock(WebMvcTagsContributor.class);
		}

		@Bean
		WebMvcTagsContributor tagContributorTwo() {
			return mock(WebMvcTagsContributor.class);
		}

	}

	@Deprecated(since = "3.0.0", forRemoval = true)
	private static final class TestWebMvcTagsProvider implements WebMvcTagsProvider {

		@Override
		public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response, Object handler,
				Throwable exception) {
			return Collections.emptyList();
		}

		@Override
		public Iterable<Tag> getLongRequestTags(HttpServletRequest request, Object handler) {
			return Collections.emptyList();
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class TestServerHttpObservationFilterRegistrationConfiguration {

		@Bean
		@SuppressWarnings("unchecked")
		FilterRegistrationBean<ServerHttpObservationFilter> testServerHttpObservationFilter() {
			return mock(FilterRegistrationBean.class);
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class TestServerHttpObservationFilterConfiguration {

		@Bean
		ServerHttpObservationFilter testServerHttpObservationFilter() {
			return new ServerHttpObservationFilter(TestObservationRegistry.create());
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class TestFilterRegistrationConfiguration {

		@Bean
		@SuppressWarnings("unchecked")
		FilterRegistrationBean<Filter> testFilter() {
			return mock(FilterRegistrationBean.class);
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class TestFilterConfiguration {

		@Bean
		Filter testFilter() {
			return mock(Filter.class);
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class CustomConventionConfiguration {

		@Bean
		CustomConvention customConvention() {
			return new CustomConvention();
		}

	}

	static class CustomConvention extends DefaultServerRequestObservationConvention {

	}

}


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var kurtosis = require( './../lib' );

// FIXTURES //

var data = require( './fixtures/julia/data.json' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof kurtosis, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN` for `k`, the function returns `NaN`', function test( t ) {
	var v = kurtosis( NaN );
	t.equal( isnan( v ), true, 'returns NaN' );
	t.end();
});

tape( 'if provided a degrees of freedom parameter `k` that is not a positive number, the function returns `NaN`', function test( t ) {
	var v;

	v = kurtosis( -1.0 );
	t.equal( isnan( v ), true, 'returns NaN' );

	v = kurtosis( 0.0 );
	t.equal( isnan( v ), true, 'returns NaN' );

	v = kurtosis( NINF );
	t.equal( isnan( v ), true, 'returns NaN' );

	t.end();
});

tape( 'the function returns the kurtosis of a chi-squared distribution', function test( t ) {
	var expected;
	var k;
	var i;
	var y;

	expected = data.expected;
	k = data.k;
	for ( i = 0; i < expected.length; i++ ) {
		y = kurtosis( k[i] );
		t.equal( y, expected[i], 'k: '+k[i]+', y: '+y+', expected: '+expected[i] );
	}
	t.end();
});


text:
import React from 'react';
import { styled } from '@storybook/theming';
import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';

const Panel = styled.div();

export default {
  title: 'Addons/Viewport',
  parameters: {
    viewport: {
      viewports: INITIAL_VIEWPORTS,
    },
  },
};
export const DefaultFn = () => (
  <Panel>I don't have problems being rendered using the default viewport.</Panel>
);
DefaultFn.storyName = 'default';


text:
CKEDITOR.dialog.add( 'uicolor', function( editor ) {
	var dialog, picker, pickerContents,
	// Actual UI color value.
	uiColor = editor.getUiColor(),
		pickerId = 'cke_uicolor_picker' + CKEDITOR.tools.getNextNumber();

	function setNewPickerColor( color ) {
		// Convert HEX representation to RGB, stripping # char.
		if ( /^#/.test( color ) )
			color = window.YAHOO.util.Color.hex2rgb( color.substr( 1 ) );
		picker.setValue( color, true );
		// Refresh picker UI.
		picker.refresh( pickerId );
	}

	function setNewUiColor( color ) {
		editor.setUiColor( color );
		// Write new config string into textbox.
		dialog._.contents.tab1.configBox.setValue( 'config.uiColor = "#' + picker.get( "hex" ) + '"' );
	}

	pickerContents = {
		id: 'yuiColorPicker',
		type: 'html',
		html: "

",
		onLoad: function( event ) {
			var url = CKEDITOR.getUrl( 'plugins/uicolor/yui/' );

			// Create new color picker widget.
			picker = new window.YAHOO.widget.ColorPicker( pickerId, {
				showhsvcontrols: true,
				showhexcontrols: true,
				images: {
					PICKER_THUMB: url + "assets/picker_thumb.png",
					HUE_THUMB: url + "assets/hue_thumb.png"
				}
			} );

			// Make Yahoo widget available to public.
			this.picker = picker;

			// Set actual UI color to the picker.
			if ( uiColor )
				setNewPickerColor( uiColor );

			// Subscribe to the rgbChange event.
			picker.on( "rgbChange", function() {
				// Reset predefined box.
				dialog._.contents.tab1.predefined.setValue( '' );
				setNewUiColor( '#' + picker.get( 'hex' ) );
			} );

			// Fix input class names.
			var inputs = new CKEDITOR.dom.nodeList( picker.getElementsByTagName( 'input' ) );
			for ( var i = 0; i < inputs.count(); i++ )
				inputs.getItem( i ).addClass( 'cke_dialog_ui_input_text' );
		}
	};

	return {
		title: editor.lang.uicolor.title,
		minWidth: 360,
		minHeight: 320,
		onLoad: function() {
			dialog = this;
			this.setupContent();

			// #3808
			if ( CKEDITOR.env.ie7Compat )
				dialog.parts.contents.setStyle( 'overflow', 'hidden' );
		},
		contents: [
			{
			id: 'tab1',
			label: '',
			title: '',
			expand: true,
			padding: 0,
			elements: [
				pickerContents,
			{
				id: 'tab1',
				type: 'vbox',
				children: [
					{
					type: 'hbox',
					children: [
						{
						id: 'predefined',
						type: 'select',
						'default': '',
						label: editor.lang.uicolor.predefined,
						items: [
							[ '' ],
							[ 'Light blue', '#9AB8F3' ],
							[ 'Sand', '#D2B48C' ],
							[ 'Metallic', '#949AAA' ],
							[ 'Purple', '#C2A3C7' ],
							[ 'Olive', '#A2C980' ],
							[ 'Happy green', '#9BD446' ],
							[ 'Jezebel Blue', '#14B8C4' ],
							[ 'Burn', '#FF893A' ],
							[ 'Easy red', '#FF6969' ],
							[ 'Pisces 3', '#48B4F2' ],
							[ 'Aquarius 5', '#487ED4' ],
							[ 'Absinthe', '#A8CF76' ],
							[ 'Scrambled Egg', '#C7A622' ],
							[ 'Hello monday', '#8E8D80' ],
							[ 'Lovely sunshine', '#F1E8B1' ],
							[ 'Recycled air', '#B3C593' ],
							[ 'Down', '#BCBCA4' ],
							[ 'Mark Twain', '#CFE91D' ],
							[ 'Specks of dust', '#D1B596' ],
							[ 'Lollipop', '#F6CE23' ]
							],
						onChange: function() {
							var color = this.getValue();
							if ( color ) {
								setNewPickerColor( color );
								setNewUiColor( color );
								// Refresh predefined preview box.
								CKEDITOR.document.getById( 'predefinedPreview' ).setStyle( 'background', color );
							} else
								CKEDITOR.document.getById( 'predefinedPreview' ).setStyle( 'background', '' );
						},
						onShow: function() {
							var color = editor.getUiColor();
							if ( color )
								this.setValue( color );
						}
					},
						{
						id: 'predefinedPreview',
						type: 'html',
						html: '
' +
							'

' +
							'
'
					}
					]
				},
					{
					id: 'configBox',
					type: 'text',
					label: editor.lang.uicolor.config,
					onShow: function() {
						var color = editor.getUiColor();
						if ( color )
							this.setValue( 'config.uiColor = "' + color + '"' );
					}
				}
				]
			}
			]
		}
		],
		buttons: [ CKEDITOR.dialog.okButton ]
	};
} );


text:
<?php

namespace Symfony\Component\Finder\Iterator;

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * IgnoreVcsFilterIterator filters out VCS files and directories.
 *
 * It currently supports Subversion, CVS, DARCS, Gnu Arch, Monotone, Bazaar-NG, GIT, and Mercurial.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class IgnoreVcsFilterIterator extends ExcludeDirectoryFilterIterator
{
    /**
     * Constructor.
     *
     * @param \Iterator $iterator The Iterator to filter
     */
    public function __construct(\Iterator $iterator)
    {
        parent::__construct($iterator, array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg'));
    }
}


text:
package org.ppwcode.value_III.legacy;

import static org.ppwcode.metainfo_I.License.Type.APACHE_V2;
import static org.ppwcode.util.reflect_I.PropertyHelpers.hasProperty;

import org.ppwcode.metainfo_I.Copyright;
import org.ppwcode.metainfo_I.License;
import org.ppwcode.metainfo_I.vcs.SvnInfo;
import org.ppwcode.vernacular.exception_II.InternalException;
import org.ppwcode.vernacular.value_III.SemanticValueException;
import org.ppwcode.vernacular.value_III.Value;
import org.toryt.annotations_I.Basic;
import org.toryt.annotations_I.Expression;
import org.toryt.annotations_I.Invars;
import org.toryt.annotations_I.MethodContract;

/**
 *
PropertyExceptions are exceptions that carry with them information about the property for which they occurred.
 *   They are usually thrown by a property setter during validation. If the property name is null, it
 *   means that the exception could not be attributed to a specific property of {@link #getOrigin()}.
 *   The origin should not be null, except when the exception is thrown during
 *   construction of an object (or more objects are involved, see below), that could not be completed. In that case,
 *   the type should be filled out. Carrying the reference to the object would expose an incompletely initialized
 *   object, as the exception signals a failure to complete the initialization. The originType
 *   should not be null, except when the exception is a compound that gathers validation
 *   information over many objects. Specific property exception subtypes will make these advises binding in most
 *   cases.

 * MUDO move this discussion to l10n package
 *
Localized messages are sought in a *.properties file for {@link #getOriginType() originType} and its
 *   super types. The properties files should be in the directory next to the bean class, with name
 *   <var>{@link #getOrigin()}.getClass().getName()</var>_<var>_locale_identification</var>.properties.
 *   Alternatively, messages can be added to a properties file that comes with the exception, with name
 *   <var>}getClass().getName()</var>_<var>_locale_identification</var>.properties.

 *
The keys for the localized messages in the {@link #getOriginType() originType} properties files have to have the
 *   form
 *   <var>this.getClass().getCanonicalName()</var>.<var>{@link #getPropertyName()}</var>.<var>{@link #getMessage()}</var>.
 *   If such a key does not exist, we look for a key
 *   <var>this.getClass().getCanonicalName()</var>.<var>{@link #getPropertyName()}</var>, and next for
 *   <var>this.getClass().getCanonicalName()</var>.<var>{@link #getMessage()}</var> ,and then for
 *   <var>this.getClass().getCanonicalName()</var>. If neither of these keys are found, we look in the properties file
 *   that comes with the exception for an entry with the key
 *   <var>{@link #getMessage()}</var>, and if that is not found, for an entry with key
 *   {@link InternalException#DEFAULT_MESSAGE_KEY}.

 *
The values in the properties files can use data from exception as parameters in the message. Available are:

 * MUDO This feature is not implemented yet.
 *

 *
the localized name of the origin type, as {originType}, or {originTypes} for the plural

 *
the localized name of the property as {propertyName}

 *
the origin object, as {origin}; this can be used with concatenation to get the values of certain
 *     properties, like {origin.<var>myProperty.myProperty</var>}; if {@code null} is encountered along this chain,
 *     the entire expression evaluates to the string {@code "null"}

 *
any property a subtype of PropertyException might introduce, as {<var>propertyName</var>}.

 *

 *
 *
 * @note Throwables cannot have generic parameters. Otherwise we would have used this instead of {@link #getOriginType()}.
 *
 * @author    Jan Dockx
 * @author    PeopleWare n.v.
 */
@Copyright("2004 - $Date$, PeopleWare n.v.")
@License(APACHE_V2)
@SvnInfo(revision = "$Revision$",
         date     = "$Date$")
@Invars(
  @Expression("message == null || ! message.equals(EMPTY)")
)
public class PropertyException extends SemanticValueException {

  /*<construction>*/
  //-------------------------------------------------------------------------

  /**
   * Specialized constructor for Compound subtype, without a property name, type
   * or origin.
   *
   * @param     message
   *            The message that describes the exceptional circumstance.
   * @param     cause
   *            The exception that occurred, causing this exception to be
   *            thrown, if that is the case.
   */
  @MethodContract(
    pre  = {
      @Expression("_message == null || ! _message.equals(EMPTY)")
    },
    post = {
      @Expression("origin == null"),
      @Expression("originType == null"),
      @Expression("propertyName == null"),
      @Expression("message == _message == null ? DEFAULT_MESSAGE_KEY : _message"),
      @Expression("cause == _cause")
    }
  )
  protected PropertyException(final String message, final Throwable cause) {
    super(Value.class, message, cause);
    assert (message == null) || (! message.equals(""));
  }

  /**
   * @param     origin
   *            The bean that has thrown this exception.
   * @param     propertyName
   *            The name of the property of which the setter has thrown
   *            this exception because parameter validation failed.
   * @param     message
   *            The message that describes the exceptional circumstance.
   * @param     cause
   *            The exception that occurred, causing this exception to be
   *            thrown, if that is the case.
   */
  @MethodContract(
    pre  = {
      @Expression("_origin != null"),
      @Expression("_propertyName != null ? hasProperty(_origin.class, _propertyName)"),
      @Expression("_message == null || ! _message.equals(EMPTY)")
    },
    post = {
      @Expression("origin == _origin"),
      @Expression("originType == _origin.class"),
      @Expression("propertyName == _propertyName"),
      @Expression("message == _message == null ? DEFAULT_MESSAGE_KEY : _message"),
      @Expression("cause == _cause")
    }
  )
  public PropertyException(final Value origin,
                           final String propertyName,
                           final String message,
                           final Throwable cause) {
    super(origin, message, cause);
    assert (propertyName == null) || hasProperty(origin.getClass(), propertyName);
    assert (message == null) || (! message.equals(""));
    $propertyName = propertyName;
  }

  /**
   * @param     origin
   *            The bean that has thrown this exception.
   * @param     inOriginInitialization
   *            Set to true if this active
   *            property is created during the origin initialization;
   *            if so, an exception will not carry a reference
   *            to the bean, but only to the bean type.
   * @param     propertyName
   *            The name of the property of which the setter has thrown
   *            this exception because parameter validation failed.
   * @param     message
   *            The message that describes the exceptional circumstance.
   * @param     cause
   *            The exception that occurred, causing this exception to be
   *            thrown, if that is the case.
   *
   * @since IV 1.1.0/1.0
   */
  @MethodContract(
    pre  = {
      @Expression("_origin != null"),
      @Expression("_propertyName != null ? hasProperty(_origin.class, _propertyName)"),
      @Expression("_message == null || ! _message.equals(EMPTY)")
    },
    post = {
      @Expression("_inOriginInitialization ? origin == null : origin == _origin"),
      @Expression("originType == _origin.class"),
      @Expression("propertyName == _propertyName"),
      @Expression("message == _message == null ? DEFAULT_MESSAGE_KEY : _message"),
      @Expression("cause == _cause")
    }
  )
  public PropertyException(final Value origin,
                           final boolean inOriginInitialization,
                           final String propertyName,
                           final String message,
                           final Throwable cause) {
    super(origin, message, cause);
    assert (propertyName == null) || hasProperty(origin.getClass(), propertyName);
    assert (message == null) || (!message.equals(""));
    $propertyName = propertyName;
  }

  /**
   * @param     originType
   *            The bean that has thrown this exception.
   * @param     propertyName
   *            The name of the property of which the setter has thrown
   *            this exception because parameter validation failed.
   * @param     message
   *            The message that describes the exceptional circumstance.
   * @param     cause
   *            The exception that occurred, causing this exception to be
   *            thrown, if that is the case.
   *
   * @since IV
   */
  @MethodContract(
    pre  = {
      @Expression("_originType != null"),
      @Expression("_propertyName != null ? hasProperty(_originType, _propertyName)"),
      @Expression("_message == null || ! _message.equals(EMPTY)")
    },
    post = {
      @Expression("origin == null"),
      @Expression("originType == _originType"),
      @Expression("propertyName == _propertyName"),
      @Expression("message == _message == null ? DEFAULT_MESSAGE_KEY : _message"),
      @Expression("cause == _cause")
    }
  )
  public PropertyException(final Class<? extends Value> originType,
                           final String propertyName,
                           final String message,
                           final Throwable cause) {
    super(originType, message, cause);
    assert (propertyName == null) || hasProperty(originType, propertyName);
    assert (message == null) || (!message.equals(""));
    $propertyName = propertyName;
  }

  /*</construction>*/

  /*<property name="propertyName">*/
  //------------------------------------------------------------------

  /**
   * The name of the property for which this
   */
  @Basic(
    invars = @Expression("propertyName != null ? hasProperty(originType, propertyName)")
  )
  public final String getPropertyName() {
    return $propertyName;
  }

  private String $propertyName;

  /*</property>*/

  /*
*/
  //------------------------------------------------------------------

  /**
   * Compare {@code other} to this: is other of the the exact same
   * type and does other have the exact same properties.
   *
   * This method is an alternative to {@link #equals(Object)}, which
   * we cannot override, because we need to keep reference semantics
   * for exceptions.
   *
   * This method is introduced mainly for use in contracts of methods
   * that throw property exceptions, and in unit tests for those
   * methods.
   *
   * This method must be overridden in every subclass that adds a property
   * to include that property in the comparison.
   *
   * @note methods was formerly called {@code hasSameValues}, and now replaces
   *       {@code hasSameValues}, 2 {@code contains} methods and 2 {@code reportsOn}
   *       methods, which in practice did not fulfill their promise.
   *
   * @since VI
   */
  @MethodContract(
    post = @Expression("result ? (_other != null) && (_other.class = class) && " +
                       "(origin == _other.origin) && (originType == _other.originType) && " +
                       "(propertyName == _other.propertyName) && (message == _other.message) && " +
                       "(cause == _other.cause)")
  )
  public boolean like(PropertyException other) {
    return (other != null) && (other.getClass() == getClass()) &&
           (other.getValue() == getValue()) &&
           (other.getValueType() == getValueType()) &&
           eqn(other.getPropertyName(), getPropertyName()) &&
           eqn(other.getMessage(), getMessage()) &&
           (other.getCause() == getCause());
  }

  protected final boolean eqn(Object o1, Object o2) {
    return o1 == null ? o2 == null : o1.equals(o2);
  }

}


text:
package org.wso2.carbon.apimgt.impl.clients;

import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;

@SuppressWarnings("unused")
public class OAuthAdminClient {

    private static final Log log = LogFactory.getLog(OAuthAdminClient.class);

    private static final int TIMEOUT_IN_MILLIS = 15 * 60 * 1000;

    private OAuthAdminServiceStub oAuthAdminServiceStub;
    private String cookie;

    public OAuthAdminClient() throws APIManagementException {
        KeyManagerConfiguration configuration = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();
        String serviceURL = configuration.getParameter(APIConstants.AUTHSERVER_URL);
        if (serviceURL == null) {
            throw new APIManagementException("Required connection details for the key management server not provided");
        }

        try {
            ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
            oAuthAdminServiceStub = new OAuthAdminServiceStub(ctx, serviceURL + "OAuthAdminService");

            ServiceClient client = oAuthAdminServiceStub._getServiceClient();
            Options options = client.getOptions();
            options.setTimeOutInMilliSeconds(TIMEOUT_IN_MILLIS);
            options.setProperty(HTTPConstants.SO_TIMEOUT, TIMEOUT_IN_MILLIS);
            options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, TIMEOUT_IN_MILLIS);
            options.setCallTransportCleanup(true);
            options.setManageSession(true);

        } catch (AxisFault axisFault) {
            throw new APIManagementException("Error while initializing the OAuth admin service stub", axisFault);
        }
    }

    public OAuthConsumerAppDTO getOAuthApplicationData(String consumerKey, String username) throws Exception {
        Util.setAuthHeaders(oAuthAdminServiceStub._getServiceClient(), username);
        return oAuthAdminServiceStub.getOAuthApplicationData(consumerKey);

    }

    public OAuthConsumerAppDTO getOAuthApplicationDataByAppName(String appName, String username) throws Exception {
        Util.setAuthHeaders(oAuthAdminServiceStub._getServiceClient(), username);
        return oAuthAdminServiceStub.getOAuthApplicationDataByAppName(appName);
    }

    public void registerOAuthApplicationData(OAuthConsumerAppDTO application, String username) throws Exception {
        Util.setAuthHeaders(oAuthAdminServiceStub._getServiceClient(), username);
        oAuthAdminServiceStub.registerOAuthApplicationData(application);

    }

    public void removeOAuthApplicationData(String consumerKey, String username) throws Exception {
        Util.setAuthHeaders(oAuthAdminServiceStub._getServiceClient(), username);
        oAuthAdminServiceStub.removeOAuthApplicationData(consumerKey);
    }

    public void updateOAuthApplicationData(OAuthConsumerAppDTO consumerAppDTO, String username) throws Exception {
        Util.setAuthHeaders(oAuthAdminServiceStub._getServiceClient(), username);
        oAuthAdminServiceStub.updateConsumerApplication(consumerAppDTO);
    }

}


text:
layout: post
title: ONOS Application Tutorial - PortStatistics Application
categories: SDN
tags:
- SDN, ONOS, Tutorial
---

ONOS - Yet another SDN controller. This was the thought I had when I first heard about this opensource program. A lot has changed about my perception of ONOS, after getting a feel of what it is actually.

In this post, I'm going to concentrate on how to write an ONOS app.

### Basics

ONOS applications are having special extension - OAR ( ONOS Application aRchive format ). The main reason for this special kind of treatment goes to one of the special reason behind using ONOS - Distributed systems .

ONOS at its heart - a distributed system. ONOS unline ODL focus more on service provider use-case. Hence HA, scalablity & resiliency has been implicit requirements for ONOS.

In distributed system, multiple ONOS nodes cater to serve a single ONOS cluster. Deploying app in .OAR format ensures that, these apps gets installed in all ONOS nodes thereby achieving consistency across the ndoes.

Below diagram gives module level view of ONOS
![ ](http://sdnhub.org/wp-content/uploads/2015/01/onos-architecture.png  "ONOS arch")

### Getting Started

The [Template Application Tutorial](https://wiki.onosproject.org/display/ONOS/Template+Application+Tutorial) contains all the required content to get started. But it doesn't offer a full working template application. In this post, let me guide you to create a working application.

#### Create a sample app from template

When you setup a ONOS dev environment as per [this link](https://wiki.onosproject.org/display/ONOS/Development+Environment+Setup), things will become soooo easy.

When a new developer set-out to write a SDN app in ODL, the learning curve is way too steep. Even though ONOS also follows [maven archetypes](https://maven.apache.org/guides/introduction/introduction-to-archetypes.html) , ONOS developers had made things simpler by providing a wrapper called **onos-create-app**.

I will let you glean-through the [Template Application Tutorial](https://wiki.onosproject.org/display/ONOS/Template+Application+Tutorial) to setup the skeleton app. Once you are done, continue reading through.

#### Scope of our application

Let us now create a simple application to get the **Port Statistics** of all the ports from all the devices ( possibly openflow devices ) that are attached to the controller.

So what exactly we mean about port statistics?? Well, it is basically the amount of packet, bytes that are sent to / recieved from a given port from a given device.

ONOS also maintain another special version of statistics known as **Port Delta Statistics** which actually provides the **delta** between 2 given probe intervals.

#### How to get our data from controller ?

ONOS exposes different services to poke into and get data. One such service is **DeviceService**. This particular service abstracts the south bound device irrespective of the south bound interface that is connected with.

So let us use this service to get the list of devices first. But before that, we need to get a reference of the interface class.

{% highlight java %}

@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
 protected DeviceService deviceService;

  Iterable<Device> devices = deviceService.getDevices();
  List<PortStatistics> portStatisticsList = deviceService.getPortDeltaStatistics(d.id());
                for (PortDeltaStatistics portdeltastat : portStatisticsList) {
                	 if(portdeltastat != null)
                    		log.info("portdeltastat bytes recieved" + portdeltastat.bytesReceived());
                	else
                    		log.info("Unable to read portDeltaStats");
                }
{% endhighlight %}

While this rudimentry, why not let us monitor every port of every device in autonomous way? Sounds good right??

All we need now is a worker for us to work in independant fashion. Well the solution is `TimerTask`.
So let us create a new class `portStatsReaderTask` extending `TimerTask` and fire an independant task operation as follows.

But before that, let us look how our `portStatsReaderTask` might look.

{% highlight java %}

public class portStatsReaderTask {

    class Task extends TimerTask {

        public Device getDevice() {
            return device;
        }
        public DeviceService getDeviceService() {
            return deviceService;
        }
        public long getDelay() {
            return delay;
        }

        @Override
        public void run() {
            while (!isExit()) {
                log.info("####### Into run() ");
                List<PortStatistics> portStatisticsList = getDeviceService().getPortDeltaStatistics(getDevice().id());
                for (PortStatistics portStats : portStatisticsList) {
                    log.info("########## port is " + portStats.port());
                    if (portStats.port() == getPort()) {
                        log.info("Port " + port + "has recieved " + portStats.bytesReceived() + "bytes");
                        try {
                            Thread.sleep((getDelay() * 1000));
                            break;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public void schedule() {
        this.getTimer().schedule(new Task(), 0, 1000);
    }
--snip--
{% endhighlight %}

 Hope you get the implementation. `portStatsReaderTask` contains an *inner class* named `Task` that extends `TimerTask`. This is necessary if we want to use `portStatsReaderTask` as a self contained component ( you will get more clarity in the place where we really use this class ).

 The `run()` & `schedule()` are really the heart & nerve of this whole logic. For the sake of this blog, I didn't make the full source available. I shall provide a link to github source at the end of this post.

 Having defined our worker, let us give some work to the worker.

#####  `activate()` & `deactivate` function :

The `AppComponent` class provides `activate()` & `deactivate()` functions which marks the start & end of every ONOS app's lifecycle. So we are going to place our logic in `activate()` function.

{% highlight java %}

@Activate
    protected void activate() {

        log.info("Started");
        Iterable<Device> devices = deviceService.getDevices();

        List<PortStatistics> portStatisticsList = deviceService.getPortDeltaStatistics(d.id());
                for (PortStatistics portStats : portStatisticsList) {
                    try {
                        int port = portStats.port();
                        log.info("#### Creating object for " + port);
                        portStatsReaderTask task = new portStatsReaderTask();
                        task.setDelay(3);
                        task.setExit(false);
                        task.setLog(log);
                        task.setPort(port);
                        task.setDeviceService(deviceService);
                        task.setDevice(d);
                        map.put(port, task);
                        task.schedule();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
      }
{% endhighlight %}

 First every device, we get `List<PortStatistics>` objects. And for every element in list, we prepare a map of `PortStatistics` with `port number` and spawn a new `portStatsReaderTask` for every element in list. Now you can understand the reason for create a wrapper as explained above.

<pre>
Note : As per ONOS's openflow driver (provider/of/device/impl/OpenFlowDeviceProvider.java), the polling frequency is set to 5 seconds.

Hence you might need to understand that the B/W measurement depends on this 5 seconds polling intervals. If incase you are trying to match the B/W data with external observer data ( like iperf for example ), you might need to fix the probing interval of that observer as well to 5 seconds.
</pre>

#### Github source

Please feel free to visit [myapps](https://github.com/kspviswa/myapps/tree/master/sample) page to view the complete source. Make sure you read the [Read.me](https://github.com/kspviswa/myapps/blob/master/README.md) before attempting to use the code .

#### Just before saying Cya...

I hope this post would have provided you enough inputs on getting started with your ONOS app development. The idea is to provide a complete walkthrough of a simple app and I hope I did justice to that intent. Feel free to fire in any questions / comments / clarifications and I would be happy to help.

Cya!!!


text:
def parse_example(example):
    letters_count = 0
    digits_count = 0
    for c in example:
        if c in letters:
            letters_count += 1
        if c in digits:
            digits_count += 1
    return letters_count, digits_count

def count_combinations(quantity, letters, digits):
    letters_count, digits_count = quantity
    return len(letters) ** letters_count * len(digits) ** digits_count

letters = list('ABCEHKMOPTXY')
digits = list('1234567890')
example = input('input number: ')
print(count_combinations(parse_example(example), letters, digits))


text:
public class a {
  void f1()
  {
    new a() {
    <error descr="Inner classes cannot have static declarations">static</error>
      int i;

    // compile time constant is OK
    static final int f1 = 3 < 4 ? (a.ix==5 ?  1 : 3) / 4 + 18 : 0;

    // its not a compile time constant
    <error descr="Inner classes cannot have static declarations">static</error>
      final Object o = null;

    <error descr="Inner classes cannot have static declarations">static</error>
      final int f2 = x instanceof Integer ? 1 : 0;

    <error descr="Inner classes cannot have static declarations">static</error>
      class a_ic_c2 {}

    <error descr="Inner classes cannot have static declarations">static</error>
      int a_ic_m2(String s) { return 0; }
    // static initializer
    <error descr="Inner classes cannot have static declarations">static</error>
    {}
    };
  }
}


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

namespace EPI.Graphs
{
	/// <summary>
	/// Search a Maze
	/// Given a 2D array of black and white entries representing a maze with
	/// designated entrance and exit points, find a path from the entrance to
	/// the exit, if one exists.
	/// </summary>
	public static class SearchAMaze
	{
		[DebuggerDisplay("{X}, {Y}")]
		public struct Coordinate
		{
			public int X, Y;
		}

		#region DFS implementation

		/// <summary>
		/// Uses DFS (depth-first search) to find * a path* (not guaranteed to be the shortest path)
		/// in the maze from start to end
		/// </summary>
		/// <param name="maze">2D array (n x m size)representing a maze. Value of 0 implies white pixel</param>
		/// <param name="start">x, y coordinates of starting point</param>
		/// <param name="end">x, y coordinates of ending point</param>
		/// <returns>list of path coordinates, empty path means to solutions exists</returns>
		public static IList<Coordinate> SearchDfs(int[,] maze, Coordinate start, Coordinate end)
		{
			List<Coordinate> path = new List<Coordinate>();
			maze[start.X, start.Y] = 1;
			path.Add(start);
			if (!SearchMazeHelper(start, end, maze, path))
			{
				path.RemoveAt(path.Count - 1);
			}

			return path;
		}

		private static bool SearchMazeHelper(Coordinate current, Coordinate end, int[,] maze, List<Coordinate> path)
		{
			if (Equals(current, end)) // base case
				return true;

			int[,] neighbors = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
			for (int i = 0; i < neighbors.GetLength(0); i++)
			{
				Coordinate next = new Coordinate(){ X = current.X + neighbors[i, 0], Y = current.Y + neighbors[i, 1]};
				if (IsFeasible(next, maze))
				{
					maze[next.X, next.Y] = 1;
					path.Add(next);
					if (SearchMazeHelper(next, end, maze, path))
					{
						return true;
					}
					path.RemoveAt(path.Count - 1);
				}
			}
			return false;
		}

		#endregion

		/// <summary>
		/// Checks if current coordinate is within the maze and a white pixel
		/// </summary>
		/// <param name="current">Coordinate to check</param>
		/// <param name="maze">2d array maze</param>
		/// <returns>true upon success, false otherwise</returns>
		private static bool IsFeasible(Coordinate current, int[,] maze)
		{
			return current.X >= 0 && current.X < maze.GetLength(0)
				&& current.Y >= 0 && current.Y < maze.GetLength(1)
				&& maze[current.X, current.Y] == 0; // white pixel
		}

		#region BFS implementation

		/// <summary>
		/// Uses BFS (breadth-first search) to find the shortest path in the maze from start to end
		/// </summary>
		/// <param name="maze">2D array (n x m size)representing a maze. Value of 0 implies open area</param>
		/// <param name="start">x, y coordinates of starting point</param>
		/// <param name="end">x, y coordinates of ending point</param>
		/// <returns>list of path coordinates, empty path means to solutions exists</returns>
		public static IList<Coordinate> SearchBfs(int[,] maze, Coordinate start, Coordinate end)
		{
			// BFS will use a queue to *visit* coordinate
			// queue stores the (x,y) coord + the path from start leading upto (x, y)
			Queue<KeyValuePair<Coordinate, IList<Coordinate>>> queue = new Queue<KeyValuePair<Coordinate, IList<Coordinate>>>();
			queue.Enqueue(new KeyValuePair<Coordinate, IList<Coordinate>>(start, new List<Coordinate>()));

			// mark the coordinate as visited (re-use 1 here for simplicity)
			maze[start.X, start.Y] = 1;

			while (queue.Count > 0)
			{
				var c = queue.Dequeue();
				Coordinate current = c.Key;
				IList<Coordinate> currentPath = new List<Coordinate>(c.Value);
				currentPath.Add(current);

				// termination case
				if (current.X == end.X && current.Y == end.Y)
				{
					return currentPath;
				}

				int[,] neighbors = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
				for (int i = 0; i < neighbors.GetLength(0); i++)
				{
					Coordinate next = new Coordinate() { X = current.X + neighbors[i, 0], Y = current.Y + neighbors[i, 1] };
					if (IsFeasible(next, maze))
					{
						maze[next.X, next.Y] = 1;
						queue.Enqueue(new KeyValuePair<Coordinate, IList<Coordinate>>(next, currentPath));
					}
				}
			}

			return new List<Coordinate>();
		}

		#endregion

	}
}