text:
namespace Fluent.Automation.Peers
{
    using System.Collections.Generic;
    using System.Runtime.CompilerServices;
    using System.Windows.Automation;
    using System.Windows.Automation.Peers;
    using JetBrains.Annotations;

    /// <summary>
    /// Automation peer wrapper for <see cref="RibbonTabItem"/>.
    /// </summary>
    public class RibbonTabItemAutomationPeer : FrameworkElementAutomationPeer
    {
        /// <summary>
        /// Creates a new instance.
        /// </summary>
        public RibbonTabItemAutomationPeer([NotNull] RibbonTabItem owner)
            : base(owner)
        {
            this.OwningTab = owner;
        }

        private RibbonTabItem OwningTab { get; }

        /// <inheritdoc />
        public override object GetPattern(PatternInterface patternInterface)
        {
            switch (patternInterface)
            {
                case PatternInterface.Scroll:
                    var container = this.OwningTab.GroupsContainer;
                    if (container != null)
                    {
                        var automationPeer = CreatePeerForElement(container);
                        if (automationPeer != null)
                        {
                            return automationPeer.GetPattern(patternInterface);
                        }
                    }

                    break;
            }

            return base.GetPattern(patternInterface);
        }

        /// <inheritdoc />
        protected override List<AutomationPeer> GetChildrenCore()
        {
            var children = GetHeaderChildren() ?? new List<AutomationPeer>();

            if (this.OwningTab.IsSelected == false)
            {
                return children;
            }

            foreach (var @group in this.OwningTab.Groups)
            {
                var peer = CreatePeerForElement(@group);

                if (peer != null)
                {
                    children.Add(peer);
                }
            }

            return children;

            List<AutomationPeer> GetHeaderChildren()
            {
                if (this.OwningTab.Header is string)
                {
                    return null;
                }

                if (this.OwningTab.HeaderContentHost != null)
                {
                    return new FrameworkElementAutomationPeer(this.OwningTab.HeaderContentHost).GetChildren();
                }

                return null;
            }
        }

