text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package dk.statsbiblioteket.summa.facetbrowser.browse;

import dk.statsbiblioteket.summa.common.configuration.Configuration;
import dk.statsbiblioteket.summa.common.configuration.storage.MemoryStorage;
import dk.statsbiblioteket.summa.common.lucene.index.IndexConnector;
import dk.statsbiblioteket.summa.facetbrowser.IndexBuilder;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.StringWriter;

@SuppressWarnings({"DuplicateStringLiteralInspection"})
public class BrowserImplTest extends TestCase {
    private static Log log = LogFactory.getLog(BrowserImplTest.class);
    public BrowserImplTest(String name) {
        super(name);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }

    private String arrayToString(String[] strings) {
        StringWriter sw = new StringWriter(strings.length * 10);
        for (int i = 0 ; i < strings.length ; i++) {
            sw.append(strings[i]);
            if (i < strings.length - 1) {
                sw.append(", ");
            }
        }
        return sw.toString();
    }

    // TODO: Rewrite this
    private Configuration getConfiguration() {
        String[] facets = new String[]{ IndexBuilder.AUTHOR,
                                        IndexBuilder.AUTHOR_NORMALISED,
                                        IndexBuilder.TITLE,
                                        IndexBuilder.GENRE,
                                        IndexBuilder.VARIABLE };
        MemoryStorage memStore = new MemoryStorage();
//        memStore.put(StructureDescription.FACETS, arrayToString(facets));
        memStore.put(IndexConnector.INDEXROOT + IndexConnector.TYPE,
                     IndexConnector.INDEXTYPE.singleIndex);
        memStore.put(IndexConnector.INDEXROOT + IndexConnector.LINKS,
                     IndexBuilder.INDEX_LOCATION);
/*        memStore.put(TagHandlerFactory.FORCE_REBUILD, true);
        memStore.put(TagHandlerFactory.TAG_HANDLER,
                     TagHandlerFactory.TAGHANDLERS.MemoryTagHandler);
        memStore.put(TagHandlerFactory.TAG_DATA_LOCATION,
                     new File(IndexBuilder.INDEX_LOCATION, "facets").toString());*/
        return new Configuration(memStore);
    }

    /**
     * Indirect test of the browser, where all the parts that makes up a
     * Browser are handled explicitly.
     * @throws Exception if an assertion failed.
     */
    public void testParts() throws Exception {
        // TODO: Change this to use IndexConnector
/*        IndexBuilder.checkIndex();
//        IndexReader reader = IndexBuilder.getReader();
        Configuration config = getConfiguration();
        StructureDescription structure = new StructureDescription(config);
        IndexConnector connector = new IndexConnector(config);

        TagHandler tagHandler =
                TagHandlerFactory.getTagHandler(config, connector);
        assertTrue("The tag handler should not be empty",
                   tagHandler.getTagCount() > 0);

        CoreMap coreMap =
                CoreMapFactory.getCoreMap(connector.getReader().maxDoc(),
                                          structure.getFacetNames().size(),
                                          tagHandler.getMaxTagCount());
        // Consider adding stopwords to the configuration
        CoreMapFactory.fillMap(coreMap, structure, tagHandler,
                               connector.getReader(),
                               config, false);
        assertEquals("The core map should map all documents",
                     IndexBuilder.REPLICATIONCOUNT * IndexBuilder.comics.length,
                     coreMap.getDocCount());

        TagCounter tagCounter = new TagCounterArray(structure, tagHandler);

        int[] docIDs = new int[] {0, 1, 2, 3, 4};
        coreMap.markCounterLists(tagCounter, docIDs, 0, docIDs.length-1);
        FacetResult facetStructure =
                tagCounter.getFirst(FacetResult.TagSortOrder.popularity);
        String browseXML = facetStructure.toXML();
        assertTrue("The result should be something",
                   browseXML.length() > "<facetmodel>\n</facetmodel>".length());*/
    }

    public void dumpPerformance() throws Exception {
        // TODO: Change this to use IndexConnector
/*        log.info("Getting reader...");
        IndexReader reader = IndexBuilder.getReader();
        log.info("Setting up system...");
        Configuration config = getConfiguration();
        StructureDescription structure = new StructureDescription(config);
        IndexConnector connector = new IndexConnector(config);

        TagHandler tagHandler =
                TagHandlerFactory.getTagHandler(config, connector);
        CoreMap coreMap =
                CoreMapFactory.getCoreMap(reader.maxDoc(),
                                          structure.getFacetNames().size(),
                                          tagHandler.getMaxTagCount());
        // Consider adding stopwords to the configuration
        CoreMapFactory.fillMap(coreMap, structure, tagHandler, reader,
                               config, false);
        TagCounter tagCounter = new TagCounterArray(structure, tagHandler);

        Random random = new Random();
        int[] docCounts = new int[] {1, 100, 1000, 10000, 100000, 1000000,
                                     10000000};
        int warmup = 2;
        int runs = 3;
        Profiler profiler = new Profiler();
        profiler.setExpectedTotal(runs);
        int maxDoc = reader.maxDoc();
        log.info("Running tests...");
        for (int docCount: docCounts) {
//            log.info("Testing with " + docCount + " docIDs...");
            int[] docIDs = new int[docCount];
            for (int pos = 0 ; pos < docCount ; pos++) {
                docIDs[pos] = random.nextInt(maxDoc);
            }
            for (int i = 0 ; i < warmup ; i++) {
                coreMap.markCounterLists(tagCounter, docIDs, 0, docCount-1);
            }
            System.gc();
            profiler.reset();
            for (int i = 0 ; i < runs ; i++) {
                coreMap.markCounterLists(tagCounter, docIDs, 0, docCount-1);
           tagCounter.getFirst(FacetResult.TagSortOrder.popularity).toXML();
                profiler.beat();
            }
            log.info("Average time for marking and extracting tags " +
                               "for " + docCount + " documents: "
                               + 1000 / profiler.getBps(true) + " ms");

        }*/
    }

    public void testGetReader() throws Exception {
        assertNotNull("The reader must not be null", IndexBuilder.getReader());
    }

    public void dumpPerformanceDirect() throws Exception {
        // TODO: Change this to use IndexConnector
/*        log.info("Getting reader...");
        IndexReader reader = IndexBuilder.getReader();
        log.info("Setting up system...");
        Configuration config = getConfiguration();
        config.set(FacetSearchNode.BROWSERTHREADS_PROPERTY, 2);
        config.set(FacetSearchNode.BROWSERTHREADS_TIMEOUT_PROPERTY, 5000);
        StructureDescription structure = new StructureDescription(config);
        IndexConnector connector = new IndexConnector(config);

        TagHandler tagHandler =
                TagHandlerFactory.getTagHandler(config, connector);
        CoreMap coreMap =
                CoreMapFactory.getCoreMap(reader.maxDoc(),
                                          structure.getFacetNames().size(),
                                          tagHandler.getMaxTagCount());
        // Consider adding stopwords to the configuration
        CoreMapFactory.fillMap(coreMap, structure, tagHandler, reader,
                               config, false);
//        TagCounter tagCounter = new TagCounterArray(structure, tagHandler);
        SearchDescriptor descriptor =
                new SearchDescriptor(IndexBuilder.INDEX_LOCATION);
        descriptor.loadDescription(IndexBuilder.INDEX_LOCATION);

        SummaQueryParser queryParser =
                new SummaQueryParser(new String[]{"foo", "bar"},
                                     new SimpleAnalyzer(), descriptor);

        FacetSearchNode browser = new FacetSearchNode(config, null, queryParser,
                                              tagHandler,
                                              structure, coreMap);

        Random random = new Random();
        int[] docCounts = new int[] {1, 100, 1000, 10000, 100000, 1000000,
                                     10000000};
        int warmup = 2;
        int runs = 3;
        FacetResult.TagSortOrder[] orders =
                new FacetResult.TagSortOrder[]{
                        FacetResult.TagSortOrder.popularity,
                        FacetResult.TagSortOrder.tag};
        Profiler profiler = new Profiler();
        profiler.setExpectedTotal(runs);
        int maxDoc = reader.maxDoc();

        log.info("Running tests...");
        SlimCollector slimCollector = new SlimCollector();
        for (int docCount: docCounts) {
            for (FacetResult.TagSortOrder order: orders) {
                slimCollector.clean();
                for (int pos = 0 ; pos < docCount ; pos++) {
                    slimCollector.collect(random.nextInt(maxDoc), 0.0f);
                }
                for (int i = 0 ; i < warmup ; i++) {
                    browser.getFacetMap("Flam", order, slimCollector);
                }
                System.gc();
                profiler.reset();
                for (int i = 0 ; i < runs ; i++) {
                    browser.getFacetMap("Flam", order, slimCollector);
                    profiler.beat();
                }
                log.info("Average time for marking and extracting "
                                   + "tags for " + docCount + " documents: "
                                   + 1000 / profiler.getBps(true) + " ms - "
                                   + order);
            }
        }*/
    }

    public static Test suite() {
        return new TestSuite(BrowserImplTest.class);
    }
}


text:
using System.ComponentModel;

