text:
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Security;
using BuildingBlocks.Membership.Contract;
using BuildingBlocks.Membership.Entities;
using Common.Logging;

namespace BuildingBlocks.Membership
{
    public class MembershipProvider : System.Web.Security.MembershipProvider, IForcedPasswordChangeProvider
    {
        private static readonly ILog _log = LogManager.GetLogger<MembershipProvider>();
        private string _applicationName;
        private const int TokenSizeInBytes = 16;
        private readonly Lazy<IUserRepository> _userRepository;
        private int? _minRequiredPasswordLength;
        private int? _minRequiredNonAlphanumericCharacters;
        private int? _maxInvalidPasswordAttempts;
        private int? _passwordAttemptWindow;

        public MembershipProvider()
        {
            _userRepository = new Lazy<IUserRepository>(() => RepositoryFactory.Current.CreateUserRepository(), true);
        }

        public IUserRepository UserRepository
        {
            get { return _userRepository.Value; }
        }

        public override string ApplicationName
        {
            get
            {
                return _applicationName ?? (_applicationName = GetType().Namespace);
            }
            set
            {
                _applicationName = value;
            }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return _maxInvalidPasswordAttempts ?? 5; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return _minRequiredNonAlphanumericCharacters ?? 0; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return _minRequiredPasswordLength ?? 6; }
        }

        public override int PasswordAttemptWindow
        {
            get { return _passwordAttemptWindow ?? 0; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return MembershipPasswordFormat.Hashed; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return string.Empty; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            _log.Trace(m => m("MembershipProvider initalization started"));

            if (config == null)
                throw new ArgumentNullException("config");

            if (string.IsNullOrEmpty(name))
            {
                name = "BuildingBlocks.MembershipProvider";
            }

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Simple membership provider");
            }

            _minRequiredPasswordLength            = config.GetOf<int?>("minRequiredPasswordLength", validator: ShouldBePositive);
            _minRequiredNonAlphanumericCharacters = config.GetOf<int?>("minRequiredNonalphanumericCharacters", validator: ShouldBePositive);
            _maxInvalidPasswordAttempts           = config.GetOf<int?>("maxInvalidPasswordAttempts", validator: ShouldBePositive);
            _passwordAttemptWindow                = config.GetOf<int?>("passwordAttemptWindow", validator: ShouldBePositive);

            base.Initialize(name, config);

            ApplicationName = !string.IsNullOrEmpty(config["applicationName"])
                ? config["applicationName"]
                : ProviderHelpers.GetDefaultAppName();

            _log.Trace(m => m("MembershipProvider with name {0} sucessfully initalized", name));
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            _log.Trace(m => m("User creation started"));

            status = MembershipCreateStatus.Success;
            if (string.IsNullOrEmpty(username))
            {
                status = MembershipCreateStatus.InvalidUserName;
            }
            if (string.IsNullOrEmpty(password))
            {
                status = MembershipCreateStatus.InvalidPassword;
            }
            if (string.IsNullOrEmpty(email))
            {
                status = MembershipCreateStatus.InvalidEmail;
            }

            var hashedPassword = Crypto.HashPassword(password);
            if (hashedPassword.Length > 128)
            {
                status = MembershipCreateStatus.InvalidPassword;
            }

            var userRepository = RepositoryFactory.Current.CreateUserRepository();
            if (userRepository.HasUserWithName(ApplicationName, username))
            {
                status = MembershipCreateStatus.DuplicateUserName;
            }

            if (userRepository.HasUserWithEmail(ApplicationName, email))
            {
                status = MembershipCreateStatus.DuplicateEmail;
            }

            if (status != MembershipCreateStatus.Success)
            {
                _log.LogUserCreateStatus(username, status);
                return null;
            }

            var newUser = new User(Guid.NewGuid(), username, email, ApplicationName)
            {
                Password = hashedPassword,
                IsApproved = isApproved,
                CreateDate = DateTime.UtcNow,
                LastPasswordChangedDate = DateTime.UtcNow,
                PasswordFailuresSinceLastSuccess = 0,
                LastLoginDate = DateTime.UtcNow,
                LastActivityDate = DateTime.UtcNow,
                LastLockoutDate = DateTime.UtcNow,
                IsLockedOut = false,
                LastPasswordFailureDate = DateTime.UtcNow
            };

            userRepository.AddUser(newUser);

            _log.Trace(m => m("User successfully created"));
            return new MembershipUser(
                System.Web.Security.Membership.Provider.Name,
                newUser.Username,
                newUser.UserId,
                newUser.Email,
                null,
                newUser.Comment,
                newUser.IsApproved,
                newUser.IsLockedOut,
                newUser.CreateDate.Value,
                newUser.LastLoginDate.Value,
                newUser.LastActivityDate.Value,
                newUser.LastPasswordChangedDate.Value,
                newUser.LastLockoutDate.Value
            );
        }

        public override bool ValidateUser(string username, string password)
        {
            _log.Trace(m => m("User with name \"{0}\" validation started", username));
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                return false;

            var user = FindUserByName(username);
            _log.LogUserStateForValidationOperation(username, user);
            if (user == null || !user.IsApproved || user.IsLockedOut)
                return false;

            var hashedPassword = user.Password;
            var verificationSucceeded = hashedPassword != null && Crypto.VerifyHashedPassword(hashedPassword, password);
            if (verificationSucceeded)
            {
                _log.Debug(m => m("Password verification succeeded for user with name \"{0}\"", username));
                user.PasswordFailuresSinceLastSuccess = 0;
                user.LastLoginDate = DateTime.UtcNow;
                user.LastActivityDate = DateTime.UtcNow;
            }
            else
            {
                _log.Debug(m => m("Password verification FAILED! for user with name \"{0}\"", username));
                var failures = user.PasswordFailuresSinceLastSuccess;
                if (failures < MaxInvalidPasswordAttempts)
                {
                    user.PasswordFailuresSinceLastSuccess += 1;
                    user.LastPasswordFailureDate = DateTime.UtcNow;
                    _log.PasswordFailuresIncreased(user);
                }
                else if (failures >= MaxInvalidPasswordAttempts)
                {
                    user.LastPasswordFailureDate = DateTime.UtcNow;
                    user.LastLockoutDate = DateTime.UtcNow;
                    user.IsLockedOut = true;
                    _log.UserLockedBecousePasswordVerificationAttemptsIsOver(user);
                }
            }

            UserRepository.SaveUser(user);
            _log.Trace(m => m("User with name \"{0}\" validation successfully completed with result {1}", username, verificationSucceeded));
            return verificationSucceeded;
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            _log.Trace(m => m("Find user by name \"{0}\"", username));
            if (string.IsNullOrEmpty(username))
            {
                _log.Debug(m => m("Given username is empty", username));
                return null;
            }

            var user = FindUserByName(username);
            if (user == null)
            {
                _log.UserNotFoundByName(username);
                return null;
            }

            if (userIsOnline)
            {
                SaveLastUserActivity(user);
            }

            _log.Trace(m => m("User with name \"{0}\" successfully founded", username));
            return new MembershipUser(
                System.Web.Security.Membership.Provider.Name,
                user.Username,
                user.UserId,
                user.Email,
                null,
                user.Comment,
                user.IsApproved,
                user.IsLockedOut,
                user.CreateDate.Value,
                user.LastLoginDate.Value,
                user.LastActivityDate.Value,
                user.LastPasswordChangedDate.Value,
                user.LastLockoutDate.Value
            );
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            _log.Trace(m => m("Find user by provider key \"{0}\"", providerUserKey));
            if (!(providerUserKey is Guid))
            {
                _log.Debug(m => m("Given provider key \"{0}\" is not Guid", providerUserKey));
                return null;
            }

            var user = UserRepository.FindUserById((Guid) providerUserKey);
            if (user == null)
            {
                _log.UserNotFoundByKey(providerUserKey);
                return null;
            }
            _log.Debug(m => m("User by provider key \"{0}\" founded, username is \"{1}\"", providerUserKey, user.Username));

            if (userIsOnline)
            {
                SaveLastUserActivity(user);
            }

            _log.Trace(m => m("User with key \"{0}\" successfully founded", providerUserKey));
            return new MembershipUser(
                System.Web.Security.Membership.Provider.Name,
                user.Username,
                user.UserId,
                user.Email,
                null,
                user.Comment,
                user.IsApproved,
                user.IsLockedOut,
                user.CreateDate.Value,
                user.LastLoginDate.Value,
                user.LastActivityDate.Value,
                user.LastPasswordChangedDate.Value,
                user.LastLockoutDate.Value
            );
        }

        bool IForcedPasswordChangeProvider.ChangePassword(string username, string newPassword)
        {
            _log.Trace(m => m("Started password changing for user \"{0}\"", username));
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(newPassword))
            {
                _log.Debug(m => m("Invalid parameters"));
                return false;
            }
            var user = FindUserByName(username);
            if (user == null)
            {
                _log.Debug(m => m("User is not found"));
                return false;
            }

            var newHashedPassword = Crypto.HashPassword(newPassword);
            if (newHashedPassword.Length > 128)
            {
                _log.Debug(m => m("New password hash has invalid lenght"));
                return false;
            }

            user.Password = newHashedPassword;
            user.LastPasswordChangedDate = DateTime.UtcNow;
            UserRepository.SaveUser(user);