        /// <inheritdoc />
        protected override string GetClassNameCore()
        {
            return this.Owner.GetType().Name;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal void RaiseTabExpandCollapseAutomationEvent(bool oldValue, bool newValue)
        {
            this.EventsSource?.RaisePropertyChangedEvent(ExpandCollapsePatternIdentifiers.ExpandCollapseStateProperty, oldValue ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed, newValue ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal void RaiseTabSelectionEvents()
        {
            var eventsSource = this.EventsSource;
            if (eventsSource != null)
            {
                if (this.OwningTab.IsSelected)
                {
                    eventsSource.RaiseAutomationEvent(AutomationEvents.SelectionItemPatternOnElementSelected);
                }
                else
                {
                    eventsSource.RaiseAutomationEvent(AutomationEvents.SelectionItemPatternOnElementRemovedFromSelection);
                }
            }
        }
    }
}


text:
package org.neo4j.ogm.domain.mappings;

import java.util.HashSet;
import java.util.Set;

import org.neo4j.ogm.annotation.Relationship;

/**
 * @author Nils Dr\u00F6ge
 */
public class Person extends Entity {

    @Relationship(type = "RELATED_TO")
    public Set<RichRelation> relations = new HashSet<>();

    public void addRelation(Article article, RichRelation relation) {
        relation.person = this;
        relation.article = article;
        relations.add(relation);
        article.relations.add(relation);
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coryne corticalis Fuckel

### Remarks
null


text:
package com.azure.identity;

import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenRequestContext;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.util.Configuration;
import com.azure.identity.implementation.util.IdentityUtil;
import com.microsoft.aad.msal4j.MsalServiceException;
import org.junit.Assert;
import org.junit.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.time.OffsetDateTime;

import static org.junit.Assert.fail;

public class EnvironmentCredentialTests {
    @Test
    public void testCreateEnvironmentClientSecretCredential() {
        Configuration.getGlobalConfiguration()
            .put(Configuration.PROPERTY_AZURE_CLIENT_ID, "foo")
            .put(Configuration.PROPERTY_AZURE_CLIENT_SECRET, "bar")
            .put(Configuration.PROPERTY_AZURE_TENANT_ID, "baz");

        EnvironmentCredential credential = new EnvironmentCredentialBuilder().build();

        // authentication will fail client-id=foo, but should be able to create ClientSecretCredential
        StepVerifier.create(credential.getToken(new TokenRequestContext().addScopes("qux/.default"))
            .doOnSuccess(s -> fail())
            .onErrorResume(t -> {
                String message = t.getMessage();
                Assert.assertFalse(message != null && message.contains("Cannot create any credentials with the current environment variables"));
                return Mono.just(new AccessToken("token", OffsetDateTime.MAX));
            }))
            .expectNextMatches(token -> "token".equals(token.getToken()))
            .verifyComplete();

        // Validate Sync flow.
        try {
            credential.getTokenSync(new TokenRequestContext().addScopes("qux/.default"));
            fail();
        } catch (Exception e) {
            String message = e.getMessage();
            Assert.assertFalse(message != null && message.contains("Cannot create any credentials with the current environment variables"));
        }
    }

    @Test
    public void testCreateEnvironmentClientCertificateCredential() {
        Configuration.getGlobalConfiguration()
            .put(Configuration.PROPERTY_AZURE_CLIENT_ID, "foo")
            .put(Configuration.PROPERTY_AZURE_CLIENT_CERTIFICATE_PATH, "bar")
            .put(Configuration.PROPERTY_AZURE_CLIENT_CERTIFICATE_PASSWORD, "password")
            .put(Configuration.PROPERTY_AZURE_TENANT_ID, "baz");

        EnvironmentCredential credential = new EnvironmentCredentialBuilder().build();

        // authentication will fail client-id=foo, but should be able to create ClientCertificateCredential
        StepVerifier.create(credential.getToken(new TokenRequestContext().addScopes("qux/.default"))
            .doOnSuccess(s -> fail())
            .onErrorResume(t -> {
                String message = t.getMessage();
                Assert.assertFalse(message != null && message.contains("Cannot create any credentials with the current environment variables"));
                return Mono.just(new AccessToken("token", OffsetDateTime.MAX));
            }))
            .expectNextMatches(token -> "token".equals(token.getToken()))
            .verifyComplete();

        // Validate Sync flow.
        try {
            credential.getTokenSync(new TokenRequestContext().addScopes("qux/.default"));
            fail();
        } catch (Exception e) {
            String message = e.getMessage();
            Assert.assertFalse(message != null && message.contains("Cannot create any credentials with the current environment variables"));
        }
    }

    @Test
    public void testCreateEnvironmentUserPasswordCredential() {
        Configuration.getGlobalConfiguration()
            .put(Configuration.PROPERTY_AZURE_CLIENT_ID, "foo")
            .put(Configuration.PROPERTY_AZURE_USERNAME, "bar")
            .put(Configuration.PROPERTY_AZURE_PASSWORD, "baz");

        EnvironmentCredential credential = new EnvironmentCredentialBuilder().build();

        // authentication will fail client-id=foo, but should be able to create UsernamePasswordCredential
        StepVerifier.create(credential.getToken(new TokenRequestContext().addScopes("qux/.default"))
            .doOnSuccess(s -> fail())
            .onErrorResume(t -> {
                String message = t.getMessage();
                Assert.assertFalse(message != null && message.contains("Cannot create any credentials with the current environment variables"));
                return Mono.just(new AccessToken("token", OffsetDateTime.MAX));
            }))
            .expectNextMatches(token -> "token".equals(token.getToken()))
            .verifyComplete();

        // Validate Sync flow.
        try {
            credential.getTokenSync(new TokenRequestContext().addScopes("qux/.default"));
            fail();
        } catch (Exception e) {
            String message = e.getMessage();
            Assert.assertFalse(message != null && message.contains("Cannot create any credentials with the current environment variables"));
        }
    }

    @Test
    public void testInvalidAdditionalTenant() throws Exception {
        // setup
        Configuration.getGlobalConfiguration()
            .put(Configuration.PROPERTY_AZURE_CLIENT_ID, "foo")
            .put(Configuration.PROPERTY_AZURE_CLIENT_SECRET, "bar")
            .put(Configuration.PROPERTY_AZURE_TENANT_ID, "baz")
            .put(IdentityUtil.AZURE_ADDITIONALLY_ALLOWED_TENANTS, "RANDOM");

        TokenRequestContext request = new TokenRequestContext().addScopes("https://vault.azure.net/.default")
            .setTenantId("newTenant");

        EnvironmentCredential credential =
            new EnvironmentCredentialBuilder().build();

        StepVerifier.create(credential.getToken(request))
            .expectErrorMatches(e -> e instanceof ClientAuthenticationException && (e.getMessage().startsWith("The current credential is not configured to")))
            .verify();
    }

    @Test
    public void testInvalidMultiTenantAuth() throws Exception {
        // setup
        Configuration.getGlobalConfiguration()
            .put(Configuration.PROPERTY_AZURE_CLIENT_ID, "foo")
            .put(Configuration.PROPERTY_AZURE_CLIENT_SECRET, "bar")
            .put(Configuration.PROPERTY_AZURE_TENANT_ID, "baz");

        TokenRequestContext request = new TokenRequestContext().addScopes("https://vault.azure.net/.default")
            .setTenantId("newTenant");

        EnvironmentCredential credential =
            new EnvironmentCredentialBuilder().build();
        StepVerifier.create(credential.getToken(request))
            .expectErrorMatches(e -> e instanceof ClientAuthenticationException && (e.getMessage().startsWith("The current credential is not configured to")))
            .verify();
    }

    @Test
    public void testValidMultiTenantAuth() throws Exception {
        // setup
        Configuration.getGlobalConfiguration()
            .put(Configuration.PROPERTY_AZURE_CLIENT_ID, "foo")
            .put(Configuration.PROPERTY_AZURE_CLIENT_SECRET, "bar")
            .put(Configuration.PROPERTY_AZURE_TENANT_ID, "baz")
            .put(IdentityUtil.AZURE_ADDITIONALLY_ALLOWED_TENANTS, "*");

        TokenRequestContext request = new TokenRequestContext().addScopes("https://vault.azure.net/.default")
            .setTenantId("newTenant");

        EnvironmentCredential credential =
            new EnvironmentCredentialBuilder().build();
        StepVerifier.create(credential.getToken(request))
            .expectErrorMatches(e -> e instanceof MsalServiceException)
            .verify();
    }
}


text:
namespace Fluent.Extensions
{
    using System.Windows;

    /// <summary>
    /// Class with extension methods for <see cref="FrameworkElement"/>.
    /// </summary>
    internal static class FrameworkElementExtensions
    {
        public static void ForceMeasure(this FrameworkElement element)
        {
            element.InvalidateMeasure();

            // Calling UpdateLayout on not already loaded elements causes weird side effects
            if (element.IsLoaded)
            {
                element.UpdateLayout();
            }
        }

        public static void ForceMeasureAndArrange(this FrameworkElement element)
        {
            element.InvalidateMeasure();
            element.InvalidateArrange();

            // Calling UpdateLayout on not already loaded elements causes weird side effects
            if (element.IsLoaded)
            {
                element.UpdateLayout();
            }
        }
    }
}


text:
module opendolphin {

    export class Attribute {
        public static QUALIFIER_PROPERTY = "qualifier";
        public static DIRTY_PROPERTY = "dirty";
        public static BASE_VALUE = "baseValue";
        public static VALUE = "value";
        public static TAG = "tag";
    }
}


text:
{% extends "layout-opg-b.html" %}
{% block page_title %}
  Blank page
{% endblock %}

{% block content %}

Home

OPG guidance

HR

OPG guidance

HR

Flexible working

HR

Content owner: OPG HR

Last updated: 27 March 2016

OPG-specific HR policies can be found in this section.

Flexible working

{% endblock %}


text:
package net.zomis.spring.games.generic;

import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

public class TokenGenerator {

    private static final int TOKEN_LENGTH = 20;
    private final SecureRandom random = new SecureRandom();
    private final Set<String> usedTokens = new HashSet<>();

    public String generateToken() {
        byte[] token = new byte[TOKEN_LENGTH];
        String hex;
        do {
            random.nextBytes(token);
            UUID uuid = UUID.nameUUIDFromBytes(token);
            hex = uuid.toString(); //toHex(token);
        } while (!usedTokens.add(hex));
        return hex;
    }

    private String toHex(byte[] token) {
        StringBuilder str = new StringBuilder(token.length * 2);
        for (int i = 0; i < token.length; i++) {
            int value = Byte.toUnsignedInt(token[i]);
            String hex = Integer.toHexString(value);
            str.append(hex);
        }
        return str.toString();
    }

}


text:
{% extends 'base.html' %}
{% block title %}WebSocket Raw Data{% endblock %}
{% block container %}

Raw Data Stream

Placeholder for raw data stream.

				<form id="subscribe"  role="form">

					Subscribe topic
					<input class="form-control" id="sub_topic" placeholder="Enter topic">

				  <button type="submit" class="btn btn-default">Subscribe</button>
				</form>

				<form id="unsubscribe"  role="form">

					Unsubscribe topic
					<input class="form-control" id="unsub_topic" placeholder="Enter topic">

				  <button type="submit" class="btn btn-default">Unsubscribe</button>
				</form>
				<form id="cleardata"  role="form">
				  <button type="submit" class="btn btn-default">Clear Data</button>
				</form>

{% endblock %}
{% block js_end %}
{{ super() }}

{% endblock %}


text:
package com.orbuculum.app.services.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.orbuculum.app.dao.IUsersDao;
import com.orbuculum.app.domain.User;
import com.orbuculum.app.services.IUsersService;
import com.orbuculum.app.services.helpers.UsersServiceHelper;

/**
 * Service implementation for IUsersService
 */
@Service
public class UsersServiceImpl implements IUsersService {

  @Autowired
  private IUsersDao usersDao;

  @Autowired
  private UsersServiceHelper usersServiceHelper;

  @Override
  public void createUser(User user) {
    usersServiceHelper.validateUser(user);
    usersDao.createUser(user);
  }

  @Override
  public User getUser(int userId) {
    return usersDao.getUser(userId);
  }

  @Override
  public void updateUser(User user) {
    usersServiceHelper.validateUser(user);
    usersDao.updateUser(user);
  }

  @Override
  public void deleteUser(int userId) {
    usersDao.deleteUser(userId);
  }
}


text:
/*globals pako, prettyBytes*/
'use strict';
importScripts('/lib/pako/dist/pako_deflate.js', '/lib/pretty-bytes/pretty-bytes.js');

var hashCode = function(str) {
  var hash = 0;
  if (str.length === 0) {
    return hash;
  }
  for (var i = 0; i < str.length; i++) {
    var char = str.charCodeAt(i);
    hash = ((hash<<5)-hash)+char;
    hash = hash & hash;
  }

  return hash;
};

var hash = {};

onmessage = function(msg) {
  var hashedConfig = hashCode(msg.data);
  var data = JSON.parse(msg.data);
  var build = data.build;
  var response = hash[hashedConfig];

  if (!response) {
    response = {
      original: prettyBytes(build.length),
      compressed: prettyBytes(pako.deflate(build, {level: 6}).length)
    };

    hash[hashedConfig] = response;
  }

  postMessage(response);
};


text:
function CoinTileBuilder(game, config) {
    BaseTileBuilder.call(this, game, config);
}

CoinTileBuilder.prototype = Object.create(BaseTileBuilder.prototype);

CoinTileBuilder.prototype.build = function () {
    var xPosition = this.width * this.column + this.width / 2;
    var yPosition = this.height * this.row + this.height / 1.15;
    var sprite = this.game.add.sprite(xPosition, yPosition, this.config.coinSprite);
    sprite.animations.add(this.config.coinSprite);
    sprite.animations.play(this.config.coinSprite, 10, true);
    sprite.anchor.set(0.5);
    return sprite;
};


text:
package govopendata.orgnization.service;

import govopendata.orgnization.entity.OrgRelationType;
import govopendata.utils.ResultStatus;

public interface OrgRelationService {
	public ResultStatus create(Long sourceOrgId, Long destOrgId,OrgRelationType relationType);
	public ResultStatus delete(Long sourceOrgId, Long destOrgId,OrgRelationType relationType);
}


text:
package ua.org.afonmad.wrapper;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.log4j.Logger;

import ua.org.afonmad.exchange.MetadataInfo;
import ua.org.afonmad.utils.FSUtils;

import com.google.gdata.data.media.mediarss.MediaContent;
import com.google.gdata.data.photos.ExifTags;
import com.google.gdata.data.photos.PhotoEntry;

/**
 * The wrapper on PhotoEntry but
 * containing only useful for downloading information such as URL,
 * filename, creation date etc.
 */
public class SimplePhotoEntry {

	private static final String VIDEO_MEDIUM = "video";
	private final Logger logger = Logger.getLogger(this.getClass().getName());

	@SuppressWarnings("serial")
	public static final Map<String, String> TYPE_TO_EXTENSION = new HashMap<String, String>() {
		{
			put("application/x-shockwave-flash", "flv");
			put("video/mpeg4", "mpg");
			put("image/jpeg", "jpg");
			put("image/bmp", "jpg");
			put("image/gif", "gif");
			put("image/png", "png");
		}
	};

	/**
	 * The URL from which file should be downloaded
	 */
	private String url;

	/**
	 * A date of file/photo creation. Grabbed either from EXIF info or
	 * photoEntry
	 */
	private Date date;

	private String fileName;

	private SimpleAlbumEntry album;

	public SimplePhotoEntry(PhotoEntry photo, SimpleAlbumEntry simpleAlbum) throws Exception {
		MetadataInfo.printPhotoInfo(photo);

		String mediaType = setUrl(photo);
		setFileName(photo, mediaType);

		setAlbum(simpleAlbum);
		setDate(photo);
	}

	public String getUrl() {
		return url;
	}

	private String setUrl(PhotoEntry photo) {
		MediaContent downloadableMediaContent = photo.getMediaContents().get(0);
		if (photo.getMediaContents().size() > 1) {
			downloadableMediaContent = findBiggestVideo(photo.getMediaContents());
		}
		this.url = downloadableMediaContent.getUrl();
		return downloadableMediaContent.getType();
	}

	public Date getDate() {
		return date;
	}

	private void setDate(PhotoEntry photo) throws Exception {
		Calendar relevantDate = Calendar.getInstance();
		relevantDate.set(Calendar.YEAR, 1990);
		ExifTags exifTags = photo.getExifTags();

		if (photo.getTimestamp() != null && photo.getTimestamp().after(relevantDate.getTime())) {
			this.date = photo.getTimestamp();
		} else if (exifTags != null && exifTags.getTime() != null && exifTags.getTime().after(relevantDate.getTime())) {
			this.date = exifTags.getTime();
		} else {
			this.date = new Date(photo.getPublished().getValue());
		}
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String newName) {
		fileName = newName;
	}

	private void setFileName(PhotoEntry photo, String mediaType) {
		String fileBaseName = FilenameUtils.getBaseName(photo.getTitle().getPlainText());
		String fileExt = TYPE_TO_EXTENSION.get(mediaType);
		String result = fileBaseName + "." + fileExt;

		if (!FSUtils.validateFileName(result)) {
			try {
				result = FSUtils.fixFileName(result);
			} catch (Exception e) {
				logger.warn("Can't use orig photo name as filename, [" + result + "]. Using photoId [" + photo.getGphotoId() + "]");
				logger.warn("Cause: " + e.getMessage());
				result = photo.getGphotoId() + "." + fileExt;
			}
		}

		this.fileName = result;
	}

	public String getAlbumName() {
		return album.getName();
	}

	public SimpleAlbumEntry getAlbum() {
		return album;
	}

	private void setAlbum(SimpleAlbumEntry album) {
		this.album = album;
	}

	private MediaContent findBiggestVideo(List<MediaContent> mediaContents) {
		MediaContent biggestVideo = mediaContents.get(0);
		for (MediaContent mediaContent : mediaContents) {
			if (isBiggerVideo(biggestVideo, mediaContent)) {
				biggestVideo = mediaContent;
			}
		}
		return biggestVideo;
	}

	private boolean isBiggerVideo(MediaContent biggestVideo, MediaContent mediaContent) {
		boolean isWidthBigger = mediaContent.getWidth() >= biggestVideo.getWidth();
		boolean isVideoMediumType = VIDEO_MEDIUM.equals(mediaContent.getMedium());

		return isVideoMediumType && isWidthBigger;
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(date).append(url).append(fileName).append(album.getName()).toHashCode();
	}

	@Override
	public boolean equals(Object obj) {
		SimplePhotoEntry rhs = (SimplePhotoEntry) obj;
		return new EqualsBuilder().append(date, rhs.date).append(url, rhs.url).append(fileName, rhs.fileName)
				.append(album.getName(), rhs.album.getName()).isEquals();
	}

	@Override
	public String toString() {
		return new StringBuilder(getClass().getSimpleName())
			.append(" [").append(album.getName()).append(", ").append(fileName).append("]").toString();
	}

}


text:
package io.getquill.quotation

import scala.annotation.StaticAnnotation
import scala.reflect.ClassTag
import scala.reflect.macros.whitebox.Context

import io.getquill.ast._
import io.getquill.util.Messages.RichContext
import io.getquill.norm.BetaReduction

case class QuotedAst(ast: Ast) extends StaticAnnotation

trait Quotation extends Liftables with Unliftables with Parsing with ReifyLiftings {
  val c: Context
  import c.universe._

  def quote[T](body: Tree)(implicit t: WeakTypeTag[T]) = {

    val ast = BetaReduction(astParser(body))

    val id = TermName(s"id${ast.hashCode.abs}")

    val (reifiedAst, liftings) = reifyLiftings(ast)

    val quotation =
      q"""
        new ${c.prefix}.Quoted[$t] {

          @${c.weakTypeOf[QuotedAst]}($reifiedAst)
          def quoted = ast

          override def ast = $reifiedAst
          override def toString = ast.toString

          def $id() = ()

          $liftings
        }
      """

    IsDynamic(ast) match {
      case true  => q"$quotation: ${c.prefix}.Quoted[$t]"
      case false => quotation
    }
  }

  def doubleQuote[T: WeakTypeTag](body: Expr[Any]) =
    body.tree match {
      case q"null" => c.fail("Can't quote null")
      case tree    => q"${c.prefix}.unquote($tree)"
    }

  def quotedFunctionBody(func: Expr[Any]) =
    func.tree match {
      case q"(..$p) => $b" => q"${c.prefix}.quote((..$p) => ${c.prefix}.unquote($b))"
    }

  protected def unquote[T](tree: Tree)(implicit ct: ClassTag[T]) =
    astTree(tree).flatMap(astUnliftable.unapply).map {
      case ast: T => ast
    }

  private def astTree(tree: Tree) =
    for {
      method <- tree.tpe.decls.find(_.name.decodedName.toString == "quoted")
      annotation <- method.annotations.headOption
      astTree <- annotation.tree.children.lastOption
    } yield (astTree)
}


text:
package org.apache.storm.sql.planner.streams.rel;

import java.util.List;

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.prepare.Prepare;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rex.RexNode;
import org.apache.storm.sql.planner.StormRelUtils;
import org.apache.storm.sql.planner.rel.StormStreamInsertRelBase;
import org.apache.storm.sql.planner.streams.StreamsPlanCreator;
import org.apache.storm.sql.runtime.streams.functions.StreamInsertMapToPairFunction;
import org.apache.storm.streams.Stream;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.tuple.Values;

public class StreamsStreamInsertRel extends StormStreamInsertRelBase implements StreamsRel {
    private final int primaryKeyIndex;

    public StreamsStreamInsertRel(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, Prepare.CatalogReader catalogReader,
                                  RelNode child, Operation operation, List<String> updateColumnList, List<RexNode> sourceExpressionList,
                                  boolean flattened, int primaryKeyIndex) {
        super(cluster, traits, table, catalogReader, child, operation, updateColumnList, sourceExpressionList, flattened);
        this.primaryKeyIndex = primaryKeyIndex;
    }

    @Override
    public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) {
        return new StreamsStreamInsertRel(getCluster(), traitSet, getTable(), getCatalogReader(),
                sole(inputs), getOperation(), getUpdateColumnList(), getSourceExpressionList(), isFlattened(), primaryKeyIndex);
    }

    @Override
    public void streamsPlan(StreamsPlanCreator planCreator) throws Exception {
        // SingleRel
        RelNode input = getInput();
        StormRelUtils.getStormRelInput(input).streamsPlan(planCreator);
        Stream<Values> inputStream = planCreator.pop();

        Preconditions.checkArgument(isInsert(), "Only INSERT statement is supported.");

        // Calcite ensures that the value is structurized to the table definition
        // hence we can use PK index directly
        // To elaborate, if table BAR is defined as ID INTEGER PK, NAME VARCHAR, DEPTID INTEGER
        // and query like INSERT INTO BAR SELECT NAME, ID FROM FOO is executed,
        // Calcite makes the projection ($1 <- ID, $0 <- NAME, null) to the value before INSERT.

        String tableName = Joiner.on('.').join(getTable().getQualifiedName());
        IRichBolt consumer = planCreator.getSources().get(tableName).getConsumer();

        // To make logic simple, it assumes that all the tables have one PK (which it should be extended to support composed key),
        // and provides PairStream(KeyedStream) to consumer bolt.
        inputStream.mapToPair(new StreamInsertMapToPairFunction(primaryKeyIndex)).to(consumer);

        planCreator.addStream(inputStream);
    }

}


text:
//                     The PathScale libopenmp
//
// Copyright (c) 2005-2013 PathScale Inc. All rights reserved.
// Copyright (c) 2013-     Argonne National Laboratory. All rights reserved.
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#ifndef __pmp_atomic_gcc_h
#define __pmp_atomic_gcc_h

#include <stdint.h>

/* see
 * http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html
 * http://gcc.gnu.org/onlinedocs/gcc-4.6.2/gcc/Atomic-Builtins.html
 * for details */

static inline void __pmp_inline_atomic_add32 (volatile int32_t *p,
                                              int32_t addend)
{
/*  *p += addend; */
    __sync_fetch_and_add(p, addend);
}

static inline int32_t __pmp_inline_atomic_xadd32 (volatile int32_t *p,
                                                  int32_t addend)
{
/* int32_t result = *p;
   *p += addend;
   return result; */
    return __sync_fetch_and_add(p, addend);
}

static inline int32_t __pmp_inline_atomic_xchg32 (volatile int32_t *p,
                                                  int32_t new_value)
{
/*  int32_t value = *p;
    *p = new_value;
    return value; */
    int32_t value = *p;
    return __sync_val_compare_and_swap(p, value, new_value);
}

static inline int32_t __pmp_inline_atomic_cmpxchg32 (volatile int32_t *p,
                                                     int32_t old_value,
                                                     int32_t new_value)
{
/*  int32_t value = *p;
    if (old_value == value) {
      *p = new_value;
    }
    return value; */
    return __sync_val_compare_and_swap(p, old_value, new_value);
}

/* in theory we could test the size of void* and use either 32 or 64 as appropriate */
static inline void *__pmp_inline_atomic_cmpxchgptr  (volatile voidptr_t *p,
                                                     void *old_value,
                                                     void *new_value)
{
/*  void *value = *p;
    if (old_value == value) {
      *p = new_value;
    }
    return value; */
    return __sync_val_compare_and_swap(p, old_value, new_value);
}

#if __WORDSIZE == 64
static inline int64_t __pmp_inline_atomic_xadd64 (volatile int64_t *p,
                                                  int64_t addend)
{
/*  int64_t result = *p;
    *p += addend;
    return result; */
    return __sync_fetch_and_add(p, addend);
}

static inline void __pmp_inline_atomic_add64 (volatile int64_t *p,
                                              int64_t addend)
{
/*  *p += addend; */
    __sync_fetch_and_add(p, addend);
}

static inline int64_t __pmp_inline_atomic_cmpxchg64 (volatile int64_t *p,
                                                     int64_t old_value,
                                                     int64_t new_value)
{
/*  int64_t value = *p;
    if (old_value == value) {
      *p = new_value;
    }
    return value; */
    return __sync_val_compare_and_swap(p, old_value, new_value);
}
#endif

static inline void __pmp_inline_memory_fence ()
{
    __sync_synchronize();
}

#endif


text:
/* tslint:disable */
import { Observable } from 'rxjs/Observable';
import { createSelector } from 'reselect';
import { Action } from '@ngrx/store';
import { SDKToken, Account } from '../models';
import { LoopbackAuthActionTypes } from '../actions/auth';
import { UserActionTypes } from '../actions/user';

const initialState: SDKToken = {
  id: null,
  user: null,
  userId: null,
  issuedAt: null,
  created: null,
  ttl: null,
  rememberMe: null
};

/**
 * @module LoopbackAuthReducer
 * @author João Ribeiro <@JonnyBGod> <github:JonnyBGod>
 * @license MIT
 * @description
 * Provides with a LoopBack compatible authentication reducer.
 */
export function LoopbackAuthReducer(state = initialState, action: Action): SDKToken {
  switch (action.type) {
    case UserActionTypes.LOGIN_SUCCESS:
    case LoopbackAuthActionTypes.SET_TOKEN:
    case LoopbackAuthActionTypes.LOAD_TOKEN_SUCCESS: {
      const token: SDKToken = action.payload;

      return Object.assign({}, token);
    }

    case LoopbackAuthActionTypes.SET_USER: {
      const user: any = action.payload;
      let updateState = Object.assign({}, state);

      updateState.user = user;
      updateState.userId = user.id;

      return updateState;
    }

    case UserActionTypes.LOGOUT_SUCCESS:
    case UserActionTypes.LOGOUT_FAIL: {
      return Object.assign({}, initialState);
    }

    case LoopbackAuthActionTypes.UPDATE_USER_PROPERTIES_SUCCESS: {
      const userProperties: any = action.payload;
      let updateState = Object.assign({}, state);

      updateState.user = Object.assign(updateState.user, userProperties);

      return updateState;
    }

    default: {
      return state;
    }
  }
}

export function getLoopbackAuthState() {
  return (state$: Observable<any>) => state$
    .select((s) => s.loopbackAuth);
}

export function getLoopbackAuthToken() {
  return (state$: Observable<any>) => state$
    .select((s) => s.loopbackAuth.id);
}

export function getLoopbackAuthUser() {
  return (state$: Observable<any>) => state$
    .select((s) => s.loopbackAuth.user);
}

export function getLoopbackAuthUserId() {
  return (state$: Observable<any>) => state$
    .select((s) => s.loopbackAuth.userId);
}


text:
// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," "));
        var now = new Date();
        // Timezone offsets are in minutes
		var diff = (((now.getTime() + (now.getTimezoneOffset() * 60 * 1000)) - date.getTime()) / 1000);
		var day_diff = Math.floor(diff / 86400);

	if ( isNaN(day_diff) || day_diff < 0 || day_diff > 300 )
		return;

    // JRV 2009-01-26 - date thresholds changed
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 13 && day_diff + " days ago" ||
		day_diff < 45 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
        day_diff < 300 && Math.ceil(day_diff/30) + " months ago"
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" ) {
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};

    // Jesse Vincent added this function to let you prettify a div rather than
    // an HREF on 2009-01-26
    jQuery.fn.prettyDateTag = function(){
        return this.each(function(){
            var original_date = (this.title || this.innerHTML);
            var date = prettyDate(original_date);
             if (!date) return;
            jQuery(this).attr('title', original_date) ;
            jQuery(this).html(''+original_date+''+ date );
        });
    }

}


text:
<?php

namespace HRis\Providers;

use Dingo\Api\Auth\Auth;
use Dingo\Api\Auth\Provider\OAuth2;
use Illuminate\Support\ServiceProvider;
use Irradiate\Eloquent\User;

class OAuthServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app[Auth::class]->extend('oauth', function ($app) {
            $provider = new OAuth2($app['oauth2-server.authorizer']->getChecker());

            $provider->setUserResolver(function ($id) {
                return User::findOrFail($id);
            });

            $provider->setClientResolver(function ($id) {
                return User::findOrFail($id);
            });

            return $provider;
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
[![Latest release](http://img.shields.io/github/release/purescript/purescript-validation.svg)](https://github.com/purescript/purescript-validation/releases)
[![Build status](https://github.com/purescript/purescript-validation/workflows/CI/badge.svg?branch=master)](https://github.com/purescript/purescript-validation/actions?query=workflow%3ACI+branch%3Amaster)
[![Pursuit](https://pursuit.purescript.org/packages/purescript-validation/badge)](https://pursuit.purescript.org/packages/purescript-validation)

Applicative validation.

## Installation

```
spago install validation
```

## Documentation

Module documentation is [published on Pursuit](http://pursuit.purescript.org/packages/purescript-validation).

There is also an [entire chapter in PureScript by Example](https://book.purescript.org/chapter7.html#applicative-validation-1) dedicated to describing how to use this module.


text:
from django.core.management.base import LabelCommand

from corehq.apps.grapevine.api import GrapevineBackend
from corehq.apps.sms.models import INCOMING, OUTGOING
from corehq.apps.smsbillables.models import SmsGatewayFee

class Command(LabelCommand):
    help = "bootstrap Grapevine gateway fees"
    args = ""
    label = ""

    def handle(self, *args, **options):
        SmsGatewayFee.create_new(GrapevineBackend.get_api_id(), INCOMING, 0.02)
        SmsGatewayFee.create_new(GrapevineBackend.get_api_id(), OUTGOING, 0.02)
        print "Updated Grapevine gateway fees."


text:
random
======

Random stuff


text:
This application makes use of the following third party libraries:

## Alamofire

Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)

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.

## BmobSDK

  Copyright (c) 2013年 Bmob. All rights reserved.
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.

## Bugly

Copyright 2017 tencent.com. All rights reserved.

## Cartography

Copyright (c) 2014 Robert Böhnke <robb@robb.is>

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.

This license does not apply to the contents of the images folder.

---

This project uses portions of code from FLKAutoLayout,
copyright (c) 2013 Florian Kugler <mail@floriankugler.de>

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.

## DGElasticPullToRefresh

The MIT License (MIT)

Copyright (c) 2015 Danil Gontovnik

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.

## HandyJSON

   Copyright 1999-2016  Alibaba Group Holding Ltd.

   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.

## IQKeyboardManagerSwift

IQKeyboardManager license
=========================

The MIT License (MIT)

Copyright (c) 2013-16 Iftekhar Qurashi

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.

## MBProgressHUD

Copyright © 2009-2016 Matej Bukovinski

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.

## Masonry

Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry

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.

## RxCocoa

**The MIT License**
**Copyright © 2015 Krunoslav Zaher**
**All rights reserved.**

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.

## RxSwift

**The MIT License**
**Copyright © 2015 Krunoslav Zaher**
**All rights reserved.**

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.

## SDWebImage

Copyright (c) 2016 Olivier Poitrey rs@dailymotion.com

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.

## SwiftDate

Copyright (c) 2015 daniele margutti <me@danielemargutti.com>

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.

## SwiftyJSON

The MIT License (MIT)

Copyright (c) 2016 Ruoyu Fu

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.

## UMengAnalytics-NO-IDFA

Copyright 2011 - 2015 UMeng.com. All rights reserved.

## WechatOpenSDK

Copyright 2017 tencent.com. All rights reserved.

## XLPhotoBrowser+CoderXL

The MIT License (MIT)

Copyright (c) 2016 github共享库验证

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.

## YYKit

The MIT License (MIT)

Copyright (c) 2015 ibireme <ibireme@gmail.com>

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.

## pop

BSD License

For Pop software

Copyright (c) 2014, Facebook, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither the name Facebook nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Generated by CocoaPods - https://cocoapods.org


text:
module ActiveRecord
  module Locking
    # Locking::Pessimistic provides support for row-level locking using
    # SELECT ... FOR UPDATE and other lock types.
    #
    # Chain <tt>ActiveRecord::Base#find</tt> to <tt>ActiveRecord::QueryMethods#lock</tt> to obtain an exclusive
    # lock on the selected rows:
    #   # select * from accounts where id=1 for update
    #   Account.lock.find(1)
    #
    # Call <tt>lock('some locking clause')</tt> to use a database-specific locking clause
    # of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
    #
    #   Account.transaction do
    #     # select * from accounts where name = 'shugo' limit 1 for update
    #     shugo = Account.where("name = 'shugo'").lock(true).first
    #     yuko = Account.where("name = 'yuko'").lock(true).first
    #     shugo.balance -= 100
    #     shugo.save!
    #     yuko.balance += 100
    #     yuko.save!
    #   end
    #
    # You can also use <tt>ActiveRecord::Base#lock!</tt> method to lock one record by id.
    # This may be better if you don't need to lock every row. Example:
    #
    #   Account.transaction do
    #     # select * from accounts where ...
    #     accounts = Account.where(...)
    #     account1 = accounts.detect { |account| ... }
    #     account2 = accounts.detect { |account| ... }
    #     # select * from accounts where id=? for update
    #     account1.lock!
    #     account2.lock!
    #     account1.balance -= 100
    #     account1.save!
    #     account2.balance += 100
    #     account2.save!
    #   end
    #
    # You can start a transaction and acquire the lock in one go by calling
    # <tt>with_lock</tt> with a block. The block is called from within
    # a transaction, the object is already locked. Example:
    #
    #   account = Account.first
    #   account.with_lock do
    #     # This block is called within a transaction,
    #     # account is already locked.
    #     account.balance -= 100
    #     account.save!
    #   end
    #
    # Database-specific information on row locking:
    #   MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
    #   PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
    module Pessimistic
      # Obtain a row lock on this record. Reloads the record to obtain the requested
      # lock. Pass an SQL locking clause to append the end of the SELECT statement
      # or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
      # the locked record.
      def lock!(lock = true)
        reload(:cases => lock) if persisted?
        self
      end

      # Wraps the passed block in a transaction, locking the object
      # before yielding. You can pass the SQL locking clause
      # as argument (see <tt>lock!</tt>).
      def with_lock(lock = true)
        transaction do
          lock!(lock)
          yield
        end
      end
    end
  end
end


text:
from setuptools import setup, find_packages

setup(
    name='nodemgr',
    version='0.1dev',
    install_requires=[
        'pyyaml',
        'psutil>=0.6.0,!=5.5.0',
    ],
    packages=['nodemgr',
              'nodemgr.analytics_nodemgr',
              'nodemgr.analytics_snmp_nodemgr',
              'nodemgr.analytics_alarm_nodemgr',
              'nodemgr.control_nodemgr',
              'nodemgr.config_nodemgr',
              'nodemgr.analytics_database_nodemgr',
              'nodemgr.config_database_nodemgr',
              'nodemgr.vrouter_nodemgr',
              'nodemgr.common',
              'nodemgr.common.sandesh',
              'nodemgr.common.sandesh.nodeinfo',
              'nodemgr.common.sandesh.nodeinfo.cpuinfo',
              'nodemgr.common.sandesh.nodeinfo.process_info',
              'nodemgr.common.sandesh.supervisor_events'],
    package_data={'': ['*.html', '*.css', '*.xml']},
    zip_safe=False,
    long_description="Nodemgr Implementation",
    entry_points={
        'console_scripts': [
            'contrail-nodemgr = nodemgr.main:main',
        ],
    },
)


text:
<?php

namespace AppBundle\Form\Field;

use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Service\UserService;

class RolePickerType extends SelectPickerType {
	/**
	 *
	 * @var UserService $userService
	 */
	private $userService;

	public function __construct(UserService $userService)
	{
		parent::__construct();
		$this->userService = $userService;
	}

	/**
	 * @param OptionsResolver $resolver
	 */
	public function configureOptions(OptionsResolver $resolver)
	{
		$choices = $this->getExistingRoles();

		$resolver->setDefaults(array(
			'choices' => $choices,
			'attr' => [
					'data-live-search' => true
			],
			'choice_attr' => function($category, $key, $index) {
				//TODO: it would be nice to translate the roles
				return [
						'data-content' => "
  ".$this->humanize($key).'
'
				];
			},
			'choice_value' => function ($value) {
		       return $value;
		    },
		));
	}

	private  function getExistingRoles()
	{
		$roleHierarchy = $this->userService->getsecurityRoles();
		$roles = array_keys($roleHierarchy);

		$theRoles['not-defined'] = 'not-defined';
		$theRoles['ROLE_USER'] = 'ROLE_USER';

		foreach ($roles as $role) {
			$theRoles[$role] = $role;
		}
		$theRoles['ROLE_API'] = 'ROLE_API';
		return $theRoles;
	}
}


text:
TunableSpec
===========

TunableSpec provides live tweaking of UI spec values in a running iOS app.

The goal is to make throwing up a slider easier than doing guess-and-check to choose a value.

![Screenshot](https://github.com/kongtomorrow/TunableSpec/raw/master/Screenshot.png)

If changing a value requires restarting the app, you're never going to get as good results as if you're looking at the response live.
Are your alpha values all multiples of 0.1? If so, this is for you.

Usage
-----
To use, add `KFTunableSpec.h` and `KFTunableSpec.m` to your project.

The only class, `KFTunableSpec`, is similar to `NSUserDefaults`.

```objc
KFTunableSpec *spec = [KFTunableSpec specNamed:@"MainSpec"];

CGFloat dur = [spec doubleForKey:@"SpringDuration"];
CGFloat damp = [spec doubleForKey:@"SpringDamping"];
```

Besides simple getters, "maintain" versions are provided for live UI updates. The maintenance block is called whenever the value changes due to being tuned. For example, with

```objc
[spec withDoubleForKey:@"LabelText" owner:self maintain:^(id owner, double doubleValue) {
 [[owner label] setText:[NSString stringWithFormat:@"%g", doubleValue]];
}];
```

the label text will live-update as you drag the tuning slider.

The values come from a JSON file that looks like this:

```
[
  {
    "sliderMaxValue" : 2,
    "key" : "SpringDuration",
    "label" : "Duration",
    "sliderValue" : 0.5756578999999999,
    "sliderMinValue" : 0
  },
  {
    "sliderMaxValue" : 1,
    "key" : "SpringDamping",
    "label" : "Damping",
    "sliderValue" : 0.5115132,
    "sliderMinValue" : 0
  }
]
```

When you've changed values in a way you want to keep, a "share" button in the UI exports a replacement JSON file to be checked into source control.

See `KFTunableSpec.h` for full documentation, and `Spring Playground` for an example app.


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

  <parent>
    <groupId>com.squareup.spoon</groupId>
    <artifactId>parent</artifactId>
    <version>1.2.1-SNAPSHOT</version>
  </parent>

  <artifactId>spoon-maven-plugin</artifactId>
  <packaging>maven-plugin</packaging>
  <name>Spoon Maven Plugin</name>

  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>spoon-runner</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-plugin-plugin</artifactId>
        <executions>
          <execution>
            <phase>process-classes</phase>
            <goals>
              <goal>descriptor</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
Führe Kommando aus

Diese Seite stellt den kompletten Auswurf (STDOUT und STDIN( Ihres Kommando dar, den Sie gerade ausgeführt haben.


text:
"""
Description : This file implements the LogMine algorithm for log parsing
Author      : LogPAI team
License     : MIT
"""

import sys
import re
import os
import alignment
import copy
import hashlib
import pandas as pd
from datetime import datetime
from collections import defaultdict

class partition():
    def __init__(self, idx, log="", lev=-1):
        self.logs_idx = [idx]
        self.patterns = [log]
        self.level = lev

class LogParser():
    def __init__(self, indir, outdir, log_format, max_dist=0.001, levels=2, k=1, k1=1, k2=1, alpha=100, rex=[]):
        self.logformat = log_format
        self.path = indir
        self.savePath = outdir
        self.rex = rex
        self.levels = levels
        self.max_dist = max_dist
        self.k = k
        self.k1 = k1
        self.k2 = k2
        self.alpha = alpha
        self.df_log = None
        self.logname = None
        self.level_clusters = {}

    def parse(self, logname):
        print('Parsing file: ' + os.path.join(self.path, logname))
        self.logname = logname
        starttime = datetime.now()
        self.load_data()
        for lev in range(self.levels):
            if lev == 0:
                # Clustering
                self.level_clusters[0] = self.get_clusters(self.df_log['Content_'], lev)
            else:
                # Clustering
                patterns = [c.patterns[0] for c in self.level_clusters[lev-1]]
                self.max_dist *= self.alpha
                clusters = self.get_clusters(patterns, lev, self.level_clusters[lev-1])

                # Generate patterns
                for cluster in clusters:
                    cluster.patterns = [self.sequential_merge(cluster.patterns)]
                self.level_clusters[lev] = clusters
        self.dump()
        print('Parsing done. [Time taken: {!s}]'.format(datetime.now() - starttime))

    def dump(self):
        if not os.path.isdir(self.savePath):
            os.makedirs(self.savePath)

        templates = [0] * self.df_log.shape[0]
        ids = [0] * self.df_log.shape[0]
        templates_occ = defaultdict(int)
        for cluster in self.level_clusters[self.levels-1]:
            EventTemplate = cluster.patterns[0]
            EventId = hashlib.md5(' '.join(EventTemplate).encode('utf-8')).hexdigest()[0:8]
            Occurences = len(cluster.logs_idx)
            templates_occ[EventTemplate] += Occurences

            for idx in cluster.logs_idx:
                ids[idx] = EventId
                templates[idx]= EventTemplate
        self.df_log['EventId'] = ids
        self.df_log['EventTemplate'] = templates

        occ_dict = dict(self.df_log['EventTemplate'].value_counts())
        df_event = pd.DataFrame()
        df_event['EventTemplate'] = self.df_log['EventTemplate'].unique()
        df_event['Occurrences'] = self.df_log['EventTemplate'].map(occ_dict)
        df_event['EventId'] = self.df_log['EventTemplate'].map(lambda x: hashlib.md5(x.encode('utf-8')).hexdigest()[0:8])

        self.df_log.drop("Content_", inplace=True, axis=1)
        self.df_log.to_csv(os.path.join(self.savePath, self.logname + '_structured.csv'), index=False)
        df_event.to_csv(os.path.join(self.savePath, self.logname + '_templates.csv'), index=False, columns=["EventId","EventTemplate","Occurrences"])

    def get_clusters(self, logs, lev, old_clusters=None):
        clusters = []
        old_clusters = copy.deepcopy(old_clusters)
        for logidx, log in enumerate(logs):
            match = False
            for cluster in clusters:
                dis = self.msgDist(log, cluster.patterns[0]) if lev == 0 else self.patternDist(log, cluster.patterns[0])
                if dis and dis < self.max_dist:
                    if lev == 0:
                        cluster.logs_idx.append(logidx)
                    else:
                        cluster.logs_idx.extend(old_clusters[logidx].logs_idx)
                        cluster.patterns.append(old_clusters[logidx].patterns[0])
                    match = True

            if not match:
                if lev == 0:
                    clusters.append(partition(logidx, log, lev)) # generate new cluster
                else:
                    old_clusters[logidx].level = lev
                    clusters.append(old_clusters[logidx]) # keep old cluster

        return clusters

    def sequential_merge(self, logs):
        log_merged = logs[0]
        for log in logs[1:]:
            log_merged = self.pair_merge(log_merged, log)
        return log_merged

    def pair_merge(self, loga, logb):
        loga, logb = alignment.water(loga.split(), logb.split())
        logn = []
        for idx, value in enumerate(loga):
            logn.append('<*>' if value != logb[idx] else value)
        return " ".join(logn)

    def print_cluster(self, cluster):
        print "------start------"
        print "level: {}".format(cluster.level)
        print "idxs: {}".format(cluster.logs_idx)
        print "patterns: {}".format(cluster.patterns)
        print "count: {}".format(len(cluster.patterns))
        for idx in cluster.logs_idx:
            print self.df_log.iloc[idx]['Content_']
        print "------end------"

    def msgDist(self, seqP, seqQ):
        dis = 1
        seqP = seqP.split()
        seqQ = seqQ.split()
        maxlen = max(len(seqP), len(seqQ))
        minlen = min(len(seqP), len(seqQ))
        for i in range(minlen):
            dis -= (self.k if seqP[i]==seqQ[i] else 0 * 1.0) / maxlen
        return dis

    def patternDist(self, seqP, seqQ):
        dis = 1
        seqP = seqP.split()
        seqQ = seqQ.split()
        maxlen = max(len(seqP), len(seqQ))
        minlen = min(len(seqP), len(seqQ))
        for i in range(minlen):
            if seqP[i] == seqQ[i]:
                if seqP[i] == "<*>":
                    dis -= self.k2 * 1.0 / maxlen
                else:
                    dis -= self.k1 * 1.0 / maxlen
        return dis

    def load_data(self):
        def preprocess(line):
            for currentRex in self.rex:
                line = re.sub(currentRex, '', line)
            return line

        headers, regex = self.generate_logformat_regex(self.logformat)
        self.df_log = self.log_to_dataframe(os.path.join(self.path, self.logname), regex, headers, self.logformat)
        self.df_log['Content_'] = self.df_log['Content'].map(preprocess)

    def log_to_dataframe(self, log_file, regex, headers, logformat):
        ''' Function to transform log file to dataframe '''
        log_messages = []
        linecount = 0
        with open(log_file, 'r') as fin:
            for line in fin.readlines():
                try:
                    match = regex.search(line.strip())
                    message = [match.group(header) for header in headers]
                    log_messages.append(message)
                    linecount += 1
                except Exception as e:
                    pass
        logdf = pd.DataFrame(log_messages, columns=headers)
        logdf.insert(0, 'LineId', None)
        logdf['LineId'] = [i + 1 for i in range(linecount)]
        return logdf

    def generate_logformat_regex(self, logformat):
        '''
        Function to generate regular expression to split log messages
        '''
        headers = []
        splitters = re.split(r'(<[^<>]+>)', logformat)
        regex = ''
        for k in range(len(splitters)):
            if k % 2 == 0:
                splitter = re.sub(' +', '\s+', splitters[k])
                regex += splitter
            else:
                header = splitters[k].strip('<').strip('>')
                regex += '(?P<%s>.*?)' % header
                headers.append(header)
        regex = re.compile('^' + regex + '$')
        return headers, regex


text:
/*jscs:disable maximumLineLength */
describe('State Functions', () => {
  describe('State.syncEntityEvents()', () => {
    var AbstractStateful;

    beforeEach(() => {
      var State = Mn.State.extend({
        defaultState: {
          foo: 1,
          bar: 2,
          baz: 3
        }
      });

      var Model = Bb.Model.extend({
        defaults: {
          foo: 1,
          bar: 2,
          baz: 3
        }
      });

      var Collection = Bb.Collection;

      AbstractStateful = Mn.Object.extend({
        stateEvents: {
          'all':                              'onAll',
          'change':                           'onChange onChange2',
          'change:foo':                       'onChangeFoo',
          'reset':                            'onReset',
          'change:foo change:bar change:baz': 'onChangeFooBarBaz'
        },
        modelEvents: {
          'all':                              'onAll',
          'change':                           'onChange onChange2',
          'change:foo':                       'onChangeFoo',
          'reset':                            'onReset',
          'change:foo change:bar change:baz': 'onChangeFooBarBaz'
        },
        collectionEvents: {
          'all':        'onCollectionAll',
          'reset':      'onCollectionReset onCollectionReset2',
          'all reset':  'onCollectionAllReset',
          'add':        'onCollectionAdd',
          'remove':     'onCollectionRemove',
          'change':     'onCollectionChange',
          'change:foo': 'onCollectionChangeFoo'
        },
        constructor() {
          this.state = new State();
          this.model = new Model();
          this.collection = new Collection();
          AbstractStateful.__super__.constructor.apply(this, arguments);
        },
        onAll:                 stub(),
        onChange:              stub(),
        onChange2:             stub(),
        onChangeFoo:           stub(),
        onChangeFooBarBaz:     stub(),
        onReset:               stub(),
        onCollectionAll:       stub(),
        onCollectionReset:     stub(),
        onCollectionReset2:    stub(),
        onCollectionAllReset:  stub(),
        onCollectionAdd:       stub(),
        onCollectionRemove:    stub(),
        onCollectionChange:    stub(),
        onCollectionChangeFoo: stub()
      });
    });

    describe('when syncing', () => {
      var stateful;
      var onInlineChange;
      var onInlineReset;

      beforeEach(() => {
        onInlineChange = stub();
        onInlineReset = stub();
        var Stateful = AbstractStateful.extend({
          inlineEvents: {
            'change': onInlineChange,
            'reset':  onInlineReset
          },
          initialize() {
            Mn.State.syncEntityEvents(this, this.state, this.stateEvents);
            Mn.State.syncEntityEvents(this, this.model, this.modelEvents);
            Mn.State.syncEntityEvents(this, this.collection, this.collectionEvents);

            Mn.State.syncEntityEvents(this, this.state, this.inlineEvents);
            Mn.State.syncEntityEvents(this, this.model, this.inlineEvents);
            Mn.State.syncEntityEvents(this, this.collection, this.inlineEvents);
          }
        });
        stateful = new Stateful();
      });

      it('should call handlers for Model or State {change|change:value|all} events', () => {
        expect(stateful.onAll).to.have.been.calledTwice;
        expect(stateful.onChange).to.have.been.calledTwice;
        expect(stateful.onChangeFoo).to.have.been.calledTwice;
      });

      it('should not call handlers for Model or State events besides {change|change:value|all}', () => {
        expect(stateful.onReset).to.not.have.been.calledTwice;
      });

      it('should call handlers for Collection {all|reset} events', () => {
        expect(stateful.onCollectionAll).to.have.been.calledOnce;
        expect(stateful.onCollectionReset).to.have.been.calledOnce;
      });

      it('should not call handlers for Collection events besides {all|reset}', () => {
        expect(stateful.onCollectionAdd).to.not.have.been.called;
        expect(stateful.onCollectionRemove).to.not.have.been.called;
        expect(stateful.onCollectionChange).to.not.have.been.called;
        expect(stateful.onCollectionChangeFoo).to.not.have.been.called;
      });

      it('should call handlers with the target object as context', () => {
        expect(stateful.onAll).to.always.have.been.calledOn(stateful);
        expect(stateful.onCollectionAll).to.always.have.been.calledOn(stateful);
      });

      it('should call handlers with standard Backbone event arguments', () => {
        expect(stateful.onChange).to.have.been.calledTwice
          .to.have.been.calledTwice
          .and.to.have.been.calledWith(stateful.model)
          .and.to.have.been.calledWith(stateful.state);
        expect(stateful.onChangeFoo).to.have.been.calledTwice
          .to.have.been.calledTwice
          .and.to.have.been.calledWith(stateful.model, 1)
          .and.to.have.been.calledWith(stateful.state, 1);
        expect(stateful.onCollectionReset)
          .to.have.been.calledOnce
          .and.to.have.been.calledWith(stateful.collection);
      });

      it('should pass { syncing: true } as a Backbone event handler option', () => {
        expect(stateful.onChange).to.have.been.calledTwice
          .to.have.been.calledTwice
          .and.to.have.been.calledWith(stateful.model, { syncing: true })
          .and.to.have.been.calledWith(stateful.state, { syncing: true });
        expect(stateful.onChangeFoo).to.have.been.calledTwice
          .to.have.been.calledTwice
          .and.to.have.been.calledWith(stateful.model, 1, { syncing: true })
          .and.to.have.been.calledWith(stateful.state, 1, { syncing: true });
        expect(stateful.onCollectionReset)
          .to.have.been.calledOnce
          .and.to.have.been.calledWith(stateful.collection, { syncing: true });
      });

      it('should call handler for multiple inlined events', () => {
        expect(stateful.onChangeFooBarBaz.callCount).to.equal(6);
        expect(stateful.onCollectionAllReset.callCount).to.equal(2);
      });

      it('should call multiple handlers for a single event', () => {
        expect(stateful.onChange).to.have.been.calledTwice;
        expect(stateful.onChange2).to.have.been.calledTwice;
        expect(stateful.onCollectionReset).to.have.been.calledOnce;
        expect(stateful.onCollectionReset2).to.have.been.calledOnce;
      });

      it('should call inline function handlers', () => {
        expect(onInlineChange)
          .to.have.been.calledTwice
          .and.to.have.been.calledWith(stateful.model)
          .and.to.have.been.calledWith(stateful.state)
          .and.to.always.have.been.calledOn(stateful);
        expect(onInlineReset)
          .to.have.been.calledOnce
          .and.to.have.been.calledWith(stateful.collection)
          .and.to.always.have.been.calledOn(stateful);
      });
    });

    describe('when syncing with missing parameters', () => {
      var stateful;

      beforeEach(() => {
        var Stateful = AbstractStateful.extend({
          syncWithoutBindings() {
            Mn.State.syncEntityEvents(this, this.state, null);
          },

          syncWithoutEntity() {
            Mn.State.syncEntityEvents(this, null, this.stateEvents);
          }
        });
        stateful = new Stateful();
        sinon.spy(stateful, 'syncWithoutBindings');
        sinon.spy(stateful, 'syncWithoutEntity');
      });

      it('should throw an exception without bindings', () => {
        expect(() => stateful.syncWithoutBindings()).to.throw('`bindings` must be provided.');
      });

      it('should throw an exception without entity', () => {
        expect(() => stateful.syncWithoutEntity()).to.throw('`entity` must be provided.');
      });
    });

    describe('when syncing on a target event', () => {
      var stateful;

      beforeEach(() => {
        var Stateful = AbstractStateful.extend({
          initialize() {
            this.stateSyncing =
              Mn.State.syncEntityEvents(this, this.state, this.stateEvents, 'render');
            this.modelSyncing =
              Mn.State.syncEntityEvents(this, this.model, this.stateEvents, 'render');
            this.collectionSyncing =
              Mn.State.syncEntityEvents(this, this.collection, this.collectionEvents, 'render');
          },
          render() {
            this.trigger('render');
          }
        });
        stateful = new Stateful();
      });

      it('should not sync immediately', () => {
        expect(stateful.onChange).to.not.have.been.called;
        expect(stateful.onChangeFoo).to.not.have.been.called;
        expect(stateful.onCollectionReset).to.not.have.been.called;
      });

      it('should sync on target event', () => {
        stateful.render();

        expect(stateful.onChange)
          .to.have.been.calledTwice
          .and.to.have.been.calledWith(stateful.model)
          .and.to.have.been.calledWith(stateful.state);
        expect(stateful.onChangeFoo)
          .to.have.been.calledTwice
          .and.to.have.been.calledWith(stateful.model, 1)
          .and.to.have.been.calledWith(stateful.state, 1);
        expect(stateful.onCollectionReset)
          .to.have.been.calledOnce
          .and.to.have.been.calledWith(stateful.collection);
      });

      describe('when calling stop on the Syncing instance', () => {
        beforeEach(() => {
          stateful.stateSyncing.stop();
          stateful.modelSyncing.stop();
          stateful.collectionSyncing.stop();
        });

        it('should not sync on target event', () => {
          stateful.render();
          expect(stateful.onChange).to.not.have.been.called;
          expect(stateful.onChangeFoo).to.not.have.been.called;
          expect(stateful.onCollectionReset).to.not.have.been.called;
        });

        it('should not fire change handlers for future change events', () => {
        });
      });
    });
  });

  describe('State.hasAnyChanged()', () => {
    var unchangedModel;
    var changedModel;
    var unchangedState;
    var changedState;

    beforeEach(() => {
      var Model = Bb.Model.extend({
        defaults: {
          foo: 1,
          bar: 2,
          baz: 3
        }
      });
      var State = Mn.State.extend({
        defaultState: {
          foo: 1,
          bar: 2,
          baz: 3
        }
      });

      unchangedModel = new Model();
      changedModel = new Model();
      changedModel.set({
        foo: 10,
        bar: 20,
        baz: 3
      });

      unchangedState = new State();
      changedState = new State();
      changedState.set({
        foo: 10,
        bar: 20,
        baz: 3
      });
    });

    describe('when model or state is newly created', () => {
      it('should return false for all default attributes', () => {
        expect(Mn.State.hasAnyChanged(unchangedModel, 'foo', 'bar', 'baz')).to.equal(false);
        expect(Mn.State.hasAnyChanged(unchangedState, 'foo', 'bar', 'baz')).to.equal(false);
      });
    });

    describe('when model or state is set with some changed and some unchanged attributes', () => {
      it('should return true for all changed attributes', () => {
        expect(Mn.State.hasAnyChanged(changedModel, 'foo', 'bar')).to.equal(true);
        expect(Mn.State.hasAnyChanged(changedState, 'foo', 'bar')).to.equal(true);
      });
      it('should return true for some changed and some unchanged attributes', () => {
        expect(Mn.State.hasAnyChanged(changedModel, 'foo', 'baz')).to.equal(true);
        expect(Mn.State.hasAnyChanged(changedState, 'foo', 'baz')).to.equal(true);
      });
      it('should return false for all unchanged attributes', () => {
        expect(Mn.State.hasAnyChanged(changedModel, 'baz')).to.equal(false);
        expect(Mn.State.hasAnyChanged(changedState, 'baz')).to.equal(false);
      });
    });
  });
});


text:
; Copyright (c) 2019 The cxkernel Authors. All rights reserved.
; Use of this source code is governed by a MIT-style
; license that can be found in the LICENSE file or at
; https://opensource.org/licenses/MIT
;
; @file   start.asm
; @author Kevin Dai \<kevindai02@outlook.com\>
; @date   Created on October 08 2018, 4:35 PM

[BITS 32]
ALIGN 4

; Declare constants for the multiboot header
ALIGNN   equ 1 << 0           ; align loaded modules on page boundaries
MEMINFO  equ 1 << 1           ; provide memory map
FLAGS    equ ALIGNN | MEMINFO ; this is the Multiboot 'flag' field
MAGIC    equ 0x1BADB002       ; 'magic number' lets bootloader find the header
CHECKSUM equ -(MAGIC + FLAGS) ; checksum of above, to prove we are multiboot

ARCH_PAGE_SIZE equ 0x1000

; Declare a multiboot header that marks the program as a kernel. These are magic
; values that are documented in the multiboot standard. The bootloader will
; search for this signature in the first 8 KiB of the kernel file, aligned at a
; 32-bit boundary. The signature is in its own section so the header can be
; forced to be within the first 8 KiB of the kernel file.
SECTION .multiboot ALIGN=4
dd MAGIC
dd FLAGS
dd CHECKSUM

; The multiboot standard does not define the value of the stack pointer register
; (esp) and it is up to the kernel to provide a stack. This allocates room for a
; small stack by creating a symbol at the bottom of it, then allocating 16384
; bytes for it, and finally creating a symbol at the top. The stack grows
; downwards on x86. The stack is in its own section so it can be marked nobits,
; which means the kernel file is smaller because it does not contain an
; uninitialized stack. The stack on x86 must be 16-byte aligned according to the
; System V ABI standard and de-facto extensions. The compiler will assume the
; stack is properly aligned and failure to align the stack will result in
; undefined behavior.
SECTION .bootloader_stack nobits alloc write ALIGN=4
[GLOBAL stack_top]
[GLOBAL stack_bottom]
stack_bottom:
    resb 4096 ; This should be enough
stack_top:

; The linker script specifies _start as the entry point to the kernel and the
; bootloader will jump to this position once the kernel has been loaded. It
; doesn't make sense to return from this function as the bootloader is gone.
SECTION .text
[GLOBAL _start]
[EXTERN main]

_start:
    ; Oh how I love NASM
    cli
    mov esp, stack_top ; Set up stack
    push ebx ; Push grub multiboot structs
    push eax
    call main
    cli
.0b:
    hlt
    jmp .0b

[GLOBAL load_gdt]
load_gdt:
    mov eax, [esp+4]  ; Get the pointer to the GDT, passed as a parameter.
    lgdt [eax]        ; Load the new GDT pointer
    mov ax, 0x10      ; 0x10 is the offset in the GDT to our data segment
    mov ds, ax        ; Load all data segment selectors
    mov es, ax
    mov fs, ax
    mov gs, ax
    mov ss, ax
    jmp 0x08:.flush   ; 0x08 is the offset to our code segment: Far jump!
.flush:
    ret

[GLOBAL enable_xd]
enable_xd:
    mov ecx, 0xC0000080
    rdmsr
    or eax, 1 << 11
    wrmsr

[GLOBAL jump32]
jump32:
    cli


text:
document.addEventListener("DOMContentLoaded", function(event) {

	// The code below requires jQuery
	var $ = django.jQuery;

	$("#id_template").select2({
	  tags: true,
	  createTag: function (params) {
	    return {
	      id: params.term,
	      text: params.term,
	      newOption: true
	    }
	  },
	   templateResult: function (data) {
	    var $result = $("");

	    $result.text(data.text);

	    if (data.newOption) {
	      $result.append(" (new)");
	    }

	    return $result;
	  }
	});
});


text:
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ochrons/scalajs-spa-tutorial?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Scala.js](https://www.scala-js.org/assets/badges/scalajs-0.6.17.svg)](https://www.scala-js.org)

Tutorial for creating a simple (but potentially complex!) Single Page Application with
[Scala.js](http://www.scala-js.org/) and [Play](https://www.playframework.com/).

## Purpose

This project demonstrates typical design patterns and practices for developing SPAs with Scala.js with special focus on
building a complete application. It started as a way to learn more about Scala.js and related libraries, but then I
decided to make it more tutorial-like for the greater good :)

The code covers typical aspects of building a SPA using Scala.js but it doesn't try to be an all-encompassing example
for all the things possible with Scala.js. Before going through this tutorial, it would be helpful if you already know
the basics of Scala.js and have read through the official [Scala.js tutorial](http://www.scala-js.org/doc/tutorial.html)
and the great e-book [Hands-on Scala.js](http://lihaoyi.github.io/hands-on-scala-js/#Hands-onScala.js) by
[Li Haoyi (@lihaoyi)](https://github.com/lihaoyi).

# Documentation

Tutorial [documentation](https://ochrons.github.io/scalajs-spa-tutorial) is now presented as a GitBook.

日本語を話せますか?Scala.js is Big in Japan, so I'm looking for help to translate the tutorial documentation into Japanese.
Contact me on twitter (@ochrons) or via email (otto@chrons.me) if you're interested! お願いします!

# Scala IDE users

If you are using Scala IDE, you need to set additional settings to get your Eclipse project exported from SBT.

```
set EclipseKeys.skipParents in ThisBuild := false
eclipse
```


text: fix: rename toolbox.xml to avoid name collisions, fixes #248 (Shyim)


text:
@implementation PKTRightValueTransformer

- (instancetype)init {
  return [self initWithBlock:^id(id value) {
    return @([PKTRightValueTransformer rightFromArray:value]);
  }];
}

#pragma mark - Private

+ (PKTRight)rightFromString:(NSString *)key {
  NSParameterAssert([key isKindOfClass:[NSString class]]);

  static NSDictionary *rightsMapping = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    rightsMapping = @{
      @"view": @(PKTRightView),
      @"update": @(PKTRightUpdate),
      @"delete": @(PKTRightDelete),
      @"subscribe": @(PKTRightSubscribe),
      @"comment": @(PKTRightComment),
      @"rate": @(PKTRightRate),
      @"share": @(PKTRightShare),
      @"install": @(PKTRightInstall),
      @"add_app": @(PKTRightAddApp),
      @"add_item": @(PKTRightAddItem),
      @"add_file": @(PKTRightAddFile),
      @"add_task": @(PKTRightAddTask),
      @"add_space": @(PKTRightAddSpace),
      @"add_status": @(PKTRightAddStatus),
      @"add_conversation": @(PKTRightAddConversation),
      @"reply": @(PKTRightReply),
      @"add_widget": @(PKTRightAddWidget),
      @"statistics": @(PKTRightStatistics),
      @"add_contact": @(PKTRightAddContact),
      @"add_hook": @(PKTRightAddHook),
      @"add_question": @(PKTRightAddQuestion),
      @"add_answer": @(PKTRightAddAnswer),
      @"add_contract": @(PKTRightAddContract),
      @"add_user": @(PKTRightAddUser),
      @"add_user_light": @(PKTRightAddUserLight),
      @"move": @(PKTRightMove),
      @"export": @(PKTRightExport),
      @"reference": @(PKTRightReference),
      @"view_admins": @(PKTRightViewAdmins),
      @"download": @(PKTRightDownload),
      @"grant": @(PKTRightGrant),
      @"grant_view": @(PKTRightGrantView)
    };
  });

  PKTRight right = PKTRightNone;
  NSValue *rightValue = rightsMapping[key];
  [rightValue getValue:&right];

  return right;
}

+ (PKTRight)rightFromArray:(NSArray *)keys {
  NSParameterAssert([keys isKindOfClass:[NSArray class]]);

  PKTRight right = PKTRightNone;
  for (NSString *key in keys) {
    right |= [self rightFromString:key];
  }

  return right;
}

@end


text:
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost {
namespace interprocess {

typedef pdalboost::date_time::microsec_clock<pdalboost::posix_time::ptime> microsec_clock;

}
}

#ifdef _WIN32
#ifdef BOOST_INTERPROCESS_WIN32_LEAN_AND_MEAN
#undef WIN32_LEAN_AND_MEAN
#undef BOOST_INTERPROCESS_WIN32_LEAN_AND_MEAN
#endif   //#ifdef BOOST_INTERPROCESS_WIN32_LEAN_AND_MEAN
#endif   //#ifdef _WIN32

#endif   //#ifndef BOOST_INTERPROCESS_POSIX_TIMES_WRK_HPP


text:
#include "config.h"
#include "FESpecularLighting.h"

#include "LightSource.h"
#include <wtf/text/TextStream.h>

namespace WebCore {

FESpecularLighting::FESpecularLighting(Filter& filter, const Color& lightingColor, float surfaceScale, float specularConstant, float specularExponent, float kernelUnitLengthX, float kernelUnitLengthY, Ref<LightSource>&& lightSource)
    : FELighting(filter, SpecularLighting, lightingColor, surfaceScale, 0, specularConstant, specularExponent, kernelUnitLengthX, kernelUnitLengthY, WTFMove(lightSource))
{
}

Ref<FESpecularLighting> FESpecularLighting::create(Filter& filter, const Color& lightingColor, float surfaceScale, float specularConstant, float specularExponent, float kernelUnitLengthX, float kernelUnitLengthY, Ref<LightSource>&& lightSource)
{
    return adoptRef(*new FESpecularLighting(filter, lightingColor, surfaceScale, specularConstant, specularExponent, kernelUnitLengthX, kernelUnitLengthY, WTFMove(lightSource)));
}

FESpecularLighting::~FESpecularLighting() = default;

bool FESpecularLighting::setSpecularConstant(float specularConstant)
{
    if (m_specularConstant == specularConstant)
        return false;
    m_specularConstant = specularConstant;
    return true;
}

bool FESpecularLighting::setSpecularExponent(float specularExponent)
{
    if (m_specularExponent == specularExponent)
        return false;
    m_specularExponent = specularExponent;
    return true;
}

TextStream& FESpecularLighting::externalRepresentation(TextStream& ts) const
{
    ts << indent << "[feSpecularLighting";
    FilterEffect::externalRepresentation(ts);
    ts << " surfaceScale=\"" << m_surfaceScale << "\" "
       << "specualConstant=\"" << m_specularConstant << "\" "
       << "specularExponent=\"" << m_specularExponent << "\"]\n";

    TextStream::IndentScope indentScope(ts);
    inputEffect(0)->externalRepresentation(ts);
    return ts;
}

} // namespace WebCore


text:
"""This module defines an abstract interface for datastore backends.

Datastore backends should guarantee implementation of the methods detailed in
the Backend class, below. This allows datastore backend users a reliable
interface and an easy path for migrating between backends.

Similarly, datastore backends should raise exceptions defined here, instead of
raising exceptions defined in their own modules. This allows users to catch
these exceptions without concern when migrating between backends, and allows for
a common point of reference for exceptions.
"""

class Error(Exception):
    """Common exception that all other exceptions in this module inherit from.
    """
    pass

class DeleteError(Error):
    """An error occurred while deleting data from the datastore.
    """
    pass
class EditError(Error):
    """An error occurred while editing data in the datastore.
    """
    pass
class LoadError(Error):
    """An error occurred loading data from the datastore.
    """
    pass
class QueryError(Error):
    """An error occurred while querying the datastore.
    """
    pass

class RequestType:
    """Requests to the datastore backend can be referenced by these constants.
    """
    EDIT = 'edit'
    DELETE = 'delete'
    NEW = 'new'

class Backend(object):
    """An abstract interface that all datastore backends must honor.

    Refer to the specific datastore backend implementation for details of how
    each of these methods should be treated. Results may vary.
    """
    def SetClientHTTP(self, http):
        pass
    def ExistingDates(self):
        pass

    def DeleteMetricInfo(self, metric_name):
        pass
    def GetMetricInfo(self, metric_name=None):
        pass
    def SetMetricInfo(self, request_type, metric_name, metric_info):
        pass

    def CreateMetricDataTable(self, metric_name):
        pass

    def DeleteMetricData(self, metric_name, date=None):
        pass
    def GetMetricData(self, metric_name, date, locale):
        pass
    def SetMetricData(self, metric_name, date, locale, value):
        pass

    def GetLocaleData(self, locale_type):
        pass