text:
package org.elasticsearch.index.mapper.date;

import org.apache.lucene.analysis.NumericTokenStream.NumericTermAttribute;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.NumericRangeFilter;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.LocaleUtils;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.mapper.*;
import org.elasticsearch.index.mapper.core.DateFieldMapper;
import org.elasticsearch.index.mapper.core.LongFieldMapper;
import org.elasticsearch.index.mapper.core.StringFieldMapper;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.ElasticsearchSingleNodeTest;
import org.elasticsearch.test.TestSearchContext;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;

import java.io.IOException;
import java.util.*;

import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.hamcrest.Matchers.*;

public class SimpleDateMappingTests extends ElasticsearchSingleNodeTest {

    @Test
    public void testAutomaticDateParser() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("properties").endObject()
                .endObject().endObject().string();

        DocumentMapper defaultMapper = mapper(mapping);

        defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                .startObject()
                .field("date_field1", "2011/01/22")
                .field("date_field2", "2011/01/22 00:00:00")
                .field("wrong_date1", "-4")
                .field("wrong_date2", "2012/2")
                .field("wrong_date3", "2012/test")
                .endObject()
                .bytes());

        FieldMapper<?> fieldMapper = defaultMapper.mappers().smartNameFieldMapper("date_field1");
        assertThat(fieldMapper, instanceOf(DateFieldMapper.class));
        fieldMapper = defaultMapper.mappers().smartNameFieldMapper("date_field2");
        assertThat(fieldMapper, instanceOf(DateFieldMapper.class));

        fieldMapper = defaultMapper.mappers().smartNameFieldMapper("wrong_date1");
        assertThat(fieldMapper, instanceOf(StringFieldMapper.class));
        fieldMapper = defaultMapper.mappers().smartNameFieldMapper("wrong_date2");
        assertThat(fieldMapper, instanceOf(StringFieldMapper.class));
        fieldMapper = defaultMapper.mappers().smartNameFieldMapper("wrong_date3");
        assertThat(fieldMapper, instanceOf(StringFieldMapper.class));
    }

    @Test
    public void testParseLocal() {
        assertThat(Locale.GERMAN, equalTo(LocaleUtils.parse("de")));
        assertThat(Locale.GERMANY, equalTo(LocaleUtils.parse("de_DE")));
        assertThat(new Locale("de","DE","DE"), equalTo(LocaleUtils.parse("de_DE_DE")));

        try {
            LocaleUtils.parse("de_DE_DE_DE");
            fail();
        } catch(ElasticsearchIllegalArgumentException ex) {
            // expected
        }
        assertThat(Locale.ROOT,  equalTo(LocaleUtils.parse("")));
        assertThat(Locale.ROOT,  equalTo(LocaleUtils.parse("ROOT")));
    }

    @Test
    public void testLocale() throws IOException {
        String mapping = XContentFactory.jsonBuilder()
                    .startObject()
                        .startObject("type")
                            .startObject("properties")
                                .startObject("date_field_default")
                                    .field("type", "date")
                                    .field("format", "E, d MMM yyyy HH:mm:ss Z")
                                .endObject()
                                .startObject("date_field_en")
                                    .field("type", "date")
                                    .field("format", "E, d MMM yyyy HH:mm:ss Z")
                                    .field("locale", "EN")
                                .endObject()
                                 .startObject("date_field_de")
                                    .field("type", "date")
                                    .field("format", "E, d MMM yyyy HH:mm:ss Z")
                                    .field("locale", "DE_de")
                                .endObject()
                            .endObject()
                .endObject().endObject().string();

        DocumentMapper defaultMapper = mapper(mapping);
        ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                .startObject()
                  .field("date_field_en", "Wed, 06 Dec 2000 02:55:00 -0800")
                  .field("date_field_de", "Mi, 06 Dez 2000 02:55:00 -0800")
                  .field("date_field_default", "Wed, 06 Dec 2000 02:55:00 -0800") // check default - no exception is a successs!
                .endObject()
                .bytes());
        assertNumericTokensEqual(doc, defaultMapper, "date_field_en", "date_field_de");
        assertNumericTokensEqual(doc, defaultMapper, "date_field_en", "date_field_default");
    }

    int i = 0;

    private DocumentMapper mapper(String mapping) throws IOException {
        // we serialize and deserialize the mapping to make sure serialization works just fine
        DocumentMapperParser parser = createIndex("test-" + (i++)).mapperService().documentMapperParser();
        DocumentMapper defaultMapper = parser.parse(mapping);
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.startObject();
        defaultMapper.toXContent(builder, ToXContent.EMPTY_PARAMS);
        builder.endObject();
        String rebuildMapping = builder.string();
        return parser.parse(rebuildMapping);
    }

    private void assertNumericTokensEqual(ParsedDocument doc, DocumentMapper defaultMapper, String fieldA, String fieldB) throws IOException {
        assertThat(doc.rootDoc().getField(fieldA).tokenStream(defaultMapper.indexAnalyzer(), null), notNullValue());
        assertThat(doc.rootDoc().getField(fieldB).tokenStream(defaultMapper.indexAnalyzer(), null), notNullValue());

        TokenStream tokenStream = doc.rootDoc().getField(fieldA).tokenStream(defaultMapper.indexAnalyzer(), null);
        tokenStream.reset();
        NumericTermAttribute nta = tokenStream.addAttribute(NumericTermAttribute.class);
        List<Long> values = new ArrayList<>();
        while(tokenStream.incrementToken()) {
            values.add(nta.getRawValue());
        }

        tokenStream = doc.rootDoc().getField(fieldB).tokenStream(defaultMapper.indexAnalyzer(), null);
        tokenStream.reset();
        nta = tokenStream.addAttribute(NumericTermAttribute.class);
        int pos = 0;
        while(tokenStream.incrementToken()) {
            assertThat(values.get(pos++), equalTo(nta.getRawValue()));
        }
        assertThat(pos, equalTo(values.size()));
    }

    @Test
    public void testTimestampAsDate() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("properties").startObject("date_field").field("type", "date").endObject().endObject()
                .endObject().endObject().string();

        DocumentMapper defaultMapper = mapper(mapping);

        long value = System.currentTimeMillis();
        ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                .startObject()
                .field("date_field", value)
                .endObject()
                .bytes());

        assertThat(doc.rootDoc().getField("date_field").tokenStream(defaultMapper.indexAnalyzer(), null), notNullValue());
    }

    @Test
    public void testDateDetection() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .field("date_detection", false)
                .startObject("properties").startObject("date_field").field("type", "date").endObject().endObject()
                .endObject().endObject().string();

        DocumentMapper defaultMapper = mapper(mapping);

        ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                .startObject()
                .field("date_field", "2010-01-01")
                .field("date_field_x", "2010-01-01")
                .endObject()
                .bytes());

        assertThat(doc.rootDoc().get("date_field"), nullValue());
        assertThat(doc.rootDoc().get("date_field_x"), equalTo("2010-01-01"));
    }

    @Test
    public void testHourFormat() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .field("date_detection", false)
                .startObject("properties").startObject("date_field").field("type", "date").field("format", "HH:mm:ss").endObject().endObject()
                .endObject().endObject().string();

        DocumentMapper defaultMapper = mapper(mapping);

        ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                .startObject()
                .field("date_field", "10:00:00")
                .endObject()
                .bytes());
        assertThat(((LongFieldMapper.CustomLongNumericField) doc.rootDoc().getField("date_field")).numericAsString(), equalTo(Long.toString(new DateTime(TimeValue.timeValueHours(10).millis(), DateTimeZone.UTC).getMillis())));

        Filter filter;
        try {
            SearchContext.setCurrent(new TestSearchContext());
            filter = defaultMapper.mappers().smartNameFieldMapper("date_field").rangeFilter("10:00:00", "11:00:00", true, true, null);
        } finally {
            SearchContext.removeCurrent();
        }
        assertThat(filter, instanceOf(NumericRangeFilter.class));
        NumericRangeFilter<Long> rangeFilter = (NumericRangeFilter<Long>) filter;
        assertThat(rangeFilter.getMax(), equalTo(new DateTime(TimeValue.timeValueHours(11).millis()).getMillis()));
        assertThat(rangeFilter.getMin(), equalTo(new DateTime(TimeValue.timeValueHours(10).millis()).getMillis()));
    }

    @Test
    public void testDayWithoutYearFormat() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .field("date_detection", false)
                .startObject("properties").startObject("date_field").field("type", "date").field("format", "MMM dd HH:mm:ss").endObject().endObject()
                .endObject().endObject().string();

        DocumentMapper defaultMapper = mapper(mapping);

        ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                .startObject()
                .field("date_field", "Jan 02 10:00:00")
                .endObject()
                .bytes());
        assertThat(((LongFieldMapper.CustomLongNumericField) doc.rootDoc().getField("date_field")).numericAsString(), equalTo(Long.toString(new DateTime(TimeValue.timeValueHours(34).millis(), DateTimeZone.UTC).getMillis())));

        Filter filter;
        try {
            SearchContext.setCurrent(new TestSearchContext());
            filter = defaultMapper.mappers().smartNameFieldMapper("date_field").rangeFilter("Jan 02 10:00:00", "Jan 02 11:00:00", true, true, null);
        } finally {
            SearchContext.removeCurrent();
        }
        assertThat(filter, instanceOf(NumericRangeFilter.class));
        NumericRangeFilter<Long> rangeFilter = (NumericRangeFilter<Long>) filter;
        assertThat(rangeFilter.getMax(), equalTo(new DateTime(TimeValue.timeValueHours(35).millis()).getMillis()));
        assertThat(rangeFilter.getMin(), equalTo(new DateTime(TimeValue.timeValueHours(34).millis()).getMillis()));
    }

    @Test
    public void testIgnoreMalformedOption() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("properties")
                .startObject("field1").field("type", "date").field("ignore_malformed", true).endObject()
                .startObject("field2").field("type", "date").field("ignore_malformed", false).endObject()
                .startObject("field3").field("type", "date").endObject()
                .endObject()
                .endObject().endObject().string();

        DocumentMapper defaultMapper = mapper(mapping);

        ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                .startObject()
                .field("field1", "a")
                .field("field2", "2010-01-01")
                .endObject()
                .bytes());
        assertThat(doc.rootDoc().getField("field1"), nullValue());
        assertThat(doc.rootDoc().getField("field2"), notNullValue());

        try {
            defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                    .startObject()
                    .field("field2", "a")
                    .endObject()
                    .bytes());
        } catch (MapperParsingException e) {
            assertThat(e.getCause(), instanceOf(MapperParsingException.class));
        }

        // Verify that the default is false
        try {
            defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                    .startObject()
                    .field("field3", "a")
                    .endObject()
                    .bytes());
        } catch (MapperParsingException e) {
            assertThat(e.getCause(), instanceOf(MapperParsingException.class));
        }

        // Unless the global ignore_malformed option is set to true
        Settings indexSettings = settingsBuilder().put("index.mapping.ignore_malformed", true).build();
        defaultMapper = createIndex("test2", indexSettings).mapperService().documentMapperParser().parse(mapping);
        doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                .startObject()
                .field("field3", "a")
                .endObject()
                .bytes());
        assertThat(doc.rootDoc().getField("field3"), nullValue());

        // This should still throw an exception, since field2 is specifically set to ignore_malformed=false
        try {
            defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
                    .startObject()
                    .field("field2", "a")
                    .endObject()
                    .bytes());
        } catch (MapperParsingException e) {
            assertThat(e.getCause(), instanceOf(MapperParsingException.class));
        }
    }

    @Test
    public void testThatMergingWorks() throws Exception {
        String initialMapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("properties")
                    .startObject("field").field("type", "date")
                        .field("format", "EEE MMM dd HH:mm:ss.S Z yyyy||EEE MMM dd HH:mm:ss.SSS Z yyyy")
                    .endObject()
                .endObject()
                .endObject().endObject().string();

        String updatedMapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("properties")
                .startObject("field")
                        .field("type", "date")
                        .field("format", "EEE MMM dd HH:mm:ss.S Z yyyy||EEE MMM dd HH:mm:ss.SSS Z yyyy||yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
                .endObject()
                .endObject()
                .endObject().endObject().string();

        DocumentMapper defaultMapper = mapper(initialMapping);
        DocumentMapper mergeMapper = mapper(updatedMapping);

        assertThat(defaultMapper.mappers().name("field").mapper(), is(instanceOf(DateFieldMapper.class)));
        DateFieldMapper initialDateFieldMapper = (DateFieldMapper) defaultMapper.mappers().name("field").mapper();
        Map<String, String> config = getConfigurationViaXContent(initialDateFieldMapper);
        assertThat(config.get("format"), is("EEE MMM dd HH:mm:ss.S Z yyyy||EEE MMM dd HH:mm:ss.SSS Z yyyy"));

        DocumentMapper.MergeResult mergeResult = defaultMapper.merge(mergeMapper, DocumentMapper.MergeFlags.mergeFlags().simulate(false));

        assertThat("Merging resulting in conflicts: " + Arrays.asList(mergeResult.conflicts()), mergeResult.hasConflicts(), is(false));
        assertThat(defaultMapper.mappers().name("field").mapper(), is(instanceOf(DateFieldMapper.class)));

        DateFieldMapper mergedFieldMapper = (DateFieldMapper) defaultMapper.mappers().name("field").mapper();
        Map<String, String> mergedConfig = getConfigurationViaXContent(mergedFieldMapper);
        assertThat(mergedConfig.get("format"), is("EEE MMM dd HH:mm:ss.S Z yyyy||EEE MMM dd HH:mm:ss.SSS Z yyyy||yyyy-MM-dd'T'HH:mm:ss.SSSZZ"));
    }

    private Map<String, String> getConfigurationViaXContent(DateFieldMapper dateFieldMapper) throws IOException {
        XContentBuilder builder = JsonXContent.contentBuilder().startObject();
        dateFieldMapper.toXContent(builder, ToXContent.EMPTY_PARAMS).endObject();
        Map<String, Object> dateFieldMapperMap = JsonXContent.jsonXContent.createParser(builder.string()).mapAndClose();
        assertThat(dateFieldMapperMap, hasKey("field"));
        assertThat(dateFieldMapperMap.get("field"), is(instanceOf(Map.class)));
        return (Map<String, String>) dateFieldMapperMap.get("field");
    }
}