            _log.Trace(m => m("Password sucessfully changed for user \"{0}\"", username));
            return true;
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            _log.Trace(m => m("Started password changing for user \"{0}\"", username));
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(oldPassword) || string.IsNullOrEmpty(newPassword))
                return false;
            var user = FindUserByName(username);
            if (user == null)
                return false;

            var hashedPassword = user.Password;
            var verificationSucceeded = (hashedPassword != null &&
                                         Crypto.VerifyHashedPassword(hashedPassword, oldPassword));
            if (verificationSucceeded)
            {
                _log.Debug(m => m("Old password verification succeeded for user with name \"{0}\"", username));
                user.PasswordFailuresSinceLastSuccess = 0;
            }
            else
            {
                _log.Debug(m => m("Old verification FAILED! for user with name \"{0}\"", username));
                var failures = user.PasswordFailuresSinceLastSuccess;
                if (failures < MaxInvalidPasswordAttempts)
                {
                    user.PasswordFailuresSinceLastSuccess += 1;
                    user.LastPasswordFailureDate = DateTime.UtcNow;
                    _log.PasswordFailuresIncreased(user);
                }
                else if (failures >= MaxInvalidPasswordAttempts)
                {
                    user.LastPasswordFailureDate = DateTime.UtcNow;
                    user.LastLockoutDate = DateTime.UtcNow;
                    user.IsLockedOut = true;
                    _log.UserLockedBecousePasswordVerificationAttemptsIsOver(user);
                }
                UserRepository.SaveUser(user);
                return false;
            }

            var newHashedPassword = Crypto.HashPassword(newPassword);
            if (newHashedPassword.Length > 128)
            {
                _log.Debug(m => m("New password hash has invalid lenght"));
                return false;
            }

            user.Password = newHashedPassword;
            user.LastPasswordChangedDate = DateTime.UtcNow;
            UserRepository.SaveUser(user);

            _log.Trace(m => m("Password sucessfully changed for user \"{0}\"", username));
            return true;
        }

        public override bool UnlockUser(string userName)
        {
            _log.Trace(m => m("Start unlock user with name \"{0}\"", userName));
            var user = FindUserByName(userName);
            if (user == null)
            {
                _log.UserNotFoundByName(userName);
                return false;
            }

            user.IsLockedOut = false;
            user.PasswordFailuresSinceLastSuccess = 0;
            UserRepository.SaveUser(user);

            _log.Trace(m => m("Password sucessfully changed for user \"{0}\"", userName));
            return true;
        }

        public override int GetNumberOfUsersOnline()
        {
            _log.Trace(m => m("Start searching for online users"));

            try
            {
                var userIsOnlineTimeWindow = (double) System.Web.Security.Membership.UserIsOnlineTimeWindow;
                var dateActive = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(userIsOnlineTimeWindow));
                _log.Debug(m => m("All users with last activity more then\"{0}\" is online", dateActive));

                return UserRepository.GetUsersCountWithLastActivityDateGreaterThen(ApplicationName, dateActive);
            }
            finally
            {
                _log.Trace(m => m("Online users successfully founded!"));
            }
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            _log.Trace(m => m("Start deleting user with name \"{0}\"", username));
            if (string.IsNullOrEmpty(username))
            {
                _log.Debug(m => m("User name is empty"));
                return false;
            }

            var user = FindUserByName(username);
            if (user == null)
            {
                _log.UserNotFoundByName(username);
                return false;
            }

            UserRepository.DeleteUser(user);

            _log.Trace(m => m("User with name \"{0}\" successfully deleted", username));
            return true;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="user"></param>
        /// <exception cref="MembershipUpdateUserException">The user to update could not be found.</exception>
        public override void UpdateUser(MembershipUser user)
        {
            _log.Trace(m => m("Start updating user with name \"{0}\"", user.UserName));
            var existUser = UserRepository.FindUserById((Guid) user.ProviderUserKey);
            if (existUser == null)
            {
                _log.UserNotFoundByKey((Guid) user.ProviderUserKey);
                throw new MembershipUpdateUserException("The user to update could not be found.");
            }

            existUser.Username = user.UserName;
            existUser.Email = user.Email;
            existUser.Comment = user.Comment;
            existUser.CreateDate = user.CreationDate;
            existUser.IsApproved = user.IsApproved;
            existUser.IsLockedOut = user.IsLockedOut;
            existUser.LastActivityDate = user.LastActivityDate;
            existUser.LastLockoutDate = user.LastLockoutDate;
            existUser.LastLoginDate = user.LastLoginDate;
            existUser.LastPasswordChangedDate = user.LastPasswordChangedDate;
            UserRepository.SaveUser(existUser);

            _log.Trace(m => m("User with name \"{0}\" sucessfully updated", user.UserName));
        }

        public override string GetUserNameByEmail(string email)
        {
            _log.Trace(m => m("Start getting username by email \"{0}\"", email));

            var user = UserRepository.FindUserByEmail(ApplicationName, email);
            if (user == null)
            {
                _log.Debug(m => m("User not found by email \"{0}\"", email));
                return string.Empty;
            }

            _log.Trace(m => m("User with email \"{0}\" successfully found, username is \"{1}\"", email, user.Username));
            return user.Username;
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            _log.Trace(m => m("Finding users by email part \"{0}\"", emailToMatch));

            var page = UserRepository.GetUsersPageByEmail(emailToMatch, ApplicationName, pageIndex, pageSize);
            totalRecords = (int) page.TotalItemCount;

            var membershipUsers = new MembershipUserCollection();
            foreach (var user in page.Items)
            {
                var membershipUser = new MembershipUser(
                    System.Web.Security.Membership.Provider.Name,
                    user.Username,
                    user.UserId,
                    user.Email,
                    null,
                    user.Comment,
                    user.IsApproved,
                    user.IsLockedOut,
                    user.CreateDate.Value,
                    user.LastLoginDate.Value,
                    user.LastActivityDate.Value,
                    user.LastPasswordChangedDate.Value,
                    user.LastLockoutDate.Value
                );
                membershipUsers.Add(membershipUser);
            }

            _log.FoundedUsersCont(totalRecords);
            _log.Trace(m => m("Users with email part \"{0}\" successfully loaded", emailToMatch));
            return membershipUsers;
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            _log.Trace(m => m("Finding users by username part \"{0}\"", usernameToMatch));

            var page = UserRepository.GetUsersPageByUsername(usernameToMatch, ApplicationName, pageIndex, pageSize);
            totalRecords = (int) page.TotalItemCount;

            var membershipUsers = new MembershipUserCollection();
            foreach (var user in page.Items)
            {
                var membershipUser = new MembershipUser(
                    System.Web.Security.Membership.Provider.Name,
                    user.Username,
                    user.UserId,
                    user.Email,
                    null,
                    user.Comment,
                    user.IsApproved,
                    user.IsLockedOut,
                    user.CreateDate.Value,
                    user.LastLoginDate.Value,
                    user.LastActivityDate.Value,
                    user.LastPasswordChangedDate.Value,
                    user.LastLockoutDate.Value
                );
                membershipUsers.Add(membershipUser);
            }

            _log.FoundedUsersCont(totalRecords);
            _log.Trace(m => m("Users with username part \"{0}\" successfully loaded", usernameToMatch));
            return membershipUsers;
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            _log.Trace(m => m("Loading users"));

            var page = UserRepository.GetUsersPage(ApplicationName, pageIndex, pageSize);
            totalRecords = (int) page.TotalItemCount;

            var membershipUsers = new MembershipUserCollection();
            foreach (var user in page.Items)
            {
                var membershipUser = new MembershipUser(
                    System.Web.Security.Membership.Provider.Name,
                    user.Username,
                    user.UserId,
                    user.Email,
                    null,
                    user.Comment,
                    user.IsApproved,
                    user.IsLockedOut,
                    user.CreateDate.Value,
                    user.LastLoginDate.Value,
                    user.LastActivityDate.Value,
                    user.LastPasswordChangedDate.Value,
                    user.LastLockoutDate.Value
                );
                membershipUsers.Add(membershipUser);
            }

            _log.FoundedUsersCont(totalRecords);
            _log.Trace(m => m("Users successfully loaded"));
            return membershipUsers;
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotSupportedException("Can not retrieve password");
        }

        public override bool EnablePasswordReset
        {
            get { return false; }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotSupportedException("Can not reset password.");
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotSupportedException("Can not change password querstion and password.");
        }

        private User FindUserByName(string username)
        {
            var users = UserRepository.FindUsersByNames(ApplicationName, username);
            if (users == null)
                return null;
            try
            {
                return users.SingleOrDefault();
            }
            catch (InvalidOperationException ex)
            {
                throw new MembershipProviderException(string.Format("For username \"{0}\" founded more than one user", username), ex);
            }
        }

        private string ShouldBePositive(int? value)
        {
            if (value.HasValue && value.Value < 0)
            {
                return "value should be greater then -1";
            }
            return null;
        }

        private void SaveLastUserActivity(User user)
        {
            _log.Debug(m => m("Mark that user with name \"{0}\" is online", user.Username));
            user.LastActivityDate = DateTime.UtcNow;
            UserRepository.SaveUser(user);
        }

        private static string GenerateToken()
        {
            using (var cryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                return GenerateToken(cryptoServiceProvider);
            }
        }

        private static string GenerateToken(RandomNumberGenerator generator)
        {
            var tokenBytes = new byte[TokenSizeInBytes];
            generator.GetBytes(tokenBytes);
            return HttpServerUtility.UrlTokenEncode(tokenBytes);
        }
    }
}


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.google.gwt.samples.karaf</groupId>
		<artifactId>gwt-karaf-parent</artifactId>
		<version>1-SNAPSHOT</version>
		<relativePath>parent</relativePath>
	</parent>

	<version>1.0.0-SNAPSHOT</version>
	<artifactId>gwt-karaf-main</artifactId>
	<packaging>pom</packaging>
	<name>GWT Samples for Apache Karaf :: Main project</name>

	<modules>
		<module>starter</module>
		<module>validation</module>
		<module>dynatable</module>
		<module>dynatablerf</module>
		<module>mobilewebapp</module>
		<module>features</module>
	</modules>

</project>

redpajama_set_name: RedPajamaGithub


text:
<?php

class PDReferenceDocument {

         /*
         * Document data
         */
	public $data;
         /*
         * Document name that will show up in Project Director
         */
	public $name;

	public function getResourceInfo() {
		$resourceInfo = new ResourceInfo ();
		$resourceInfo->size = strlen ( $this->data );
		$resourceInfo->name = $this->name;
		return $resourceInfo;
	}
}

?>


text:
package main

import "fmt"

func main() {
	leagueTitles := make(map[string]int)

	leagueTitles["Sunderland"] = 6
	leagueTitles["Newcastle"] = 4

	recentHead2Head := map[string]int {
		"Sunderland": 5,
		"Newcastle": 4,
	}

	fmt.Printf("\nLeague titles: %v\nRecent head to heads: %v\n",
		leagueTitles, recentHead2Head)
}


text:
from rest_framework import serializers

from anaf.sales.models import SaleStatus, Product, SaleSource, Lead, Opportunity, SaleOrder, Subscription, \
    OrderedProduct
from anaf.serializers import common_exclude

class SaleStatusSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = SaleStatus
        exclude = common_exclude

class ProductSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Product
        exclude = common_exclude

class SaleSourceSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = SaleSource
        exclude = common_exclude

class LeadSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Lead
        exclude = common_exclude

class OpportunitySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Opportunity
        exclude = common_exclude

class SaleOrderSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = SaleOrder
        exclude = common_exclude

class SubscriptionSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Subscription
        exclude = common_exclude

class OrderedProductSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = OrderedProduct
        exclude = common_exclude


text:
"""Descriptor schema viewset."""
from rest_framework import mixins, viewsets

from resolwe.flow.filters import DescriptorSchemaFilter
from resolwe.flow.models import DescriptorSchema
from resolwe.flow.serializers import DescriptorSchemaSerializer
from resolwe.permissions.loader import get_permissions_class
from resolwe.permissions.mixins import ResolwePermissionsMixin
from resolwe.permissions.models import PermissionModel