namespace LinqAn.Google.Metrics
{
	/// <summary>
	/// 	The name of the requested custom metric, where 118 refers the number/index of the custom metric. Note that the data type of ga:metric118 can be INTEGER, CURRENCY or TIME.
	/// </summary>
	[Description("The name of the requested custom metric, where 118 refers the number/index of the custom metric. Note that the data type of ga:metric118 can be INTEGER, CURRENCY or TIME.")]
	public class Metric118: Metric<float>
	{
		/// <summary>
		/// 	Instantiates a <seealso cref="Metric118" />.
		/// </summary>
		public Metric118(): base("Custom Metric 118 Value",true,"ga:metric118")
		{

		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
========================
 S3 compatibility tests
========================

This is a set of unofficial Amazon AWS S3 compatibility
tests, that can be useful to people implementing software
that exposes an S3-like API. The tests use the Boto2 and Boto3 libraries.

The tests use the Nose test framework. To get started, ensure you have
the ``virtualenv`` software installed; e.g. on Debian/Ubuntu::

	sudo apt-get install python-virtualenv

and then run::

	./bootstrap

You will need to create a configuration file with the location of the
service and two different credentials. A sample configuration file named
``s3tests.conf.SAMPLE`` has been provided in this repo. This file can be
used to run the s3 tests on a Ceph cluster started with vstart.

Once you have that file copied and edited, you can run the tests with::

	S3TEST_CONF=your.conf ./virtualenv/bin/nosetests

You can specify which directory of tests to run::

	S3TEST_CONF=your.conf ./virtualenv/bin/nosetests s3tests.functional

You can specify which file of tests to run::

	S3TEST_CONF=your.conf ./virtualenv/bin/nosetests s3tests.functional.test_s3

You can specify which test to run::

	S3TEST_CONF=your.conf ./virtualenv/bin/nosetests s3tests.functional.test_s3:test_bucket_list_empty

To gather a list of tests being run, use the flags::

	 -v --collect-only

Some tests have attributes set based on their current reliability and
things like AWS not enforcing their spec stricly. You can filter tests
based on their attributes::

	S3TEST_CONF=aws.conf ./virtualenv/bin/nosetests -a '!fails_on_aws'

Most of the tests have both Boto3 and Boto2 versions. Tests written in
Boto2 are in the ``s3tests`` directory. Tests written in Boto3 are
located in the ``s3test_boto3`` directory.

You can run only the boto3 tests with::

        S3TEST_CONF=your.conf ./virtualenv/bin/nosetests -v -s -A 'not fails_on_rgw' s3tests_boto3.functional

========================
 STS compatibility tests
========================

This section contains some basic tests for the AssumeRole, GetSessionToken and AssumeRoleWithWebIdentity API's. The test file is located under ``s3tests_boto3/functional``.

You can run only the sts tests (all the three API's) with::

        S3TEST_CONF=your.conf ./virtualenv/bin/nosetests s3tests_boto3.functional.test_sts

You can filter tests based on the attributes. There is a attribute named ``test_of_sts`` to run AssumeRole and GetSessionToken tests and ``webidentity_test`` to run the AssumeRoleWithWebIdentity tests. If you want to execute only ``test_of_sts`` tests you can apply that filter as below::

        S3TEST_CONF=your.conf ./virtualenv/bin/nosetests -v -s -A 'test_of_sts' s3tests_boto3.functional.test_sts

For running ``webidentity_test`` you'll need have Keycloak running.

In order to run any STS test you'll need to add "iam" section to the config file. For further reference on how your config file should look check ``s3tests.conf.SAMPLE``.


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

  angular
    .module('restaurants')
    .run(menuConfig);

  menuConfig.$inject = ['menuService'];

  function menuConfig(menuService) {
  }
}());


text:
import React from 'react';
import moment from 'moment';

import RelativeDate from './RelativeDate.react';
import MZBenchActions from '../actions/MZBenchActions';
import Star from './Star.react';
import MZBenchRouter from '../utils/MZBenchRouter';
import GlobalStore from '../stores/GlobalStore';
import PropTypes from 'prop-types';
import {OverlayTrigger, Tooltip} from 'react-bootstrap';

class TimelineElement extends React.Component {
    render() {
        if (GlobalStore.isDashboardModeOn()) {
            return this.renderDashboard();
        } else {
            return this.renderBench();
        }
    }
    renderDashboard() {
        let item = this.props.bench;
        let isSelected = this.props.isSelected;

        let cssClass = "bs bs-progress";

        if (isSelected) {
            cssClass += " bs-selected";
        }

        return (
            <a href={`#/dashboard/${item.id}/overview`} className="bs-link">

                        #{item.id} {item.name}

        );
    }
    renderBench() {
        let { bench, isSelected, duration } = this.props;

        let cssClass = "bs bs-" + (bench.isRunning() ? "progress" :  bench.status);

        if (isSelected) {
            cssClass += " bs-selected";
        }

        var tags = bench.tags.length <= 0 ? [] :

                {bench.tags.map(
                    (t, i) => {
                        return
                                 { return this._onTagClick(t, e) }} key={i}>{"#"+t}

                    })}

;

        let author = null;

        if (bench.author != "anonymous") {
            if (bench.author_name == "") {
                author = (
by {bench.author}
);
            } else {
                author = (
by {bench.author_name}
);
            }
        }

        const searchTooltip = <Tooltip id="search-tooltip">Search for similar benchmarks</Tooltip>;

        return (
            <a href={`#/bench/${bench.id}/overview`} className="bs-link">

                        <Star selected={bench.tags.indexOf("favorites") > -1} onClick={(v) => {
                                if (v == true) MZBenchActions.addBenchTag(bench.id, "favorites");
                                else MZBenchActions.removeBenchTag(bench.id, "favorites");
                            }}/>
                        #{bench.id} {bench.name}
                        {bench.isRunning() ? {bench.status} : null}
                        <OverlayTrigger delay={200} placement="top" overlay={searchTooltip}>
                             {
                                    e.preventDefault();
                                    MZBenchRouter.navigate("/timeline", {q: bench.name});
                                }}/>
                        </OverlayTrigger>

                    {tags}

 <RelativeDate date = {bench.create_time_client} />

 {moment.duration(duration).humanize()}

                    {author}

        );
    }

    _onTagClick(tag, event) {
        event.preventDefault();
        MZBenchRouter.navigate("/timeline", {q: "#"+tag});
    }

    _onClick() {
        MZBenchActions.selectBenchById(this.props.bench.id);
    }
}

TimelineElement.propTypes = {
    bench: PropTypes.object.isRequired,
    isSelected: PropTypes.bool
};

TimelineElement.defaultProps = {
    isSelected: false
};

export default TimelineElement;


text:
<?php

namespace app\controllers\admin;

use app\controllers\AbstractController;
use app\libraries\FileUtils;
use app\libraries\response\JsonResponse;
use app\libraries\routers\AccessControl;
use app\libraries\response\MultiResponse;
use app\libraries\response\WebResponse;
use app\models\RainbowCustomizationJSON;
use app\views\admin\ConfigurationView;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Class ConfigurationController
 * @package app\controllers\admin
 * @AccessControl(role="INSTRUCTOR")
 */
class ConfigurationController extends AbstractController {
    // The message that should be returned to the user if they fail the required validation to enable the nightly
    // rainbow grades build checkbox
    const FAIL_AUTO_RG_MSG = 'You may not enable automatic rainbow grades generation until you have supplied a ' .
    'customization.json file.  To have one generated for you, you may use the Web-Based Rainbow Grades Generation inside the Grade ' .
    'Reports tab.  You may also manually create the file and upload it to your course\'s rainbow_grades directory.';

    /**
     * @Route("/api/courses/{_semester}/{_course}/config", methods={"GET"})
     * @Route("/courses/{_semester}/{_course}/config", methods={"GET"})
     * @return MultiResponse
     */
    public function viewConfiguration(): MultiResponse {
        $fields = [
            'course_name'                    => $this->core->getConfig()->getCourseName(),
            'course_home_url'                => $this->core->getConfig()->getCourseHomeUrl(),
            'default_hw_late_days'           => $this->core->getConfig()->getDefaultHwLateDays(),
            'default_student_late_days'      => $this->core->getConfig()->getDefaultStudentLateDays(),
            'zero_rubric_grades'             => $this->core->getConfig()->shouldZeroRubricGrades(),
            'upload_message'                 => $this->core->getConfig()->getUploadMessage(),
            'display_rainbow_grades_summary' => $this->core->getConfig()->displayRainbowGradesSummary(),
            'display_custom_message'         => $this->core->getConfig()->displayCustomMessage(),
            'course_email'                   => $this->core->getConfig()->getCourseEmail(),
            'vcs_base_url'                   => $this->core->getConfig()->getVcsBaseUrl(),
            'vcs_type'                       => $this->core->getConfig()->getVcsType(),
            'forum_enabled'                  => $this->core->getConfig()->isForumEnabled(),
            'forum_create_thread_message'    => $this->core->getConfig()->getForumCreateThreadMessage(),
            'regrade_enabled'                => $this->core->getConfig()->isRegradeEnabled(),
            'regrade_message'                => $this->core->getConfig()->getRegradeMessage(),
            'private_repository'             => $this->core->getConfig()->getPrivateRepository(),
            'room_seating_gradeable_id'      => $this->core->getConfig()->getRoomSeatingGradeableId(),
            'seating_only_for_instructor'    => $this->core->getConfig()->isSeatingOnlyForInstructor(),
            'auto_rainbow_grades'            => $this->core->getConfig()->getAutoRainbowGrades(),
            'queue_enabled'                  => $this->core->getConfig()->isQueueEnabled(),
            'queue_message'                  => $this->core->getConfig()->getQueueMessage(),
            'seek_message_enabled'           => $this->core->getConfig()->isSeekMessageEnabled(),
            'seek_message_instructions'      => $this->core->getConfig()->getSeekMessageInstructions(),
            'queue_announcement_message'     => $this->core->getConfig()->getQueueAnnouncementMessage(),
            'polls_enabled'                  => $this->core->getConfig()->isPollsEnabled()
        ];
        $seating_options = $this->getGradeableSeatingOptions();
        $admin_in_course = false;
        if ($this->core->getConfig()->isSubmittyAdminUserVerified()) {
            $admin_in_course =  $this->core->getQueries()->checkIsInstructorInCourse(
                $this->core->getConfig()->getVerifiedSubmittyAdminUser(),
                $this->core->getConfig()->getCourse(),
                $this->core->getConfig()->getSemester()
            );
        }

        return new MultiResponse(
            JsonResponse::getSuccessResponse([
                'config' => $fields,
                'gradeable_seating_options' => $seating_options,
                'email_enabled' => $this->core->getConfig()->isEmailEnabled(),
                'submitty_admin_user' => [
                    'user_id' => $this->core->getConfig()->getVerifiedSubmittyAdminUser(),
                    'verified' => $this->core->getConfig()->isSubmittyAdminUserVerified(),
                    'in_course' => $admin_in_course,
                ]
            ]),
            new WebResponse(
                ConfigurationView::class,
                'viewConfig',
                $fields,
                $seating_options,
                $this->core->getConfig()->isEmailEnabled(),
                [
                    'user_id' => $this->core->getConfig()->getVerifiedSubmittyAdminUser(),
                    'verified' => $this->core->getConfig()->isSubmittyAdminUserVerified(),
                    'in_course' => $admin_in_course,
                ],
                $this->core->getCsrfToken()
            )
        );
    }