text:
    Kill The Yak

guides

contribute

source

        Yak shaving sucks. So let's kill the yak.

redpajama_set_name: RedPajamaGithub


text:
import cn from 'classnames';
import { bind } from 'decko';
import * as React from 'react';
import { connect } from 'react-redux';

import CodeVersion from 'shared/view/domain/CodeVersion/CodeVersion';
import ProjectEntityDescriptionManager from 'features/descriptionManager/view/ProjectEntityDescriptionManager/ProjectEntityDescriptionManager';
import ProjectEntityTagsManager from 'features/tagsManager/view/ProjectEntityTagsManager/ProjectEntityTagsManager';
import WithCurrentUserActionsAccesses from 'shared/view/domain/WithCurrentUserActionsAccesses/WithCurrentUserActionsAccesses';
import { ICommunication } from 'shared/utils/redux/communication';
import Experiment from 'shared/models/Experiment';
import { selectDeletingExperiment } from 'features/experiments/store';
import { IConnectedReduxProps, IApplicationState } from 'setup/store/store';

import ExperimentBulkDeletion from './ExperimentBulkDeletion/ExperimentBulkDeletion';
import styles from './ExperimentWidget.module.css';
import WithCopyTextIcon from 'shared/view/elements/WithCopyTextIcon/WithCopyTextIcon';

interface ILocalProps {
  projectId: string;
  experiment: Experiment;
  onViewExprRuns(): void;
}

interface IPropsFromState {
  deletingExperiment: ICommunication;
}

type AllProps = ILocalProps & IPropsFromState & IConnectedReduxProps;

class ExperimentWidget extends React.PureComponent<AllProps> {
  public render() {
    const { projectId, experiment, deletingExperiment } = this.props;

    return (
      <WithCurrentUserActionsAccesses
        entityType="experiment"
        entityId={experiment.id}
        actions={['delete']}
      >
        {({ actionsAccesses }) => (
          <ExperimentBulkDeletion
            id={experiment.id}
            isEnabled={actionsAccesses.delete}
          >
            {togglerForBulkDeletion => (

                      <WithCopyTextIcon
                        text={experiment.name}
                        onClick={this.preventOnViewExprRuns}
                      >
                        {experiment.name}
                      </WithCopyTextIcon>

                        <ProjectEntityDescriptionManager
                          entityId={experiment.id}
                          description={experiment.description}
                          entityType={'experiment'}
                        />

                    <ProjectEntityTagsManager
                      id={experiment.id}
                      projectId={projectId}
                      tags={experiment.tags}
                      entityType="experiment"
                      isDraggableTags={true}
                      onClick={this.onTagsManagerClick}
                    />

                  {experiment.codeVersion && (

                        Code version:

                        <CodeVersion
                          entityType="experiment"
                          entityId={experiment.id}
                          codeVersion={experiment.codeVersion}
                        />

                  )}

                      Created: {experiment.dateCreated.toLocaleDateString()}

                      Updated: {experiment.dateUpdated.toLocaleDateString()}

                    {togglerForBulkDeletion && (

                        {togglerForBulkDeletion}

                    )}

            )}
          </ExperimentBulkDeletion>
        )}
      </WithCurrentUserActionsAccesses>
    );
  }

  @bind
  private onTagsManagerClick(e: React.MouseEvent, byEmptiness: boolean) {
    if (!byEmptiness) {
      this.preventOnViewExprRuns(e);
    }
  }

  @bind
  private preventOnViewExprRuns(e: React.MouseEvent) {
    e.stopPropagation();
  }

  @bind
  private onViewExprRuns(e: React.MouseEvent<any>) {
    this.props.onViewExprRuns();
  }
}

const mapStateToProps = (
  state: IApplicationState,
  localProps: ILocalProps
): IPropsFromState => {
  return {
    deletingExperiment: selectDeletingExperiment(
      state,
      localProps.experiment.id
    ),
  };
};

export default connect(mapStateToProps)(ExperimentWidget);


text:
void test08()
{
   using namespace boost::multiprecision;
#ifdef TEST_CPP_INT
   test_miller_rabin<checked_uint1024_t>("checked_uint1024_t");
#endif
}


text:
package org.genericConfig.admin.client.views.configGraph

import org.genericConfig.admin.client.views.html.{HtmlElementIds, HtmlElementText}
import org.scalajs.jquery.jQuery

class NodeEditPage {
  def showNodeEditPage() : Unit = {
    jQuery(HtmlElementIds.jQueryConfigGraphNodeEdit).remove()
    val configGraphNodePage = HtmlElementText.configGraphNodePage("")
    configGraphNodePage.appendTo(jQuery(HtmlElementIds.section))
  }
}


text:
#region MIT License

// UtilityBehaviour.cs
// Version: 0.01
// Last Modified: 2012/09/16 15:57
// Created: 2012/09/12 9:45
//
// Author: Jing-Jun Wei
// Mail: jingjunwei@outlook.com
// Homepage: http://jingjunwei.github.com/unity3d-trajectory-prototypes/
//
// MIT License
// Copyright (c) 2012 Jing-Jun Wei
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#endregion

#region Usings

using UnityEngine;
using System;
using System.Collections.Generic;
using KeigunGi.Example;
using KeigunGi.Spawn;
using UnityEngine;
using KeigunGi.General;
using KeigunGi.Message;
using ObjectMode = KeigunGi.General.ObjectSelector.ObjectMode;

#endregion

public class UtilityBehaviour : ExtendBehaviour
{
    #region  Action

    protected readonly Action<int, Action<int>> For = (length, init) =>
    {
        for(var i = 0; i < length; i++)
        {
            init(i);
        }
    };

    #endregion

    #region  Func

    protected readonly Func<Type, int> GetLength = EnumUtility.GetLength;

    protected readonly Func<object, Enum, Type> GetEnumType =
        EnumUtility.GetInnerEnumType;

    protected readonly Func<Type, List<string>> GetNames = EnumUtility.GetNames;

    #endregion

    #region Message

    public readonly Type[] SenderParameterTypes = new[]
    {
        typeof(string), typeof(object[])
    };

    #endregion

    #region  Collection

    protected virtual List<T> Fill<T>(T value, int length)
    {
        return Collection.Fill(value, length);
    }

    #endregion

    #region Enum

    /// <summary>
    /// 便利で枚挙のストリングをゲット
    /// </summary>
    protected virtual string GetName<T>(T target)
    {
        return EnumUtility.GetName(target);
    }

    //TODO HACK: Func With Nested Gerneric
    protected virtual T GetById<T>(List<T> list, Enum method)
    {
        return EnumUtility.GetById(list, method);
    }

    #endregion
}


text:
using System;
using System.Linq;
using Xunit;
using VstsNotifications.Models;
using VstsNotifications.Services.Interfaces;
using VstsNotifications.Services.Models;

namespace VstsNotifications.Services.Tests
{
    public class PullRequestMessageServiceTests
    {
        private readonly IPullRequestMessageService _pullRequestMessageService;

        public PullRequestMessageServiceTests()
        {
            _pullRequestMessageService = new PullRequestMessageService();
        }

        [Fact]
        public void CreatePullRequestMessagesWithPullRequestInfoNullThrowsNullReferenceException()
        {
            // Arrange
            var contributorOne = new Contributor { Id = "idone", SlackUserId = "shone" };
            var contributorTwo = new Contributor { Id = "idtwo", SlackUserId = "shtwo" };

            var pullRequestInfo = (PullRequestInfo) null;
            var contributorsInfo = new [] { contributorOne, contributorTwo };

            // Act

            // Assert
            Assert.Throws<NullReferenceException>(() => _pullRequestMessageService.CreatePullRequestMessages(pullRequestInfo, contributorsInfo));
        }