class DescriptorSchemaViewSet(
    mixins.RetrieveModelMixin,
    mixins.ListModelMixin,
    ResolwePermissionsMixin,
    viewsets.GenericViewSet,
):
    """API view for :class:`DescriptorSchema` objects."""

    qs_permission_model = PermissionModel.objects.select_related("user", "group")
    queryset = DescriptorSchema.objects.all().select_related("contributor")
    serializer_class = DescriptorSchemaSerializer
    permission_classes = (get_permissions_class(),)
    filterset_class = DescriptorSchemaFilter
    ordering_fields = ("id", "created", "modified", "name", "version")
    ordering = ("id",)

    def get_queryset(self):
        """Prefetch permissions for current user."""
        return self.prefetch_current_user_permissions(self.queryset)


text:
This is the repository for code written for an interpreter for a Language Processors course offered at the University of the West Indies, Mona Campus. JLex is used for the Lexer and cup is used for the Parser. The description of both the Language and the problem are provided as pdf files in the repository.

# Instructions on how to run

To run just execute the following command from the command line in the src directory:
```
java -cp "java_cup.runtime.jar:." hpl/sys/HPLRepl
```

# Contributing
Unfortunately I haven't made a makefile as yet, but to run you can modify the runner.c file appropriately, then compile and run it.


text:
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonStreamParser;
import org.jboss.summit2015.beacon.Beacon;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import java.util.zip.GZIPInputStream;

/**
 * @author Scott Stark (sstark@redhat.com) (C) 2014 Red Hat Inc.
 */
public class EntryExitEvents {
   static DateFormat df = new SimpleDateFormat("H:m:s");
   static long DURATION = 15000;

   static class FileSupplier implements Supplier<Beacon> {
      long firstBucketStart;
      int bucketCount;
      private long bucketStart;
      private long bucketEnd;
      boolean bucketComplete = false;
      HashMap<String, AvgBeacon> eventByBeacon = new HashMap<>();
      Iterator<AvgBeacon> bucketIterator;
      JsonStreamParser jsp;
      Gson gson;

      FileSupplier() throws IOException {
         String dataSet = "FourScannersRun1-2015-03-10.json.gz";
         gson = new Gson();
         jsp = getDataSetParser(dataSet);
      }
      @Override
      public Beacon get() {
         if(jsp.hasNext() == false)
            return null;

         if(bucketComplete) {
            if(bucketIterator == null)
               bucketIterator = eventByBeacon.values().iterator();
            if(bucketIterator.hasNext()) {
               AvgBeacon avg = bucketIterator.next();
               Beacon event = avg.getAvgBeacon();
               return event;
            }
            bucketComplete = false;
            bucketIterator = null;
            eventByBeacon.clear();
            // Next bucket
            Date d0 = new Date(bucketStart);
            Date d1 = new Date(bucketEnd);
            System.out.printf("Processing(%d): %s-%s\n", bucketCount, df.format(d0), df.format(d1));
         }

         // Fill the next bucket
         do {
            if(jsp.hasNext() == false) {
               System.out.printf("How does this happen???\n");
               return null;
            }
            JsonElement jse = jsp.next();
            Beacon beacon = gson.fromJson(jse, Beacon.class);
            int tag = beacon.getMinor();
            String key = beacon.getScannerID() + ':' + tag;
            long time = beacon.getTime();
            if(beacon.getMessageType() != 0)
               continue;

            if (bucketStart == 0) {
               bucketStart = time;
               if(firstBucketStart == 0)
                  firstBucketStart = time;
               bucketEnd = bucketStart + DURATION;
               Date d0 = new Date(bucketStart);
               Date d1 = new Date(bucketEnd);
               System.out.printf("Processing(%d): %s-%s\n", bucketCount, df.format(d0), df.format(d1));
            }
            // Get accumluation beacon event
            AvgBeacon bucket = eventByBeacon.get(key);
            long elapsed = time - bucketStart;
            if (bucket == null) {
               bucket = new AvgBeacon(beacon);
               eventByBeacon.put(key, bucket);
            }
            else if (elapsed <= DURATION) {
               // Avg
               bucket.update(beacon);
            } else {
               bucketComplete = true;
               bucketStart = bucketEnd;
               bucketEnd += DURATION;
               bucketCount ++;
            }
         } while(bucketComplete == false);

         return get();
      }
   }

   static class TimeBucketCombiner implements BinaryOperator<Beacon> {
      private long bucketStart;
      private long bucketEnd;

      @Override
      public Beacon apply(Beacon beacon, Beacon beacon2) {
         long time1 = beacon.getTime();
         return beacon;
      }
   }

   static class TestSpliterator implements Spliterator<Beacon> {
      private ConcurrentLinkedDeque<JsonElement> beacons = new ConcurrentLinkedDeque<>();
      JsonStreamParser jsp;
      int[] ids;
      Gson gson;

      class BeaconSpliterator implements Spliterator<Beacon> {
         int id;
         int splitCount;
         JsonStreamParser jsp;

         BeaconSpliterator(int id, JsonStreamParser jsp) {
            this.id = id;
         }

         @Override
         public boolean tryAdvance(Consumer<? super Beacon> action) {
            JsonElement jse = beacons.peekFirst();
            Beacon beacon = gson.fromJson(jse, Beacon.class);
            action.accept(beacon);
            return true;
         }

         @Override
         public Spliterator<Beacon> trySplit() {
            if(splitCount < ids.length)
               return new BeaconSpliterator(ids[splitCount++], jsp);
            return null;
         }

         @Override
         public long estimateSize() {
            return 0;
         }

         @Override
         public int characteristics() {
            return 0;
         }
      }
      TestSpliterator(int[] ids) {
         this.ids = ids;
      }
      @Override
      public boolean tryAdvance(Consumer<? super Beacon> action) {

         JsonElement jse = null;
         synchronized (jsp) {
            if(jsp.hasNext() == false)
               return false;
            jse = jsp.next();
         }
         Beacon beacon = gson.fromJson(jse, Beacon.class);
         action.accept(beacon);
         return true;
      }

      @Override
      public Spliterator<Beacon> trySplit() {
         return null;
      }

      @Override
      public long estimateSize() {
         return 0;
      }

      @Override
      public int characteristics() {
         return 0;
      }

      TestSpliterator() throws IOException {
         String dataSet = "FourScannersRun1-2015-03-10.json.gz";
         // Get the dataSet input stream directly from git
         URL gitURL = new URL("file:/Users/starksm/Dev/IoT/BLE/RaspberryPiBeaconParser/data/" + dataSet);
         InputStream is = gitURL.openStream();
         GZIPInputStream gzip = new GZIPInputStream(is);
         InputStreamReader reader = new InputStreamReader(gzip);
         gson = new Gson();
         jsp = new JsonStreamParser(reader);
      }

   }

   static JsonStreamParser getDataSetParser(String dataSet) throws IOException {
      // Get the dataSet input stream directly from git
      URL gitURL = new URL("file:/Users/starksm/Dev/IoT/BLE/RaspberryPiBeaconParser/data/" + dataSet);
      InputStream is = gitURL.openStream();
      GZIPInputStream gzip = new GZIPInputStream(is);
      InputStreamReader reader = new InputStreamReader(gzip);
      JsonStreamParser jsp = new JsonStreamParser(reader);
      return jsp;
   }
   /**
    * Simple test of processing the json data using a serial spliterator
    * @throws IOException
    */
   static void basicStreamTest() throws IOException {
      Stream<Beacon> eventStream = StreamSupport.stream(new TestSpliterator(), false);
      //Supplier<Beacon> supplier = new TestSupplier();
      Comparator<Beacon> cmp = (o1, o2) -> {
         int compare = o1.getMinor() - o2.getMinor();
         if(compare == 0) {
            compare = (int) (o1.getTime() - o2.getTime());
         }
         return compare;
      };
      eventStream.filter(b -> b.getMinor() < 20).sorted(cmp).forEach(e -> System.out.printf("%s\n", e));
   }
   /**
    * Test of processing the json data using a serial spliterator with collection into an N second time window
    * @throws IOException
    */
   static void basicStreamCollectTest() throws IOException {
   }

   /**
    * Non stream version of N second window creation
    * @param jsp
    * @return
    */
   static List<Beacon> averageEvents(JsonStreamParser jsp) {
      Gson gson = new Gson();
      ArrayList<Beacon> windows = new ArrayList<>();
      HashMap<Integer, HashMap<String, AvgBeacon>> eventWindowByBeacon = new HashMap<>();
      long bucketStart = 0;
      long bucketEnd = 0;
      long firstTime = 0;
      int bucketCount = 0;

      while(jsp.hasNext()) {
         JsonElement jse = jsp.next();
         JsonPrimitive messageType = jse.getAsJsonObject().getAsJsonPrimitive("messageType");
         if(messageType.getAsInt() != 0)
            continue;

         //
         Beacon beacon = gson.fromJson(jse, Beacon.class);
         int tag = beacon.getMinor();
         // Key is the scannerID + beacon tag
         String key = beacon.getScannerID() + ':' + tag;
         long time = beacon.getTime();

         if(firstTime == 0) {
            firstTime = time;
            bucketStart = time;
            bucketEnd = bucketStart + DURATION;
            Date d0 = new Date(bucketStart);
            Date d1 = new Date(bucketEnd);
            System.out.printf("Processing(%d): %s-%s\n", bucketCount, df.format(d0), df.format(d1));
         }
         // Get accumulation events for the beacon
         HashMap<String, AvgBeacon> beaconRooms = eventWindowByBeacon.get(tag);
         long elapsed = time - bucketStart;
         if (beaconRooms == null) {
            beaconRooms = new HashMap<>();
            eventWindowByBeacon.put(tag, beaconRooms);
         }

         // Get the accumulation bucket for the beacon/room combination
         AvgBeacon bucket = beaconRooms.get(key);
         if(bucket == null) {
            bucket = new AvgBeacon(beacon);
            beaconRooms.put(key, bucket);
         } else if (elapsed <= DURATION) {
            // Average the scanner events into the time window
            bucket.update(beacon);
         } else {
            // Drop duplicate beacon/room events by selecting the room with the largest rssi signal
            for (HashMap<String, AvgBeacon> testRooms : eventWindowByBeacon.values()) {
               Beacon closest = null;
               // Iterate over the rooms that scanned the beacon to select the largest rssi
               for(AvgBeacon avg : testRooms.values()) {
                  Beacon test = avg.getAvgBeacon();
                  if(closest == null) {
                     closest = test;
                     continue;
                  }
                  if(closest.getRssi() < test.getRssi()) {
                     System.out.printf("Dropping %s/%d in favor of %s/%d for %d\n",
                        closest.getScannerID(), closest.getRssi(), test.getScannerID(), test.getRssi(), test.getMinor());
                     closest = test;
                  }
               }
               // Add the event closest to a scanner to the window events
               windows.add(closest);
            }
            eventWindowByBeacon.clear();
            bucketStart = bucketEnd;
            bucketEnd += DURATION;
            bucketCount ++;
            Date d0 = new Date(bucketStart);
            Date d1 = new Date(bucketEnd);
            System.out.printf("Processing(%d): %s-%s\n", bucketCount, df.format(d0), df.format(d1));
         }

      }

      return windows;
   }