    /**
     * @Route("/api/courses/{_semester}/{_course}/config", methods={"POST"})
     * @Route("/courses/{_semester}/{_course}/config", methods={"POST"})
     * @return MultiResponse
     */
    public function updateConfiguration(): MultiResponse {
        if (!isset($_POST['name'])) {
            return MultiResponse::JsonOnlyResponse(
                JsonResponse::getFailResponse('Name of config value not provided')
            );
        }
        $name = $_POST['name'];

        if (!isset($_POST['entry'])) {
            return MultiResponse::JsonOnlyResponse(
                JsonResponse::getFailResponse('Name of config entry not provided')
            );
        }
        $entry = $_POST['entry'];

        if ($name === "room_seating_gradeable_id") {
            $gradeable_seating_options = $this->getGradeableSeatingOptions();
            $gradeable_ids = [];
            foreach ($gradeable_seating_options as $option) {
                $gradeable_ids[] = $option['g_id'];
            }
            if (!in_array($entry, $gradeable_ids)) {
                return MultiResponse::JsonOnlyResponse(
                    JsonResponse::getFailResponse('Invalid gradeable chosen for seating')
                );
            }
        }
        elseif (in_array($name, ['default_hw_late_days', 'default_student_late_days'])) {
            if (!ctype_digit($entry)) {
                return MultiResponse::JsonOnlyResponse(
                    JsonResponse::getFailResponse('Must enter a number for this field')
                );
            }
            $entry = intval($entry);
        }
        elseif (
            in_array(
                $name,
                [
                    'zero_rubric_grades',
                    'display_rainbow_grades_summary',
                    'display_custom_message',
                    'forum_enabled',
                    'regrade_enabled',
                    'seating_only_for_instructor',
                    'queue_enabled',
                    'seek_message_enabled',
                    'polls_enabled'
                ]
            )
        ) {
            $entry = $entry === "true";
        }
        elseif ($name == "course_home_url") {
            if (!filter_var($entry, FILTER_VALIDATE_URL) && !empty($entry)) {
                return MultiResponse::JsonOnlyResponse(
                    JsonResponse::getFailResponse($entry . ' is not a valid URL')
                );
            }
        }
        elseif ($name === 'auto_rainbow_grades') {
            // Special validation for auto_rainbow_grades checkbox
            // Get a new customization json object
            $customization_json = new RainbowCustomizationJSON($this->core);

            // If a custom_customization.json does not exist, then check for the presence of a regular one
            if (!$customization_json->doesCustomCustomizationExist()) {
                // Attempt to populate it from the customization.json in the course rainbow_grades directory
                // If no file exists do not allow user to enable this check mark until one is supplied
                try {
                    $customization_json->loadFromJsonFile();
                }
                catch (\Exception $e) {
                    return MultiResponse::JsonOnlyResponse(
                        JsonResponse::getFailResponse(ConfigurationController::FAIL_AUTO_RG_MSG)
                    );
                }
            }

            $entry = $entry === "true";
        }

        if ($name === 'forum_enabled' && $entry == 1) {
            // Only create default categories when there is no existing categories (only happens when first enabled)
            if (empty($this->core->getQueries()->getCategories())) {
                $categories = ["General Questions", "Homework Help", "Quizzes" , "Tests"];
                foreach ($categories as $rank => $category) {
                    $this->core->getQueries()->addNewCategory($category, $rank);
                }
            }
        }

        $config_json = $this->core->getConfig()->getCourseJson();
        if (!isset($config_json['course_details'][$name])) {
            return MultiResponse::JsonOnlyResponse(
                JsonResponse::getFailResponse('Not a valid config name')
            );
        }
        $config_json['course_details'][$name] = $entry;

        if (!$this->core->getConfig()->saveCourseJson(['course_details' => $config_json['course_details']])) {
            return MultiResponse::JsonOnlyResponse(
                JsonResponse::getFailResponse('Could not save config file')
            );
        }

        // All late day cache now invalid
        if ($name === 'default_student_late_days') {
            $this->core->getQueries()->flushAllLateDayCache();
        }

        return MultiResponse::JsonOnlyResponse(
            JsonResponse::getSuccessResponse(null)
        );
    }

    private function getGradeableSeatingOptions(): array {
        $gradeable_seating_options = $this->core->getQueries()->getAllGradeablesIdsAndTitles();

        $seating_dir = FileUtils::joinPaths($this->core->getConfig()->getCoursePath(), 'reports', 'seating');

        $gradeable_seating_options = array_filter($gradeable_seating_options, function ($seating_option) use ($seating_dir) {
            return is_dir(FileUtils::joinPaths($seating_dir, $seating_option['g_id']));
        });

        return array_merge([['g_id' => '', 'g_title' => '--None--']], $gradeable_seating_options);
    }
}


text:
layout: page
title: All About Us
modified:
image:
  feature: about-feature.jpg
shareable: no
permalink: about/one
---

This site collects all the Micro:bit MicroPython code on the internet. Contributing is easy---just email or send it to the Github repository.

Happy clicking!

## Python micro:bit Resources

