text:
// <copyright file="MemberServiceTest.cs" company="Logikfabrik">
//   Copyright (c) 2016 anton(at)logikfabrik.se. Licensed under the MIT license.
// </copyright>

namespace Logikfabrik.Umbraco.Jet.Test.Web.Data
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using global::Umbraco.Core.Models;
    using Jet.Web.Data;
    using Moq.AutoMock;
    using Shouldly;
    using SpecimenBuilders;
    using Utilities;
    using Xunit;

    public class MemberServiceTest
    {
        [Theory]
        [CustomAutoData]
        public void CanGetContentIdByConvention(int id, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "Id", id.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.Id).Returns(id);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("Id").ShouldBe(id);
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentUrlByConvention(int id, string url, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "Url", url.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.Url).Returns(url);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("Url").ShouldBe(url);
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentNameByConvention(int id, string name, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "Name", name.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.Name).Returns(name);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("Name").ShouldBe(name);
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentCreateDateByConvention(int id, DateTime createDate, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "CreateDate", createDate.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.CreateDate).Returns(createDate);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("CreateDate").ShouldBe(createDate);
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentUpdateDateByConvention(int id, DateTime updateDate, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "UpdateDate", updateDate.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.UpdateDate).Returns(updateDate);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("UpdateDate").ShouldBe(updateDate);
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentCreatorIdByConvention(int id, int creatorId, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "CreatorId", creatorId.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.CreatorId).Returns(creatorId);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("CreatorId").ShouldBe(creatorId);
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentCreatorNameByConvention(int id, string creatorName, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "CreatorName", creatorName.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.CreatorName).Returns(creatorName);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("CreatorName").ShouldBe(creatorName);
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentWriterIdByConvention(int id, int writerId, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "WriterId", writerId.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.WriterId).Returns(writerId);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("WriterId").ShouldBe(writerId);
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentWriterNameByConvention(int id, string writerName, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, "WriterName", writerName.GetType());

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.WriterName).Returns(writerName);

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue("WriterName").ShouldBe(writerName);
        }

        [Fact]
        public void CanNotGetContentForInvalidType()
        {
            var mocker = new AutoMocker();

            var service = mocker.CreateInstance<MemberService>();

            Assert.Throws<ArgumentException>(() => service.GetContent(mocker.Get<IPublishedContent>(), typeof(object)));
        }

        [Theory]
        [CustomAutoData]
        public void CanGetContentForValidType(MemberTypeModelTypeBuilder builder)
        {
            var mocker = new AutoMocker();

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(mocker.Get<IPublishedContent>(), builder.Create(Scope.Public));

            content.ShouldNotBeNull();
        }

        [Theory]
        [ClassAutoData(typeof(CanGetContentForTypeWithPropertyClassData))]
        public void CanGetContentForTypeWithProperty(Type propertyType, object propertyValue, string propertyName, int id, MemberTypeModelTypeBuilder builder)
        {
            builder.AddProperty(Scope.Public, Accessors.GetSet, propertyName, propertyType);

            var mocker = new AutoMocker();

            var contentMock = mocker.GetMock<IPublishedContent>();

            contentMock.Setup(m => m.Properties).Returns(() =>
            {
                var property = mocker.GetMock<IPublishedProperty>();

                property.Setup(m => m.PropertyTypeAlias).Returns(propertyName);
                property.Setup(m => m.Value).Returns(propertyValue);

                return new[] { property.Object };
            });

            var umbracoHelperWrapperMock = mocker.GetMock<IUmbracoHelperWrapper>();

            umbracoHelperWrapperMock.Setup(m => m.TypedMember(id)).Returns(contentMock.Object);

            var service = mocker.CreateInstance<MemberService>();

            var content = service.GetContent(id, builder.Create(Scope.Public));

            content.GetPropertyValue(propertyName).ShouldBe(propertyValue);
        }

        private class CanGetContentForTypeWithPropertyClassData : IEnumerable<object[]>
        {
            public IEnumerator<object[]> GetEnumerator()
            {
                yield return new object[] { typeof(string), "abc123" };
                yield return new object[] { typeof(int), 1 };
                yield return new object[] { typeof(float), 1.1f };
                yield return new object[] { typeof(decimal), 1.1m };
                yield return new object[] { typeof(bool), true };
                yield return new object[] { typeof(DateTime), DateTime.Now };
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context="com.rubberduck.materialjumpstart.fragments.MainFragment">

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

    <include layout="@layout/main_card" />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
var App = require('app');

App.MainController = Em.Controller.extend({
  name: 'mainController',
  isUserActive: true,
  checkActivenessInterval: null,
  lastUserActiveTime: null,
  userTimeOut: 0,
  userTimeOutModal: null,

  updateTitle: function(){
    var name = App.router.get('clusterController.clusterName');
    if(App.router.get('clusterInstallCompleted')) {
      if (name && App.router.get('clusterController').get('isLoaded')) {
        name = name.length > 13 ? name.substr(0, 10) + "..." : name;
      } else {
        name = Em.I18n.t('common.loading');
      }
      $('title').text(Em.I18n.t('app.name.subtitle').format(name));
    }
  }.observes('App.router.clusterController.clusterName', 'App.router.clusterInstallCompleted', 'App.router.clusterController.isLoaded'),

  isClusterDataLoaded: Em.computed.alias('App.router.clusterController.isLoaded'),

  clusterDataLoadedPercent: Em.computed.alias('App.router.clusterController.clusterDataLoadedPercent'),
  /**
   * run all processes and cluster's data loading
   */
  initialize: function(){
    // Since we use only defaultTransaction, we can stub removeCleanRecords method,
    // because it would remove from and add records to the same (default) transaction
    App.store.defaultTransaction.reopen({
      removeCleanRecords: Em.K
    });
    const startSubscription = App.router.get('updateController').startSubscriptions.bind(App.router.get('updateController'));
    App.StompClient.connect()
      .done(startSubscription)
      .fail((dfd) => {dfd.always(startSubscription)});
    App.router.get('clusterController').loadClusterData();
  },

  dataLoading: function () {
    var self = this;
    var dfd = $.Deferred();
    if (App.router.get('clusterController.isLoaded')) {
      dfd.resolve();
    } else {
      var interval = setInterval(function () {
        if (self.get('isClusterDataLoaded')) {
          dfd.resolve();
          clearInterval(interval);
        }
      }, 50);
    }
    return dfd.promise();
  },

  /**
   *
   * @param isLoaded {Boolean}
   * @param opts {Object}
   * {
   *   period {Number}
   * }
   * @return {*|{then}}
   */
  isLoading: function(isLoaded, opts) {
    var dfd = $.Deferred();
    var self = this;
    opts = opts || {};
    var period =  opts.period || 20;
    if (this.get(isLoaded)) {
      dfd.resolve();
    } else {
      var interval = setInterval(function () {
        if (self.get(isLoaded)) {
          dfd.resolve();
          clearInterval(interval);
        }
      }, period);
    }
    return dfd.promise();
  },

  startPolling: function () {
    if (App.router.get('applicationController.isExistingClusterDataLoaded')) {
      App.router.get('updateController').set('isWorking', true);
    }
  }.observes('App.router.applicationController.isExistingClusterDataLoaded'),

  stopPolling: function(){
    App.router.get('updateController').set('isWorking', false);
  },

  reloadTimeOut: null,

  pageReload: function () {

    clearTimeout(this.get("reloadTimeOut"));

    this.set('reloadTimeOut',
    setTimeout(function () {
      if (App.clusterStatus.get('isInstalled')) {
        location.reload();
      }
    }, App.pageReloadTime)
    );
  }.observes("App.router.location.lastSetURL", "App.clusterStatus.isInstalled"),

  setAmbariServerVersion: function (data) {
    var clientVersion = App.get('version');
    var serverVersion = (data.RootServiceComponents.component_version).toString();
    this.set('ambariServerVersion', serverVersion);
    if (clientVersion) {
      this.set('versionConflictAlertBody', Em.I18n.t('app.versionMismatchAlert.body').format(serverVersion, clientVersion));
      this.set('isServerClientVersionMismatch', clientVersion !== serverVersion);
    } else {
      this.set('isServerClientVersionMismatch', false);
    }
    App.set('isManagedMySQLForHiveEnabled', App.config.isManagedMySQLForHiveAllowed(data.RootServiceComponents.properties['server.os_family']));
  },

  monitorInactivity: function() {
    var timeout = Number(App.router.get('clusterController.ambariProperties')['user.inactivity.timeout.default']);
    var readonly_timeout = Number(App.router.get('clusterController.ambariProperties')['user.inactivity.timeout.role.readonly.default']);
    var isAdmin = App.get('isAdmin');
    if (isAdmin && timeout > 0) {
      this.set('userTimeOut', timeout * 1000);
    } else if (!isAdmin && readonly_timeout > 0) {
      this.set('userTimeOut', readonly_timeout * 1000);
    }
    if (this.get('userTimeOut') > 0) {
      this.startMonitorInactivity();
    }
  },

  startMonitorInactivity: function() {
    this.set('isUserActive', true);
    this.set('lastUserActiveTime', Date.now());

    this.rebindActivityEventMonitors();
    if (!this.get('checkActivenessInterval')) {
      this.set('checkActivenessInterval', window.setInterval(this.checkActiveness, 1000));
    }
  },

  /* this will be triggerred by user driven events: 'mousemove', 'keypress' and 'click' */
  keepActive: function() {
    var scope = App.router.get('mainController');
    if (scope.get('isUserActive')) {
      scope.set('lastUserActiveTime', Date.now());
    }
  },

  checkActiveness: function() {
    var scope = App.router.get('mainController');
    if (!scope.isOnWizard()) {
      var remainTime = scope.get('userTimeOut') - (Date.now() - scope.get('lastUserActiveTime'));
      if (remainTime < 0) {
        scope.set('isUserActive', false);
        scope.unbindActivityEventMonitors();
        clearInterval(scope.get('checkActivenessInterval'));
        App.router.logOff({});
      } else if (remainTime < App.inactivityRemainTime * 1000 && !scope.userTimeOutModal) {
        // show alert 60 seconds before logging user out
        scope.userTimeOutModal = App.ModalPopup.show({
          primary: Em.I18n.t('common.timeout.warning.popup.primary'),
          secondary: Em.I18n.t('common.timeout.warning.popup.secondary'),
          third: false,
          header: Em.I18n.t('common.timeout.warning.popup.header'),
          showCloseButton: false,
          bodyClass: Ember.View.extend({
            template: Ember.Handlebars.compile('
{{view.beforeMsg}}{{view.remainTime}}{{view.afterMsg}}
'),
            beforeMsg: Em.I18n.t('common.timeout.warning.popup.body.before'),
            afterMsg: Em.I18n.t('common.timeout.warning.popup.body.after'),
            remainTime: App.inactivityRemainTime,
            didInsertElement: function() {
              var self = this;
              setInterval(function(){self.countDown();}, 1000)
            },
            countDown: function() {
              if (this.get('remainTime') > 0) {
                this.set('remainTime', this.get('remainTime') - 1);
              }
              if (this.get('remainTime') == 0) {
                App.router.logOff({});
              }
            }
          }),
          onPrimary: function() {
            scope.keepActive();
            scope.userTimeOutModal.hide();
            delete scope.userTimeOutModal;
          },
          onSecondary: function() {
            scope.userTimeOutModal.hide();
            delete scope.userTimeOutModal;
            App.router.logOff({});
          }
        });
      }
    }
  },

  rebindActivityEventMonitors: function() {
    this.unbindActivityEventMonitors();
    this.bindActivityEventMonitors();
  },

  isOnWizard: function() {
    var isWizard = window.location.href.indexOf('/step') != -1;
    var isUpgrade = window.location.href.indexOf('/stack/upgrade') != -1;
    return isWizard || isUpgrade;
  },

  bindActivityEventMonitors: function() {
    $(window).bind('mousemove', this.keepActive);
    $(window).bind('keypress', this.keepActive);
    $(window).bind('click', this.keepActive);
    // iframes need to be monitored as well
    var iframes = $('iframe');
    if (iframes.length > 0) {
      for (var i = 0; i < iframes.length; i++) {
        var iframe = iframes[i];
        $(iframe.contentWindow).bind('mousemove', this.keepActive);
        $(iframe.contentWindow).bind('keypress', this.keepActive);
        $(iframe.contentWindow).bind('click', this.keepActive);
      }
    }
  },

  unbindActivityEventMonitors: function() {
    $(window).unbind('mousemove', this.keepActive);
    $(window).unbind('keypress', this.keepActive);
    $(window).unbind('click', this.keepActive);
    // iframes need to be monitored as well
    var iframes = $('iframe');
    if (iframes.length > 0) {
      for (var i = 0; i < iframes.length; i++) {
        var iframe = iframes[i];
        $(iframe.contentWindow).unbind('mousemove', this.keepActive);
        $(iframe.contentWindow).unbind('keypress', this.keepActive);
        $(iframe.contentWindow).unbind('click', this.keepActive);
      }
    }
  }
});


text:
package cn.sheep3.service;

import cn.sheep3.entity.Post;
import cn.sheep3.model.status.PostStatus;
import cn.sheep3.exception.PostInputException;
import cn.sheep3.repository.PostRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.sheep3.config.Constant.PAGE_CACHE_NAME;
import static cn.sheep3.config.Constant.POST_CACHE_NAME;

/**
 * Created by sheep3 on 16-9-16.
 */
@Slf4j
@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostRepository postRepo;

    @Autowired
    private UserService userSrv;

    @Autowired
    private TagService tagSrv;

    @CachePut(value = POST_CACHE_NAME, key = "'post_cache_key_'+#title")
    @CacheEvict(value = PAGE_CACHE_NAME, allEntries = true)
    @Override
    public Post editPost(Long id, String title, String markdown, String html, List<String> tagStringList) throws Exception {
        if (id < 0) {
            throw new PostInputException("不存在的文章!");
        } else if (StringUtils.isBlank(title)) {
            throw new PostInputException("标题不可为空!");
        }
        Post tmpPost = postRepo.findByPostTitle(title);
        if (tmpPost != null && tmpPost.getId() != id) {
            throw new PostInputException("标题不能重复!");
        }

        Post post = postRepo.findOne(id);
        post.setUser(userSrv.getUser());
        post.setPostTitle(title);
        post.setPostContent(markdown);
        post.setPostShow(html);
        post.setTags(tagSrv.strListToTagList(tagStringList));

        return postRepo.save(post);
    }

    @CachePut(value = POST_CACHE_NAME, key = "'post_cache_key_'+#title")
    @CacheEvict(value = PAGE_CACHE_NAME, allEntries = true)
    @Override
    public Post pushPost(String title, String markdown, String html, List<String> tagStringList, PostStatus postStatus) throws Exception {
        if (StringUtils.isBlank(title)) {
            throw new PostInputException("标题不能为空!");
        } else if (findByPostTitle(title) != null) {
            throw new PostInputException("标题不能重复!");
        }

        Post post = new Post();
        post.setUser(userSrv.getUser());
        post.setPostStatus(postStatus);
        post.setPostTitle(title);
        post.setPostContent(markdown);
        post.setPostShow(html);
        post.setTags(tagSrv.strListToTagList(tagStringList));

        return postRepo.save(post);
    }

    @Cacheable(value = POST_CACHE_NAME, key = "'post_cache_key_'+#postTitle")
    @Override
    public Post findByPostTitle(String postTitle) throws PostInputException {
        if (StringUtils.isBlank(postTitle)) {
            throw new PostInputException("标题不能为空!");
        }

        return postRepo.findByPostTitle(postTitle);
    }

    @Cacheable(value = PAGE_CACHE_NAME, key = "'page_cache_key_'+#page+'_'+#size")
    @Override
    public Page<Post> findPostByIndexAndSize(int page, int size) {
        if (size < 1 || page < 0) {
            log.error("错误的分页数据:page=" + page + ",size=" + size);
            return null;
        }

        Sort sort = new Sort(Sort.Direction.DESC, "createdDate");
        Pageable pageable = new PageRequest(page, size, sort);

        return postRepo.findAll(pageable);
    }

    @Cacheable(value = PAGE_CACHE_NAME, key = "'hot_page_cache_key_'")
    @Override
    public Page<Post> getHotPost() {
        Sort sort = new Sort(Sort.Direction.DESC, "lastModifiedDate");
        Pageable pageable = new PageRequest(0, 10, sort);
        return postRepo.findAll(pageable);
    }

    @Caching(evict = {
            @CacheEvict(value = POST_CACHE_NAME, key = "'post_cache_key_'+#postTitle"),
            @CacheEvict(value = PAGE_CACHE_NAME, allEntries = true)}
    )
    @Override
    public void removePage(String postTitle) throws PostInputException {
        Post post = findByPostTitle(postTitle);
        if (post == null) {
            log.info("不存在的文章!");
            return;
        }
        post.setTags(null);
        postRepo.save(post);
        postRepo.delete(post.getId());
    }

    @Cacheable(value = PAGE_CACHE_NAME, key = "'all_page_cache_key_'")
    @Override
    public List<Post> findAll() {
        return postRepo.findAll();
    }
}


text:
package com.data2semantics.yasgui.server.fetchers.endpoints;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import au.com.bytecode.opencsv.CSVReader;
import com.data2semantics.yasgui.shared.Endpoints;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;

public class MondecaAndCkanFetcher {

	private static String MONDECA_CSV = "http://labs.mondeca.com/sparqlEndpointsStatus/stats/sparql_availability.csv";
	private static int CSV_KEY_DATASET = 0;
	private static int[] CSV_KEYS_AVAILABILITY = new int[]{1,2,3};
	public static String fetch() throws JSONException, IOException, ParseException {
		ArrayList<String> availableEndpoints = fetchAvailableEndpointsFromCsv();
		ResultSet ckanResultSet = CkanFetcher.queryCkan();

		JSONArray endpoints = new JSONArray();
		while (ckanResultSet.hasNext()) {
			QuerySolution querySolution = ckanResultSet.next();

			String datasetUri = EndpointsFetcher.getBindingValueAsString(querySolution.get(Endpoints.KEY_DATASETURI));
			if (availableEndpoints.contains(datasetUri)) {
				JSONObject endpointObject = new JSONObject();
				Iterator<String> varNames = querySolution.varNames();
				while (varNames.hasNext()) {
					String varName = varNames.next();
					endpointObject.put(varName, EndpointsFetcher.getBindingValueAsString(querySolution.get(varName)));
				}
				endpoints.put(endpointObject);
			}
		}
		if (endpoints.length() == 0) {
			throw new IOException("No endpoints retrieved using Mondeca + Ckan");
		}
		return endpoints.toString();
	}

	private static ArrayList<String> fetchAvailableEndpointsFromCsv() throws MalformedURLException, IOException, ParseException {
		InputStream inputStream = new URL( MONDECA_CSV ).openStream();
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        CSVReader reader = new CSVReader(in,';');
        ArrayList<String> availableEndpoints = new ArrayList<String>();;
        String [] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            // nextLine[] is an array of values from the line
        	boolean available = true;
        	NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);

        	for (int rowKey: CSV_KEYS_AVAILABILITY) {
        		Number number = format.parse(nextLine[rowKey]);
        		double d = number.doubleValue();
        		if (d == 0) {
        			available = false;
        		}

        	}
        	if (available) {
    			availableEndpoints.add(nextLine[CSV_KEY_DATASET]);
    		}
        }
        in.close();
        reader.close();
        return availableEndpoints;
	}

	public static void main(String[] args) {
		try {
			System.out.println(MondecaAndCkanFetcher.fetch());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}


text:
'''
just a dictionary for my layouting alias because if I written it into Alias file
it's really damn hurt to see, what the hell if I write everything into one file.
'''

alias = (['IntroLayout' , 'IntroLayout@intro'],

         ['HomeLayout'       , 'HomeLayout@home'],
         ['HomeSidecontent'  , 'HomeSidecontent@home'],
         ['HomeButtonwrapper', 'HomeButtonwrapper@home'],
         ['HomeImagewrapper' , 'HomeImagewrapper@home'],

         # -- Game layout. how the hell you set'em if you want to create a bigger game ?
         ['GameLayout'       , 'GameLayout@game'],
         ['GameContainer'    , 'GameContainer@game'],
         ['GameFooter'       , 'GameFooter@game'],
         ['GameTextwrapper'  , 'GameTextwrapper@game'],
         ['GameButtonwrapper', 'GameButtonwrapper@game'],

         ['EndLayout'    , 'EndLayout@end'],
         ['EndContainer' , 'EndContainer@end'],
         ['EndWrapper'   , 'EndWrapper@end'],

         # -- Modal layout. option model well, watch out for misspelled dude.
         ['OptionPopup'   , 'OptionPopup@option'],
         ['OptionContainer', 'OptionContainer@option'],
         ['OptionWrapper'  , 'OptionWrapper@option'],
         ['OptionOption'   , 'OptionOption@option'],

         # -- Serialize layout here, why the hell I name it "serialize" ?
         ['SerializePopup' , 'SerializePopup@serialize'],
         ['SerializeContent', 'SerializeContent@serialize'])


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

import java.math.BigDecimal;

/**
 * This class formats floating point number to textual representation with given precision.
 * Not thread safe.
 * For large numbers this method falls back to BigDecimal.toPlainString().
 * Note: formatter always uses '.' dot as decimal separator (regardless of current locale).
 *
 */
public final class DoubleFormatter {

    public static final int MAX_WIDTH = 21;
    public static final int MAX_PRECISION = 15;
    private static final long MAX = Long.MAX_VALUE / 10;

    private final byte [] buffer = new byte [MAX_WIDTH];

    private final int maxLength;
    private final int precision;
    private final long factor;

    public DoubleFormatter (int precision) {
        this (precision, MAX_WIDTH);
    }

    /**
     * @param precision maximum number of digits after decimal point (e.g. 3). Truncated part will be rounded.
     * @param maxLength maximum length a whole string should take (e.g. 16).
     */
    public DoubleFormatter (int precision, int maxLength) {
        if (precision < 0 || precision > MAX_PRECISION)
            throw new IllegalArgumentException("Precision");
        if (maxLength < 0 || maxLength > MAX_WIDTH)
            throw new IllegalArgumentException("Length");
        this.precision = precision;
        this.maxLength = maxLength;
        this.factor = Math.round(Math.pow(10, precision+1));
    }

    /** Formats given number into output byte buffer */
    public int format (double number, byte [] output, int offset) {
        return format(number, precision, true, maxLength, factor, output, offset);
    }

    /** Formats given number into output byte buffer */
    public int format (double number, int precision, byte [] output, int offset) {
        return format(number, precision, MAX_WIDTH, output, offset);
    }

    /**
     * @param precision maximum number of digits after decimal point (e.g. 3). Truncated part will be rounded.
     * @param maxLength maximum length a whole string should take (e.g. 16).
     */
    public int format (double number, int precision, int maxLength, byte [] output, int offset) {
        return format(number, precision, true, maxLength, output, offset);
    }

    /**
     * @param precision maximum number of digits after decimal point (e.g. 3). Truncated part will be rounded.
     * @param roundUp defines rounding mode (RoundingMode.HALF_UP or RoundingMode.HALF_DOWN)
     * @param maxLength maximum length a whole string should take (e.g. 16).
     */
    public int format (double number, int precision, boolean roundUp, int maxLength, byte [] output, int offset) {
        long factor = 10;
        for (int i = 0; i < precision; i++)
            factor*= 10;
        return format(number, precision, roundUp, maxLength, factor, output, offset);
    }

    /**
     * @param precision maximum number of digits after decimal point (e.g. 3). Truncated part will be rounded.
     * @param roundUp defines rounding mode (HALF_UP or HALF_DOWN)
     * @param maxLength maximum length a whole string should take (e.g. 16).
     */
    private int format (double number, int precision, boolean roundUp, int maxLength, long factor10, byte [] output, int offset) {
        if (precision < 0 || precision > MAX_PRECISION)
            throw new IllegalArgumentException("Precision");
        if (maxLength < 0 || maxLength > MAX_WIDTH)
            throw new IllegalArgumentException("Length");
        if (Double.isNaN(number)) // Infinity will be checked a bit later
            throw new IllegalArgumentException("NaN");

        boolean sign = false;
        double factoredNumber = number;
        if (number < 0) {
            sign = true;
            factoredNumber = Math.abs(number);
        }
        factoredNumber = factoredNumber*factor10;
        if (Double.isInfinite(factoredNumber) || factoredNumber > MAX)
            return formatLargeNumber (number, output, offset);

        //long numberAsDecimal = Math.round(factoredNumber);  // this call costs 8% of total time we spend in this method on avg.
        long numberAsDecimal;
        {
            //factoredNumber = factoredNumber * 10;
            numberAsDecimal = (long) factoredNumber;
            double smallestDigit = factoredNumber % 10;
            numberAsDecimal = numberAsDecimal / 10;
            if (roundUp) {
                if (smallestDigit >= 5)
                    numberAsDecimal++; // round up;
            } else {
                if (smallestDigit > 5)
                    numberAsDecimal++; // round up;
            }
        }
        if (numberAsDecimal == 0)
            return formatZero(output, offset);

        int i = MAX_WIDTH;
        int fractional_part = precision;

        boolean needLeadingZero = (fractional_part > 0);
        while (numberAsDecimal > 0) {
            int digit = (int) (numberAsDecimal % 10);
            if (digit != 0 || i != MAX_WIDTH || fractional_part == 0) // skip trailing zeros
                buffer [--i] = IntFormatter.Digits[digit];

            numberAsDecimal = numberAsDecimal / 10;
            if (fractional_part > 0) {
                fractional_part --;
                if (fractional_part == 0) {
                    if (i != MAX_WIDTH)
                        buffer [--i] = '.';
                    needLeadingZero = (numberAsDecimal == 0);
                }
            }
        }
        if (needLeadingZero) {
            if (fractional_part > 0) { // if number was less than zero
                while (fractional_part-- > 0)
                    buffer [--i] = '0';
                buffer [--i] = '.';
            }
            buffer [--i] = '0';
        }

        if (sign)
            buffer [--i] = '-';

        int len = Math.min(MAX_WIDTH - i, maxLength);
        System.arraycopy(buffer, i, output, offset, len);
        return offset + len;
    }

    private static int formatZero(byte[] output, int offset) {
        output[offset++] = '0';
        return offset;
    }

    // Super Rarely used to represent prices
    private static int formatLargeNumber(double number, byte[] output, int offset) {
        final String text = new BigDecimal(number).toPlainString();
        final int cnt = text.length();
        for(int i=0; i < cnt; i++)
            output[offset++] = (byte) text.charAt(i);
        return offset;
    }

}


text:
package collabware.web.shared;

import static collabware.model.operations.SerializationConstants.COMPLEX_OPERATION;
import static collabware.model.operations.SerializationConstants.DESCRIPTION;
import static collabware.model.operations.SerializationConstants.NO_OPERATION;
import static collabware.model.operations.SerializationConstants.OPERATIONS;
import static collabware.model.operations.SerializationConstants.TYPE;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import collabware.api.document.PrimitiveOperationDeserializer;
import collabware.api.operations.ComplexOperationImpl;
import collabware.api.operations.NoOperation;
import collabware.api.operations.Operation;
import collabware.api.operations.PrimitiveOperation;

public class OperationDejsonizer<OT, AT> {

	private final PrimitiveOperationDeserializer opertionsProvider;
	private final JsonProvider<OT, AT> jsonProvider;

	public OperationDejsonizer(PrimitiveOperationDeserializer opertionsProvider, JsonProvider<OT,AT> jsonProvider) {
		this.opertionsProvider = opertionsProvider;
		this.jsonProvider = jsonProvider;
	}

	public Operation dejsonize(OT json) throws JsonizationException {
		if (jsonProvider.getString(json, TYPE).equals(NO_OPERATION)) {
			return NoOperation.NOP;
		} else if (jsonProvider.getString(json, TYPE).equals(COMPLEX_OPERATION)){
			return dejsonizeComplex(json);
		} else {
			return dejsonizePrimitiveOperation(json);
		}
	}

	private Operation dejsonizePrimitiveOperation(OT json) throws JsonizationException {
		return opertionsProvider.deserializeOperation(asMap(json) );
	}

	private Map<String, Object> asMap(OT json) throws JsonizationException {
		Map<String, Object> map = new HashMap<String, Object>();
		for (String key: jsonProvider.getKeys(json)) {
			map.put(key, jsonProvider.getOpt(json, key));
		}
		return map;
	}

	private Operation dejsonizeComplex(OT json) throws JsonizationException {

		String description = jsonProvider.getOptString(json, DESCRIPTION, "");
		AT ops = jsonProvider.getArray(json, OPERATIONS);
		List<PrimitiveOperation> primitiveOperations = new ArrayList<PrimitiveOperation>();
		for (int i = 0; i < jsonProvider.length(ops); i++) {
			PrimitiveOperation op = (PrimitiveOperation) dejsonize(jsonProvider.getObject(ops, i));
			primitiveOperations.add(op);
		}
		return new ComplexOperationImpl(description, primitiveOperations);
	}

}


text:
name 'motd_test'
maintainer 'The Authors'
maintainer_email 'you@example.com'
license 'all_rights'
description 'Installs/Configures motd'
long_description 'Installs/Configures motd'
version '0.1.0'

depends 'motd'


text:
MIN_HOMEBREW_COMMIT_DATE = Time.parse "Wed Aug 17 11:07:17 2016 +0100"
HOMEBREW_REPOSITORY.cd do
  if MIN_HOMEBREW_COMMIT_DATE > Time.parse(`git show -s --format=%cD`)
    odie "Your Homebrew is outdated. Please run `brew update`."
  end
end

BUNDLE_ROOT = File.expand_path "#{File.dirname(__FILE__)}/.."
BUNDLE_LIB = Pathname.new(BUNDLE_ROOT)/"lib"

$LOAD_PATH.unshift(BUNDLE_LIB)

require "bundle"

if ARGV.include?("--version")
  puts Bundle::VERSION
  exit 0
end

# Pop the named command from ARGV, leaving everything else in place
command = ARGV.named.first
ARGV.delete_at(ARGV.index(command)) unless command.nil?
begin
  case command
  when nil, "install"
    Bundle::Commands::Install.run
  when "dump"
    Bundle::Commands::Dump.run
  when "cleanup"
    Bundle::Commands::Cleanup.run
  when "check"
    Bundle::Commands::Check.run
  when "exec"
    Bundle::Commands::Exec.run
  else
    onoe "Unknown command `#{command}`!"
    abort `brew bundle --help`
  end
rescue SystemExit
  puts "Kernel.exit" if ARGV.verbose?
  raise
rescue Interrupt
  puts # seemingly a newline is typical
  exit 130
rescue RuntimeError, SystemCallError => e
  raise if e.message.empty?
  onoe e
  puts e.backtrace if ARGV.debug?
  exit 1
rescue Exception => e
  onoe e
  puts "#{Tty.white}Please report this bug:#{Tty.reset}"
  puts "    #{Formatter.url("https://github.com/Homebrew/homebrew-bundle/issues/")}"
  puts e.backtrace
  exit 1
end


text:
using namespace 'System.Resources'
using namespace 'System.Management.Automation'

class Information
{
    static [Information] $instance

    static [Information] GetInstance()
    {
        if ([Information]::instance -eq $null) {
            [Information]::instance = [Information]::new()
        }

        return [Information]::instance
    }

    $ResourceSet

    Message(
        [string]$Key,
        [string[]]$Format,
        [string]$Recommendments,
        [System.Management.Automation.ActionPreference]$Action)
    {
        if(!$this.ResourceSet) {
            $this.ResourceSet = New-Object -TypeName 'System.Resources.ResXResourceSet' -ArgumentList "$PSScriptRoot\..\..\resx\Information.resx"
        }

        $Message = $this.ResourceSet.GetString($Key)

        # TODO: this is just hanging.  was I to ammend this to Message?
        $Recommendment = ''
        if($Recommendments) {
            $Recommendment = $this.ResourceSet.GetString($Recommendments)
        }

        if($Format) {
            $Message = ($Message -f $Format)
        }

        if(!$Action) {
            $Action = [ActionPreference]::Continue
        }

        Write-Information -MessageData $Message -InformationAction $Action
    }

    [void] out([string]$ResourceKey) {
        $this.Message($ResourceKey, $null, $null, [ActionPreference]::Continue)
    }

    [void] out([string]$ResourceKey, [string[]]$Format) {
        $this.Message($ResourceKey, $Format, $null, [ActionPreference]::Continue)
    }

    [void] out([string]$ResourceKey, [string[]]$Format, [string]$Recommendments, $null) {
        $this.Message($ResourceKey, $Format, $Recommendments, [ActionPreference]::Continue)
    }

    [void] out([string]$ResourceKey, [string[]]$Format, [string]$Recommendments, [ActionPreference]$Action) {
        $this.Message($ResourceKey, $Format, $Recommendments, $Action)
    }
}


text:
package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.readability;

import com.smartcodeltd.jenkinsci.plugins.buildmonitor.readability.Lister;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class ListerTest {

    @Test
    public void should_return_an_empty_string_when_given_an_empty_list() {
        assertThat(Lister.asString(listOf()), is(""));
    }

    @Test
    public void should_return_a_string_representation_of_a_given_object() {
        assertThat(Lister.asString(listOf("apple")), is("apple"));
    }

    @Test
    public void should_use_and_instead_of_a_comma_before_the_last_item() {
        assertThat(Lister.asString(listOf("apple", "orange")), is("apple and orange"));
    }

    @Test
    public void should_use_comma_to_delimit_all_the_elements_except_the_last_one() {
        assertThat(Lister.asString(listOf("apple", "orange", "banana")), is("apple, orange and banana"));
    }

    @Test
    public void should_use_an_optional_template_to_describe_a_list_with_multiple_items() {
        assertThat(Lister.describe("Fruits: %s", listOf("apple", "orange")), is("Fruits: apple and orange"));
    }

    @Test
    public void should_say_when_the_list_has_no_items() {
        assertThat(Lister.describe("No fruit for you today :-(", "Fruits: %s", listOf()), is("No fruit for you today :-("));
    }

    @Test
    public void should_allow_to_use_a_different_template_to_describe_a_list_with_one_item() {
        assertThat(Lister.describe("Empty", "%s fruit", "Fruits: %s", listOf("apple")), is("apple fruit"));
    }

    private <T> List<T> listOf(T... items) {
        return Arrays.asList(items);
    }
}


text:
var Q = "http://counter.sina.com.cn/pvcounter?pid=";

function request_pvcounter(){
	var request_url = Q;
	var elem = document.getElementsByTagName("span");
	for( i=0; i<elem.length; i++ ) {
		var att = elem[i].getAttribute("name");
		if (att == "pvcounter") {
			var pid = elem[i].getAttribute("pid");
			var key = elem[i].getAttribute("key");
			var url = elem[i].getAttribute("url");
			var expara = elem[i].getAttribute("expara");
			if (pid==null || pid=="" || key==null || key=="" || url==null || url=="")
				return false;
			request_url += encodeURIComponent(pid);
			request_url += ("&key=" + encodeURIComponent(key));
			request_url += ("&url=" + encodeURIComponent(url));
			if (expara!=null && expara!="")
				request_url += ("&expara=" + encodeURIComponent(expara));
			break;
		}
	}

	if ( navigator.userAgent.toLowerCase().indexOf('msie') >= 0 ) {
		document.getElementById("PVCOUNTER_FORIE").src = request_url;
	} else {
		var js = document.createElement("script");
		js.setAttribute("type", "text/javascript");
		js.setAttribute("src", request_url);
		document.body.insertBefore(js, null);
	}
}

request_pvcounter();


text:
import PropTypes from 'prop-types';
import { deepmerge } from '@material-ui/utils';
import merge from './merge';

// The breakpoint **start** at this value.
// For instance with the first breakpoint xs: [xs, sm[.
const values = {
  xs: 0, // phone
  sm: 600, // tablets
  md: 900, // small laptop
  lg: 1200, // desktop
  xl: 1536, // large screens
};

const defaultBreakpoints = {
  // Sorted ASC by size. That's important.
  // It can't be configured as it's used statically for propTypes.
  keys: ['xs', 'sm', 'md', 'lg', 'xl'],
  up: (key) => `@media (min-width:${values[key]}px)`,
};

export function handleBreakpoints(props, propValue, styleFromPropValue) {
  const theme = props.theme || {};

  if (Array.isArray(propValue)) {
    const themeBreakpoints = theme.breakpoints || defaultBreakpoints;
    return propValue.reduce((acc, item, index) => {
      acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);
      return acc;
    }, {});
  }

  if (typeof propValue === 'object') {
    const themeBreakpoints = theme.breakpoints || defaultBreakpoints;
    return Object.keys(propValue).reduce((acc, breakpoint) => {
      // key is breakpoint
      if (Object.keys(themeBreakpoints.values || values).indexOf(breakpoint) !== -1) {
        const mediaKey = themeBreakpoints.up(breakpoint);
        acc[mediaKey] = styleFromPropValue(propValue[breakpoint], breakpoint);
      } else {
        const cssKey = breakpoint;
        acc[cssKey] = propValue[cssKey];
      }
      return acc;
    }, {});
  }

  const output = styleFromPropValue(propValue);

  return output;
}

function breakpoints(styleFunction) {
  const newStyleFunction = (props) => {
    const theme = props.theme || {};
    const base = styleFunction(props);
    const themeBreakpoints = theme.breakpoints || defaultBreakpoints;

    const extended = themeBreakpoints.keys.reduce((acc, key) => {
      if (props[key]) {
        acc = acc || {};
        acc[themeBreakpoints.up(key)] = styleFunction({ theme, ...props[key] });
      }
      return acc;
    }, null);

    return merge(base, extended);
  };

  newStyleFunction.propTypes =
    process.env.NODE_ENV !== 'production'
      ? {
          ...styleFunction.propTypes,
          xs: PropTypes.object,
          sm: PropTypes.object,
          md: PropTypes.object,
          lg: PropTypes.object,
          xl: PropTypes.object,
        }
      : {};

  newStyleFunction.filterProps = ['xs', 'sm', 'md', 'lg', 'xl', ...styleFunction.filterProps];

  return newStyleFunction;
}

export function createEmptyBreakpointObject(breakpointsInput = {}) {
  const breakpointsInOrder = breakpointsInput?.keys?.reduce((acc, key) => {
    const breakpointStyleKey = breakpointsInput.up(key);
    acc[breakpointStyleKey] = {};
    return acc;
  }, {});
  return breakpointsInOrder || {};
}

export function removeUnusedBreakpoints(breakpointKeys, style) {
  return breakpointKeys.reduce((acc, key) => {
    const breakpointOutput = acc[key];
    const isBreakpointUnused = Object.keys(breakpointOutput).length === 0;
    if (isBreakpointUnused) {
      delete acc[key];
    }
    return acc;
  }, style);
}

export function mergeBreakpointsInOrder(breakpointsInput, ...styles) {
  const emptyBreakpoints = createEmptyBreakpointObject(breakpointsInput);
  const mergedOutput = [emptyBreakpoints, ...styles].reduce(
    (prev, next) => deepmerge(prev, next),
    {},
  );
  return removeUnusedBreakpoints(Object.keys(emptyBreakpoints), mergedOutput);
}

export default breakpoints;


text:
(function(f) {
    if (typeof exports === "object" && typeof module !== "undefined") {
        module.exports = f()
    }
    else if (typeof define === "function" && define.amd) {
        define([], f)
    }
    else {
        var g;
        if (typeof window !== "undefined") {
            g = window
        }
        else if (typeof global !== "undefined") {
            g = global
        }
        else if (typeof self !== "undefined") {
            g = self
        }
        else {
            g = this
        }
        g.scribePluginInlineStylesToElements = f()
    }
})(function() {
    var define, module, exports;
    return (function e(t, n, r) {
        function s(o, u) {
            if (!n[o]) {
                if (!t[o]) {
                    var a = typeof require == "function" && require;
                    if (!u && a) return a(o, !0);
                    if (i) return i(o, !0);
                    var f = new Error("Cannot find module '" + o + "'");
                    throw f.code = "MODULE_NOT_FOUND", f
                }
                var l = n[o] = {
                    exports: {}
                };
                t[o][0].call(l.exports, function(e) {
                    var n = t[o][1][e];
                    return s(n ? n : e)
                }, l, l.exports, e, t, n, r)
            }
            return n[o].exports
        }
        var i = typeof require == "function" && require;
        for (var o = 0; o < r.length; o++) s(r[o]);
        return s
    })({
        1: [function(require, module, exports) {
            'use strict';

            function asHtmlFormatter(domFormatter) {
                return function(html) {
                    var bin = document.createElement('div');
                    bin.innerHTML = html;
                    return domFormatter(bin)
                        .innerHTML;
                };
            }
            module.exports = asHtmlFormatter;
}, {}],
        2: [function(require, module, exports) {
            'use strict';

            function isElement(node) {
                return node.nodeType === Node.ELEMENT_NODE;
            }

            function appendTraversedChildrenTo(n, parentNode, mapper) {
                var child = n.firstChild;
                while (child) {
                    var mappedChild = traverse(child, mapper);
                    if (mappedChild) {
                        parentNode.appendChild(mappedChild);
                    }
                    child = child.nextSibling;
                }
                return parentNode;
            }

            function appendTraversedChildren(n, mapper) {
                return appendTraversedChildrenTo(n, n.cloneNode(false), mapper);
            }

            function traverse(node, mapper) {
                return mapper(node, mapper);
            }

            function styleToElement(styleProp, styleValue, elName) {
                return function(n, mapper) {
                    if (isElement(n) && n.style[styleProp] === styleValue) {
                        var strongWrapper = document.createElement(elName);
                        var child = n.firstChild;
                        while (child) {
                            strongWrapper.appendChild(child.cloneNode(true));
                            child = child.nextSibling;
                        }
                        var nCopy = n.cloneNode(false);
                        nCopy.style[styleProp] = null;
                        if (nCopy.getAttribute('style') === '') {
                            nCopy.removeAttribute('style');
                        }
                        nCopy.appendChild(traverse(strongWrapper, mapper));
                        return nCopy;
                    }
                    else {
                        return appendTraversedChildren(n, mapper);
                    }
                };
            }
            var filters = [
        styleToElement('fontWeight', 'bold', 'b'),
        styleToElement('fontStyle', 'italic', 'i'),
        styleToElement('textDecoration', 'underline', 'u'),
        styleToElement('textDecoration', 'line-through', 'strike'),
        styleToElement('textDecorationLine', 'underline', 'u'),
        styleToElement('textDecorationLine', 'line-through', 'strike')
    ];

            function applyFilters(node) {
                return filters.reduce(traverse, node);
            }
            module.exports = applyFilters;
}, {}],
        3: [function(require, module, exports) {
            var inlineStylesFormatter = require('./inline-styles-formatter'),
                asHtmlFormatter = require('./as-html-formatter');
            'use strict';
            module.exports = function() {
                return function(scribe) {
                    scribe.registerHTMLFormatter('sanitize', asHtmlFormatter(inlineStylesFormatter));
                };
            };
}, {
            "./as-html-formatter": 1,
            "./inline-styles-formatter": 2
        }]
    }, {}, [3])(3)
});


text:
'use strict';

angular.module('myApp')
.controller('ProjectCtrl', ['$scope', '$routeParams', 'projectService', function($scope, $routeParams, projectService) {

	$scope.pageClass = 'page-project';

	projectService
    .get({projectId: $routeParams.projectId})
    .$promise
    .then(function(projectsResponse) {
      $scope.project = projectsResponse;
    });
	}]);


text:
<?php

declare(strict_types=1);

namespace Application;

use Application\Service\RabbitMQ;
use Exception;
use Laminas\Db\Sql\Select;
use Laminas\Db\TableGateway\TableGateway;
use Laminas\Json\Json;

use function Autowp\Commons\currentFromResultSetInterface;

class DuplicateFinder
{
    private RabbitMQ $rabbitmq;

    private TableGateway $distanceTable;

    public function __construct(RabbitMQ $rabbitmq, TableGateway $distanceTable)
    {
        $this->rabbitmq      = $rabbitmq;
        $this->distanceTable = $distanceTable;
    }

    /**
     * @throws Exception
     */
    public function indexImage(int $id, string $url): void
    {
        $this->rabbitmq->send('duplicate_finder', Json::encode([
            'picture_id' => $id,
            'url'        => $url,
        ]));
    }

    /**
     * @throws Exception
     */
    public function findSimilar(int $id): ?array
    {
        $row = currentFromResultSetInterface($this->distanceTable->select(function (Select $select) use ($id): void {
            $select
                ->columns([
                    'dst_picture_id',
                    'distance',
                ])
                ->where([
                    'src_picture_id' => $id,
                    'src_picture_id <> dst_picture_id',
                    'not hide',
                ])
                ->order('distance ASC')
                ->limit(1);
        }));

        if (! $row) {
            return null;
        }

        return [
            'picture_id' => $row['dst_picture_id'],
            'distance'   => $row['distance'],
        ];
    }

    public function hideSimilar(int $srcId, int $dstId): void
    {
        $this->distanceTable->update([
            'hide' => 1,
        ], [
            'src_picture_id' => $srcId,
            'dst_picture_id' => $dstId,
        ]);
        $this->distanceTable->update([
            'hide' => 1,
        ], [
            'src_picture_id' => $dstId,
            'dst_picture_id' => $srcId,
        ]);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="orange_bar_title_text_size">40sp</dimen>
    <dimen name="orange_bar_title_text_margin">40dp</dimen>
    <dimen name="orange_bar_web_btn_width">57dp</dimen>
</resources>


text:
package com.dremio.sabot.op.join.nlje;

/**
 * A concept of a range of values from two sets of records. Used to iterate over
 */
public abstract class DualRange implements AutoCloseable {

  /**
   * Whether there is available data to consume after the current data.
   * @return
   */
  public abstract boolean hasNext();

  public abstract DualRange nextOutput();

  /**
   * If the current active range is empty. Useful for determining if an empty return occurred.
   *
   * @return True if no data present.
   */
  public abstract boolean isEmpty();

  /**
   * Inform the range that the next probe batch is now available.
   * @param records Number of records in the probe batch.
   * @return
   */
  public abstract DualRange startNextProbe(int records);

  public abstract boolean isIndexRange();

  public IndexRange asIndexRange() {
    throw new UnsupportedOperationException();
  }

  public VectorRange asVectorRange() {
    throw new UnsupportedOperationException();
  }

}


text:
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GameOfLifeApplication;

namespace GameOfLifeUnitTests
{
    [TestClass]
    public class WorldTest
    {
        static World world;

        [ClassInitialize]
        public static void ClassInit(TestContext context)
        {
            var initCells = new List<int[]>() {
                new int[] {0, 0},
                new int[] {1, 1}
            };
            world = new World(2, 2, 2, initCells: initCells);
        }

        [TestMethod]
        public void TestCountLiveNeighbours()
        {
            var live = world.CountLiveNeighbours(0, 0);
            Assert.AreEqual(1, live);
            live = world.CountLiveNeighbours(0, 1);
            Assert.AreEqual(2, live);
            live = world.CountLiveNeighbours(1, 0);
            Assert.AreEqual(2, live);
            live = world.CountLiveNeighbours(1, 1);
            Assert.AreEqual(1, live);
        }

        [TestMethod]
        public void TestApplyRules()
        {
            int x = 0, y = 0;
            var live = world.CountLiveNeighbours(x, y);
            var future = world.ApplyRules(world.Grid[x, y], live);
            Assert.AreEqual(World.State.Dead, future);
            x = 0;
            y = 1;
            live = world.CountLiveNeighbours(x, y);
            future = world.ApplyRules(world.Grid[x, y], live);
            Assert.AreEqual(World.State.Dead, future);
        }

        [TestMethod]
        public void TestEvolve()
        {
            var initCells = new List<int[]>() {
                new int[] {0, 1},
                new int[] {1, 2},
                new int[] {2, 0},
                new int[] {2, 1},
                new int[] {2, 2}
            };
            var w = new World(4, 4, 2, initCells: initCells);
            for (int i = 0; i < 7; i++)
            {
                Assert.AreEqual(false, w.Evolve());
            }
            Assert.AreEqual(true, w.Evolve());
            for (int i = 0; i < w.Rows; i++)
            {
                for (int j = 0; j < w.Columns; j++)
                {
                    var cell = w.Grid[i, j];
                    if ((i == 2 || i == 3) && (j == 2 || j == 3))
                        Assert.AreEqual(World.State.Live, cell);
                    else
                        Assert.AreEqual(World.State.Dead, cell);
                }
            }
        }
    }
}


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

class AuditsController < ActionController::Base
  def audit
    @company = Models::ActiveRecord::Company.create
    render :nothing => true
  end

  def update_user
    current_user.update_attributes( :password => 'foo')
    render :nothing => true
  end

  private

  attr_accessor :current_user
  attr_accessor :custom_user
end

describe AuditsController, :adapter => :active_record do
  include RSpec::Rails::ControllerExampleGroup
  render_views

  before(:each) do
    Audited.current_user_method = :current_user
  end

  let( :user ) { create_user }

  describe "POST audit" do

    it "should audit user" do
      controller.send(:current_user=, user)
      expect {
        post :audit
      }.to change( Audited.audit_class, :count )

      expect(assigns(:company).audits.last.user).to eq(user)
    end

    it "should support custom users for sweepers" do
      controller.send(:custom_user=, user)
      Audited.current_user_method = :custom_user

      expect {
        post :audit
      }.to change( Audited.audit_class, :count )

      expect(assigns(:company).audits.last.user).to eq(user)
    end

    it "should record the remote address responsible for the change" do
      request.env['REMOTE_ADDR'] = "1.2.3.4"
      controller.send(:current_user=, user)

      post :audit

      expect(assigns(:company).audits.last.remote_address).to eq('1.2.3.4')
    end

    it "should record a UUID for the web request responsible for the change" do
      allow_any_instance_of(ActionDispatch::Request).to receive(:uuid).and_return("abc123")
      controller.send(:current_user=, user)

      post :audit

      expect(assigns(:company).audits.last.request_uuid).to eq("abc123")
    end

  end

  describe "POST update_user" do

    it "should not save blank audits" do
      controller.send(:current_user=, user)

      expect {
        post :update_user
      }.to_not change( Audited.audit_class, :count )
    end

  end
end

describe Audited::Sweeper, :adapter => :active_record do

  it "should be thread-safe" do
    t1 = Thread.new do
      sleep 0.5
      Audited::Sweeper.instance.controller = 'thread1 controller instance'
      expect(Audited::Sweeper.instance.controller).to eq('thread1 controller instance')
    end

    t2 = Thread.new do
      Audited::Sweeper.instance.controller = 'thread2 controller instance'
      sleep 1
      expect(Audited::Sweeper.instance.controller).to eq('thread2 controller instance')
    end

    t1.join; t2.join

    expect(Audited::Sweeper.instance.controller).to be_nil
  end

end