   /**
    * Create the room entry/exit events given a list of time ordered events for a single beacon
    * TODO: when replaying events how to identify missing beacon events?
    * @param windowEvents
    */
   static void generateEntryExitEvents(List<Beacon> windowEvents) {
      String lastScanner = "Unknown";

      for(Beacon event : windowEvents) {
         if(!event.getScannerID().equalsIgnoreCase(lastScanner)) {
            System.out.printf("Beacon(%d) exited: %s\n", event.getMinor(), lastScanner);
            lastScanner = event.getScannerID();
            System.out.printf("Beacon(%d) entered: %s\n", event.getMinor(), lastScanner);
         }
      }
   }

   static void dumpToFile(List<Beacon> events, String name) throws IOException {
      FileWriter fw = new FileWriter("/tmp/"+name);
      for(Beacon event : events) {
         fw.write(event.toString());
         fw.write('\n');
      }
      fw.close();
   }
   public static void main(String[] args) throws Exception {
      String dataSet = "FourScannersRun1-2015-03-13.json.gz";
      //String dataSet = "FourScannersBeacon5Run2-2015-03-13.json.gz";
      JsonStreamParser jsp = getDataSetParser(dataSet);
      List<Beacon> windowEvents = averageEvents(jsp);
      Comparator<Beacon> cmp = (o1, o2) -> {
         int compare = o1.getMinor() - o2.getMinor();
         if(compare == 0) {
            compare = (int) (o1.getTime() - o2.getTime());
         }
         return compare;
      };
      Collections.sort(windowEvents, cmp);
      dumpToFile(windowEvents, "averageEvents.log");
      // Break the sequence of events into a map of events by the beacon tag
      HashMap<Integer, List<Beacon>> eventsByBeacon = new HashMap<>();
      windowEvents.forEach(b -> {
            int tag = b.getMinor();
            List<Beacon> events = eventsByBeacon.get(tag);
            if(events == null) {
               events = new ArrayList<Beacon>();
               eventsByBeacon.put(tag, events);
            }
            events.add(b);
         }
      );
      // Now generate exit/entry events for each beacon
      for(List<Beacon> beaconEvents : eventsByBeacon.values()) {
         generateEntryExitEvents(beaconEvents);
      }
   }
}


text:
using System;
using System.Linq;
using Bib3.Geometrik;
using BotEngine.Common;
using MemoryStruct = Sanderling.Interface.MemoryStruct;
using System.Collections.Generic;

namespace Sanderling.Parse
{
	public interface INeocom : MemoryStruct.INeocom
	{
		MemoryStruct.IUIElement PeopleAndPlacesButton { get; }

		MemoryStruct.IUIElement ChatButton { get; }

		MemoryStruct.IUIElement MailButton { get; }

		MemoryStruct.IUIElement FittingButton { get; }

		MemoryStruct.IUIElement InventoryButton { get; }

		MemoryStruct.IUIElement MarketButton { get; }

        MemoryStruct.IUIElement WalletButton { get; }

    }

	public class Neocom : INeocom
	{
		public MemoryStruct.INeocom Raw { private set; get; }

		public MemoryStruct.IUIElement PeopleAndPlacesButton { private set; get; }

		public MemoryStruct.IUIElement ChatButton { private set; get; }

		public MemoryStruct.IUIElement MailButton { private set; get; }

		public MemoryStruct.IUIElement FittingButton { private set; get; }

		public MemoryStruct.IUIElement InventoryButton { private set; get; }

		public MemoryStruct.IUIElement MarketButton { private set; get; }

        public MemoryStruct.IUIElement WalletButton { private set; get; }

        public MemoryStruct.IUIElement EveMenuButton => Raw?.EveMenuButton;

		public MemoryStruct.IUIElement CharButton => Raw?.CharButton;

		public MemoryStruct.ISprite[] Button => Raw?.Button;

		public MemoryStruct.IUIElementText Clock => Raw?.Clock;

		public IEnumerable<MemoryStruct.IUIElementText> ButtonText => Raw?.ButtonText;

		public IEnumerable<MemoryStruct.IUIElementInputText> InputText => Raw?.InputText;

		public IEnumerable<MemoryStruct.IUIElementText> LabelText => Raw?.LabelText;

		public IEnumerable<MemoryStruct.ISprite> Sprite => Raw?.Sprite;

		public RectInt Region => Raw?.Region ?? default(RectInt);

		public Int32? InTreeIndex => Raw?.InTreeIndex;

		public Int32? ChildLastInTreeIndex => Raw?.ChildLastInTreeIndex;

		public MemoryStruct.IUIElement RegionInteraction => Raw?.RegionInteraction;

		public Int64 Id => Raw?.Id ?? 0;

		Neocom()
		{ }

		public Neocom(MemoryStruct.INeocom raw)
		{
			this.Raw = raw;

			if (null == raw)
			{
				return;
			}

			var ButtonWithTexturePathMatch = new Func<string, MemoryStruct.IUIElement>(texturePathRegexPattern =>
				raw?.Button?.FirstOrDefault(candidate => candidate?.TexturePath?.RegexMatchSuccess(texturePathRegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase) ?? false));

			PeopleAndPlacesButton = ButtonWithTexturePathMatch("peopleandplaces");

			ChatButton = ButtonWithTexturePathMatch("chat");

			MailButton = ButtonWithTexturePathMatch("mail");

			FittingButton = ButtonWithTexturePathMatch("fitting");

			InventoryButton = ButtonWithTexturePathMatch("items");

			MarketButton = ButtonWithTexturePathMatch("market");

            		WalletButton = ButtonWithTexturePathMatch("wallet");
        }
	}
}


text:
set -e

source hack/common.sh
source hack/config.sh

bazel run \
    --config=${HOST_ARCHITECTURE} \
    //vendor/mvdan.cc/sh/v3/cmd/shfmt:shfmt -- -i 4 -w ${KUBEVIRT_DIR}/hack/ ${KUBEVIRT_DIR}/images/
bazel run \
    --config=${HOST_ARCHITECTURE} \
    //:gazelle -- pkg/ tools/ tests/ cmd/
bazel run \
    --config=${HOST_ARCHITECTURE} \
    //:goimports
# allign BAZEL files to a single format
bazel run \
    --config=${HOST_ARCHITECTURE} \
    //:buildifier


text:
     SproutStudy Cohorts

    <legend>Edit Cohort</legend>

    <form method="post" id="user" name="addCohort" novalidate autocomplete="false">