* [Micro:bit Tutorials](https://microbit-micropython.readthedocs.org/en/latest/tutorials/introduction.html) - Beginner friendly tutorials for MicroPython on the BBC micro:bit.
* [mu Editor](https://github.com/ntoll/mu) - A code editor for Python on the micro:bit.
* [Micro:bit MicroPython API](http://microbit-micropython.readthedocs.org/en/latest/microbit_micropython_api.html) - Developer-friendly API docs for MicroPython.

### bootstrap forms

<form class="form-inline">

    Name
    <input type="text" class="form-control" id="exampleInputName2" placeholder="Jane Doe">

    Email
    <input type="email" class="form-control" id="exampleInputEmail2" placeholder="jane.doe@example.com">

  <button type="submit" class="btn btn-primary">Send invitation</button>
</form>

## works

<fieldset>
<form action="//geekteacher.us12.list-manage.com/subscribe/post?u=2bb4bbfd1418ee5ff380a55e9&id=a37d348b5d" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe to our Mail list

Receive micro:bit related news once a fortnight.

	Email Address
	<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

<input type="text" name="b_2bb4bbfd1418ee5ff380a55e9_a37d348b5d" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" style="background-color:#F20732">

</form>
</fieldset>


text:
The following image is an output of `cargo run --bin quad --features=gl`:

![screenshot](screenshot.png "Quad")


text:
<!DOCTYPE refentry [ <!ENTITY % mathent SYSTEM "math.ent"> %mathent; ]>

<refentry xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="glCopyBufferSubData">
    <info>
        <copyright>
            <year>2010-2014</year>
            <holder>Khronos Group</holder>
        </copyright>
    </info>
    <refmeta>
        <refentrytitle>glCopyBufferSubData</refentrytitle>
        <manvolnum>3G</manvolnum>
    </refmeta>
    <refnamediv>
        <refname>glCopyBufferSubData</refname>
        <refname>glCopyNamedBufferSubData</refname>
        <refpurpose>copy all or part of the data store of a buffer object to the data store of another buffer object</refpurpose>
    </refnamediv>
    <refsynopsisdiv><title>C Specification</title>
        <funcsynopsis>
            <funcprototype>
                <funcdef>void <function>glCopyBufferSubData</function></funcdef>
                <paramdef>GLenum <parameter>readTarget</parameter></paramdef>
                <paramdef>GLenum <parameter>writeTarget</parameter></paramdef>
                <paramdef>GLintptr <parameter>readOffset</parameter></paramdef>
                <paramdef>GLintptr <parameter>writeOffset</parameter></paramdef>
                <paramdef>GLsizeiptr <parameter>size</parameter></paramdef>
            </funcprototype>
            <funcprototype>
                <funcdef>void <function>glCopyNamedBufferSubData</function></funcdef>
                <paramdef>GLuint <parameter>readBuffer</parameter></paramdef>
                <paramdef>GLuint <parameter>writeBuffer</parameter></paramdef>
                <paramdef>GLintptr <parameter>readOffset</parameter></paramdef>
                <paramdef>GLintptr <parameter>writeOffset</parameter></paramdef>
                <paramdef>GLsizeiptr <parameter>size</parameter></paramdef>
            </funcprototype>
        </funcsynopsis>
    </refsynopsisdiv>
    <refsect1 xml:id="parameters"><title>Parameters</title>
        <variablelist>
        <varlistentry>
            <term><parameter>readTarget</parameter></term>
            <listitem>
                <para>
                    Specifies the target to which the source buffer object
                    is bound for <function>glCopyBufferSubData</function>
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>writeTarget</parameter></term>
            <listitem>
                <para>
                    Specifies the target to which the destination buffer
                    object is bound for
                    <function>glCopyBufferSubData</function>.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>readBuffer</parameter></term>
            <listitem>
                <para>
                    Specifies the name of the source buffer object for
                    <function>glCopyNamedBufferSubData</function>.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>writeBuffer</parameter></term>
            <listitem>
                <para>
                    Specifies the name of the destination buffer object for
                    <function>glCopyNamedBufferSubData</function>.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>readOffset</parameter></term>
            <listitem>
                <para>
                    Specifies the offset, in basic machine units, within the
                    data store of the source buffer object at which data
                    will be read.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>writeOffset</parameter></term>
            <listitem>
                <para>
                    Specifies the offset, in basic machine units, within the
                    data store of the destination buffer object at which
                    data will be written.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>size</parameter></term>
            <listitem>
                <para>
                    Specifies the size, in basic machine units, of the data
                    to be copied from the source buffer object to the
                    destination buffer object.
                </para>
            </listitem>
        </varlistentry>
        </variablelist>
    </refsect1>
    <refsect1 xml:id="description"><title>Description</title>
        <para>
            <function>glCopyBufferSubData</function> and
            <function>glCopyNamedBufferSubData</function> copy part of the
            data store attached to a source buffer object to the data store
            attached to a destination buffer object. The number of basic
            machine units indicated by <parameter>size</parameter> is copied
            from the source at offset <parameter>readOffset</parameter> to
            the destination at <parameter>writeOffset</parameter>.
            <parameter>readOffset</parameter>,
            <parameter>writeOffset</parameter> and
            <parameter>size</parameter> are in terms of basic machine units.
        </para>
        <para>
            For <function>glCopyBufferSubData</function>,
            <parameter>readTarget</parameter> and
            <parameter>writeTarget</parameter> specify the targets to which
            the source and destination buffer objects are bound, and must
            each be one of the buffer binding targets in the following
            table:
        </para>
        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="bufferbindings.xml"/>
        <para>
            Any of these targets may be used, but the targets
            <constant>GL_COPY_READ_BUFFER</constant> and
            <constant>GL_COPY_WRITE_BUFFER</constant> are provided
            specifically to allow copies between buffers without disturbing
            other GL state.
        </para>
        <para>
            <parameter>readOffset</parameter>,
            <parameter>writeOffset</parameter> and
            <parameter>size</parameter> must all be greater than or equal to
            zero. Furthermore, $readOffset+size$ must not exceeed the size
            of the source buffer object, and $writeOffset+size$ must not
            exceeed the size of the buffer bound to
            <parameter>writeTarget</parameter>. If the source and
            destination are the same buffer object, then the source and
            destination ranges must not overlap.
        </para>
    </refsect1>
    <refsect1 xml:id="notes"><title>Notes</title>
        <para>
            The <constant>GL_DISPATCH_INDIRECT_BUFFER</constant> and
            <constant>GL_SHADER_STORAGE_BUFFER</constant> targets are
            available only if the GL version is 4.3 or greater.
        </para>
        <para>
            The <constant>GL_QUERY_BUFFER</constant> target is available
            only if the GL version is 4.4 or greater.
        </para>
    </refsect1>
    <refsect1 xml:id="errors"><title>Errors</title>
        <para>
            <constant>GL_INVALID_ENUM</constant> is generated by
            <function>glCopyBufferSubData</function> if
            <parameter>readTarget</parameter> or
            <parameter>writeTarget</parameter> is not one of the buffer
            binding targets listed above.
        </para>
        <para>
            <constant>GL_INVALID_OPERATION</constant> is generated by
            <function>glCopyBufferSubData</function> if zero is bound to
            <parameter>readTarget</parameter> or
            <parameter>writeTarget</parameter>.
        </para>
        <para>
            <constant>GL_INVALID_OPERATION</constant> is generated by
            <function>glCopyNamedBufferSubData</function> if
            <parameter>readBuffer</parameter> or
            <parameter>writeBuffer</parameter> is not the name of an
            existing buffer object.
        </para>
        <para>
            <constant>GL_INVALID_VALUE</constant> is generated if any of
            <parameter>readOffset</parameter>,
            <parameter>writeOffset</parameter> or
            <parameter>size</parameter> is negative, if $readOffset + size$
            is greater than the size of the source buffer object (its value
            of <constant>GL_BUFFER_SIZE</constant>), or if $writeOffset +
            size$ is greater than the size of the destination buffer object.
        </para>
        <para>
            <constant>GL_INVALID_VALUE</constant> is generated if the source
            and destination are the same buffer object, and the ranges
            $[readOffset,readOffset+size)$ and
            $[writeOffset,writeOffset+size)$ overlap.
        </para>
        <para>
            <constant>GL_INVALID_OPERATION</constant> is generated if either
            the source or destination buffer object is mapped with
            <citerefentry><refentrytitle>glMapBufferRange</refentrytitle></citerefentry>
            or
            <citerefentry><refentrytitle>glMapBuffer</refentrytitle></citerefentry>,
            unless they were mapped with the
            <constant>GL_MAP_PERSISTENT</constant> bit set in the
            <function>glMapBufferRange</function>
            <parameter>access</parameter> flags.
        </para>
    </refsect1>
    <refsect1 xml:id="versions"><title>Version Support</title>
        <informaltable>
            <tgroup cols="13" align="left">
                <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apifunchead.xml" xpointer="xpointer(/*/*)"/>
                <tbody>
                    <row>
                        <entry><function>glCopyBufferSubData</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='31']/*)"/>
                    </row>
                    <row>
                        <entry><function>glCopyNamedBufferSubData</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='45']/*)"/>
                    </row>
                </tbody>
            </tgroup>
        </informaltable>
    </refsect1>
    <refsect1 xml:id="seealso"><title>See Also</title>
        <para>
            <citerefentry><refentrytitle>glGenBuffers</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glBindBuffer</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glBufferData</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glBufferSubData</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glGetBufferSubData</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glMapBuffer</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glMapBufferRange</refentrytitle></citerefentry>
        </para>
    </refsect1>
    <refsect1 xml:id="Copyright"><title>Copyright</title>
        <para>
            Copyright <trademark class="copyright"/> 2010-2014 Khronos Group.
            This material may be distributed subject to the terms and conditions set forth in
            the Open Publication License, v 1.0, 8 June 1999.
            <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://opencontent.org/openpub/">http://opencontent.org/openpub/</link>.
        </para>
    </refsect1>
</refentry>


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@drawable/multi_media_vedio_select"></item>
	<item android:state_pressed="false" android:drawable="@drawable/multi_media_vedio_noselect"></item>
</selector>


text:
module PageObject
  module Platforms
    module SeleniumWebDriver

      module TextField

        #
        # Set the value of the TextField
        #
        def value=(new_value)
          element.clear
          element.send_keys(new_value)
        end
      end
    end
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Boea leporina H.J. Lam

### Remarks
null


text:
package org.lnu.is.web.rest.controller.benefit;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.lnu.is.facade.facade.Facade;
import org.lnu.is.resource.benefit.BenefitResource;
import org.lnu.is.resource.message.MessageResource;
import org.lnu.is.resource.message.MessageType;
import org.lnu.is.resource.search.PagedRequest;
import org.lnu.is.resource.search.PagedResultResource;
import org.lnu.is.web.rest.constant.Request;
import org.lnu.is.web.rest.controller.BaseController;
import org.lnu.is.web.rest.controller.CrudController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**
 * Benefit controller.
 * @author ivanursul
 *
 */
@RestController
@RequestMapping("/benefits")
public class BenefitController extends BaseController implements CrudController<BenefitResource, BenefitResource> {
	private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);

	@Resource(name = "benefitFacade")
	private Facade<BenefitResource, BenefitResource, Long> facade;

	@Override
	@ResponseStatus(HttpStatus.OK)
	@RequestMapping(method = RequestMethod.GET)
	public PagedResultResource<BenefitResource> getPagedResource(final PagedRequest<BenefitResource> request) {
		LOGGER.info("Getting paged result for benefits:{}", request);
		return facade.getResources(request);
	}

	@Override
	@ResponseStatus(HttpStatus.OK)
	@RequestMapping(value = Request.ID, method = RequestMethod.GET)
	public BenefitResource getResource(@PathVariable("id") final Long id) {
		LOGGER.info("Getting benefit by id: {}", id);
		return facade.getResource(id);
	}

	@Override
	@ResponseStatus(HttpStatus.CREATED)
	@RequestMapping(method = RequestMethod.POST)
	public BenefitResource createResource(@Valid @RequestBody final BenefitResource resource) {
		LOGGER.info("Creating new benefit:{}", resource);
		return facade.createResource(resource);
	}

	@Override
	@ResponseStatus(HttpStatus.OK)
	@RequestMapping(value = Request.ID, method = RequestMethod.PUT)
	public MessageResource updateResource(@PathVariable("id") final Long id,
			@Valid @RequestBody final BenefitResource resource) {
		LOGGER.info("Updating new resource, id:{}, resource:{}", id, resource);
		facade.updateResource(id, resource);
		return new MessageResource(MessageType.INFO, "Benefit updated");
	}

	@Override
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@RequestMapping(value = Request.ID, method = RequestMethod.DELETE)
	public MessageResource removeResource(@PathVariable("id") final Long id) {
		LOGGER.info("Removing benefit:{}", id);
		facade.removeResource(id);
		return new MessageResource(MessageType.INFO, "Benefit removed");
	}

}


text:
package uk.gov.register.protocols.classpath;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class ClasspathURLConnectionTest {
    @Before
    public void setProtocolHandlers(){
        System.setProperty("java.protocol.handler.pkgs", "uk.gov.register.protocols");
    }

    @Test
    public void shouldGetInputStream() throws Exception {
        URL url = new URL("classpath://config/external-fields.json");
        ClasspathURLConnection connection = new ClasspathURLConnection(url);
        InputStream inputStream = connection.getInputStream();
        Scanner scanner = new Scanner(inputStream);
        String line1 = scanner.nextLine();
        assertThat(line1, is("{"));
        String line2 = scanner.nextLine();
        assertThat(line2, is("  \"country\": {"));

    }

    @Test(expected = MalformedURLException.class)
    public void shouldFailForInvalidScheme() throws Exception{
        URL url = new URL("zz:///my-path");
        ClasspathURLConnection connection = new ClasspathURLConnection(url);
    }

    @After
    public void unsetProtocolHandlers(){
        System.clearProperty("java.protocol.handler.pkgs");
    }
}


text:
var common     = require('../common');
var assert     = require('assert');

assert.equal(
	common.Select().from('table1').order('col').build(),
	"SELECT * FROM `table1` ORDER BY `col` ASC"
);

assert.equal(
	common.Select().from('table1').order('col', 'A').build(),
	"SELECT * FROM `table1` ORDER BY `col` ASC"
);

assert.equal(
	common.Select().from('table1').order('col', 'Z').build(),
	"SELECT * FROM `table1` ORDER BY `col` DESC"
);

assert.equal(
	common.Select().from('table1').order('col').order('col2', 'Z').build(),
	"SELECT * FROM `table1` ORDER BY `col` ASC, `col2` DESC"
);

assert.equal(
	common.Select().from('table1').order('col', []).build(),
	"SELECT * FROM `table1` ORDER BY col"
);

assert.equal(
	common.Select().from('table1').order('?? DESC', ['col']).build(),
	"SELECT * FROM `table1` ORDER BY `col` DESC"
);

assert.equal(
	common.Select().from('table1').order('ST_Distance(??, ST_GeomFromText(?,4326))', ['geopoint', 'POINT(-68.3394 27.5578)']).build(),
	"SELECT * FROM `table1` ORDER BY ST_Distance(`geopoint`, ST_GeomFromText('POINT(-68.3394 27.5578)',4326))"
);


text:
module Fastlane
  module Actions
    class ClipboardAction < Action
      def self.run(params)
        UI.message("Storing '#{params[:value]}' in the clipboard 🎨")

        `echo "#{params[:value]}" | tr -d '\n' | pbcopy` # we don't use `sh`, as the command looks ugly
      end

      #####################################################
      # @!group Documentation
      #####################################################

      def self.description
        "Copies a given string into the clipboard. Works only on macOS"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :value,
                                       env_name: "FL_CLIPBOARD_VALUE",
                                       description: "The string that should be copied into the clipboard")
        ]
      end

      def self.authors
        ["KrauseFx"]
      end

      def self.is_supported?(platform)
        true
      end

      def self.example_code
        [
          'clipboard(value: "https://github.com/fastlane/fastlane/tree/master/fastlane")',
          'clipboard(value: lane_context[SharedValues::HOCKEY_DOWNLOAD_LINK] || "")'
        ]
      end

      def self.category
        :misc
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mylocals">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
    <!-- Complies with: https://developer.android.com/guide/topics/location/strategies.html#Permission -->
    <uses-feature android:name="android.hardware.location.gps" />

    <application
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.mylocals.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustNothing"></activity>
        <activity
            android:name="com.mylocals.SavedListActivity"
            android:label="Saved List"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.mylocals.AboutActivity"
            android:label="About"
            android:screenOrientation="portrait" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyD4xwdTy24XH55ifN2CFLls5jFiTQYbVS4" />

        <activity
            android:name="com.mylocals.ActivityRegistration"
            android:label="@string/title_activity_activity_registration">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.mylocals.MapsActivity"
            android:label="@string/title_activity_maps"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name="com.mylocals.SettingsActivity"
            android:label="@string/title_activity_settings"></activity>
    </application>

</manifest>


text:
#ifndef __BL_STRINGBUFFER__
#define __BL_STRINGBUFFER__

#include <stddef.h>
#include <bl/base/allocator.h>

/*------------------------------------------------------------------------------
 A structure representing a buffer containing a string.

 Notice that a deallocated buffer is expressed by str = NULL. maxlen = 0 with a
 non-NULL "str" means that "str" has capacity only for the null termination
------------------------------------------------------------------------------*/
typedef struct bl_strbuf {
  char*  str;    /* string */
  size_t len;    /* actual string length (excluding null termination )*/
  size_t maxlen; /* max/allocated length (excluding null termination )*/
}
bl_strbuf;
/*----------------------------------------------------------------------------*/
static inline bl_strbuf bl_strbuf_init (char* str, size_t len, size_t maxlen)
{
  bl_strbuf b = { str, len, maxlen };
  return b;
}
/*------------------------------------------------------------------------------
 A structure representing a buffer containing a string and the allocator that
 generated it.
------------------------------------------------------------------------------*/
typedef struct bl_dstrbuf {
  char*  str;    /* string */
  size_t len;    /* actual string length (excluding null termination )*/
  size_t maxlen; /* max/allocated length (excluding null termination )*/
  bl_alloc_tbl const* alloc; /* allocator used to allocate "str" */
}
bl_dstrbuf;
/*----------------------------------------------------------------------------*/
static inline bl_dstrbuf bl_dstrbuf_init(
  char* str, size_t len, size_t maxlen, struct bl_alloc_tbl const* alloc
  )
{
  bl_dstrbuf b = { str, len, maxlen, alloc };
  return b;
}
/*----------------------------------------------------------------------------*/
static inline void bl_dstrbuf_try_trim (bl_dstrbuf* b, size_t threshold_len)
{
  size_t maxlen = b->len + threshold_len;
  if (maxlen <= b->maxlen || maxlen <= b->len || !b->str) {
    /* not required or overflow */
    return;
  }
  void* ptr = bl_realloc (b->alloc, b->str, maxlen + 1);
  if (ptr) {
    b->maxlen = maxlen;
    b->str    = (char*) ptr;
  }
}
/*----------------------------------------------------------------------------*/
#endif


text:
package org.apache.struts2.convention.actions.parentpackage.sub;

import org.apache.struts2.convention.actions.parentpackage.PackageLevelParentPackageAction;

/**
 * Extends a class the has a @ParentPackage at the package level
 */
public class PackageLevelParentPackageChildAction extends PackageLevelParentPackageAction {
}


text:
import ConfigParser

from csflog import csflog

class csfCfg(object):

    # Init attribute
    def __init__(self, cfgfile = ''):
        csflog.init_logger("../logs/wechat.log")
        self._cfgfile = cfgfile
        self._parser  = ConfigParser.ConfigParser()

    # Init the configure file
    def _init(self, cfgfile):
        self._cfgfile = cfgfile
        self._read()
        csflog.info("Configure file is %s" % self._cfgfile)

    # Read a configure file
    def _read(self):
        self._parser.read(self._cfgfile)

    # Get Sections in configure file
    def _sections(self):
        return self._parser.sections()

    # Get Options for one Section
    def _options(self, section):
        return self._parser.options(section)

    # Get Key-Value pairs for one Section
    def _items(self, section):
        return self._parser.items(section)

    # Get the Value of one Option in Section
    def _get(self, section, option):
        return self._parser.get(section, option)

    # Dump all info
    def _dump(self):
        print
        print "%-10s | %-10s | %-10s" \
            % ( 'Section', 'Option', 'Value')
        print "%-10s | %-10s | %-10s" \
            % ( '-'*10, '-'*10, '-'*10)
        for section in self._sections():
            for option in self._options(section):
                value = self._get(section,option)
                print "%-10s | %-10s | %-10s" \
                    % ( section, option, value)
        print
        print self._get('logs', 'logfile')

# csfcfg global hanlder
csfcfg = csfCfg()

def _test():
    cfg = csfCfg("../cfg.ini")
    cfg._dump()

if __name__ == "__main__":
    _test()


text:
/* globals module require __dirname Promise */

const path = require("path");

const low = require("lowdb");
const db = low(path.join(__dirname, "../db/db.json"));
db._.mixin(require("underscore-db"));
db.defaults({
    books: []
}).value();

module.exports = {
    getAllBooks() {
        let books = db.get("books")
            .value();
        return Promise.resolve(books);
    },
    getBookById(id) {
        let book = db.get("books")
            .getById(id)
            .value();
        return Promise.resolve(book);
    },
    addBook(book) {
        const newBook = db.get("books")
            .insert(book)
            .value();
        Promise.resolve(newBook);
    }
};


text:
package de.windowsfreak.testjni.writer;

import de.windowsfreak.testjni.reader.ImageReader;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.function.Predicate;

/**
 * Created by lazer_000 on 25.06.2015.
 */
public class TCPWriter {
    ServerSocketChannel serverSocketChannel;
    boolean running = false;
    Thread thread;
    public LinkedList<TCPWriterInstance> instances = new LinkedList<TCPWriterInstance>();
    public Selector selector;
    Object waitRead = new Object();
    class TCPWriterInstance {
        SocketChannel socketChannel;
        public Selector selector;
        TCPWriterInstance(SocketChannel socketChannel) throws IOException {
            this.socketChannel = socketChannel;
            this.selector = Selector.open();
        }
    }
    public void initialize() throws IOException {
        selector = Selector.open();
        if (serverSocketChannel != null) {
            try {
                shutDown();
            } catch (Exception e) {
                new Exception("Could not close previous ServerSocketChannel", e).printStackTrace();
            }
        }
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9999));
        new Thread() {
            public void run() {
                while(!(this.isInterrupted()))
                {
                    try {
                        SocketChannel sc = TCPWriter.this.serverSocketChannel.accept();
                        sc.configureBlocking(false);
                        sc.register(selector, SelectionKey.OP_READ);
                        TCPWriterInstance instance = new TCPWriterInstance(sc);
                        sc.register(instance.selector, SelectionKey.OP_WRITE);
                        instances.add(instance);
                    } catch (IOException e) {
                        System.out.println("TCP Server stopped!"); //e.printStackTrace();
                        //e.printStackTrace();
                        return;
                    }
                }
            }
        }.start();
    }
    public ByteBuffer receiveCommandHeader() {
        for (TCPWriterInstance instance : instances) {
            try {
                selector.select();
                Set readyKeys = selector.selectedKeys();
                Iterator iterator = readyKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = (SelectionKey) iterator.next();
                    iterator.remove();
                    if (key.isReadable()) {
                        SocketChannel client = (SocketChannel) key.channel();
                        synchronized(header) {
                            header.clear();
                            int bytesRead = 0, headerBytes = 0;
                            while (headerBytes < headerSize) {
                                bytesRead = client.read(header);
                                headerBytes += bytesRead;
                                if (bytesRead < 1) break;
                            }
                            if (headerBytes < 8) continue;
                            header.flip();
                            return header;
                        }
                    }
                }
            } catch (Exception e) {
                new Exception("Could not receive command headers", e).printStackTrace();
            }
        }
        return null;
    }

    public void shutDown() throws IOException {
        for (TCPWriterInstance instance : instances) {
            try {
                instance.socketChannel.close();
            } catch (Exception e) {
                new Exception("Could not close SocketChannel", e).printStackTrace();
            }
        }
        instances.clear();
        try {
            serverSocketChannel.close();
        } finally {
            serverSocketChannel = null;
        }
    }

    final int headerSize = 8;
    ByteBuffer header = ByteBuffer.allocateDirect(headerSize);
    public boolean writeImage(int x, int y, ByteBuffer in) {
        boolean errors = false;
        TCPWriterInstance erroneous = null;
        synchronized(in) {
            in.rewind();
            int size = in.remaining();
            synchronized(header) {
                header.clear();
                header.putInt(size);
                header.putShort((short) x);
                header.putShort((short) y);
                header.flip();
                int totalBytes = header.remaining() + size;
                // not thread safe !!!
                for (TCPWriterInstance instance : instances) {
                    try {
                        SocketChannel channel = instance.socketChannel;
                        header.rewind();
                        in.rewind();
                        int totalWritten = 0;
                        while (totalWritten < totalBytes) {
                            instance.selector.select();
                            Set readyKeys = instance.selector.selectedKeys();
                            Iterator iterator = readyKeys.iterator();
                            while (iterator.hasNext()) {
                                SelectionKey key = (SelectionKey) iterator.next();
                                iterator.remove();
                                if (key.isWritable()) {
                                    SocketChannel client = (SocketChannel) key.channel();
                                    int bytesWritten = (int) client.write(new ByteBuffer[]{header, in});
                                    totalWritten += bytesWritten;
                                    if (bytesWritten < 0) throw new Exception("Could not complete writing!");
                                }
                            }
                        }
                    } catch (Exception e) {
                        new Exception("Could not write to SocketChannel", e).printStackTrace();
                        erroneous = instance;
                        errors = true;
                    }
                }
            }
        }
        if (errors) {
            instances.remove(erroneous);
            instances.removeIf(new Predicate<TCPWriterInstance>() {
                @Override
                public boolean test(TCPWriterInstance instance) {
                    return !instance.socketChannel.isOpen();
                }
            });
        }
        return !errors;
    }
}