        [Fact]
        public void CreatePullRequestMessagesWithoutReviewersAndEmptyContributorsReturnsEmpty()
        {
            // Arrange
            var contributorOne = new Contributor { Id = "idone", SlackUserId = "shone" };
            var contributorTwo = new Contributor { Id = "idtwo", SlackUserId = "shtwo" };

            var pullRequestInfo = new PullRequestInfo();
            var contributorsInfo = new Contributor[0];

            // Act
            var pullRequestMessages = _pullRequestMessageService.CreatePullRequestMessages(pullRequestInfo, contributorsInfo);

            // Assert
            Assert.NotNull(pullRequestMessages);
            Assert.Empty(pullRequestMessages);
        }

        [Fact]
        public void CreatePullRequestMessagesWithoutReviewersReturnsEmpty()
        {
            // Arrange
            var contributorOne = new Contributor { Id = "idone", SlackUserId = "shone" };
            var contributorTwo = new Contributor { Id = "idtwo", SlackUserId = "shtwo" };

            var pullRequestInfo = new PullRequestInfo();
            var contributorsInfo = new [] { contributorOne, contributorTwo };

            // Act
            var pullRequestMessages = _pullRequestMessageService.CreatePullRequestMessages(pullRequestInfo, contributorsInfo);

            // Assert
            Assert.NotNull(pullRequestMessages);
            Assert.Empty(pullRequestMessages);
        }

        [Fact]
        public void CreatePullRequestMessagesWithAllParametersReturnsPullRequestMessages()
        {
            // Arrange
            var contributorOne = new Contributor { Id = "two@collaborator.com", SlackUserId = "shone" };
            var contributorTwo = new Contributor { Id = "three@collaborator.com", SlackUserId = "shtwo" };

            var author = new Collaborator { UniqueName = "one@collaborator.com", DisplayName = "Collaborator one" };

            var reviewerOne = new Collaborator { UniqueName = "two@collaborator.com", DisplayName = "Collaborator two" };
            var reviewerTwo = new Collaborator { UniqueName = "three@collaborator.com", DisplayName = "Collaborator three" };

            var pullRequestInfo = new PullRequestInfo
            {
                Url = new Uri("http://my.pullrequest.com"),
                Author = author,
            };
            pullRequestInfo.Reviewers.Add(reviewerOne);
            pullRequestInfo.Reviewers.Add(reviewerTwo);

            var contributorsInfo = new [] { contributorOne, contributorTwo };

            // Act
            var pullRequestMessages = _pullRequestMessageService.CreatePullRequestMessages(pullRequestInfo, contributorsInfo);

            // Assert
            Assert.NotNull(pullRequestMessages);
            Assert.Equal(1, pullRequestMessages.Count());

            Assert.Equal(contributorOne.SlackUserId, pullRequestMessages.ElementAt(0).ReviewersSlackUserId.ElementAt(0));
            Assert.Equal(contributorTwo.SlackUserId, pullRequestMessages.ElementAt(0).ReviewersSlackUserId.ElementAt(1));
            Assert.Equal(author.DisplayName, pullRequestMessages.ElementAt(0).AuthorDisplayName);
            Assert.Equal(pullRequestInfo.Url, pullRequestMessages.ElementAt(0).PullRequestUrl);
        }

        [Fact]
        public void CreatePullRequestMessagesWithMissingContributorReturnsPullRequestMessagesForExistingOnes()
        {
            // Arrange
            var contributorOne = new Contributor { Id = "two@collaborator.com", SlackUserId = "shone" };
            var contributorTwo = new Contributor { Id = "four@collaborator.com", SlackUserId = "shfour" };

            var author = new Collaborator { UniqueName = "one@collaborator.com", DisplayName = "Collaborator one" };

            var reviewerOne = new Collaborator { UniqueName = "two@collaborator.com", DisplayName = "Collaborator two" };
            var reviewerTwo = new Collaborator { UniqueName = "three@collaborator.com", DisplayName = "Collaborator three" };

            var pullRequestInfo = new PullRequestInfo
            {
                Url = new Uri("http://my.pullrequest.com"),
                Author = author,
            };
            pullRequestInfo.Reviewers.Add(reviewerOne);
            pullRequestInfo.Reviewers.Add(reviewerTwo);

            var contributorsInfo = new [] { contributorOne, contributorTwo };

            // Act
            var pullRequestMessages = _pullRequestMessageService.CreatePullRequestMessages(pullRequestInfo, contributorsInfo);

            // Assert
            Assert.NotNull(pullRequestMessages);
            Assert.Equal(1, pullRequestMessages.Count());
            Assert.Equal(1, pullRequestMessages.ElementAt(0).ReviewersSlackUserId.Count());

            Assert.Equal(contributorOne.SlackUserId, pullRequestMessages.ElementAt(0).ReviewersSlackUserId.ElementAt(0));
            Assert.Equal(author.DisplayName, pullRequestMessages.ElementAt(0).AuthorDisplayName);
            Assert.Equal(pullRequestInfo.Url, pullRequestMessages.ElementAt(0).PullRequestUrl);
        }
    }
}


text:
build: components style.css
	@component build --dev

style.css: darktone-tip.css
	rework --vars < $< > $@

components:
	@component install --dev

clean:
	rm -fr build components

.PHONY: clean


text:
package org.snaker.engine.test;

import org.snaker.engine.IProcessService;
import org.snaker.engine.IQueryService;
import org.snaker.engine.SnakerEngine;
import org.snaker.engine.cfg.Configuration;

/**
 * 测试辅助基类,提供execute的递归方法及SnakerEngine实例
 * @author yuqs
 * @version 1.0
 */
public class TestSnakerBase {
	protected String processId;
	protected SnakerEngine engine = getEngine();
	protected IProcessService processService = engine.process();
	protected IQueryService queryService = engine.query();