{{saveCohortMessage}}

            Description

                <textarea ng-model="cohort.description" id="description" required  autocomplete="false"
                       class="field-label message-text" style="width: 20em;" />

            <button class="btn btn-primary" ng-click="onSaveCohort()" ng-disabled="cohort == undefined || cohort.name == undefined || cohort.name == ''">Submit</button>
            Cancel

    </form>


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Graphics;
using osu.Framework.Screens;
using osu.Game.Graphics.Containers;
using osu.Game.Screens.Backgrounds;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestCaseParallaxContainer : OsuTestCase
    {
        public TestCaseParallaxContainer()
        {
            ParallaxContainer parallax;

            Add(parallax = new ParallaxContainer
            {
                Child = new ScreenStack(new BackgroundScreenDefault { Alpha = 0.8f })
                {
                    RelativeSizeAxes = Axes.Both,
                }
            });

            AddStep("default parallax", () => parallax.ParallaxAmount = ParallaxContainer.DEFAULT_PARALLAX_AMOUNT);
            AddStep("high parallax", () => parallax.ParallaxAmount = ParallaxContainer.DEFAULT_PARALLAX_AMOUNT * 10);
            AddStep("no parallax", () => parallax.ParallaxAmount = 0);
            AddStep("negative parallax", () => parallax.ParallaxAmount = -ParallaxContainer.DEFAULT_PARALLAX_AMOUNT);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<project>

	<meta title="BunnyMark" package="org.openfl.samples.bunnymark" version="1.0.0" company="OpenFL" />
	<app main="Main" path="Export" file="BunnyMark" />

	<window width="800" height="600" fps="1000" />

	<source path="Source" />

	<haxelib name="openfl" />

	<assets path="Assets" rename="assets" />

</project>


text:
using System.Data.Entity;
using Finance.Server.Models;

namespace Finance.Server.Database
{
    public class FinanceContext : DbContext
    {
        public FinanceContext()
            : base("name=Finance")
        {
        }

        public IDbSet<Account> Accounts { get; set; }

        public IDbSet<Stock> Stocks { get; set; }

        public IDbSet<Order> Orders { get; set; }
    }
}


text:
import urllib
import os

TARGET_URL = 'http://python.org/ftp/python/2.7.4/'
TARGET_FILE = 'Python-2.7.4.tgz'

class CustomURLOpener(urllib.FancyURLopener):
    """Override FancyURLopener to skip error 206 (when a
       partial file is being sent)
    """
    def http_error_206(self, url, fp, errcode, errmsg, headers, data=None):
		pass

def resume_download():
	file_exists = False
	CustomURLClass = CustomURLOpener()
	if os.path.exists(TARGET_FILE):
		out_file = open(TARGET_FILE,"ab")
		file_exists = os.path.getsize(TARGET_FILE)
		#If the file exists, then only download the unfinished part
		CustomURLClass.addheader("range","bytes=%s-" % (file_exists))
	else:
		out_file = open(TARGET_FILE,"wb")

	web_page = CustomURLClass.open(TARGET_URL + TARGET_FILE)

	#Check if last download was OK
	if int(web_page.headers['Content-Length']) == file_exists:
		loop = 0
		print "File already downloaded!"

	byte_count = 0
	while True:
		data = web_page.read(8192)
		if not data:
			break
		out_file.write(data)
		byte_count = byte_count + len(data)

	web_page.close()
	out_file.close()

	for k,v in web_page.headers.items():
		print k, "=",v
	print "File copied", byte_count, "bytes from", web_page.url

if __name__ == '__main__':
	resume_download()


text:
<?php
namespace App\Model;

class Fight extends \SlaxWeb\Database\BaseModel
{
}


text:
use std::collections::VecDeque;

use {JmespathError, ErrorReason};
use ast::{Ast, KeyValuePair, Comparator};
use lexer::{tokenize, Token, TokenTuple};

/// Result of parsing an expression.
pub type ParseResult = Result<Ast, JmespathError>;

/// Parses a JMESPath expression into an AST.
pub fn parse(expr: &str) -> ParseResult {
    let tokens = try!(tokenize(expr));
    Parser::new(tokens, expr).parse()
}

/// The maximum binding power for a token that can stop a projection.
const PROJECTION_STOP: usize = 10;

struct Parser<'a> {
    /// Parsed tokens
    token_queue: VecDeque<TokenTuple>,
    /// Shared EOF token
    eof_token: Token,
    /// Expression being parsed
    expr: &'a str,
    /// The current character offset in the expression
    offset: usize,
}

impl<'a> Parser<'a> {
    fn new(tokens: VecDeque<TokenTuple>, expr: &'a str) -> Parser<'a> {
        Parser {
            token_queue: tokens,
            eof_token: Token::Eof,
            offset: 0,
            expr: expr,
        }
    }

    #[inline]
    fn parse(&mut self) -> ParseResult {
        self.expr(0)
            .and_then(|result| {
                // After parsing the expr, we should reach the end of the stream.
                match self.peek(0) {
                    &Token::Eof => Ok(result),
                    t @ _ => Err(self.err(t, "Did not parse the complete expression", true)),
                }
            })
    }

    #[inline]
    fn advance(&mut self) -> Token {
        self.advance_with_pos().1
    }

    #[inline]
    fn advance_with_pos(&mut self) -> (usize, Token) {
        match self.token_queue.pop_front() {
            Some((pos, tok)) => {
                self.offset = pos;
                (pos, tok)
            }
            None => (self.offset, Token::Eof),
        }
    }

    #[inline]
    fn peek(&self, lookahead: usize) -> &Token {
        match self.token_queue.get(lookahead) {
            Some(&(_, ref t)) => t,
            None => &self.eof_token,
        }
    }

    /// Returns a formatted error with the given message.
    fn err(&self, current_token: &Token, error_msg: &str, is_peek: bool) -> JmespathError {
        let mut actual_pos = self.offset;
        let mut buff = error_msg.to_string();
        buff.push_str(&format!(" -- found {:?}", current_token));
        if is_peek {
            if let Some(&(p, _)) = self.token_queue.get(0) {
                actual_pos = p;
            }
        }
        JmespathError::new(&self.expr, actual_pos, ErrorReason::Parse(buff))
    }

    /// Main parse function of the Pratt parser that parses while RBP < LBP
    fn expr(&mut self, rbp: usize) -> ParseResult {
        let mut left = self.nud();
        while rbp < self.peek(0).lbp() {
            left = self.led(Box::new(try!(left)));
        }
        left
    }

    fn nud(&mut self) -> ParseResult {
        let (offset, token) = self.advance_with_pos();
        match token {
            Token::At => Ok(Ast::Identity { offset: offset }),
            Token::Identifier(value) => {
                Ok(Ast::Field {
                    name: value,
                    offset: offset,
                })
            }
            Token::QuotedIdentifier(value) => {
                match self.peek(0) {
                    &Token::Lparen => {
                        let message = "Quoted strings can't be a function name";
                        Err(self.err(&Token::Lparen, message, true))
                    }
                    _ => {
                        Ok(Ast::Field {
                            name: value,
                            offset: offset,
                        })
                    }
                }
            }
            Token::Star => self.parse_wildcard_values(Box::new(Ast::Identity { offset: offset })),
            Token::Literal(value) => {
                Ok(Ast::Literal {
                    value: value,
                    offset: offset,
                })
            }
            Token::Lbracket => {
                match self.peek(0) {
                    &Token::Number(_) |
                    &Token::Colon => self.parse_index(),
                    &Token::Star if self.peek(1) == &Token::Rbracket => {
                        self.advance();
                        self.parse_wildcard_index(Box::new(Ast::Identity { offset: offset }))
                    }
                    _ => self.parse_multi_list(),
                }
            }
            Token::Flatten => self.parse_flatten(Box::new(Ast::Identity { offset: offset })),
            Token::Lbrace => {
                let mut pairs = vec![];
                loop {
                    // Requires at least on key value pair.
                    pairs.push(try!(self.parse_kvp()));
                    match self.advance() {
                        // Terminal condition is the Rbrace token
                        Token::Rbrace => break,
                        // Skip commas as they are used to delineate kvps
                        Token::Comma => continue,
                        ref t @ _ => return Err(self.err(t, "Expected '}' or ','", false)),
                    }
                }
                Ok(Ast::MultiHash {
                    elements: pairs,
                    offset: offset,
                })
            }
            t @ Token::Ampersand => {
                let rhs = try!(self.expr(t.lbp()));
                Ok(Ast::Expref {
                    ast: Box::new(rhs),
                    offset: offset,
                })
            }
            t @ Token::Not => {
                Ok(Ast::Not {
                    node: Box::new(try!(self.expr(t.lbp()))),
                    offset: offset,
                })
            }
            Token::Filter => self.parse_filter(Box::new(Ast::Identity { offset: offset })),
            Token::Lparen => {
                let result = try!(self.expr(0));
                match self.advance() {
                    Token::Rparen => Ok(result),
                    ref t @ _ => Err(self.err(t, "Expected ')' to close '('", false)),
                }
            }
            ref t @ _ => Err(self.err(t, "Unexpected nud token", false)),
        }
    }

    fn led(&mut self, left: Box<Ast>) -> ParseResult {
        let (offset, token) = self.advance_with_pos();
        match token {
            t @ Token::Dot => {
                if self.peek(0) == &Token::Star {
                    // Skip the star and parse the rhs
                    self.advance();
                    self.parse_wildcard_values(left)
                } else {
                    let offset = offset;
                    let rhs = try!(self.parse_dot(t.lbp()));
                    Ok(Ast::Subexpr {
                        offset: offset,
                        lhs: left,
                        rhs: Box::new(rhs),
                    })
                }
            }
            Token::Lbracket => {
                match match self.peek(0) {
                    &Token::Number(_) |
                    &Token::Colon => true,
                    &Token::Star => false,
                    t @ _ => return Err(self.err(t, "Expected number, ':', or '*'", true)),
                } {
                    true => {
                        Ok(Ast::Subexpr {
                            offset: offset,
                            lhs: left,
                            rhs: Box::new(try!(self.parse_index())),
                        })
                    }
                    false => {
                        self.advance();
                        self.parse_wildcard_index(left)
                    }
                }
            }
            t @ Token::Or => {
                let offset = offset;
                let rhs = try!(self.expr(t.lbp()));
                Ok(Ast::Or {
                    offset: offset,
                    lhs: left,
                    rhs: Box::new(rhs),
                })
            }
            t @ Token::And => {
                let offset = offset;
                let rhs = try!(self.expr(t.lbp()));
                Ok(Ast::And {
                    offset: offset,
                    lhs: left,
                    rhs: Box::new(rhs),
                })
            }
            t @ Token::Pipe => {
                let offset = offset;
                let rhs = try!(self.expr(t.lbp()));
                Ok(Ast::Subexpr {
                    offset: offset,
                    lhs: left,
                    rhs: Box::new(rhs),
                })
            }
            Token::Lparen => {
                match *left {
                    Ast::Field { name: v, .. } => {
                        Ok(Ast::Function {
                            offset: offset,
                            name: v,
                            args: try!(self.parse_list(Token::Rparen)),
                        })
                    }
                    _ => Err(self.err(self.peek(0), "Invalid function name", true)),
                }
            }
            Token::Flatten => self.parse_flatten(left),
            Token::Filter => self.parse_filter(left),
            Token::Eq => self.parse_comparator(Comparator::Equal, left),
            Token::Ne => self.parse_comparator(Comparator::NotEqual, left),
            Token::Gt => self.parse_comparator(Comparator::GreaterThan, left),
            Token::Gte => self.parse_comparator(Comparator::GreaterThanEqual, left),
            Token::Lt => self.parse_comparator(Comparator::LessThan, left),
            Token::Lte => self.parse_comparator(Comparator::LessThanEqual, left),
            ref t @ _ => Err(self.err(t, "Unexpected led token", false)),
        }
    }

    fn parse_kvp(&mut self) -> Result<KeyValuePair, JmespathError> {
        match self.advance() {
            Token::Identifier(value) |
            Token::QuotedIdentifier(value) => {
                if self.peek(0) == &Token::Colon {
                    self.advance();
                    Ok(KeyValuePair {
                        key: value,
                        value: try!(self.expr(0)),
                    })
                } else {
                    Err(self.err(self.peek(0), "Expected ':' to follow key", true))
                }
            }
            ref t @ _ => Err(self.err(t, "Expected Field to start key value pair", false)),
        }
    }

    /// Parses a filter token into a Projection that filters the right
    /// side of the projection using a Condition node. If the Condition node
    /// returns a truthy value, then the value is yielded by the projection.
    fn parse_filter(&mut self, lhs: Box<Ast>) -> ParseResult {
        // Parse the LHS of the condition node.
        let condition_lhs = Box::new(try!(self.expr(0)));
        // Eat the closing bracket.
        match self.advance() {
            Token::Rbracket => {
                let condition_rhs = Box::new(try!(self.projection_rhs(Token::Filter.lbp())));
                Ok(Ast::Projection {
                    offset: self.offset,
                    lhs: lhs,
                    rhs: Box::new(Ast::Condition {
                        offset: self.offset,
                        predicate: condition_lhs,
                        then: condition_rhs,
                    }),
                })
            }
            ref t @ _ => Err(self.err(t, "Expected ']'", false)),
        }
    }

    fn parse_flatten(&mut self, lhs: Box<Ast>) -> ParseResult {
        let rhs = Box::new(try!(self.projection_rhs(Token::Flatten.lbp())));
        Ok(Ast::Projection {
            offset: self.offset,
            lhs: Box::new(Ast::Flatten {
                offset: self.offset,
                node: lhs,
            }),
            rhs: rhs,
        })
    }

    /// Parses a comparator token into a Comparison (e.g., foo == bar)
    fn parse_comparator(&mut self, cmp: Comparator, lhs: Box<Ast>) -> ParseResult {
        let rhs = Box::new(try!(self.expr(Token::Eq.lbp())));
        Ok(Ast::Comparison {
            offset: self.offset,
            comparator: cmp,
            lhs: lhs,
            rhs: rhs,
        })
    }

    /// Parses the right hand side of a dot expression.
    fn parse_dot(&mut self, lbp: usize) -> ParseResult {
        match match self.peek(0) {
            &Token::Lbracket => true,
            &Token::Identifier(_) |
            &Token::QuotedIdentifier(_) |
            &Token::Star |
            &Token::Lbrace |
            &Token::Ampersand => false,
            t @ _ => {
                return Err(self.err(t, "Expected identifier, '*', '{', '[', '&', or '[?'", true))
            }
        } {
            true => {
                self.advance();
                self.parse_multi_list()
            }
            false => self.expr(lbp),
        }
    }

    /// Parses the right hand side of a projection, using the given LBP to
    /// determine when to stop consuming tokens.
    fn projection_rhs(&mut self, lbp: usize) -> ParseResult {
        match match self.peek(0) {
            &Token::Dot => true,
            &Token::Lbracket | &Token::Filter => false,
            ref t @ _ if t.lbp() < PROJECTION_STOP => {
                return Ok(Ast::Identity { offset: self.offset });
            },
            ref t @ _ => {
                return Err(self.err(t, "Expected '.', '[', or '[?'", true));
            },
        } {
            true => {
                self.advance();
                self.parse_dot(lbp)
            }
            false => self.expr(lbp),
        }
    }

    /// Creates a projection for "[*]"
    fn parse_wildcard_index(&mut self, lhs: Box<Ast>) -> ParseResult {
        match self.advance() {
            Token::Rbracket => {
                let rhs = Box::new(try!(self.projection_rhs(Token::Star.lbp())));
                Ok(Ast::Projection {
                    offset: self.offset,
                    lhs: lhs,
                    rhs: rhs,
                })
            }
            ref t @ _ => Err(self.err(t, "Expected ']' for wildcard index", false)),
        }
    }

    /// Creates a projection for "*"
    fn parse_wildcard_values(&mut self, lhs: Box<Ast>) -> ParseResult {
        let rhs = Box::new(try!(self.projection_rhs(Token::Star.lbp())));
        Ok(Ast::Projection {
            offset: self.offset,
            lhs: Box::new(Ast::ObjectValues {
                offset: self.offset,
                node: lhs,
            }),
            rhs: rhs,
        })
    }

    /// Parses [0], [::-1], [0:-1], [0:1], etc...
    fn parse_index(&mut self) -> ParseResult {
        let mut parts = [None, None, None];
        let mut pos = 0;
        loop {
            match self.advance() {
                Token::Number(value) => {
                    parts[pos] = Some(value);
                    match self.peek(0) {
                        &Token::Colon | &Token::Rbracket => (),
                        t @ _ => return Err(self.err(t, "Expected ':', or ']'", true)),
                    };
                }
                Token::Rbracket => break,
                Token::Colon if pos >= 2 => {
                    return Err(self.err(&Token::Colon, "Too many colons in slice expr", false));
                }
                Token::Colon => {
                    pos += 1;
                    match self.peek(0) {
                        &Token::Number(_) |
                        &Token::Colon |
                        &Token::Rbracket => continue,
                        ref t @ _ => return Err(self.err(t, "Expected number, ':', or ']'", true)),
                    };
                }
                ref t @ _ => return Err(self.err(t, "Expected number, ':', or ']'", false)),
            }
        }

        if pos == 0 {
            // No colons were found, so this is a simple index extraction.
            Ok(Ast::Index {
                offset: self.offset,
                idx: parts[0].unwrap(),
            })
        } else {
            // Sliced array from start (e.g., [2:])
            Ok(Ast::Projection {
                offset: self.offset,
                lhs: Box::new(Ast::Slice {
                    offset: self.offset,
                    start: parts[0],
                    stop: parts[1],
                    step: parts[2].unwrap_or(1),
                }),
                rhs: Box::new(try!(self.projection_rhs(Token::Star.lbp()))),
            })
        }
    }

    /// Parses multi-select lists (e.g., "[foo, bar, baz]")
    fn parse_multi_list(&mut self) -> ParseResult {
        Ok(Ast::MultiList {
            offset: self.offset,
            elements: try!(self.parse_list(Token::Rbracket)),
        })
    }

    /// Parse a comma separated list of expressions until a closing token.
    ///
    /// This function is used for functions and multi-list parsing. Note
    /// that this function allows empty lists. This is fine when parsing
    /// multi-list expressions because "[]" is tokenized as Token::Flatten.
    ///
    /// Examples: [foo, bar], foo(bar), foo(), foo(baz, bar)
    fn parse_list(&mut self, closing: Token) -> Result<Vec<Ast>, JmespathError> {
        let mut nodes = vec![];
        while self.peek(0) != &closing {
            nodes.push(try!(self.expr(0)));
            // Skip commas
            if self.peek(0) == &Token::Comma {
                self.advance();
                if self.peek(0) == &closing {
                    return Err(self.err(self.peek(0), "invalid token after ','", true));
                }
            }
        }
        self.advance();
        Ok(nodes)
    }
}


text:
import { exec as _exec } from 'child_process';
import { envMock, mockExecAll } from '../../../../test/exec-util';
import { getName, mocked } from '../../../../test/util';
import { setAdminConfig } from '../../../config/admin';
import * as _env from '../../../util/exec/env';
import * as _lernaHelper from './lerna';

jest.mock('child_process');
jest.mock('../../../util/exec/env');
jest.mock('../../../manager/npm/post-update/node-version');

const exec: jest.Mock<typeof _exec> = _exec as any;
const env = mocked(_env);
const lernaHelper = mocked(_lernaHelper);

function lernaPkgFile(lernaClient: string) {
  return {
    lernaClient,
    deps: [{ depName: 'lerna', currentValue: '2.0.0' }],
  };
}

function lernaPkgFileWithoutLernaDep(lernaClient: string) {
  return {
    lernaClient,
  };
}
describe(getName(), () => {
  describe('generateLockFiles()', () => {
    beforeEach(() => {
      jest.resetAllMocks();
      jest.resetModules();
      env.getChildProcessEnv.mockReturnValue(envMock.basic);
    });
    it('returns if no lernaClient', async () => {
      const res = await lernaHelper.generateLockFiles({}, 'some-dir', {}, {});
      expect(res.error).toBe(false);
    });
    it('returns if invalid lernaClient', async () => {
      const res = await lernaHelper.generateLockFiles(
        lernaPkgFile('foo'),
        'some-dir',
        {},
        {}
      );
      expect(res.error).toBe(false);
    });
    it('generates package-lock.json files', async () => {
      const execSnapshots = mockExecAll(exec);
      const skipInstalls = true;
      const res = await lernaHelper.generateLockFiles(
        lernaPkgFile('npm'),
        'some-dir',
        {},
        {},
        skipInstalls
      );
      expect(res.error).toBe(false);
      expect(execSnapshots).toMatchSnapshot();
    });
    it('performs full npm install', async () => {
      const execSnapshots = mockExecAll(exec);
      const skipInstalls = false;
      const res = await lernaHelper.generateLockFiles(
        lernaPkgFile('npm'),
        'some-dir',
        {},
        {},
        skipInstalls
      );
      expect(res.error).toBe(false);
      expect(execSnapshots).toMatchSnapshot();
    });
    it('generates yarn.lock files', async () => {
      const execSnapshots = mockExecAll(exec);
      const res = await lernaHelper.generateLockFiles(
        lernaPkgFile('yarn'),
        'some-dir',
        { constraints: { yarn: '^1.10.0' } },
        {}
      );
      expect(execSnapshots).toMatchSnapshot();
      expect(res.error).toBe(false);
    });
    it('defaults to latest if lerna version unspecified', async () => {
      const execSnapshots = mockExecAll(exec);
      const res = await lernaHelper.generateLockFiles(
        lernaPkgFileWithoutLernaDep('npm'),
        'some-dir',
        {},
        {}
      );
      expect(res.error).toBe(false);
      expect(execSnapshots).toMatchSnapshot();
    });
    it('allows scripts for trust level high', async () => {
      const execSnapshots = mockExecAll(exec);
      setAdminConfig({ allowScripts: true });
      const res = await lernaHelper.generateLockFiles(
        lernaPkgFile('npm'),
        'some-dir',
        { constraints: { npm: '^6.0.0' } },
        {}
      );
      expect(res.error).toBe(false);
      expect(execSnapshots).toMatchSnapshot();
    });
  });

  describe('getLernaVersion()', () => {
    it('returns specified version', () => {
      const pkg = {
        deps: [{ depName: 'lerna', currentValue: '2.0.0' }],
      };
      expect(lernaHelper.getLernaVersion(pkg)).toBe('2.0.0');
    });
    it('returns specified range', () => {
      const pkg = {
        deps: [
          { depName: 'lerna', currentValue: '1.x || >=2.5.0 || 5.0.0 - 7.2.3' },
        ],
      };
      expect(lernaHelper.getLernaVersion(pkg)).toBe(
        '1.x || >=2.5.0 || 5.0.0 - 7.2.3'
      );
    });
    it('returns latest if no lerna dep is specified', () => {
      const pkg = {
        deps: [{ depName: 'something-else', currentValue: '1.2.3' }],
      };
      expect(lernaHelper.getLernaVersion(pkg)).toBe('latest');
    });
    it('returns latest if pkg has no deps at all', () => {
      const pkg = {};
      expect(lernaHelper.getLernaVersion(pkg)).toBe('latest');
    });
    it('returns latest if specified lerna version is not a valid semVer range', () => {
      const pkg = {
        deps: [{ depName: 'lerna', currentValue: '[a.b.c;' }],
      };
      expect(lernaHelper.getLernaVersion(pkg)).toBe('latest');
    });
  });
});


text:
#!/usr/bin/env php
<?php

require __DIR__.'/vendor/autoload.php';

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\VarExporter\VarExporter;

Builder::cleanTarget();
$emojisCodePoints = Builder::getEmojisCodePoints();
Builder::saveRules(Builder::buildRules($emojisCodePoints));
Builder::saveRules(Builder::buildGitHubRules($emojisCodePoints));
Builder::saveRules(Builder::buildSlackRules($emojisCodePoints));

final class Builder
{
    private const TARGET_DIR = __DIR__.'/../data/transliterator/emoji/';

    public static function getEmojisCodePoints(): array
    {
        $lines = file(__DIR__.'/vendor/unicode-org/cldr/tools/cldr-code/src/main/resources/org/unicode/cldr/util/data/emoji/emoji-test.txt');

        $emojisCodePoints = [];
        foreach ($lines as $line) {
            $line = trim($line);
            if (!$line || str_starts_with($line, '#')) {
                continue;
            }

            // 263A FE0F    ; fully-qualified     # ☺ E0.6 smiling face
            preg_match('{^(?<codePoints>[\w ]+) +; [\w-]+ +# (?<emoji>.+) E\d+\.\d+ ?(?<name>.+)$}Uu', $line, $matches);
            if (!$matches) {
                throw new \DomainException("Could not parse line: \"$line\".");
            }

            $codePoints = strtolower(trim($matches['codePoints']));
            $emojisCodePoints[$codePoints] = $matches['emoji'];
            // We also add a version without the "Zero Width Joiner"
            $codePoints = str_replace('200d ', '', $codePoints);
            $emojisCodePoints[$codePoints] = $matches['emoji'];
        }

        return $emojisCodePoints;
    }

    public static function buildRules(array $emojisCodePoints): Generator
    {
        $files = (new Finder())
            ->files()
            ->in([
                __DIR__.'/vendor/unicode-org/cldr/common/annotationsDerived',
                __DIR__.'/vendor/unicode-org/cldr/common/annotations',
            ])
            ->name('*.xml')
        ;

        $ignored = [];
        $mapsByLocale = [];

        foreach ($files as $file) {
            $locale = $file->getBasename('.xml');

            $document = new DOMDocument();
            $document->loadXML(file_get_contents($file));
            $xpath = new DOMXPath($document);
            $results = $xpath->query('.//annotation[@type="tts"]');

            foreach ($results as $result) {
                $emoji = $result->getAttribute('cp');
                $name = $result->textContent;
                $parts = preg_split('//u', $emoji, -1, \PREG_SPLIT_NO_EMPTY);
                $emojiCodePoints = implode(' ', array_map('dechex', array_map('mb_ord', $parts)));
                if (!array_key_exists($emojiCodePoints, $emojisCodePoints)) {
                    $ignored[] = [
                        'locale' => $locale,
                        'emoji' => $emoji,
                        'name' => $name,
                    ];
                    continue;
                }
                self::testEmoji($emoji, $locale);
                $codePointsCount = mb_strlen($emoji);
                $mapsByLocale[$locale][$codePointsCount][$emoji] = $name;
            }
        }

        ksort($mapsByLocale);

        foreach ($mapsByLocale as $locale => $maps) {
            $parentLocale = $locale;

            while (false !== $i = strrpos($parentLocale, '_')) {
                $parentLocale = substr($parentLocale, 0, $i);
                $maps += $mapsByLocale[$parentLocale] ?? [];
            }

            yield strtolower($locale) => self::createRules($maps);
        }
    }

    public static function buildGitHubRules(array $emojisCodePoints): iterable
    {
        $emojis = json_decode(file_get_contents(__DIR__.'/vendor/github-emojis.json'), true);

        $ignored = [];
        $maps = [];

        foreach ($emojis as $shortCode => $url) {
            $emojiCodePoints = str_replace('-', ' ', strtolower(basename(parse_url($url, \PHP_URL_PATH), '.png')));
            if (!array_key_exists($emojiCodePoints, $emojisCodePoints)) {
                $ignored[] = [
                    'emojiCodePoints' => $emojiCodePoints,
                    'shortCode' => $shortCode,
                ];
                continue;
            }
            $emoji = $emojisCodePoints[$emojiCodePoints];
            self::testEmoji($emoji, 'github');
            $codePointsCount = mb_strlen($emoji);
            $maps[$codePointsCount][$emoji] = ":$shortCode:";
        }

        return ['github' => self::createRules($maps)];
    }

    public static function buildSlackRules(array $emojisCodePoints): iterable
    {
        $emojis = json_decode(file_get_contents(__DIR__.'/vendor/slack-emojis.json'), true);

        $ignored = [];
        $maps = [];

        foreach ($emojis as $data) {
            $emojiCodePoints = str_replace('-', ' ', strtolower($data['unified']));
            $shortCode = $data['short_name'];
            if (!array_key_exists($emojiCodePoints, $emojisCodePoints)) {
                $ignored[] = [
                    'emojiCodePoints' => $emojiCodePoints,
                    'shortCode' => $shortCode,
                ];
                continue;
            }
            $emoji = $emojisCodePoints[$emojiCodePoints];
            self::testEmoji($emoji, 'slack');
            $codePointsCount = mb_strlen($emoji);
            $maps[$codePointsCount][$emoji] = ":$shortCode:";
        }

        return ['slack' => self::createRules($maps)];
    }

    public static function cleanTarget(): void
    {
        $fs = new Filesystem();
        $fs->remove(self::TARGET_DIR);
        $fs->mkdir(self::TARGET_DIR);
    }

    public static function saveRules(iterable $rulesByLocale): void
    {
        $firstChars = [];
        foreach ($rulesByLocale as $locale => $rules) {
            file_put_contents(self::TARGET_DIR."/emoji-$locale.php", "<?php\n\nreturn ".VarExporter::export($rules).";\n");

            foreach ($rules as $k => $v) {
                for ($i = 0; ord($k[$i]) < 128 || "\xC2" === $k[$i]; ++$i) {
                }
                for ($j = $i; isset($k[$j]) && !isset($firstChars[$k[$j]]); ++$j) {
                }
                $c = $k[$j] ?? $k[$i];
                $firstChars[$c] = $c;
            }

            if (':' === $v[0]) {
                file_put_contents(self::TARGET_DIR."/$locale-emoji.php", "<?php\n\nreturn ".VarExporter::export(array_flip($rules)).";\n");
            }
        }
        sort($firstChars);

        $quickCheck = '"'.str_replace('%', '\\x', rawurlencode(implode('', $firstChars))).'"';

        $file = dirname(__DIR__, 2).'/Transliterator/EmojiTransliterator.php';
        file_put_contents($file, preg_replace('/QUICK_CHECK = .*;/m', "QUICK_CHECK = {$quickCheck};", file_get_contents($file)));
    }

    private static function testEmoji(string $emoji, string $locale): void
    {
        if (!Transliterator::createFromRules("\\$emoji > test ;")) {
            throw new \RuntimeException(sprintf('Could not create transliterator for "%s" in "%s" locale. Error: "%s".', $emoji, $locale, intl_get_error_message()));
        }
    }

    private static function createRules(array $maps): array
    {
        // We must sort the maps by the number of code points, because the order really matters:
        // 🫶🏼 must be before 🫶
        krsort($maps);
        $maps = array_merge(...$maps);

        return $maps;
    }
}


text:
require File.dirname(__FILE__) + '/phone_number'

class Person < Valuable
  has_value :name
  has_value :age, :klass => :integer
  has_value :phone_number, :klass => PhoneNumber
end


text:
@interface SOTutorialViewController : UIViewController

@end


text:
'use strict';

import React from 'react/addons';
import classnames from 'classnames';

require('styles/sidebar/ConnectionListItem.css');

class ConnectionListItemComponent extends React.Component {
  render() {

    let classes = classnames(
      'connectionlistitem-component',
      { active: this.props.connection.active }
    );

    return (
      <li className={classes} onClick={this.props.onActivate.bind(this, this.props.connection)}>
        {this.props.connection.connection.connectionName}
      </li>
    );
  }
}

ConnectionListItemComponent.propTypes = {
  onActivate: React.PropTypes.func
};
ConnectionListItemComponent.defaultProps = {
  onActivate: () => {}
};

export default ConnectionListItemComponent;


text:
package com.github.kadi79.gaertner.annotations;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 *
UmlClassDiagrams class.

 *
 * @since 0.0.1
 */
@Retention(SOURCE)
@Target({TYPE})
public @interface UmlClassDiagrams {

	UmlClassDiagram[] value();

}


text:
package com.navercorp.pinpoint.web.vo;

import java.util.Comparator;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.navercorp.pinpoint.common.bo.AgentInfoBo;
import com.navercorp.pinpoint.common.bo.ServerMetaDataBo;
import com.navercorp.pinpoint.web.view.AgentInfoSerializer;

/**
 * @author HyunGil Jeong
 */
@JsonSerialize(using = AgentInfoSerializer.class)
public class AgentInfo {

    public static final Comparator<AgentInfo> AGENT_NAME_ASC_COMPARATOR = new Comparator<AgentInfo>() {
        @Override
        public int compare(AgentInfo lhs, AgentInfo rhs) {
            final String lhsAgentId = lhs.agentId == null ? "" : lhs.agentId;
            final String rhsAgentId = rhs.agentId == null ? "" : rhs.agentId;
            return lhsAgentId.compareTo(rhsAgentId);
        }
    };

    private String applicationName;
    private String agentId;
    private long startTimestamp;
    private String hostName;
    private String ip;
    private String ports;
    private short serviceTypeCode;
    private int pid;
    private String vmVersion;
    private String agentVersion;
    private ServerMetaDataBo serverMetaData;
    private long initialStartTimestamp;
    private AgentStatus status;

    public AgentInfo() {
    }

    public AgentInfo(AgentInfoBo agentInfoBo) {
        this.applicationName = agentInfoBo.getApplicationName();
        this.agentId = agentInfoBo.getAgentId();
        this.startTimestamp = agentInfoBo.getStartTime();
        this.hostName = agentInfoBo.getHostName();
        this.ip = agentInfoBo.getIp();
        this.ports = agentInfoBo.getPorts();
        this.serviceTypeCode = agentInfoBo.getServiceTypeCode();
        this.pid = agentInfoBo.getPid();
        this.vmVersion = agentInfoBo.getVmVersion();
        this.agentVersion = agentInfoBo.getAgentVersion();
        this.serverMetaData = agentInfoBo.getServerMetaData();
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public String getAgentId() {
        return agentId;
    }

    public void setAgentId(String agentId) {
        this.agentId = agentId;
    }

    public long getStartTimestamp() {
        return startTimestamp;
    }

    public void setStartTimestamp(long startTimestamp) {
        this.startTimestamp = startTimestamp;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getPorts() {
        return ports;
    }

    public void setPorts(String ports) {
        this.ports = ports;
    }

    public short getServiceTypeCode() {
        return serviceTypeCode;
    }

    public void setServiceTypeCode(short serviceTypeCode) {
        this.serviceTypeCode = serviceTypeCode;
    }

    public int getPid() {
        return pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    public String getVmVersion() {
        return vmVersion;
    }

    public void setVmVersion(String vmVersion) {
        this.vmVersion = vmVersion;
    }

    public String getAgentVersion() {
        return agentVersion;
    }

    public void setAgentVersion(String agentVersion) {
        this.agentVersion = agentVersion;
    }

    public ServerMetaDataBo getServerMetaData() {
        return serverMetaData;
    }

    public void setServerMetaData(ServerMetaDataBo serverMetaData) {
        this.serverMetaData = serverMetaData;
    }

    public long getInitialStartTimestamp() {
        return initialStartTimestamp;
    }

    public void setInitialStartTimestamp(long initialStartTimestamp) {
        this.initialStartTimestamp = initialStartTimestamp;
    }

    public AgentStatus getStatus() {
        return status;
    }

    public void setStatus(AgentStatus status) {
        this.status = status;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AgentInfo agentInfo = (AgentInfo) o;

        if (startTimestamp != agentInfo.startTimestamp) return false;
        return agentId != null ? agentId.equals(agentInfo.agentId) : agentInfo.agentId == null;

    }

    @Override
    public int hashCode() {
        int result = agentId != null ? agentId.hashCode() : 0;
        result = 31 * result + (int) (startTimestamp ^ (startTimestamp >>> 32));
        return result;
    }

    @Override
    public String toString() {
        return "AgentInfo [applicationName=" + applicationName + ", agentId=" + agentId + ", startTimestamp="
                + startTimestamp + ", hostName=" + hostName + ", ip=" + ip + ", ports=" + ports + ", serviceTypeCode="
                + serviceTypeCode + ", pid=" + pid + ", vmVersion=" + vmVersion + ", agentVersion=" + agentVersion
                + ", serverMetaData=" + serverMetaData + ", initialStartTimestamp=" + initialStartTimestamp
                + ", status=" + status + "]";
    }

}


text:
'use strict';

// MODULES //

var float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' );

// MAIN //

/**
* Computes the variance of a single-precision floating-point strided array using a one-pass trial mean algorithm.
*
* ## Method
*
* -   This implementation uses a one-pass trial mean approach, as suggested by Chan et al (1983).
*
* ## References
*
* -   Neely, Peter M. 1966. "Comparison of Several Algorithms for Computation of Means, Standard Deviations and Correlation Coefficients." _Communications of the ACM_ 9 (7). Association for Computing Machinery: 496–99. doi:[10.1145/365719.365958](https://doi.org/10.1145/365719.365958).
* -   Ling, Robert F. 1974. "Comparison of Several Algorithms for Computing Sample Means and Variances." _Journal of the American Statistical Association_ 69 (348). American Statistical Association, Taylor & Francis, Ltd.: 859–66. doi:[10.2307/2286154](https://doi.org/10.2307/2286154).
* -   Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. 1983. "Algorithms for Computing the Sample Variance: Analysis and Recommendations." _The American Statistician_ 37 (3). American Statistical Association, Taylor & Francis, Ltd.: 242–47. doi:[10.1080/00031305.1983.10483115](https://doi.org/10.1080/00031305.1983.10483115).
* -   Schubert, Erich, and Michael Gertz. 2018. "Numerically Stable Parallel Computation of (Co-)Variance." In _Proceedings of the 30th International Conference on Scientific and Statistical Database Management_. New York, NY, USA: Association for Computing Machinery. doi:[10.1145/3221269.3223036](https://doi.org/10.1145/3221269.3223036).
*
* @param {PositiveInteger} N - number of indexed elements
* @param {number} correction - degrees of freedom adjustment
* @param {Float32Array} x - input array
* @param {integer} stride - stride length
* @param {NonNegativeInteger} offset - starting index
* @returns {number} variance
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var x = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] );
* var N = floor( x.length / 2 );
*
* var v = svariancech( N, 1, x, 2, 1 );
* // returns 6.25
*/
function svariancech( N, correction, x, stride, offset ) {
	var mu;
	var ix;
	var M2;
	var M;
	var d;
	var n;
	var i;

	n = N - correction;
	if ( N <= 0 || n <= 0.0 ) {
		return NaN;
	}
	if ( N === 1 || stride === 0 ) {
		return 0.0;
	}
	ix = offset;

	// Use an estimate for the mean:
	mu = x[ ix ];
	ix += stride;

	// Compute the variance...
	M2 = 0.0;
	M = 0.0;
	for ( i = 1; i < N; i++ ) {
		d = float64ToFloat32( x[ ix ] - mu );
		M2 = float64ToFloat32( M2 + float64ToFloat32( d*d ) );
		M = float64ToFloat32( M + d );
		ix += stride;
	}
	return float64ToFloat32( float64ToFloat32(M2/n) - float64ToFloat32( float64ToFloat32(M/N)*float64ToFloat32(M/n) ) ); // eslint-disable-line max-len
}

// EXPORTS //

module.exports = svariancech;


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>Genesis 27 (ASV)</title>
<link href="../../../build/mobile.css" rel="stylesheet" />

American Standard VersionGenesis 27<
=
>

27

1 And it came to pass, that when Isaac was old, and his eyes were dim, so that he could not see, he called Esau his elder son, and said unto him, My son: and he said unto him, Here am I.
2 And he said, Behold now, I am old, I know not the day of my death.
3 Now therefore take, I pray thee, thy weapons, thy quiver and thy bow, and go out to the field, and take me venison;
4 and make me savory food, such as I love, and bring it to me, that I may eat; that my soul may bless thee before I die.

5 And Rebekah heard when Isaac spake to Esau his son. And Esau went to the field to hunt for venison, and to bring it.
6 And Rebekah spake unto Jacob her son, saying, Behold, I heard thy father speak unto Esau thy brother, saying,
7 Bring me venison, and make me savory food, that I may eat, and bless thee before Jehovah before my death.
8 Now therefore, my son, obey my voice according to that which I command thee.
9 Go now to the flock, and fetch me from thence two good kids of the goats; and I will make them savory food for thy father, such as he loveth:
10 and thou shalt bring it to thy father, that he may eat, so that he may bless thee before his death.
11 And Jacob said to Rebekah his mother, Behold, Esau my brother is a hairy man, and I am a smooth man.
12 My father peradventure will feel me, and I shall seem to him as a deceiver; and I shall bring a curse upon me, and not a blessing.
13 And his mother said unto him, Upon me be thy curse, my son; only obey my voice, and go fetch me them.
14 And he went, and fetched, and brought them to his mother: and his mother made savory food, such as his father loved.
15 And Rebekah took the goodly garments of Esau her elder son, which were with her in the house, and put them upon Jacob her younger son;
16 and she put the skins of the kids of the goats upon his hands, and upon the smooth of his neck:
17 and she gave the savory food and the bread, which she had prepared, into the hand of her son Jacob.

18 And he came unto his father, and said, My father: and he said, Here am I; who art thou, my son?
19 And Jacob said unto his father, I am Esau thy first-born; I have done according as thou badest me: arise, I pray thee, sit and eat of my venison, that thy soul may bless me.
20 And Isaac said unto his son, How is it that thou hast found it so quickly, my son? And he said, Because Jehovah thy God sent me good speed.
21 And Isaac said unto Jacob, Come near, I pray thee, that I may feel thee, my son, whether thou be my very son Esau or not.
22 And Jacob went near unto Isaac his father; and he felt him, and said, The voice is Jacob's voice, but the hands are the hands of Esau.
23 And he discerned him not, because his hands were hairy, as his brother Esau's hands: so he blessed him.
24 And he said, Art thou my very son Esau? And he said, I am.
25 And he said, Bring it near to me, and I will eat of my son's venison, that my soul may bless thee. And he brought it near to him, and he did eat: and he brought him wine, and he drank.
26 And his father Isaac said unto him, Come near now, and kiss me, my son.
27 And he came near, and kissed him: and he smelled the smell of his raiment, and blessed him, and said,

See, the smell of my son

Is as the smell of a field which Jehovah hath blessed:

28 And God give thee of the dew of heaven,

And of the fatness of the earth,

And plenty of grain and new wine:

29 Let peoples serve thee,

And nations bow down to thee.

Be lord over thy brethren,

And let thy mother's sons bow down to thee:

Cursed be every one that curseth thee,

And blessed be every one that blesseth thee:

30 And it came to pass, as soon as Isaac had made an end of blessing Jacob, and Jacob was yet scarce gone out from the presence of Isaac his father, that Esau his brother came in from his hunting.
31 And he also made savory food, and brought it unto his father; and he said unto his father, Let my father arise, and eat of his son's venison, that thy soul may bless me.
32 And Isaac his father said unto him, Who art thou? And he said, I am thy son, thy first-born, Esau.
33 And Isaac trembled very exceedingly, and said, Who then is he that hath taken venison, and brought it me, and I have eaten of all before thou camest, and have blessed him? yea, and he shall be blessed.
34 When Esau heard the words of his father, he cried with an exceeding great and bitter cry, and said unto his father, Bless me, even me also, O my father.
35 And he said, Thy brother came with guile, and hath taken away thy blessing.
36 And he said, Is not he rightly named Jacob? for he hath supplanted me these two times: he took away my birthright; and, behold, now he hath taken away my blessing. And he said, Hast thou not reserved a blessing for me?
37 And Isaac answered and said unto Esau, Behold, I have made him thy lord, and all his brethren have I given to him for servants; and with grain and new wine have I sustained him: and what then shall I do for thee, my son?
38 And Esau said unto his father, Hast thou but one blessing, my father? bless me, even me also, O my father. And Esau lifted up his voice, and wept.
39 And Isaac his father answered and said unto him,

Behold, of the fatness of the earth shall be thy dwelling,

And of the dew of heaven from above;

40 And by thy sword shalt thou live, and thou shalt serve thy brother;

And it shall come to pass, when thou shalt break loose,

That thou shalt shake his yoke from off thy neck.

41 And Esau hated Jacob because of the blessing wherewith his father blessed him: and Esau said in his heart, The days of mourning for my father are at hand; then will I slay my brother Jacob.
42 And the words of Esau her elder son were told to Rebekah.; and she sent and called Jacob her younger son, and said unto him, Behold, thy brother Esau, as touching thee, doth comfort himself, purposing to kill thee.
43 Now therefore, my son, obey my voice; and arise, flee thou to Laban my brother to Haran;
44 and tarry with him a few days, until thy brother's fury turn away;
45 until thy brother's anger turn away from thee, and he forget that which thou hast done to him: then I will send, and fetch thee from thence: why should I be bereaved of you both in one day?

46 And Rebekah said to Isaac, I am weary of my life because of the daughters of Heth: if Jacob take a wife of the daughters of Heth, such as these, of the daughters of the land, what good shall my life do me?

<
=
>


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.4.4.1_A2;
 * @section: 15.4.4.1, 15.2.4.7, 12.6.4;
 * @assertion: The constructor property of Array has the attribute DontEnum;
 * @description: Checking use propertyIsEnumerable, for-in;
*/

//CHECK#1
if (Array.propertyIsEnumerable('constructor') !== false) {
  $ERROR('#1: Array.propertyIsEnumerable(\'constructor\') === false. Actual: ' + (Array.propertyIsEnumerable('constructor')));
}

//CHECK#2
var result = true;
for (var p in Array){
  if (p === "constructor") {
    result = false;
  }
}

if (result !== true) {
  $ERROR('#2: result = true; for (p in Array) { if (p === "constructor") result = false; }  result === true;');
}