text:
ABSL_FLAG(int, duration, 20,
          "Duration of the random walk test measured in seconds.");

ABSL_FLAG(int, clients, 2, "The number of random walk clients in the test.");

ABSL_FLAG(bool, multinode, false,
          "If enabled, run the random walk test in multinode mode where "
          "out-of-band communication will be done using gRPC.");


text:
require 'support/unit_test_case'

module Tweetwine::Test::Unit

class UrlShortenerTest < TestCase
  before do
    mock_http
  end

  describe "for initialization" do
    it "raises exception if service should be disabled" do
      assert_raises(RuntimeError) do
        UrlShortener.new(
          :disable          => true,
          :service_url      => "http://shorten.it/create",
          :url_param_name   => "url",
          :xpath_selector   => "//input[@id='short_url']/@value")
      end
    end

    it "raises exception if service URL is not given" do
      assert_raises(RequiredOptionError) do
        UrlShortener.new(
          :service_url      => nil,
          :url_param_name   => "url",
          :xpath_selector   => "//input[@id='short_url']/@value")
      end
    end

    it "raises exception if URL parameter name is not given" do
      assert_raises(RequiredOptionError) do
        UrlShortener.new(
          :service_url      => "http://shorten.it/create",
          :url_param_name   => nil,
          :xpath_selector   => "//input[@id='short_url']/@value")
      end
    end

    it "raises exception if XPath selector is not given" do
      assert_raises(RequiredOptionError) do
        UrlShortener.new(
          :service_url      => "http://shorten.it/create",
          :url_param_name   => "url",
          :xpath_selector   => nil)
      end
    end

    it "fallbacks to use GET method if method is not given explicitly" do
      url_shortener = UrlShortener.new(
        :service_url      => "http://shorten.it/create",
        :url_param_name   => "url",
        :xpath_selector   => "//input[@id='short_url']/@value")
      @http.expects(:get)
      url_shortener.shorten("http://www.ruby-doc.org/core/")
    end

    it "raises exception if given HTTP request method is unsupported" do
      assert_raises(CommandLineError) do
        UrlShortener.new(
          :method           => "put",
          :service_url      => "http://shorten.it/create",
          :url_param_name   => "url",
          :xpath_selector   => "//input[@id='short_url']/@value")
      end
    end
  end

  describe "when configured for HTTP GET" do
    it "uses parameters as URL query parameters, with just the URL parameter" do
      url_shortener = UrlShortener.new(
        :method           => "get",
        :service_url      => "http://shorten.it/create",
        :url_param_name   => "url",
        :xpath_selector   => "//input[@id='short_url']/@value")
      @http.expects(:get).
        with("http://shorten.it/create?url=http://www.ruby-doc.org/core/")
      url_shortener.shorten("http://www.ruby-doc.org/core/")
    end

    it "uses parameters as URL query parameters, with additional extra parameters" do
      url_shortener = UrlShortener.new(
        :method           => "get",
        :service_url      => "http://shorten.it/create",
        :url_param_name   => "url",
        :extra_params     => {
          :token => "xyz"
        },
        :xpath_selector   => "//input[@id='short_url']/@value")
      @http.expects(:get).
        with("http://shorten.it/create?token=xyz&url=http://www.ruby-doc.org/core/")
      url_shortener.shorten("http://www.ruby-doc.org/core/")
    end
  end

  describe "when configured for HTTP POST" do
    it "uses parameters as payload, with just the URL parameter" do
      url_shortener = UrlShortener.new(
        :method           => "post",
        :service_url      => "http://shorten.it/create",
        :url_param_name   => "url",
        :xpath_selector   => "//input[@id='short_url']/@value")
      @http.expects(:post).
        with("http://shorten.it/create", {:url => "http://www.ruby-doc.org/core/"})
      url_shortener.shorten("http://www.ruby-doc.org/core/")
    end

    it "uses parameters as payload, with additional extra parameters" do
      url_shortener = UrlShortener.new(
        :method           => "post",
        :service_url      => "http://shorten.it/create",
        :url_param_name   => "url",
        :extra_params     => {
          :token => "xyz"
        },
        :xpath_selector   => "//input[@id='short_url']/@value")
      @http.expects(:post).
        with("http://shorten.it/create",
          :token => "xyz",
          :url   => "http://www.ruby-doc.org/core/")
      url_shortener.shorten("http://www.ruby-doc.org/core/")
    end
  end

  describe "in erroenous network situations" do
    it "passes exceptions through" do
      url_shortener = UrlShortener.new(
        :method           => "post",
        :service_url      => "http://shorten.it/create",
        :url_param_name   => "url",
        :xpath_selector   => "//input[@id='short_url']/@value")
      @http.expects(:post).
        with("http://shorten.it/create", :url => "http://www.ruby-doc.org/core/").
        raises(HttpError.new(404, "Not Found"))
      assert_raises(HttpError) { url_shortener.shorten("http://www.ruby-doc.org/core/") }
    end
  end