	private SnakerEngine getEngine() {
		return new Configuration().buildSnakerEngine();
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Elix Popup</title>

    <link rel="stylesheet" href="demos.css" />

      <button id="showPopup" onclick="samplePopup.open()">Open popup</button>
      <input type="text" />

      <elix-popup id="samplePopup">

          Here's a popup.

      </elix-popup>


text:
"""Tests for distribution."""

from absl.testing import absltest
from open_spiel.python import policy
from open_spiel.python.mfg import games  # pylint: disable=unused-import
from open_spiel.python.mfg.algorithms import distribution
import pyspiel

class DistributionTest(absltest.TestCase):

  def test_basic(self):
    game = pyspiel.load_game("python_mfg_crowd_modelling")
    uniform_policy = policy.UniformRandomPolicy(game)
    dist = distribution.DistributionPolicy(game, uniform_policy)
    state = game.new_initial_state().child(0)
    self.assertAlmostEqual(dist.value(state), 1 / game.size)

  def test_state_support_outside_distrib(self):
    game = pyspiel.load_game("mfg_crowd_modelling_2d", {
        "initial_distribution": "[0|0]",
        "initial_distribution_value": "[1.]",
    })
    uniform_policy = policy.UniformRandomPolicy(game)
    _ = distribution.DistributionPolicy(game, uniform_policy)

  def test_multi_pop(self):
    game = pyspiel.load_game("python_mfg_predator_prey")
    self.assertEqual(game.num_players(), 3)
    uniform_policy = policy.UniformRandomPolicy(game)
    dist = distribution.DistributionPolicy(game, uniform_policy)
    for pop in range(3):
      self.assertAlmostEqual(
          dist.value(game.new_initial_state_for_population(pop)), 1.)

if __name__ == "__main__":
  absltest.main()


text:
package spark.scheduler.cluster

import spark.{Utils, Logging, SparkContext}
import spark.deploy.client.{Client, ClientListener}
import spark.deploy.{Command, JobDescription}
import scala.collection.mutable.HashMap

private[spark] class SparkDeploySchedulerBackend(
    scheduler: ClusterScheduler,
    sc: SparkContext,
    master: String,
    jobName: String)
  extends StandaloneSchedulerBackend(scheduler, sc.env.actorSystem)
  with ClientListener
  with Logging {

  var client: Client = null
  var stopping = false
  var shutdownCallback : (SparkDeploySchedulerBackend) => Unit = _

  val maxCores = System.getProperty("spark.cores.max", Int.MaxValue.toString).toInt

  // Memory used by each executor (in megabytes)
  val executorMemory = {
    if (System.getenv("SPARK_MEM") != null) {
      Utils.memoryStringToMb(System.getenv("SPARK_MEM"))
      // TODO: Might need to add some extra memory for the non-heap parts of the JVM
    } else {
      512
    }
  }

  override def start() {
    super.start()

    val masterUrl = "akka://spark@%s:%s/user/%s".format(
      System.getProperty("spark.master.host"), System.getProperty("spark.master.port"),
      StandaloneSchedulerBackend.ACTOR_NAME)
    val args = Seq(masterUrl, "{{SLAVEID}}", "{{HOSTNAME}}", "{{CORES}}")
    val command = Command("spark.executor.StandaloneExecutorBackend", args, sc.executorEnvs)
    val jobDesc = new JobDescription(jobName, maxCores, executorMemory, command)

    client = new Client(sc.env.actorSystem, master, jobDesc, this)
    client.start()
  }

  override def stop() {
    stopping = true;
    super.stop()
    client.stop()
    if (shutdownCallback != null) {
      shutdownCallback(this)
    }
  }

  def connected(jobId: String) {
    logInfo("Connected to Spark cluster with job ID " + jobId)
  }

  def disconnected() {
    if (!stopping) {
      logError("Disconnected from Spark cluster!")
      scheduler.error("Disconnected from Spark cluster")
    }
  }

  def executorAdded(id: String, workerId: String, host: String, cores: Int, memory: Int) {
    logInfo("Granted executor ID %s on host %s with %d cores, %s RAM".format(
       id, host, cores, Utils.memoryMegabytesToString(memory)))
  }

  def executorRemoved(id: String, message: String) {}
}


text:
.directory-photo-img {
	width: 80px;
	height: 80px;
	border: none;
}

.directory-item {
	margin-bottom: 20px;
}

.contact-photo-wrapper {
	display: table-cell;
	table-layout: fixed;
	vertical-align: top;
}

.contact-info {
	display: table-cell;
	table-layout: fixed;
	vertical-align: top;
	padding-left: 10px;
}

.contact-info-label {
	font-weight: bold;
}

.section-subtitle-wrapper .btn-xs {
	margin-top: -2px;
}


text:
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace dnlib.IO {
	sealed unsafe class AlignedByteArrayDataStream : DataStream {
		readonly byte[] data;

		public AlignedByteArrayDataStream(byte[] data) => this.data = data;

		public override void ReadBytes(uint offset, void* destination, int length) =>
			Marshal.Copy(data, (int)offset, (IntPtr)destination, length);

		public override void ReadBytes(uint offset, byte[] destination, int destinationIndex, int length) =>
			Array.Copy(data, (int)offset, destination, destinationIndex, length);

		public override byte ReadByte(uint offset) => data[(int)offset];

		public override ushort ReadUInt16(uint offset) {
			int i = (int)offset;
			var data = this.data;
			return (ushort)(data[i++] | (data[i] << 8));
		}

		public override uint ReadUInt32(uint offset) {
			int i = (int)offset;
			var data = this.data;
			return data[i++] | ((uint)data[i++] << 8) | ((uint)data[i++] << 16) | ((uint)data[i] << 24);
		}

		public override ulong ReadUInt64(uint offset) {
			int i = (int)offset;
			var data = this.data;
			return data[i++] | ((ulong)data[i++] << 8) | ((ulong)data[i++] << 16) | ((ulong)data[i++] << 24) |
				((ulong)data[i++] << 32) | ((ulong)data[i++] << 40) | ((ulong)data[i++] << 48) | ((ulong)data[i] << 56);
		}

		public override float ReadSingle(uint offset) {
			int i = (int)offset;
			var data = this.data;
			uint value = data[i++] | ((uint)data[i++] << 8) | ((uint)data[i++] << 16) | ((uint)data[i] << 24);
			return *(float*)&value;
		}

		public override double ReadDouble(uint offset) {
			int i = (int)offset;
			var data = this.data;
			ulong value = data[i++] | ((ulong)data[i++] << 8) | ((ulong)data[i++] << 16) | ((ulong)data[i++] << 24) |
				((ulong)data[i++] << 32) | ((ulong)data[i++] << 40) | ((ulong)data[i++] << 48) | ((ulong)data[i] << 56);
			return *(double*)&value;
		}

		public override string ReadUtf16String(uint offset, int chars) {
			fixed (byte* p = data)
				return new string((char*)(p + offset), 0, chars);
		}

		public override string ReadString(uint offset, int length, Encoding encoding) {
			fixed (byte* p = data)
				return new string((sbyte*)(p + offset), 0, length, encoding);
		}

		public override bool TryGetOffsetOf(uint offset, uint endOffset, byte value, out uint valueOffset) {
			fixed (byte* pd = data) {
				// If this code gets updated, also update the other DataStream implementations

				byte* p = pd + offset;

				uint count = (endOffset - offset) / 4;
				for (uint i = 0; i < count; i++) {
					if (*p == value) {
						valueOffset = (uint)(p - pd);
						return true;
					}
					p++;
					if (*p == value) {
						valueOffset = (uint)(p - pd);
						return true;
					}
					p++;
					if (*p == value) {
						valueOffset = (uint)(p - pd);
						return true;
					}
					p++;
					if (*p == value) {
						valueOffset = (uint)(p - pd);
						return true;
					}
					p++;
				}

				byte* pe = pd + endOffset;
				while (p != pe) {
					if (*p == value) {
						valueOffset = (uint)(p - pd);
						return true;
					}
					p++;
				}
				valueOffset = 0;
				return false;
			}
		}
	}
}


text:
//$Id$
package org.hibernate.ejb.test.callbacks;
import javax.persistence.PrePersist;

/**
 * @author Emmanuel Bernard
 */
public class ExceptionListener {
	@PrePersist
	public void raiseException(Object e) {
		throw new ArithmeticException( "1/0 impossible" );
	}
}


text:
var Hapi = require('../lib');

// Declare internals

var internals = {};

internals.profile = function (request, reply) {

    reply({
        'id': 'fa0dbda9b1b',
        'name': 'John Doe'
    });
};

internals.main = function () {

    var config = {
        cache: {
            engine: 'redis',
            host: '127.0.0.1',
            port: 6379
        }
    };

    var server = new Hapi.Server(8000, config);

    server.route({ method: 'GET', path: '/profile', config: { handler: internals.profile, cache: { expiresIn: 30000 } } });

    server.method('user', function (id, next) {

        setTimeout(function () {

            next(null, {
                'id': id,
                'name': 'Item'
            });
        }, 600);    // Used to demonstrate stale response
    }, { cache: { expiresIn: 20000, staleIn: 10000, staleTimeout: 500 } });

    internals.item = function (request, reply) {

        server.methods.user(request.params.id, reply);
    };

    server.route({ method: 'GET', path: '/item/{id}', config: { handler: internals.item } });

    server.start();
};

internals.main();


text:
/*! HTML5 Boilerplate v5.0.0 | MIT License | http://h5bp.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
}

/*
 * Remove text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between audio, canvas, iframes,
 * images, videos and the bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Hide visually and from screen readers:
 * http://juicystudio.com/article/screen-readers-display-none.php
 */

.hidden {
    display: none !important;
    visibility: hidden;
}

/*
 * Hide only visually, but have it available for screen readers:
 * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element
 * to be focusable when navigated to via the keyboard:
 * https://www.drupal.org/node/897638
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screen readers, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-o-min-device-pixel-ratio: 5/4),
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid the additional HTTP request:
   http://www.phpied.com/delay-loading-your-print-css/
   ========================================================================== */

@media print {
    *,
    *:before,
    *:after {
        background: transparent !important;
        color: #000 !important; /* Black prints faster:
                                   http://www.sanbeiji.com/archives/953 */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links that are fragment identifiers,
     * or use the `javascript:` pseudo protocol
     */

    a[href^="#"]:after,
    a[href^="javascript:"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    /*
     * Printing Tables:
     * http://css-discuss.incutio.com/wiki/Printing_Tables
     */

    thead {
        display: table-header-group;
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}

/*
 * CUSTOM CSS
 */

body {
    font-family: 'Open Sans', sans-serif;
    font-size:18pt;
    color:#555;
}

/*
 * Navbar formatting
 */
.navbar {
    font-family: 'Economica', sans-serif;
    opacity:0.8;
}
img.logo {
    position:relative;
    top:-5px;
    opacity:0.6;
}

/*
 * Header and link formatting
 */
h1, h2, h3 { color:#fff; }
h1 {
    font-family: 'Raleway', sans-serif;
    font-size:60pt;
    line-height:0.1em;
}
h2 { line-height:1em; }
h2, h3 {
    font-size:40pt;
    font-family: 'Economica', sans-serif;
}
h3 {
    font-size:32pt;
    line-height:1em;
}
section { padding:100px 0px; }
h4 {
    font-size:40pt;
    font-family: 'Economica', sans-serif;
}
a:hover {
    text-decoration:none;
    color:#428bca;
}
h4:hover { color:#428bca; }

/*
 * Landing /home formatting
 */
.overlay {
    position:absolute;
    top:0;
    padding-top:150px;
    width:100%;
    text-align:center;
}

button.mentor {
    font-family: 'Montserrat', sans-serif;
    font-size:36pt;
    background:none;
    color:#428bca;
    border:#428bca 6px solid;
}

button.mentor:hover {
    opacity:0.7;
}

.register {
    font-family: 'Montserrat', sans-serif;
    font-size:36pt;
    background:none;
    color:#fff;
    border:#fff 6px solid;
}
.register:hover {
    background:#428bca;
}

/*
 * Sponsor image formatting
 */
.sponsors img { display:inline; margin:40px 20px;}
.sponsors {text-align:center;}

/* these logos are too big */
#twitter {height:100px;padding-right:5%;}
#apple {padding-left:10%;}
#wics {opacity:0.6}
#thalmic {height:50px}

.platinum img {height:150px}
.cohost img{height:100px}
.gold img {height:70px}
.silver img {height:60px}
.bronze img {width: 10%}

/*
 * Schedule formatting
 */
#schedule {
    position:absolute;
    top:-850px;
    width:100%;
}
.schedule {
    font-family: 'Montserrat', sans-serif;
    font-size:24pt;
    color:#fff;
    text-align:center;
}
.schedule table {
    width:100%;
}
.schedule h4 { color:#fff }
.zero { /* for zeroing position */
    position:relative;
    width:100%;
}
td {
    text-align:left;
    border-top:1px solid white;
    border-bottom:1px solid white;
    font-size:20pt
}
td.left {
    text-align:center;
    padding-right:25px;
    width:30%;
}
tr.im {
    background: rgba(25,50,100,.5)
}
span.hint {
    font-size:16pt;
}

/*
 * Footer formatting
 */
.footer {
    background-color:#444;
    color:#fff;
    padding-bottom:10%;
}

.footer a {
    color:#fff;
    font-weight:bold;
}

.footer_info {
    width:100%;
    padding-top:150px;
    text-align:center;
    font-family:"Economica", sans-serif;
}

.center {
    width:100%;
    text-align:center;
}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// QuickBook Example

// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//[make_2d_point
//` Shows the usage of make as a generic constructor for different point types

#include <iostream>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
#include <boost/geometry/geometries/adapted/boost_polygon/point.hpp>

BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)

struct mypoint { float _x, _y; };

BOOST_GEOMETRY_REGISTER_POINT_2D(mypoint, float, cs::cartesian, _x, _y)

template <typename Point>
void construct_and_display()
{
    using boost::geometry::make;
    using boost::geometry::get;

    Point p = make<Point>(1, 2);

    std::cout << "x=" << get<0>(p) << " y=" << get<1>(p)
        << " (" << typeid(Point).name() << ")"
        << std::endl;
}

int main()
{
    construct_and_display<boost::geometry::model::d2::point_xy<double> >();
    construct_and_display<boost::geometry::model::d2::point_xy<int> >();
    construct_and_display<boost::tuple<double, double> >();
    construct_and_display<boost::polygon::point_data<int> >();
    construct_and_display<mypoint>();
    return 0;
}

//]

//[make_2d_point_output
/*`
Output (compiled using gcc):
[pre
x=1 y=2 (N5boost8geometry5model2d28point_xyIdNS0_2cs9cartesianEEE)
x=1 y=2 (N5boost8geometry5model2d28point_xyIiNS0_2cs9cartesianEEE)
x=1 y=2 (N5boost6tuples5tupleIddNS0_9null_typeES2_S2_S2_S2_S2_S2_S2_EE)
x=1 y=2 (N5boost7polygon10point_dataIiEE)
x=1 y=2 (7mypoint)
]
*/
//]


text:
/* global zxcvbn */
window.wp = window.wp || {};

var passwordStrength;
(function ($) {
    wp.passwordStrength = {
        /**
         * Determine the strength of a given password
         *
         * @param string password1 The password
         * @param array blacklist An array of words that will lower the entropy of the password
         * @param string password2 The confirmed password
         */
        meter: function (password1, blacklist, password2) {
            if (!$.isArray(blacklist))
                blacklist = [blacklist.toString()];

            if (password1 != password2 && password2 && password2.length > 0)
                return 5;

            var result = zxcvbn(password1, blacklist);
            return result.score;
        },

        /**
         * Builds an array of data that should be penalized, because it would lower the entropy of a password if it were used
         *
         * @return array The array of data to be blacklisted
         */
        userInputBlacklist: function () {
            var i, userInputFieldsLength, rawValuesLength, currentField,
                rawValues = [],
                blacklist = [],
                userInputFields = ['user_login', 'first_name', 'last_name', 'nickname', 'display_name', 'email', 'url', 'description', 'weblog_title', 'admin_email'];

            // Collect all the strings we want to blacklist
            rawValues.push(document.title);
            rawValues.push(document.URL);

            userInputFieldsLength = userInputFields.length;
            for (i = 0; i < userInputFieldsLength; i++) {
                currentField = $('#' + userInputFields[i]);

                if (0 === currentField.length) {
                    continue;
                }

                rawValues.push(currentField[0].defaultValue);
                rawValues.push(currentField.val());
            }

            // Strip out non-alphanumeric characters and convert each word to an individual entry
            rawValuesLength = rawValues.length;
            for (i = 0; i < rawValuesLength; i++) {
                if (rawValues[i]) {
                    blacklist = blacklist.concat(rawValues[i].replace(/\W/g, ' ').split(' '));
                }
            }

            // Remove empty values, short words, and duplicates. Short words are likely to cause many false positives.
            blacklist = $.grep(blacklist, function (value, key) {
                if ('' === value || 4 > value.length) {
                    return false;
                }

                return $.inArray(value, blacklist) === key;
            });

            return blacklist;
        }
    };

    // Backwards compatibility.
    passwordStrength = wp.passwordStrength.meter;
})(jQuery);


text:
module Cryptoexchange::Exchanges
  module Luno
    module Services
      class Trades < Cryptoexchange::Services::Market
        def fetch(market_pair)
          output = super(ticker_url(market_pair))
          adapt(output, market_pair)
        end

        def ticker_url(market_pair)
          "#{Cryptoexchange::Exchanges::Luno::Market::API_URL}/trades?pair=#{market_pair.base}#{market_pair.target}"
        end

        def adapt(output, market_pair)
          output['trades'].collect do |trade|
            tr = Cryptoexchange::Models::Trade.new
            tr.base      = market_pair.base
            tr.target    = market_pair.target
            tr.market    = Luno::Market::NAME

            tr.trade_id  = trade['sequence']
            tr.type      = trade['is_buy'] ? "buy" : "sell"
            tr.price     = trade['price'].to_f
            tr.amount    = trade['volume'].to_f
            tr.timestamp = trade['timestamp']/1000
            tr.payload   = trade

            tr
          end
        end
      end
    end
  end
end


text:
title: 'Rata: osa kalustoyksikkönumeroista julkaistaan 13.05.2020 09:00'
categories: Tiedotteet
image:
lang: fi
published: true
ref: 2020-05-13-release
traffictypes:
  - Rautatieliikenne
tags:
  - Rajapinnat
  - Ylläpito
---

VR ja HSL ovat ystävällisesti antaneet luvan julkaista lähiliikenteessä käytettävien sähkömoottorijunien kalustoyksikkönumerot. Eli kalustoyksikkönumero julkaistaan, jos kaluston tyyppi on `Sm1`, `Sm2`, `Sm4` tai `Sm5`

Kalustoyksikkönumero on kaluston yksilöivä tunniste, esimerkiksi `94102081010-2`. Lisätietoa tunnisteesta löytyy vaikkapa Wikipediasta: [https://en.wikipedia.org/wiki/UIC_identification_marking_for_tractive_stock](https://en.wikipedia.org/wiki/UIC_identification_marking_for_tractive_stock)

Uusi tieto lisätään olemassaolevaan kokoonpano-vastaukseen kenttänä `vehicleNumber`. Esimerkki: [https://rata-beta.digitraffic.fi/api/v1/compositions/2020-05-19/9224](https://rata-beta.digitraffic.fi/api/v1/compositions/2020-05-19/9224) (testiympäristössä)

Julkaisu tapahtuu keskiviikkona 13.05.2020 09:00


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

three.js - css3d orthographic


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<!DOCTYPE html>

		 <meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="shortcut icon" href="imgs/favicon.ico" type="image/x-icon">
		<link rel="icon" href="imgs/favicon.ico" type="image/x-icon">
		<meta name="description" content="Responsive Twitter Bootstrap Template For Photography Portfolio">
		<meta name="author" content="Maria Antonietta Perna">

		<title>Camp Poe Gallery</title>

	   <link rel="stylesheet" href="<?php echo base_url(); ?>resoures/gallery/css/bootstrap.min.css">

		<link href="<?php echo base_url(); ?>resoures/gallery/css/font-awesome.min.css" rel="stylesheet">

		<link href="<?php echo base_url(); ?>resoures/gallery/css/blueimp-gallery.min.css" rel="stylesheet">

		<link href="<?php echo base_url(); ?>resoures/gallery/css/blueimp-gallery-indicator.css" rel="stylesheet">

		<link href="<?php echo base_url(); ?>resoures/gallery/css/theme.css" rel="stylesheet">

		<link rel="stylesheet" href="<?php echo base_url(); ?>resoures/css/all.css">

			<img src="<?php echo base_url(); ?>resoures/gallery/imgs/preloader.gif" alt="">

		 <?php include_once './resoures/imports/temp_header.php'; ?>

							Close

<a title="Work"href="<?php echo base_url(); ?>index.php/Gallery">Gallery

<a title="Blog" href="<?php echo base_url(); ?>index.php/Gallery/blog">Blog

<a title="Contact"  class="active"  href="<?php echo base_url(); ?>index.php/Gallery/albem">Albem

							Toggle sidebar view

Event One

									<a href="<?php echo base_url(); ?>resoures/gallery/imgs/work1.jpg" title="Photo 1" data-gallery>

											<img class="img-responsive album-img" src="<?php echo base_url(); ?>resoures/gallery/imgs/work1-thumb.jpg" alt="">

Photo 1

									<a href="<?php echo base_url(); ?>resoures/gallery/imgs/work4.jpg" title="Photo 2" data-gallery>

											<img class="img-responsive album-img" src="<?php echo base_url(); ?>resoures/gallery/imgs/work4-thumb.jpg" alt="">

Photo 2

									<a href="<?php echo base_url(); ?>resoures/gallery/imgs/work3.jpg" title="Photo 3" data-gallery>

											<img class="img-responsive album-img" src="<?php echo base_url(); ?>resoures/gallery/imgs/work3-thumb.jpg" alt="">

Photo 3

									<a href="<?php echo base_url(); ?>resoures/gallery/imgs/work6.jpg" title="Photo 4" data-gallery>

											<img class="img-responsive album-img" src="<?php echo base_url(); ?>resoures/gallery/imgs/work6-thumb.jpg" alt="">

Photo 4

									<a href="<?php echo base_url(); ?>resoures/gallery/imgs/work5.jpg" title="Photo 5" data-gallery>

											<img class="img-responsive album-img" src="<?php echo base_url(); ?>resoures/gallery/imgs/work5-thumb.jpg" alt="">

Photo 5

									<a href="<?php echo base_url(); ?>resoures/gallery/imgs/work10.jpg" title="Photo 6" data-gallery>

											<img class="img-responsive album-img" src="<?php echo base_url(); ?>resoures/gallery/imgs/work10-thumb.jpg" alt="">

Photo 6

			‹
			›

			 <?php include_once './resoures/imports/temp_footer.php'; ?>


text:
package org.projectfloodlight.openflow.protocol;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import java.util.Set;
import java.util.List;
import io.netty.buffer.ByteBuf;

public interface OFTableDesc extends OFObject {
    TableId getTableId();
    Set<OFTableConfig> getConfig();
    List<OFTableModProp> getProperties() throws UnsupportedOperationException;
    OFVersion getVersion();

    void writeTo(ByteBuf channelBuffer);

    Builder createBuilder();
    public interface Builder  {
        OFTableDesc build();
        TableId getTableId();
        Builder setTableId(TableId tableId);
        Set<OFTableConfig> getConfig();
        Builder setConfig(Set<OFTableConfig> config);
        List<OFTableModProp> getProperties() throws UnsupportedOperationException;
        Builder setProperties(List<OFTableModProp> properties) throws UnsupportedOperationException;
        OFVersion getVersion();
    }
}


text:
@implementation ApptentiveSurveyLayoutAttributes

- (id)copyWithZone:(NSZone *)zone {
	ApptentiveSurveyLayoutAttributes *result = [super copyWithZone:zone];

	result.valid = self.valid;
	result.validColor = [self.validColor copy];
	result.invalidColor = [self.invalidColor copy];
	result.backgroundColor = [self.backgroundColor copy];

	return result;
}

- (BOOL)isEqual:(id)object {
	if ([super isEqual:object]) {
		ApptentiveSurveyLayoutAttributes *other = (ApptentiveSurveyLayoutAttributes *)object;
		return self.valid == other.valid && [self.validColor isEqual:other.validColor] && [self.invalidColor isEqual:other.invalidColor] && [self.backgroundColor isEqual:other.backgroundColor];
	} else {
		return NO;
	}
}

@end


text:
module DomainNeutral
  class Engine < ::Rails::Engine
    isolate_namespace DomainNeutral
    paths['app/models'].autoload_once! # Ensure we do not loose table_name definition in development environment if overridden
  end
end


text:
/*
 * @author max
 */
package com.intellij.psi.impl.source.text;

import com.intellij.lang.ASTNode;
import com.intellij.pom.PomManager;
import com.intellij.pom.tree.TreeAspect;
import com.intellij.pom.tree.events.ChangeInfo;
import com.intellij.pom.tree.events.impl.ChangeInfoImpl;
import com.intellij.pom.tree.events.impl.ReplaceChangeInfoImpl;
import com.intellij.pom.tree.events.impl.TreeChangeEventImpl;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.PsiTreeChangeEventImpl;
import com.intellij.psi.impl.source.DummyHolder;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.util.diff.DiffTreeChangeBuilder;

public class ASTDiffBuilder implements DiffTreeChangeBuilder<ASTNode, ASTNode> {
  private final TreeChangeEventImpl myEvent;
  private final PsiFileImpl myFile;
  private final PsiManagerEx myPsiManager;
  private final boolean myIsPhysicalScope;

  public ASTDiffBuilder(final PsiFileImpl fileImpl) {
    myFile = fileImpl;
    myIsPhysicalScope = fileImpl.isPhysical();
    myPsiManager = (PsiManagerEx)fileImpl.getManager();
    myEvent = new TreeChangeEventImpl(PomManager.getModel(fileImpl.getProject()).getModelAspect(TreeAspect.class), fileImpl.getTreeElement());
  }

  public void nodeReplaced(ASTNode oldNode, ASTNode newNode) {
    if (oldNode instanceof FileElement && newNode instanceof FileElement) {
      BlockSupportImpl.replaceFileElement(myFile, (FileElement)oldNode, (FileElement)newNode, myPsiManager);
    }
    else {
      TreeUtil.ensureParsed(oldNode);
      transformNewChameleon(oldNode, newNode);

      ((TreeElement)newNode).rawRemove();
      ((TreeElement)oldNode).rawReplaceWithList((TreeElement)newNode);

      final ReplaceChangeInfoImpl change = (ReplaceChangeInfoImpl)ChangeInfoImpl.create(ChangeInfo.REPLACE, newNode);

      change.setReplaced(oldNode);
      myEvent.addElementaryChange(newNode, change);
      ((TreeElement)newNode).clearCaches();
      if (!(newNode instanceof FileElement)) {
        ((CompositeElement)newNode.getTreeParent()).subtreeChanged();
      }
      //System.out.println("REPLACED: " + oldNode + " to " + newNode);
    }
  }

  private static void transformNewChameleon(final ASTNode oldNode, ASTNode newNode) {
    if (newNode instanceof LazyParseableElement) {
      final FileElement dummyRoot = new DummyHolder(
          oldNode.getPsi().getManager(),
          oldNode.getPsi().getContainingFile(),
          SharedImplUtil.findCharTableByTree(oldNode)
      ).getTreeElement();
      dummyRoot.rawAddChildren((TreeElement)newNode);
      TreeUtil.ensureParsed(newNode);
    }
  }

  public void nodeDeleted(ASTNode parent, final ASTNode child) {
    PsiElement psiParent = parent.getPsi();
    PsiElement psiChild = myIsPhysicalScope ? child.getPsi() : null;

    PsiTreeChangeEventImpl event = null;
    if (psiParent != null && psiChild != null) {
      event = new PsiTreeChangeEventImpl(myPsiManager);
      event.setParent(psiParent);
      event.setChild(psiChild);
      myPsiManager.beforeChildRemoval(event);
    }

    myEvent.addElementaryChange(child, ChangeInfoImpl.create(ChangeInfo.REMOVED, child));
    ((TreeElement)child).rawRemove();
    ((CompositeElement)parent).subtreeChanged();

    /*if (event != null) {
      myPsiManager.childRemoved(event);
    }*/

    //System.out.println("DELETED from " + parent + ": " + child);
  }

  public void nodeInserted(final ASTNode oldParent, ASTNode node, final int pos) {
    transformNewChameleon(oldParent, node);

    ASTNode anchor = null;
    for (int i = 0; i < pos; i++) {
      if (anchor == null) {
        anchor = oldParent.getFirstChildNode();
      }
      else {
        anchor = anchor.getTreeNext();
      }
    }

    ((TreeElement)node).rawRemove();
    if (anchor != null) {
      ((TreeElement)anchor).rawInsertAfterMe((TreeElement)node);
    }
    else {
      if (oldParent.getFirstChildNode() != null) {
        ((TreeElement)oldParent.getFirstChildNode()).rawInsertBeforeMe((TreeElement)node);
      }
      else {
        ((CompositeElement)oldParent).rawAddChildren((TreeElement)node);
      }
    }

    myEvent.addElementaryChange(node, ChangeInfoImpl.create(ChangeInfo.ADD, node));
    ((TreeElement)node).clearCaches();
    ((CompositeElement)oldParent).subtreeChanged();

    //System.out.println("INSERTED to " + oldParent + ": " + node + " at " + pos);
  }

  public TreeChangeEventImpl getEvent() {
    return myEvent;
  }
}


text:
<?php

namespace DF\MatchBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Competition
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Competition
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="libelle", type="string", length=255)
     */
    private $libelle;

    /**
     * @var string
     *
     * @ORM\Column(name="libelle_court", type="string", length=255)
     */
    private $libelleCourt;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set libelle
     *
     * @param string $libelle
     * @return Competition
     */
    public function setLibelle($libelle)
    {
        $this->libelle = $libelle;

        return $this;
    }

    /**
     * Get libelle
     *
     * @return string
     */
    public function getLibelle()
    {
        return $this->libelle;
    }

    /**
     * Set libelleCourt
     *
     * @param string $libelleCourt
     * @return Competition
     */
    public function setLibelleCourt($libelleCourt)
    {
        $this->libelleCourt = $libelleCourt;

        return $this;
    }

    /**
     * Get libelleCourt
     *
     * @return string
     */
    public function getLibelleCourt()
    {
        return $this->libelleCourt;
    }
}


text:
<!--
  ~ Copyright (c) 2015 Evan Tatarka
  ~
  ~ 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.
  ~
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    tools:context="me.tatarka.retainstate.sample.MyFragment">

    <Button
        android:id="@+id/button_load_from_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load From Fragment" />

    <TextView
        android:id="@+id/result_load_from_fragment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="right"
        tools:text="Hello World!" />
</LinearLayout>


text:
package io.shiftleft.semanticcpg.language.types.structure

import io.shiftleft.codepropertygraph.generated.nodes
import io.shiftleft.codepropertygraph.generated.nodes._
import io.shiftleft.semanticcpg.language._
import overflowdb.traversal.Traversal

/** Type declaration - possibly a template that requires instantiation
  */
class TypeDeclTraversal(val traversal: Traversal[TypeDecl]) extends AnyVal {
  import TypeDeclTraversal._

  /** Annotations of the type declaration
    */
  def annotation: Traversal[nodes.Annotation] =
    traversal.flatMap(_._annotationViaAstOut)

  /** Types referencing to this type declaration.
    */
  def referencingType: Traversal[Type] =
    traversal.flatMap(_.refIn)

  /** Namespace in which this type declaration is defined
    */
  def namespace: Traversal[Namespace] =
    traversal.flatMap(_.namespaceBlock).namespace

  /** Methods defined as part of this type
    */
  def method: Traversal[Method] =
    canonicalType.flatMap(_._methodViaAstOut)

  /** Filter for type declarations contained in the analyzed code.
    */
  def internal: Traversal[TypeDecl] =
    canonicalType.isExternal(false)

  /** Filter for type declarations not contained in the analyzed code.
    */
  def external: Traversal[TypeDecl] =
    canonicalType.isExternal(true)

  /** Member variables
    */
  def member: Traversal[Member] =
    canonicalType.flatMap(_._memberViaAstOut)

  /** Direct base types in the inheritance graph.
    */
  def baseType: Traversal[Type] =
    canonicalType.flatMap(_._typeViaInheritsFromOut)

  /** Direct base type declaration.
    */
  def derivedTypeDecl: Traversal[TypeDecl] =
    referencingType.derivedTypeDecl

  /** Direct and transitive base type declaration.
    */
  def derivedTypeDeclTransitive: Traversal[TypeDecl] =
    traversal.repeat(_.derivedTypeDecl)(_.emitAllButFirst)

  /** Direct base type declaration.
    */
  def baseTypeDecl: Traversal[TypeDecl] =
    traversal.baseType.referencedTypeDecl

  /** Direct and transitive base type declaration.
    */
  def baseTypeDeclTransitive: Traversal[TypeDecl] =
    traversal.repeat(_.baseTypeDecl)(_.emitAllButFirst)

  /** Traverse to alias type declarations.
    */
  def isAlias: Traversal[TypeDecl] =
    traversal.filter(_.aliasTypeFullName.isDefined)

  /** Traverse to canonical type declarations.
    */
  def isCanonical: Traversal[TypeDecl] =
    traversal.filter(_.aliasTypeFullName.isEmpty)

  /** If this is an alias type declaration, go to its underlying type declaration else unchanged.
    */
  def unravelAlias: Traversal[TypeDecl] = {
    traversal.map { typeDecl =>
      val alias = for {
        tpe      <- typeDecl.aliasedType.nextOption()
        typeDecl <- tpe.referencedTypeDecl.nextOption()
      } yield typeDecl

      alias.getOrElse(typeDecl)
    }
  }

  /** Traverse to canonical type which means unravel aliases until we find a non alias type declaration.
    */
  def canonicalType: Traversal[TypeDecl] =
    traversal.repeat(_.unravelAlias)(_.until(_.isCanonical).times(maxAliasExpansions))

  /** Direct alias type declarations.
    */
  def aliasTypeDecl: Traversal[TypeDecl] =
    referencingType.aliasTypeDecl

  /** Direct and transitive alias type declarations.
    */
  def aliasTypeDeclTransitive: Traversal[TypeDecl] =
    traversal.repeat(_.aliasTypeDecl)(_.emitAllButFirst)

}

object TypeDeclTraversal {
  private val maxAliasExpansions = 100
}


text:
package com.danieloskarsson.json.persistence;

import java.io.IOException;

final class File implements JsonPersistenceInterface {

	private static final String FILENAME = "json.dat";

	public File() {
		java.io.File file = new java.io.File(FILENAME);
		if(file.exists() == false) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				throw new JsonPersistenceException(e.getMessage(), e);
			}
		}
	}

	public void save(String type, String json) throws JsonPersistenceException {
		// TODO Auto-generated method stub

	}

	public String load(String type) throws JsonPersistenceException {
		// Scanner scanner = new Scanner(new java.io.File(FILENAME));

		// TODO Auto-generated method stub
		return null;
	}

}


text:
'use strict';

import 'source-map-support/register';
import * as sinon from 'sinon';
import { assert } from 'chai';
import RED from 'node-red';
import * as bleio from '../lib/bleio';

const BLEIO_CHARS = [
  {
    subscribe: () => {},
    on: () => {},
    notify: () => {},
    write: () => {},
    read: () => {},
    uuid:'feedaa02594246d5ade581c064d03a03',
    name:null,
    type:null,
    properties:[
      'read',
      'write'
    ],
    descriptors:null,
  },
  {
    subscribe: () => {},
    on: () => {},
    notify: () => {},
    write: () => {},
    read: () => {},
    uuid:'feedaa03594246d5ade581c064d03a03',
    name:null,
    type:null,
    properties:[
      'read',
      'write'
    ],
    descriptors:null
  },
  {
    subscribe: () => {},
    on: () => {},
    notify: () => {},
    write: () => {},
    read: () => {},
    uuid:'feedaa04594246d5ade581c064d03a03',
    name:null,
    type:null,
    properties:[
      'read',
      'notify'
    ],
    descriptors:null
  },
  {
    subscribe: () => {},
    on: () => {},
    notify: () => {},
    write: () => {},
    read: () => {},
    uuid:'feedaa05594246d5ade581c064d03a03',
    name:null,
    type:null,
    properties:[
      'read',
      'notify'
    ],
    descriptors:null
  },
  {
    subscribe: () => {},
    on: () => {},
    notify: () => {},
    write: () => {},
    read: () => {},
    uuid:'feedaa06594246d5ade581c064d03a03',
    name:null,
    type:null,
    properties:[
      'read',
      'write'
    ],
    descriptors:null
  },
  {
    subscribe: () => {},
    on: () => {},
    notify: () => {},
    write: () => {},
    read: () => {},
    uuid:'feedaa07594246d5ade581c064d03a03',
    name:null,
    type:null,
    properties:[
      'read',
      'write'
    ],
    descriptors:null
  }
];

let server = sinon.spy();
let settings = sinon.spy();
RED.init(server, settings);

describe('bleio module', () => {
  RED.debug = true;
  let sandbox;
  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    RED._ = sinon.spy();
    bleio.reset();
  });
  afterEach(() => {
    sandbox = sandbox.restore();
  });
  describe('valToBuffer()', () => {
    it('should translate a numeric number into a buffer', () => {
      assert.deepEqual(new Buffer([0x0A]), bleio.valToBuffer(10));
      assert.deepEqual(new Buffer([0x00, 0x0A]), bleio.valToBuffer(10, 2));
      assert.deepEqual(new Buffer([0x01, 0xF4]), bleio.valToBuffer(500));
      assert.deepEqual(new Buffer([0x01, 0xF4]), bleio.valToBuffer(500, 2));
      assert.deepEqual(new Buffer([0x10]), bleio.valToBuffer(16));
      assert.deepEqual(new Buffer([0x00, 0x10]), bleio.valToBuffer(16, 2));
    });
    it('should translate a hex number into a buffer', () => {
      assert.deepEqual(new Buffer([0x0A]), bleio.valToBuffer('a'));
      assert.deepEqual(new Buffer([0x00, 0x0A]), bleio.valToBuffer('a', 2));
      assert.deepEqual(new Buffer([0x10]), bleio.valToBuffer('10'));
      assert.deepEqual(new Buffer([0x00, 0x10]), bleio.valToBuffer('10', 2));
    });
    it('should translate an int array into a buffer', () => {
      assert.deepEqual(new Buffer([0x0A]), bleio.valToBuffer([10]));
      assert.deepEqual(new Buffer([0x00, 0x0A]), bleio.valToBuffer([10], 2));
      assert.deepEqual(new Buffer([0x10]), bleio.valToBuffer([16]));
      assert.deepEqual(new Buffer([0x00, 0x10]), bleio.valToBuffer([16], 2));
    });
  });
  describe('acceptFunc()', () => {
    it('should return true if localName starts with BLEIo_ and its length is 7', () => {
      assert.isTrue(bleio.acceptFunc('BLEIo_0'));
      assert.isTrue(bleio.acceptFunc('BLEIo_F'));
      assert.isFalse(bleio.acceptFunc('BLEIo_01'));
      assert.isFalse(bleio.acceptFunc(''));
      assert.isFalse(bleio.acceptFunc(null));
    });
  });
  describe('registration and removal', () => {
    let testPeripheral;
    let testNode;
    let testPeripheral2;
    let testNode2;
    let characteristics;
    let sandbox;
    beforeEach(() => {
      bleio.reset();
      sandbox = sinon.sandbox.create();
      testPeripheral = sandbox.stub({
        on: () => {},
        removeListener: () => {},
        discoverSomeServicesAndCharacteristics: () => {},
        disconnect: () => {},
        connect: () => {},
        terminate: () => {},
        address: 'CC:5E:66:DD:0B:88',
        test: true
      });
      testNode = sandbox.stub({
        removeAllListeners: () => {},
        send: () => {},
        on: () => {},
        emit: () => {},
        in: false,
        bleioNode: {
          localName: 'BLEIo_0',
          address: 'CC:5E:66:DD:0B:88'
        },
        id: '1111'
      });
      testPeripheral2 = sandbox.stub({
        on: () => {},
        removeListener: () => {},
        discoverSomeServicesAndCharacteristics: () => {},
        disconnect: () => {},
        connect: () => {},
        terminate: () => {},
        address: 'FF:5E:66:DD:0B:FF',
        test: true
      });
      testNode2 = sandbox.stub({
        removeAllListeners: () => {},
        send: () => {},
        on: () => {},
        emit: () => {},
        in: true,
        bleioNode: {
          localName: 'BLEIo_F',
          address: ''
        },
        id: '2222'
      });
      characteristics = BLEIO_CHARS.map((c) => {
        c.subscribed = false;
        return sandbox.stub(c);
      });
    });
    afterEach(() => {
      sandbox = sandbox.restore();
    });

    describe('register()', () => {
      it('should register a new node', done => {
        // connect
        testPeripheral.on.onFirstCall().yields(null);
        testPeripheral.discoverSomeServicesAndCharacteristics.yields(
          null, null, characteristics);
        characteristics.forEach((c) => {
          c.subscribe.yields(null);
          // on('data') => node.send()
          c.on.yields(new Buffer('12', 'hex'), true);
        });
        // node.on()
        testNode.on.yields({
          payload: {
            type: 'DIN'
          }
        });

        // disconnect
        testPeripheral.on.onSecondCall().yields(null);

        delete testNode.peripheral;
        bleio.register(testNode, RED);
        function waitUntilDone() {
          if (testNode.peripheral) {
            assert.equal(6, characteristics.filter((c) => {
              return c.subscribed;
            }).length);
            assert.equal(1, characteristics.filter((c) => {
              return c.read.called;
            }).length);
            assert.isFalse(testNode.send.called);
            return done();
          }
          setTimeout(waitUntilDone, 1000);
        }
        setTimeout(() => {
          bleio.discoverFunc('BLEIo_0', testPeripheral, RED);
          waitUntilDone();
        }, 2000);
      }).timeout(10000);
      it('should register a new node with wildcard', done => {
        // connect
        testPeripheral2.on.onFirstCall().yields(null);
        testPeripheral2.discoverSomeServicesAndCharacteristics.yields(
          null, null, characteristics);
        characteristics.forEach((c) => {
          c.subscribe.yields(null);
          // on('data') => node.send()
          c.on.yields(new Buffer('12', 'hex'), true);
        });

        // disconnect
        testPeripheral2.on.onSecondCall().yields(null);

        delete testNode2.peripheral;
        console.log('<<<<register=========================================');
        bleio.register(testNode2, RED);
        function waitUntilDone() {
          if (testNode2.peripheral) {
            console.log('>>>register=========================================');
            assert.isTrue(testNode2.send.called);
            return done();
          }
          setTimeout(waitUntilDone, 1000);
        }
        setTimeout(() => {
          bleio.discoverFunc('BLEIo_F', testPeripheral2, RED);
          waitUntilDone();
        }, 2000);
      }).timeout(10000);
    });
  });
});

describe('registration and removal without stub', () => {
  let testPeripheral = {
    on: () => {},
    removeListener: () => {},
    discoverSomeServicesAndCharacteristics: () => {},
    disconnect: () => {},
    connect: () => {},
    terminate: () => {},
    address: 'CC:5E:66:DD:0B:88',
    test: true
  };
  let testNode = {
    removeAllListeners: () => {},
    on: () => {},
    emit: () => {},
    bleioNode: {
      localName: 'BLEIo_0',
      address: 'CC:5E:66:DD:0B:88'
    },
    id: '1111'
  };
  let testPeripheral2 = {
    on: () => {},
    discoverSomeServicesAndCharacteristics: () => {},
    disconnect: () => {},
    connect: () => {},
    terminate: () => {},
    address: 'FF:5E:66:DD:0B:FF',
    test: true
  };
  let testNode2 = {
    removeAllListeners: () => {},
    on: () => {},
    emit: () => {},
    bleioNode: {
      localName: 'BLEIo_F',
      address: ''
    },
    id: '2222'
  };
  before(() => {
    bleio.reset();
  });
  describe('register()', () => {
    it('should register a new node', done => {
      delete testNode.peripheral;
      bleio.register(testNode, RED);
      function waitUntilDone() {
        if (testNode.peripheral) {
          return done();
        }
        setTimeout(waitUntilDone, 1000);
      }
      setTimeout(() => {
        bleio.discoverFunc('BLEIo_0', testPeripheral, RED);
        waitUntilDone();
      }, 2000);
    }).timeout(10000);
    it('should register a new node with wildcard', done => {
      delete testNode2.peripheral;
      bleio.register(testNode2, RED);
      function waitUntilDone() {
        if (testNode2.peripheral) {
          return done();
        }
        setTimeout(waitUntilDone, 1000);
      }
      setTimeout(() => {
        bleio.discoverFunc('BLEIo_F', testPeripheral2, RED);
        waitUntilDone();
      }, 2000);
    }).timeout(10000);
  });
  describe('remove()', () => {
    it('should remove the existing node', done => {
      assert.isDefined(testNode.peripheral); // defined by register()
      assert.isTrue(bleio.remove(testNode, RED));
      function waitUntilDone() {
        if (!testNode.peripheral) {
          done();
        }
        setTimeout(waitUntilDone, 1000);
      }
      waitUntilDone();
    }).timeout(10000);
  });
});


text:
<!DOCTYPE html>

<?php
session_start();
require_once('../mysql_connect.php');
$currentEmployeeNum = $_SESSION['emp_number'];
if(isset($_POST['link'])){
	$formNum = $_POST['link'];
}
if(isset($_POST['submit'])){
	$formNum = $_POST['submit'];
}
$currentDate = date('Y-m-d');
$statusA = 9992;
//Getting Employees who has pending absent reversal
$queryForEmployees="SELECT 	*
							FROM 	APPLICANTS A JOIN 	EMPLOYEES E ON A.APPNO = E.APPNO
												 JOIN	REVERSALREQUESTS RQ ON E.EMPLOYEENUMBER = RQ.EMPLOYEENUMBER
						   WHERE 	RQ.FORMNUMBER = '{$formNum}'";
$result=mysqli_query($dbc,$queryForEmployees);
$rows=mysqli_fetch_array($result,MYSQLI_ASSOC);
$names = $rows['FIRSTNAME'].' '.$rows['LASTNAME'];
$position = $rows['ACTUALPOSITION'];
$dateFiled = $rows['DATE'];
$dateReversal = $rows['TABLEDATE'];
$morningIn = $rows['MORNINGTIMEIN_REQUEST'];
$lunchIn = $rows['LUNCHTIMEIN_REQUEST'];
$breakIn = $rows['BREAKTIMEIN_REQUEST'];
$lunchOut = $rows['LUNCHTIMEOUT_REQUEST'];
$breakOut = $rows['BREAKTIMEOUT_REQUEST'];
$afternoonOut = $rows['AFTERNOONTIMEOUT_REQUEST'];
$reason = $rows['REASON'];
$dmApproverID = $rows['DMAPPROVERID'];
$dmApprovedDate = $rows['DMAPPROVEDDATE'];
$dmRemarks = $rows['DMREMARKS'];
$empNum = $rows['EMPLOYEENUMBER'];

//Getting actual evaluator name
$queryForActualName="SELECT 	*
							FROM 	employees e JOIN applicants a ON e.APPNO = a.APPNO";
$resultN=mysqli_query($dbc,$queryForActualName);
while($rows=mysqli_fetch_array($resultN,MYSQLI_ASSOC))
{
	$actualNames[] = $rows['FIRSTNAME'].' '.$rows['LASTNAME'];
	$codeName[] = $rows['EMPLOYEENUMBER'];
}
$actualName = "";
for ($y=0;$y<count($actualNames);$y++)
{
	if($dmApproverID ==$codeName[$y])
	{
		$actualName = $actualNames[$y];
	}
}
//Getting Actual Position from Position code
//get all actual position
$queryForActualPosition="SELECT 	*
							FROM 	emp_positions";
$resultP=mysqli_query($dbc,$queryForActualPosition);
while($rows=mysqli_fetch_array($resultP,MYSQLI_ASSOC))
{
	$actualPos[] = $rows['EPOSITION'];
	$codePos[] = $rows['POSITION'];
}
//create array containing actual position
$positionName = "";
for ($x=0;$x<count($actualPos);$x++)
{
	if($position==$codePos[$x])
	{
		$positionName = $actualPos[$x];
	}
}

if (isset($_POST['submit'])){
	$message=NULL;

	if (empty($_POST['HRremarks'])){
		$remarks=NULL;
		$message.='
You forgot to enter the time reversal!';
	}else
		$remarks=$_POST['HRremarks'];

if(!isset($message)){
require_once('../mysql_connect.php');
$query="UPDATE 	reversalrequests
		   SET	HRREMARKS = '{$remarks}', HRAPPROVERID = '{$currentEmployeeNum}', HRAPPROVEDDATE = '{$currentDate}', STATUS = '{$statusA}'
		 WHERE	FORMNUMBER = '{$formNum}' ";
$result=mysqli_query($dbc,$query);

$query1="UPDATE 	timetable
			SET		MORNINGTIMEIN_REQUEST = '{$morningIn}', BREAKTIMEIN_REQUEST = '{$breakIn}', LUNCHTIMEIN_REQUEST = '{$lunchIn}',LUNCHTIMEOUT_REQUEST = '{$lunchOut}',BREAKTIMEOUT_REQUEST = '{$breakOut}',AFTERNOONTIMEOUT_REQUEST = '{$afternoonOut}'
		  WHERE		TABLEDATE = '{$dateReversal}'
			AND 	EMPLOYEENUMBER = '{$empNum}'";
$result1=mysqli_query($dbc,$query1);
echo "

  		Success! Timetable Updated!

";
									}
}

if (isset($message)){
	echo ''.$message. '';
}
?>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/morris.css">

    <link rel="stylesheet" href="css/custom.css">
    <link rel="stylesheet" href="css/custom-theme.css">

    <title>Absent Reversal Request</title>

Logout

Welcome!

HR Manager

                 Home

                 Recruitment

                 Employees

				 Attendance

				 Calendar

                     Reports

                         &#x25cf Leave
                         &#x25cf Overtime
                         &#x25cf Undertime
                         &#x25cf Absent Reversal
                        &#x25cf Itinerary Authorization

                     Visual Reports

                         &#x25cf Employee Tardiness
                         &#x25cf Employee Tenure
                         &#x25cf Manpower Architects
                         &#x25cf Manpower Engineers
                        &#x25cf Recruitment Newly Hired

                     Requests

                         &#x25cf Leave
                         &#x25cf Overtime
                         &#x25cf Undertime
                         &#x25cf Absent Reversal
                        &#x25cf Itinerary Authorization
                         &#x25cf Manpower
                         &#x25cf Resignation
                        &#x25cf Change Record

                 About

Detailed Absent Reversal

                              <form id="wizard-validation-form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

											Name

											<?php echo $names?>

											Position

											<?php echo $positionName?>

											Date Filed

											<?php echo $dateFiled?>

											Reversal Date

											<?php echo $dateReversal?>

											Morning In

												<?php echo $morningIn?>

											Lunch In

												<?php echo $lunchIn?>

											 Break In

												<?php echo $breakIn?>

											Lunch Out

												<?php echo $lunchOut?>

											 Break Out

												<?php echo $breakOut?>

											Afternoon Out

												<?php echo $afternoonOut?>

											Reason

												<?php echo $reason?>

											Approved By

												<?php echo $actualName?>

											 Approved Date

												<?php echo $dmApprovedDate?>

											Approver Remarks

												<?php echo $dmRemarks?>

											HR Manager Remarks

													<input type="text" name="HRremarks" class="form-control">

												<button class="btn btn-success" type="submit" name="submit" value="<?php echo $formNum?>" onclick="myFunction()">Approve</button>

												<button class="btn btn-danger"  name="reject" onclick="myFunction()">Reject</button>

                              </form>


text:
This is a Symfony2 bundle for error and exception handling and logging. It also includes component/service for formatting user readable exception messages according to environment.

[![Build Status](https://travis-ci.org/xi-project/xi-error-bundle.png)](https://travis-ci.org/xi-project/xi-error-bundle)

## Installation

This bundle requires:
* PHP >=5.3
* Symfony >=2.1
* Monolog >= 1.3

Monolog 1.3 or greater and compatible Symfony Monolog bridge is required, since that's the first PSR-3 compatible version.

Add to composer.json:

    "xi/error-bundle": "1.*"

See packagist for further versions: https://packagist.org/packages/xi/error-bundle

## Exception logging

Include XiErrorBundle in your AppKernel.php, and you get automatic exception logging. Logs are created in *%kernel.logs_dir%/exception.%kernel.environment%.log*.

```php
<?php
...
    public function registerBundles()
    {
        $bundles = array(
        ...
            new Xi\Bundle\ErrorBundle\XiErrorBundle()
        ...
        );
    }
...
```

### Why use separate exception logging?

Default Symfony2 logs have lots of other stuff, that does not help much with debugging and log surveying process. This logger also includes stack traces for exceptions.

### Does this handle errors->exception conversion?

Since Symfony 2.2, errors are automatically converted to exceptions.

## Exception message formatting

During development, every bit of information helps with debugging the code as soon as errors happen. In production it is desirable to hide the actual, possibly very detailed exception message to the public, and show something generic instead.

Exception message formatter component/service takes an exception, and returns the original exception message or a general error message *depending on the current environment*. By default, the original exception message is intended to be shown to developer in **"test"** or **"dev"** environment, and end-user sees some more general error message in other environments.

```php
<?php
    $message = 'Everything went better than expected.';

    try {
        # try something dangerous
    } catch (Exception $e) {
        # use the service...
        $service = $this->get('xi_error.exception_formatter');
        $message = $service->formatMessage($e, 'could not process your form, please try again');

        # ...or the component directly
        #$message = \Xi\Bundle\ErrorBundle\Component\ExceptionFormatter::formatMessage(
        #    $e,
        #    'could not process your form, please try again',
        #    $this->get('kernel')->getEnvironment()
        #);
    }

    return new Response($message);
    ...
```


text:
'use strict';

var grunt = require('grunt');

module.exports = {

    stylesheetImport: function(test) {
        test.expect(6);

        var stylesheet = grunt.file.read('tmp/stylesheets/stylesheetImport.html');

        test.ok(stylesheet.match(/stylesheet1\.[a-z0-9]{16}\.css/), 'testing stylesheet1');
        test.ok(stylesheet.match(/stylesheet2\.[a-z0-9]{16}\.css/), 'testing stylesheet2');
        test.ok(stylesheet.match(/stylesheet4\.[a-z0-9]{16}\.css/), 'testing stylesheet4');

        test.ok(stylesheet.match(/href="\/\/netdna.bootstrapcdn.com\/twitter-bootstrap\/2.3.2\/css\/bootstrap-combined.min.css"/), 'remotely hosted // syntax should remain untouched');
        test.ok(stylesheet.match(/href="https:\/\/twitter.github.com\/bootstrap\/assets\/css\/bootstrap.css"/), 'remotely hosted https:// syntax should remain untouched');
        test.ok(stylesheet.match(/href="http:\/\/twitter.github.com\/bootstrap\/assets\/css\/bootstrap.css"/), 'remotely hosted http:// syntax should remain untouched');

        test.done();
    },

    stylesheet: function(test) {
        test.expect(8);

        var markup = grunt.file.read('tmp/stylesheets/stylesheet.css');

        test.ok(markup.match(/css-image\.[a-z0-9]{16}\.jpg/), 'testing an image in a CSS file');
        test.ok(markup.match(/css-image-quotes.[a-z0-9]{16}\.jpg/), 'testing an image in a CSS file');
        test.ok(markup.match(/css-image-large\.[a-z0-9]{16}\.jpg/), 'testing an image in a CSS file');
        test.ok(markup.match(/image1\.[a-z0-9]{16}\.jpg/), 'testing an image in a CSS file within a media query');
        test.ok(markup.match(/image2\.[a-z0-9]{16}\.jpg/), 'testing an image in a CSS file within a media query');
        test.ok(markup.match(/'\/\/www\.external\.com\/external-image1.jpg'/), 'testing an external image in a CSS file');
        test.ok(markup.match(/'http:\/\/www\.external\.com\/external-image2.jpg'/), 'testing an external image in a CSS file');
        test.ok(markup.match(/'https:\/\/www\.external\.com\/external-image3.jpg'/), 'testing an external image in a CSS file');

        test.done();
    },

    replaceCssInSubdir: function(test) {
        test.expect(4);

        var markup = grunt.file.read('tmp/stylesheets/css/replaceCssInSubdir.css');

        test.ok(markup.match(/assets\/relative-css-image\.[a-z0-9]{16}\.jpg/), 'testing the replacement of an image when css in a different subdir than asset');
        test.ok(markup.match(/assets\/relative-css-image-quotes\.[a-z0-9]{16}\.jpg/), 'testing the replacement of an image when css in a different subdir than asset');
        test.ok(markup.match(/assets\/relative-css-image-large\.[a-z0-9]{16}\.jpg/), 'testing the replacement of an image when css in a different subdir than asset');
        test.ok(markup.match(/assets\/relative-image1\.[a-z0-9]{16}\.jpg/), 'testing the replacement of an image when css in a different subdir than asset');

        test.done();
    },

    multipleUrls: function(test) {
        test.expect(5);

        var markup = grunt.file.read('tmp/stylesheets/multipleUrls.css');

        test.ok(markup.match(/assets\/fonts\/icons\.[a-z0-9]{16}\.eot/), 'testing the that multiple urls busted');
        test.ok(markup.match(/assets\/fonts\/icons\.[a-z0-9]{16}\.eot\?#iefix/), 'testing the that multiple urls busted');
        test.ok(markup.match(/assets\/fonts\/icons\.[a-z0-9]{16}\.eot/), 'testing the that multiple urls busted');
        test.ok(markup.match(/assets\/fonts\/icons\.[a-z0-9]{16}\.woff/), 'testing the that multiple urls busted');
        test.ok(markup.match(/assets\/fonts\/icons\.[a-z0-9]{16}\.ttf/), 'testing the that multiple urls busted');

        test.done();
    }

};


text:
"""
Miscellaneous utility functions for use in generating responses.

Why not swift.common.utils, you ask? Because this way we can import things
from swob in here without creating circular imports.
"""

from swift.common.constraints import FORMAT2CONTENT_TYPE
from swift.common.swob import HTTPBadRequest, HTTPNotAcceptable
from swift.common.ondisk import validate_device_partition
from swift.common.utils import split_path
from urllib import unquote

def get_param(req, name, default=None):
    """
    Get parameters from an HTTP request ensuring proper handling UTF-8
    encoding.

    :param req: request object
    :param name: parameter name
    :param default: result to return if the parameter is not found
    :returns: HTTP request parameter value
              (as UTF-8 encoded str, not unicode object)
    :raises: HTTPBadRequest if param not valid UTF-8 byte sequence
    """
    value = req.params.get(name, default)
    if value and not isinstance(value, unicode):
        try:
            value.decode('utf8')    # Ensure UTF8ness
        except UnicodeDecodeError:
            raise HTTPBadRequest(
                request=req, content_type='text/plain',
                body='"%s" parameter not valid UTF-8' % name)
    return value

def get_listing_content_type(req):
    """
    Determine the content type to use for an account or container listing
    response.

    :param req: request object
    :returns: content type as a string (e.g. text/plain, application/json)
    :raises: HTTPNotAcceptable if the requested content type is not acceptable
    :raises: HTTPBadRequest if the 'format' query param is provided and
             not valid UTF-8
    """
    query_format = get_param(req, 'format')
    if query_format:
        req.accept = FORMAT2CONTENT_TYPE.get(
            query_format.lower(), FORMAT2CONTENT_TYPE['plain'])
    out_content_type = req.accept.best_match(
        ['text/plain', 'application/json', 'application/xml', 'text/xml'])
    if not out_content_type:
        raise HTTPNotAcceptable(request=req)
    return out_content_type

def split_and_validate_path(request, minsegs=1, maxsegs=None,
                            rest_with_last=False):
    """
    Utility function to split and validate the request path.

    :returns: result of split_path if everything's okay
    :raises: HTTPBadRequest if something's not okay
    """
    try:
        segs = split_path(unquote(request.path),
                          minsegs, maxsegs, rest_with_last)
        validate_device_partition(segs[0], segs[1])
        return segs
    except ValueError as err:
        raise HTTPBadRequest(body=str(err), request=request,
                             content_type='text/plain')