end

end


text:
LEVEL = ../../../make
OBJCXX_SOURCES := main.mm myobject.mm
include $(LEVEL)/Makefile.rules

# myobject.o needs to be built without debug info
myobject.o: myobject.mm
	$(CXX) -c -o $@ $<


text:
"""Plugwise platform for Home Assistant Core."""
from __future__ import annotations

import asyncio
from typing import Any

from aiohttp import ClientConnectionError
from plugwise.exceptions import InvalidAuthentication, PlugwiseException
from plugwise.smile import Smile

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession

from .const import (
    DEFAULT_PORT,
    DEFAULT_USERNAME,
    DOMAIN,
    LOGGER,
    PLATFORMS_GATEWAY,
    Platform,
)
from .coordinator import PlugwiseDataUpdateCoordinator

async def async_setup_entry_gw(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Plugwise Smiles from a config entry."""
    await er.async_migrate_entries(hass, entry.entry_id, async_migrate_entity_entry)

    websession = async_get_clientsession(hass, verify_ssl=False)
    api = Smile(
        host=entry.data[CONF_HOST],
        username=entry.data.get(CONF_USERNAME, DEFAULT_USERNAME),
        password=entry.data[CONF_PASSWORD],
        port=entry.data.get(CONF_PORT, DEFAULT_PORT),
        timeout=30,
        websession=websession,
    )

    try:
        connected = await api.connect()
    except InvalidAuthentication:
        LOGGER.error("Invalid username or Smile ID")
        return False
    except (ClientConnectionError, PlugwiseException) as err:
        raise ConfigEntryNotReady(
            f"Error while communicating to device {api.smile_name}"
        ) from err
    except asyncio.TimeoutError as err:
        raise ConfigEntryNotReady(
            f"Timeout while connecting to Smile {api.smile_name}"
        ) from err

    if not connected:
        raise ConfigEntryNotReady("Unable to connect to Smile")
    api.get_all_devices()

    if entry.unique_id is None and api.smile_version[0] != "1.8.0":
        hass.config_entries.async_update_entry(entry, unique_id=api.smile_hostname)

    coordinator = PlugwiseDataUpdateCoordinator(hass, api)
    await coordinator.async_config_entry_first_refresh()
    migrate_sensor_entities(hass, coordinator)

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator

    device_registry = dr.async_get(hass)
    device_registry.async_get_or_create(
        config_entry_id=entry.entry_id,
        identifiers={(DOMAIN, str(api.gateway_id))},
        manufacturer="Plugwise",
        model=api.smile_model,
        name=api.smile_name,
        sw_version=api.smile_version[0],
    )

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS_GATEWAY)

    return True

async def async_unload_entry_gw(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    if unload_ok := await hass.config_entries.async_unload_platforms(
        entry, PLATFORMS_GATEWAY
    ):
        hass.data[DOMAIN].pop(entry.entry_id)
    return unload_ok

@callback
def async_migrate_entity_entry(entry: er.RegistryEntry) -> dict[str, Any] | None:
    """Migrate Plugwise entity entries.

    - Migrates unique ID from old relay switches to the new unique ID
    """
    if entry.domain == Platform.SWITCH and entry.unique_id.endswith("-plug"):
        return {"new_unique_id": entry.unique_id.replace("-plug", "-relay")}

    # No migration needed
    return None

def migrate_sensor_entities(
    hass: HomeAssistant,
    coordinator: PlugwiseDataUpdateCoordinator,
) -> None:
    """Migrate Sensors if needed."""
    ent_reg = er.async_get(hass)

    # Migrating opentherm_outdoor_temperature to opentherm_outdoor_air_temperature sensor
    for device_id, device in coordinator.data.devices.items():
        if device.get("dev_class") != "heater_central":
            continue

        old_unique_id = f"{device_id}-outdoor_temperature"
        if entity_id := ent_reg.async_get_entity_id(
            Platform.SENSOR, DOMAIN, old_unique_id
        ):
            new_unique_id = f"{device_id}-outdoor_air_temperature"
            LOGGER.debug(
                "Migrating entity %s from old unique ID '%s' to new unique ID '%s'",
                entity_id,
                old_unique_id,
                new_unique_id,
            )
            ent_reg.async_update_entity(entity_id, new_unique_id=new_unique_id)


text:
package fr.liglab.adele.cream.it.entity.test.synchronisation;

import fr.liglab.adele.cream.annotations.entity.ContextEntity;
import fr.liglab.adele.cream.it.entity.synchronisation.ContextEntitySynchro;
import fr.liglab.adele.cream.it.entity.synchronisation.ServiceSynchroSpec;
import fr.liglab.adele.cream.it.entity.test.EntityBaseCommonConfig;
import org.apache.felix.ipojo.ConfigurationException;
import org.apache.felix.ipojo.MissingHandlerException;
import org.apache.felix.ipojo.UnacceptableConfiguration;
import org.junit.Test;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.ServiceReference;

import static org.assertj.core.api.Assertions.assertThat;

@ExamReactorStrategy(PerMethod.class)
public class EntitySynchroTest extends EntityBaseCommonConfig {

    @Test
    public void testDirectAccessSVBehavior() throws MissingHandlerException, UnacceptableConfiguration, ConfigurationException {
        ServiceSynchroSpec serviceObj1 = createContextEntity();

        ServiceReference serviceReference = osgiHelper.getServiceReference(ServiceSynchroSpec.class);

        assertThat(serviceObj1.getterMethodParam1()).isEqualTo(ServiceSynchroSpec.PARAM_1_INIT_VALUE).overridingErrorMessage("first getter call didn't return the right value");
        assertThat(serviceReference.getProperty(ContextEntity.State.id(ServiceSynchroSpec.class, ServiceSynchroSpec.PARAM_1_DIRECTACCESS))).isEqualTo(ServiceSynchroSpec.PARAM_1_INIT_VALUE).overridingErrorMessage("Service property isn't set to initial value");

        boolean newValue = !ServiceSynchroSpec.PARAM_1_INIT_VALUE;
        serviceObj1.setterMethodParam1(newValue);

        assertThat(serviceObj1.getterMethodParam1()).isEqualTo(newValue);
        assertThat(serviceReference.getProperty(ContextEntity.State.id(ServiceSynchroSpec.class, ServiceSynchroSpec.PARAM_1_DIRECTACCESS))).isEqualTo(newValue).overridingErrorMessage("Service property isn't set to the modified value");

    }

    @Test
    public void testPullSVBehavior() throws MissingHandlerException, UnacceptableConfiguration, ConfigurationException {
        createContextEntity();

        ServiceSynchroSpec serviceObj1 = osgiHelper.getServiceObject(ServiceSynchroSpec.class);
        ServiceReference serviceReference = osgiHelper.getServiceReference(ServiceSynchroSpec.class);

        assertThat(serviceObj1.getterMethodParam2()).isEqualTo(ServiceSynchroSpec.PARAM_2_VALUE);
        assertThat(serviceReference.getProperty(ContextEntity.State.id(ServiceSynchroSpec.class, ServiceSynchroSpec.PARAM_2_PULL))).isEqualTo(ServiceSynchroSpec.PARAM_2_VALUE).overridingErrorMessage("Service property isn't set to the pulled value");

        serviceObj1.setterMethodParam2(!ServiceSynchroSpec.PARAM_2_VALUE);

        assertThat(serviceObj1.getterMethodParam2()).isEqualTo(ServiceSynchroSpec.PARAM_2_VALUE);
        assertThat(serviceReference.getProperty(ContextEntity.State.id(ServiceSynchroSpec.class, ServiceSynchroSpec.PARAM_2_PULL))).isEqualTo(ServiceSynchroSpec.PARAM_2_VALUE).overridingErrorMessage("Service property isn't set to the pulled value");

    }

    @Test
    public void testApplySVBehavior() throws MissingHandlerException, UnacceptableConfiguration, ConfigurationException {
        ServiceSynchroSpec serviceObj1 = createContextEntity();

        ServiceReference serviceReference = osgiHelper.getServiceReference(ServiceSynchroSpec.class);

        assertThat(serviceObj1.getterMethodParam3ReturnAlwaysNull()).isEqualTo(null);
        assertThat(serviceObj1.getterMethodParam3WithChange()).isEqualTo(true);
        assertThat(serviceReference.getProperty(ContextEntity.State.id(ServiceSynchroSpec.class, ServiceSynchroSpec.PARAM_3_APPLY))).isEqualTo(null);

        serviceObj1.setterMethodParam3(false);
        assertThat(serviceObj1.getterMethodParam3ReturnAlwaysNull()).isEqualTo(null);
        assertThat(serviceObj1.getterMethodParam3WithChange()).isEqualTo(false);
        assertThat(serviceReference.getProperty(ContextEntity.State.id(ServiceSynchroSpec.class, ServiceSynchroSpec.PARAM_3_APPLY))).isEqualTo(null);

    }

    @Test
    public void testPullApplySVBehavior() throws MissingHandlerException, UnacceptableConfiguration, ConfigurationException {
        ServiceSynchroSpec serviceObj1 = createContextEntity();

        ServiceReference serviceReference = osgiHelper.getServiceReference(ServiceSynchroSpec.class);

        assertThat(serviceObj1.getterMethodParam5()).isEqualTo(true);
        assertThat(serviceObj1.getterMethodParam5WithChange()).isEqualTo(true);

        serviceObj1.setterMethodParam5(false);
        assertThat(serviceObj1.getterMethodParam5WithChange()).isEqualTo(false);

        /**
         * TODO : Test failed due to iPOJO bug, bugfix proposed in FELIX-5314
         *assertThat(serviceObj1.getterMethodParam5()).isEqualTo(true);
         */

        assertThat(serviceObj1.getterMethodParam5WithChange()).isEqualTo(false);

    }

    @Test
    public void testPeriodicPullSVBehavior() throws MissingHandlerException, UnacceptableConfiguration, ConfigurationException {
        ServiceSynchroSpec serviceObj1 = createContextEntity();

        ServiceReference serviceReference = osgiHelper.getServiceReference(ServiceSynchroSpec.class);
/**
 * TODO : Test fail, check init phase of behavior
 long firstValue = (long) serviceReference.getProperty(ContextEntity.State.id(BehaviorSpec1.class,BehaviorSpec1.PARAM_4_PERIODICPULL));
 **/
        try {
            Thread.currentThread().sleep(2500);
        } catch (InterruptedException e) {
            assertThat(true).isEqualTo(false);
        }

        long secondValue = (long) serviceReference.getProperty(ContextEntity.State.id(ServiceSynchroSpec.class, ServiceSynchroSpec.PARAM_4_PERIODICPULL));

        try {
            Thread.currentThread().sleep(2500);
        } catch (InterruptedException e) {
            assertThat(true).isEqualTo(false);
        }
        long thirdValue = (long) serviceReference.getProperty(ContextEntity.State.id(ServiceSynchroSpec.class, ServiceSynchroSpec.PARAM_4_PERIODICPULL));

        /**
         * see TODO
         assertThat(secondValue).isNotEqualTo(firstValue);
         **/
        assertThat(secondValue).isNotEqualTo(thirdValue);

    }

    private ServiceSynchroSpec createContextEntity() throws MissingHandlerException, UnacceptableConfiguration, ConfigurationException {
        contextHelper.getContextEntityHelper().createContextEntity(ContextEntitySynchro.class.getName(), "ContextEntityTest", null);
        return osgiHelper.getServiceObject(ServiceSynchroSpec.class);
    }
}


text:
var TWEEN_uncompressed = require('../../src/Tween.js');
var TWEEN_min = require('../../build/tween.min.js');
var getTests = require('./tests');

module.exports = {
	'tween': getTests(TWEEN_uncompressed),
	'tween_min': getTests(TWEEN_min)
};


text:
#include "tests_common.hpp"

// Test construction and clear() postconditions
template<class CharT, class DataT>
int check_empty(containers::ternary_tree<std::basic_string<CharT>, DataT>& tst)
{
	typedef containers::ternary_tree<std::basic_string<CharT>, DataT> Tst;

	long result = errors_counter();
	BOOST_CHECK(tst.empty());
	BOOST_CHECK(tst.node_count() == 0);
	BOOST_CHECK(tst.item_count() == 0);

	Tst::iterator i2(tst.begin());
	BOOST_CHECK(i2 == tst.end());

	return errors_counter() - result;
}

// insert "a" = 1, "b" = 2 etc, out of order.
// test that they are ordered and have correct value.
// insert b, d, f by operator[]
// iterator used to check order of strings.
template<class CharT>
int basic_insertion_test()
{
	long result = errors_counter();

	typedef containers::ternary_tree<std::basic_string<CharT>, int> Tst;
	Tst tst;

	const char* strings[] = { "\0", "aa", "aab", "aac", "add", "aee", "bab" };
	widen<CharT> w;

	// Construction postconditions
	check_empty(tst);

	// Standard insert()
	tst.insert(std::make_pair(w(strings[1]), 1));
	tst.insert(std::make_pair(w(strings[5]), 5));

	std::pair<std::basic_string<CharT>, int> inval(w(strings[3]), 3);
	std::pair<Tst::iterator, bool> vr = tst.insert(inval);
	BOOST_CHECK(vr.first != tst.end());
	BOOST_CHECK(vr.second == true);
	vr = tst.insert(inval);
	BOOST_CHECK(vr.first != tst.end());
	BOOST_CHECK(vr.second == false);

	BOOST_CHECK((*tst.find(w(strings[1]))) == 1);
	BOOST_CHECK((*tst.find(w(strings[3]))) == 3);
	BOOST_CHECK((*tst.find(w(strings[5]))) == 5);

	BOOST_CHECK(tst.item_count() == 3);
	BOOST_CHECK(tst.total_key_length() == 3*3-1);

	// In present version, no reassignment
	tst.insert(std::make_pair(w(strings[1]), 4));
	BOOST_CHECK((*tst.find(w(strings[1]))) == 1);
	BOOST_CHECK(tst.item_count() == 3);
	BOOST_CHECK(tst.total_key_length() == 3*3-1);

	// reference_proxy insert()
	tst[w(strings[2])] = 2;
	tst[w(strings[6])] = 6;
	tst[w(strings[4])] = 4;
	BOOST_CHECK(tst[w(strings[2])] == 2);
	BOOST_CHECK(tst[w(strings[4])] == 4);
	BOOST_CHECK(tst[w(strings[6])] == 6);

	BOOST_CHECK(tst.item_count() == 6);
	BOOST_CHECK(tst.total_key_length() == 6*3-1);

	// Now do reassignment
	tst[w(strings[1])] = 7;
	BOOST_CHECK((*tst.find(w(strings[1]))) == 7);  //1);
	tst[w(strings[1])] = 1;

	// iterator used to check sort order of strings
	Tst::const_iterator it(tst.begin());
	int expect_val = 1;
	while (it != tst.end()) {
		Tst::value_type val = *it;
		// string == "a", "b" etc
		BOOST_CHECK(expect_val == 1 || it.key().size() == 3);
		BOOST_CHECK(it.key() == w(strings[expect_val]));
		// value is 1, 2 etc
		BOOST_CHECK(val == expect_val++);
		++it;
	}
	BOOST_CHECK(expect_val == int(tst.item_count() + 1));

	// Test clear() postconditions
	tst.clear();

	check_empty(tst);

	return errors_counter() - result;
}

#endif


text:
 * Twitter plugin for [Wox](https://www.getwox.com/)

## Usage
 * tw \<tweet words>
  * First tweet is performed after authentification.
    * Please enter your password in the text form.

  ![image](https://raw.github.com/wiki/takeru0911/Wox.Plugin.Twitter/images/usage.png)


text:
import {User} from '../user/user.model'
export interface SessionData{

  isLogged:boolean;
  isAdmin:boolean;
  userLogged: User;
  authToken: string;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:theme="@style/ToolbarStyle"
            app:title="@string/device"/>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/swipe_refresh_layout"
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </android.support.v7.widget.RecyclerView>

        </android.support.v4.widget.SwipeRefreshLayout>

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/fab_add_ds"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|right"
            android:layout_marginBottom="12dp"
            android:layout_marginRight="16dp"
            android:src="@drawable/ic_add"
            app:fab_elevationCompat="4dp"/>

    </FrameLayout>

</LinearLayout>


text:
function initClick(path, domain){
    $("#content-body")
        .on('change', '.select', function(){
            var status = $(".select-status").val();
            var userTypeId = $(".select-userType").val();
            var pageSize = $("#record-pageSize").text();
            var data = {
                status: status,
                pageIndex: 1,
                userTypeId: userTypeId,
                pageSize: pageSize
            }
            getList(path, data, domain);
        })
        .on('click', '.edit', function(){

        })
        .on('click', '.remove', function(){
            var id = $(this).closest("tr").attr("data");
            console.log(id);
            var data = {
                id: id,
                status: 0
            };
            updateById(path, data);
            reloadPage(path, domain);
        })
        .on('click', '.recover', function(){
            var id = $(this).closest("tr").attr("data");
            var data = {
                id: id,
                status: 1
            };
            updateById(path, data);
            reloadPage(path, domain);
        })
        .on('click', '.delete',  function(){
            var id = $(this).closest("tr").attr("data");
            deleteById(path, id);
        })
}

$(document).ready(function(){
    var path = "user";
    var domain = "#user-list";
    initClick(path, domain);
    $(".select-status").trigger('change');
})


text:
package com.mikephil.charting.renderer;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Path;
import android.graphics.PointF;

import com.mikephil.charting.charts.BarChart;
import com.mikephil.charting.components.LimitLine;
import com.mikephil.charting.components.XAxis;
import com.mikephil.charting.components.XAxis.XAxisPosition;
import com.mikephil.charting.data.BarData;
import com.mikephil.charting.utils.FSize;
import com.mikephil.charting.utils.Transformer;
import com.mikephil.charting.utils.Utils;
import com.mikephil.charting.utils.ViewPortHandler;

import java.util.List;

public class XAxisRendererHorizontalBarChart extends XAxisRendererBarChart {

    public XAxisRendererHorizontalBarChart(ViewPortHandler viewPortHandler, XAxis xAxis,
            Transformer trans, BarChart chart) {
        super(viewPortHandler, xAxis, trans, chart);
    }

    @Override
    public void computeAxis(float xValAverageLength, List<String> xValues) {

        mAxisLabelPaint.setTypeface(mXAxis.getTypeface());
        mAxisLabelPaint.setTextSize(mXAxis.getTextSize());
        mXAxis.setValues(xValues);

        String longest = mXAxis.getLongestLabel();

        final FSize labelSize = Utils.calcTextSize(mAxisLabelPaint, longest);

        final float labelWidth = (int)(labelSize.width + mXAxis.getXOffset() * 3.5f);
        final float labelHeight = labelSize.height;

        final FSize labelRotatedSize = Utils.getSizeOfRotatedRectangleByDegrees(
                labelSize.width,
                labelHeight,
                mXAxis.getLabelRotationAngle());

        mXAxis.mLabelWidth = Math.round(labelWidth);
        mXAxis.mLabelHeight = Math.round(labelHeight);
        mXAxis.mLabelRotatedWidth = (int)(labelRotatedSize.width + mXAxis.getXOffset() * 3.5f);
        mXAxis.mLabelRotatedHeight = Math.round(labelRotatedSize.height);
    }

    @Override
    public void renderAxisLabels(Canvas c) {

        if (!mXAxis.isEnabled() || !mXAxis.isDrawLabelsEnabled())
            return;

        float xoffset = mXAxis.getXOffset();

        mAxisLabelPaint.setTypeface(mXAxis.getTypeface());
        mAxisLabelPaint.setTextSize(mXAxis.getTextSize());
        mAxisLabelPaint.setColor(mXAxis.getTextColor());

        if (mXAxis.getPosition() == XAxisPosition.TOP) {

            drawLabels(c, mViewPortHandler.contentRight() + xoffset,
                    new PointF(0.0f, 0.5f));

        } else if (mXAxis.getPosition() == XAxisPosition.TOP_INSIDE) {

            drawLabels(c, mViewPortHandler.contentRight() - xoffset,
                    new PointF(1.0f, 0.5f));

        } else if (mXAxis.getPosition() == XAxisPosition.BOTTOM) {

            drawLabels(c, mViewPortHandler.contentLeft() - xoffset,
                    new PointF(1.0f, 0.5f));

        } else if (mXAxis.getPosition() == XAxisPosition.BOTTOM_INSIDE) {

            drawLabels(c, mViewPortHandler.contentLeft() + xoffset,
                    new PointF(0.0f, 0.5f));

        } else { // BOTH SIDED

            drawLabels(c, mViewPortHandler.contentRight() + xoffset,
                    new PointF(0.0f, 0.5f));
            drawLabels(c, mViewPortHandler.contentLeft() - xoffset,
                    new PointF(1.0f, 0.5f));
        }
    }

    /**
     * draws the x-labels on the specified y-position
     *
     * @param pos
     */
    @Override
    protected void drawLabels(Canvas c, float pos, PointF anchor) {

        final float labelRotationAngleDegrees = mXAxis.getLabelRotationAngle();

        // pre allocate to save performance (dont allocate in loop)
        float[] position = new float[] {
                0f, 0f
        };

        BarData bd = mChart.getData();
        int step = bd.getDataSetCount();

        for (int i = mMinX; i <= mMaxX; i += mXAxis.mAxisLabelModulus) {

            position[1] = i * step + i * bd.getGroupSpace()
                    + bd.getGroupSpace() / 2f;

            // consider groups (center label for each group)
            if (step > 1) {
                position[1] += ((float) step - 1f) / 2f;
            }

            mTrans.pointValuesToPixel(position);

            if (mViewPortHandler.isInBoundsY(position[1])) {

                String label = mXAxis.getValues().get(i);
                drawLabel(c, label, i, pos, position[1], anchor, labelRotationAngleDegrees);
            }
        }
    }

    @Override
    public void renderGridLines(Canvas c) {

        if (!mXAxis.isDrawGridLinesEnabled() || !mXAxis.isEnabled())
            return;

        float[] position = new float[] {
                0f, 0f
        };

        mGridPaint.setColor(mXAxis.getGridColor());
        mGridPaint.setStrokeWidth(mXAxis.getGridLineWidth());

        BarData bd = mChart.getData();
        // take into consideration that multiple DataSets increase mDeltaX
        int step = bd.getDataSetCount();

        for (int i = mMinX; i <= mMaxX; i += mXAxis.mAxisLabelModulus) {

            position[1] = i * step + i * bd.getGroupSpace() - 0.5f;

            mTrans.pointValuesToPixel(position);

            if (mViewPortHandler.isInBoundsY(position[1])) {

                c.drawLine(mViewPortHandler.contentLeft(), position[1],
                        mViewPortHandler.contentRight(), position[1], mGridPaint);
            }
        }
    }

    @Override
    public void renderAxisLine(Canvas c) {

        if (!mXAxis.isDrawAxisLineEnabled() || !mXAxis.isEnabled())
            return;

        mAxisLinePaint.setColor(mXAxis.getAxisLineColor());
        mAxisLinePaint.setStrokeWidth(mXAxis.getAxisLineWidth());

        if (mXAxis.getPosition() == XAxisPosition.TOP
                || mXAxis.getPosition() == XAxisPosition.TOP_INSIDE
                || mXAxis.getPosition() == XAxisPosition.BOTH_SIDED) {
            c.drawLine(mViewPortHandler.contentRight(),
                    mViewPortHandler.contentTop(), mViewPortHandler.contentRight(),
                    mViewPortHandler.contentBottom(), mAxisLinePaint);
        }

        if (mXAxis.getPosition() == XAxisPosition.BOTTOM
                || mXAxis.getPosition() == XAxisPosition.BOTTOM_INSIDE
                || mXAxis.getPosition() == XAxisPosition.BOTH_SIDED) {
            c.drawLine(mViewPortHandler.contentLeft(),
                    mViewPortHandler.contentTop(), mViewPortHandler.contentLeft(),
                    mViewPortHandler.contentBottom(), mAxisLinePaint);
        }
    }

	/**
	 * Draws the LimitLines associated with this axis to the screen.
	 * This is the standard YAxis renderer using the XAxis limit lines.
	 *
	 * @param c
	 */
	@Override
	public void renderLimitLines(Canvas c) {

		List<LimitLine> limitLines = mXAxis.getLimitLines();

		if (limitLines == null || limitLines.size() <= 0)
			return;

		float[] pts = new float[2];
		Path limitLinePath = new Path();

		for (int i = 0; i < limitLines.size(); i++) {

			LimitLine l = limitLines.get(i);

            if(!l.isEnabled())
                continue;

			mLimitLinePaint.setStyle(Paint.Style.STROKE);
			mLimitLinePaint.setColor(l.getLineColor());
			mLimitLinePaint.setStrokeWidth(l.getLineWidth());
			mLimitLinePaint.setPathEffect(l.getDashPathEffect());

			pts[1] = l.getLimit();

			mTrans.pointValuesToPixel(pts);

			limitLinePath.moveTo(mViewPortHandler.contentLeft(), pts[1]);
			limitLinePath.lineTo(mViewPortHandler.contentRight(), pts[1]);

			c.drawPath(limitLinePath, mLimitLinePaint);
			limitLinePath.reset();
			// c.drawLines(pts, mLimitLinePaint);

			String label = l.getLabel();

			// if drawing the limit-value label is enabled
			if (label != null && !label.equals("")) {

				mLimitLinePaint.setStyle(l.getTextStyle());
				mLimitLinePaint.setPathEffect(null);
				mLimitLinePaint.setColor(l.getTextColor());
				mLimitLinePaint.setStrokeWidth(0.5f);
				mLimitLinePaint.setTextSize(l.getTextSize());

                final float labelLineHeight = Utils.calcTextHeight(mLimitLinePaint, label);
                float xOffset = Utils.convertDpToPixel(4f) + l.getXOffset();
                float yOffset = l.getLineWidth() + labelLineHeight + l.getYOffset();

                final LimitLine.LimitLabelPosition position = l.getLabelPosition();

				if (position == LimitLine.LimitLabelPosition.RIGHT_TOP) {

					mLimitLinePaint.setTextAlign(Align.RIGHT);
					c.drawText(label,
                            mViewPortHandler.contentRight() - xOffset,
							pts[1] - yOffset + labelLineHeight, mLimitLinePaint);

				} else if (position == LimitLine.LimitLabelPosition.RIGHT_BOTTOM) {

                    mLimitLinePaint.setTextAlign(Align.RIGHT);
                    c.drawText(label,
                            mViewPortHandler.contentRight() - xOffset,
                            pts[1] + yOffset, mLimitLinePaint);

                } else if (position == LimitLine.LimitLabelPosition.LEFT_TOP) {

                    mLimitLinePaint.setTextAlign(Align.LEFT);
                    c.drawText(label,
                            mViewPortHandler.contentLeft() + xOffset,
                            pts[1] - yOffset + labelLineHeight, mLimitLinePaint);

                } else {

					mLimitLinePaint.setTextAlign(Align.LEFT);
					c.drawText(label,
                            mViewPortHandler.offsetLeft() + xOffset,
							pts[1] + yOffset, mLimitLinePaint);
				}
			}
		}
	}
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'tick_bond'

require 'minitest/autorun'
require 'test_data'


text:
package main

import (
	"net/http"

	"github.com/kataras/go-sessions/v3"
)

var (
	cookieNameForSessionID = "mycookiesessionnameid"
	sess                   = sessions.New(sessions.Config{Cookie: cookieNameForSessionID})
)

func secret(w http.ResponseWriter, r *http.Request) {

	// Check if user is authenticated
	if auth, _ := sess.Start(w, r).GetBoolean("authenticated"); !auth {
		w.WriteHeader(http.StatusForbidden)
		return
	}

	// Print secret message
	w.Write([]byte("The cake is a lie!"))
}

func login(w http.ResponseWriter, r *http.Request) {
	session := sess.Start(w, r)

	// Authentication goes here
	// ...

	// Set user as authenticated
	session.Set("authenticated", true)
}

func logout(w http.ResponseWriter, r *http.Request) {
	session := sess.Start(w, r)

	// Revoke users authentication
	session.Set("authenticated", false)
}

func main() {
	app := http.NewServeMux()

	app.HandleFunc("/secret", secret)
	app.HandleFunc("/login", login)
	app.HandleFunc("/logout", logout)

	http.ListenAndServe(":8080", app)
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Zeitschr. 46: 645 (1888)

#### Original name
Achlya oblongata de Bary, 1888

### Remarks
null