text:
<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Usuarios */
/* @var $form yii\widgets\ActiveForm */
?>

<?php $form = ActiveForm::begin(); ?>

        <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'nombre')->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'apellido')->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'cedula')->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'direccion')->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'telefono')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Registrar' : 'Actualizar', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

<?php ActiveForm::end(); ?>


text:
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost {
namespace asio {
namespace detail {

  template <typename Handler, typename T>
  class coro_handler
  {
  public:
    coro_handler(basic_yield_context<Handler> ctx)
      : coro_(ctx.coro_.lock()),
        ca_(ctx.ca_),
        handler_(ctx.handler_),
        ec_(ctx.ec_),
        value_(0)
    {
    }

    void operator()(T value)
    {
      *ec_ = pdalboost::system::error_code();
      *value_ = value;
      (*coro_)();
    }

    void operator()(pdalboost::system::error_code ec, T value)
    {
      *ec_ = ec;
      *value_ = value;
      (*coro_)();
    }

  //private:
    shared_ptr<typename basic_yield_context<Handler>::callee_type> coro_;
    typename basic_yield_context<Handler>::caller_type& ca_;
    Handler& handler_;
    pdalboost::system::error_code* ec_;
    T* value_;
  };

  template <typename Handler>
  class coro_handler<Handler, void>
  {
  public:
    coro_handler(basic_yield_context<Handler> ctx)
      : coro_(ctx.coro_.lock()),
        ca_(ctx.ca_),
        handler_(ctx.handler_),
        ec_(ctx.ec_)
    {
    }

    void operator()()
    {
      *ec_ = pdalboost::system::error_code();
      (*coro_)();
    }

    void operator()(pdalboost::system::error_code ec)
    {
      *ec_ = ec;
      (*coro_)();
    }

  //private:
    shared_ptr<typename basic_yield_context<Handler>::callee_type> coro_;
    typename basic_yield_context<Handler>::caller_type& ca_;
    Handler& handler_;
    pdalboost::system::error_code* ec_;
  };

  template <typename Handler, typename T>
  inline void* asio_handler_allocate(std::size_t size,
      coro_handler<Handler, T>* this_handler)
  {
    return pdalboost_asio_handler_alloc_helpers::allocate(
        size, this_handler->handler_);
  }

  template <typename Handler, typename T>
  inline void asio_handler_deallocate(void* pointer, std::size_t size,
      coro_handler<Handler, T>* this_handler)
  {
    pdalboost_asio_handler_alloc_helpers::deallocate(
        pointer, size, this_handler->handler_);
  }

  template <typename Handler, typename T>
  inline bool asio_handler_is_continuation(coro_handler<Handler, T>*)
  {
    return true;
  }

  template <typename Function, typename Handler, typename T>
  inline void asio_handler_invoke(Function& function,
      coro_handler<Handler, T>* this_handler)
  {
    pdalboost_asio_handler_invoke_helpers::invoke(
        function, this_handler->handler_);
  }

  template <typename Function, typename Handler, typename T>
  inline void asio_handler_invoke(const Function& function,
      coro_handler<Handler, T>* this_handler)
  {
    pdalboost_asio_handler_invoke_helpers::invoke(
        function, this_handler->handler_);
  }

} // namespace detail

#if !defined(GENERATING_DOCUMENTATION)

template <typename Handler, typename ReturnType>
struct handler_type<basic_yield_context<Handler>, ReturnType()>
{
  typedef detail::coro_handler<Handler, void> type;
};

template <typename Handler, typename ReturnType, typename Arg1>
struct handler_type<basic_yield_context<Handler>, ReturnType(Arg1)>
{
  typedef detail::coro_handler<Handler, Arg1> type;
};

template <typename Handler, typename ReturnType>
struct handler_type<basic_yield_context<Handler>,
    ReturnType(pdalboost::system::error_code)>
{
  typedef detail::coro_handler<Handler, void> type;
};

template <typename Handler, typename ReturnType, typename Arg2>
struct handler_type<basic_yield_context<Handler>,
    ReturnType(pdalboost::system::error_code, Arg2)>
{
  typedef detail::coro_handler<Handler, Arg2> type;
};

template <typename Handler, typename T>
class async_result<detail::coro_handler<Handler, T> >
{
public:
  typedef T type;

  explicit async_result(detail::coro_handler<Handler, T>& h)
    : ca_(h.ca_)
  {
    out_ec_ = h.ec_;
    if (!out_ec_) h.ec_ = &ec_;
    h.value_ = &value_;
  }

  type get()
  {
    ca_();
    if (!out_ec_ && ec_) throw pdalboost::system::system_error(ec_);
    return value_;
  }

private:
  typename basic_yield_context<Handler>::caller_type& ca_;
  pdalboost::system::error_code* out_ec_;
  pdalboost::system::error_code ec_;
  type value_;
};

template <typename Handler>
class async_result<detail::coro_handler<Handler, void> >
{
public:
  typedef void type;

  explicit async_result(detail::coro_handler<Handler, void>& h)
    : ca_(h.ca_)
  {
    out_ec_ = h.ec_;
    if (!out_ec_) h.ec_ = &ec_;
  }

  void get()
  {
    ca_();
    if (!out_ec_ && ec_) throw pdalboost::system::system_error(ec_);
  }

private:
  typename basic_yield_context<Handler>::caller_type& ca_;
  pdalboost::system::error_code* out_ec_;
  pdalboost::system::error_code ec_;
};

namespace detail {

  template <typename Handler, typename Function>
  struct spawn_data : private noncopyable
  {
    spawn_data(BOOST_ASIO_MOVE_ARG(Handler) handler,
        bool call_handler, BOOST_ASIO_MOVE_ARG(Function) function)
      : handler_(BOOST_ASIO_MOVE_CAST(Handler)(handler)),
        call_handler_(call_handler),
        function_(BOOST_ASIO_MOVE_CAST(Function)(function))
    {
    }

    weak_ptr<typename basic_yield_context<Handler>::callee_type> coro_;
    Handler handler_;
    bool call_handler_;
    Function function_;
  };

  template <typename Handler, typename Function>
  struct coro_entry_point
  {
    void operator()(typename basic_yield_context<Handler>::caller_type& ca)
    {
      shared_ptr<spawn_data<Handler, Function> > data(data_);
      ca(); // Yield until coroutine pointer has been initialised.
      const basic_yield_context<Handler> yield(
          data->coro_, ca, data->handler_);
      (data->function_)(yield);
      if (data->call_handler_)
        (data->handler_)();
    }

    shared_ptr<spawn_data<Handler, Function> > data_;
  };

  template <typename Handler, typename Function>
  struct spawn_helper
  {
    void operator()()
    {
      typedef typename basic_yield_context<Handler>::callee_type callee_type;
      coro_entry_point<Handler, Function> entry_point = { data_ };
      shared_ptr<callee_type> coro(new callee_type(entry_point, attributes_));
      data_->coro_ = coro;
      (*coro)();
    }

    shared_ptr<spawn_data<Handler, Function> > data_;
    pdalboost::coroutines::attributes attributes_;
  };

  inline void default_spawn_handler() {}

} // namespace detail

template <typename Handler, typename Function>
void spawn(BOOST_ASIO_MOVE_ARG(Handler) handler,
    BOOST_ASIO_MOVE_ARG(Function) function,
    const pdalboost::coroutines::attributes& attributes)
{
  detail::spawn_helper<Handler, Function> helper;
  helper.data_.reset(
      new detail::spawn_data<Handler, Function>(
        BOOST_ASIO_MOVE_CAST(Handler)(handler), true,
        BOOST_ASIO_MOVE_CAST(Function)(function)));
  helper.attributes_ = attributes;
  pdalboost_asio_handler_invoke_helpers::invoke(helper, helper.data_->handler_);
}

template <typename Handler, typename Function>
void spawn(basic_yield_context<Handler> ctx,
    BOOST_ASIO_MOVE_ARG(Function) function,
    const pdalboost::coroutines::attributes& attributes)
{
  Handler handler(ctx.handler_); // Explicit copy that might be moved from.
  detail::spawn_helper<Handler, Function> helper;
  helper.data_.reset(
      new detail::spawn_data<Handler, Function>(
        BOOST_ASIO_MOVE_CAST(Handler)(handler), false,
        BOOST_ASIO_MOVE_CAST(Function)(function)));
  helper.attributes_ = attributes;
  pdalboost_asio_handler_invoke_helpers::invoke(helper, helper.data_->handler_);
}

template <typename Function>
void spawn(pdalboost::asio::io_service::strand strand,
    BOOST_ASIO_MOVE_ARG(Function) function,
    const pdalboost::coroutines::attributes& attributes)
{
  pdalboost::asio::spawn(strand.wrap(&detail::default_spawn_handler),
      BOOST_ASIO_MOVE_CAST(Function)(function), attributes);
}

template <typename Function>
void spawn(pdalboost::asio::io_service& io_service,
    BOOST_ASIO_MOVE_ARG(Function) function,
    const pdalboost::coroutines::attributes& attributes)
{
  pdalboost::asio::spawn(pdalboost::asio::io_service::strand(io_service),
      BOOST_ASIO_MOVE_CAST(Function)(function), attributes);
}

#endif // !defined(GENERATING_DOCUMENTATION)

} // namespace asio
} // namespace pdalboost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_IMPL_SPAWN_HPP

redpajama_set_name: RedPajamaGithub


text:
var Whateva = React.createClass({
  displayName: "Whatever",
  render: function render() {
    return null;
  }
});


text:
<SageTVPlugin>

  <Name>Sage Diamond API</Name>

  <Identifier>sage-diamond-api</Identifier>

  <Description>Diamond UI API- Do not install directly just a dependency!!</Description>

  <Author>PluckyHD</Author>

  <CreationDate>2010-12-06</CreationDate>

  <ModificationDate>2011.05.06</ModificationDate>

  <Version>3.30</Version>

  <Desktop>false</Desktop>

<Dependency>

   <Plugin>sagex-api</Plugin>

    <MinVersion>7.1.5.5</MinVersion>

  </Dependency>

  <PluginType>Library</PluginType>

  <Package>

    <PackageType>JAR</PackageType>

    <Location>https://github.com/OpenSageTV/sagetv-plugin-repo/releases/download/1/SageDiamondAPIV3.30.zip</Location>

    <MD5>8B650721368B714A5DF4A17B31BEA856</MD5>

  </Package>

</SageTVPlugin>


text:
/* ---------------------
 * GraphChangeEvent.java
 * ---------------------
 * (C) Copyright 2003-2008, by Barak Naveh and Contributors.
 *
 * Original Author:  Barak Naveh
 * Contributor(s):   -
 *
 * $Id: GraphChangeEvent.java 645 2008-09-30 19:44:48Z perfecthash $
 *
 * Changes
 * -------
 * 10-Aug-2003 : Initial revision (BN);
 *
 */
package org.jgrapht.event;

import java.util.*;

/**
 * An event which indicates that a graph has changed. This class is a root for
 * graph change events.
 *
 * @author Barak Naveh
 * @since Aug 10, 2003
 */
public class GraphChangeEvent
    extends EventObject
{
    //~ Static fields/initializers ---------------------------------------------

    private static final long serialVersionUID = 3834592106026382391L;

    //~ Instance fields --------------------------------------------------------

    /**
     * The type of graph change this event indicates.
     */
    protected int type;

    //~ Constructors -----------------------------------------------------------

    /**
     * Creates a new graph change event.
     *
     * @param eventSource the source of the event.
     * @param type the type of event.
     */
    public GraphChangeEvent(Object eventSource, int type)
    {
        super(eventSource);
        this.type = type;
    }

    //~ Methods ----------------------------------------------------------------

    /**
     * Returns the event type.
     *
     * @return the event type.
     */
    public int getType()
    {
        return type;
    }
}

// End GraphChangeEvent.java


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Transactions;
using Abp.Authorization.Roles;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Linq;
using Abp.Organizations;
using Microsoft.AspNet.Identity;

namespace Abp.Authorization.Users
{
    /// <summary>
    /// Implements 'User Store' of ASP.NET Identity Framework.
    /// </summary>
    public abstract class AbpUserStore<TRole, TUser> :
        IUserStore<TUser, long>,
        IUserPasswordStore<TUser, long>,
        IUserEmailStore<TUser, long>,
        IUserLoginStore<TUser, long>,
        IUserRoleStore<TUser, long>,
        IQueryableUserStore<TUser, long>,
        IUserLockoutStore<TUser, long>,
        IUserPermissionStore<TUser>,
        IUserPhoneNumberStore<TUser, long>,
        IUserClaimStore<TUser, long>,
        IUserSecurityStampStore<TUser, long>,
        IUserTwoFactorStore<TUser, long>,

        ITransientDependency

        where TRole : AbpRole<TUser>
        where TUser : AbpUser<TUser>
    {
        public IAsyncQueryableExecuter AsyncQueryableExecuter { get; set; }

        private readonly IRepository<TUser, long> _userRepository;
        private readonly IRepository<UserLogin, long> _userLoginRepository;
        private readonly IRepository<UserRole, long> _userRoleRepository;
        private readonly IRepository<UserClaim, long> _userClaimRepository;
        private readonly IRepository<TRole> _roleRepository;
        private readonly IRepository<UserPermissionSetting, long> _userPermissionSettingRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
        private readonly IRepository<OrganizationUnitRole, long> _organizationUnitRoleRepository;

        /// <summary>
        /// Constructor.
        /// </summary>
        protected AbpUserStore(
            IRepository<TUser, long> userRepository,
            IRepository<UserLogin, long> userLoginRepository,
            IRepository<UserRole, long> userRoleRepository,
            IRepository<TRole> roleRepository,
            IRepository<UserPermissionSetting, long> userPermissionSettingRepository,
            IUnitOfWorkManager unitOfWorkManager,
            IRepository<UserClaim, long> userClaimRepository,
            IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
            IRepository<OrganizationUnitRole, long> organizationUnitRoleRepository)
        {
            _userRepository = userRepository;
            _userLoginRepository = userLoginRepository;
            _userRoleRepository = userRoleRepository;
            _roleRepository = roleRepository;
            _unitOfWorkManager = unitOfWorkManager;
            _userClaimRepository = userClaimRepository;
            _userOrganizationUnitRepository = userOrganizationUnitRepository;
            _organizationUnitRoleRepository = organizationUnitRoleRepository;
            _userPermissionSettingRepository = userPermissionSettingRepository;

            AsyncQueryableExecuter = NullAsyncQueryableExecuter.Instance;
        }

        #region IQueryableUserStore

        public virtual IQueryable<TUser> Users => _userRepository.GetAll();

        #endregion

        #region IUserStore

        public virtual async Task CreateAsync(TUser user)
        {
            await _userRepository.InsertAsync(user);
        }

        public virtual async Task UpdateAsync(TUser user)
        {
            await _userRepository.UpdateAsync(user);
        }

        public virtual async Task DeleteAsync(TUser user)
        {
            await _userRepository.DeleteAsync(user.Id);
        }

        public virtual async Task<TUser> FindByIdAsync(long userId)
        {
            return await _userRepository.FirstOrDefaultAsync(userId);
        }

        public virtual async Task<TUser> FindByNameAsync(string userName)
        {
            var normalizedUsername = NormalizeKey(userName);

            return await _userRepository.FirstOrDefaultAsync(
                user => user.NormalizedUserName == normalizedUsername
            );
        }

        public virtual async Task<TUser> FindByEmailAsync(string email)
        {
            var normalizedEmail = NormalizeKey(email);

            return await _userRepository.FirstOrDefaultAsync(
                user => user.NormalizedEmailAddress == normalizedEmail
            );
        }

        /// <summary>
        /// Tries to find a user with user name or email address in current tenant.
        /// </summary>
        /// <param name="userNameOrEmailAddress">User name or email address</param>
        /// <returns>User or null</returns>
        public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
        {
            var normalizedUserNameOrEmailAddress = NormalizeKey(userNameOrEmailAddress);

            return await _userRepository.FirstOrDefaultAsync(
                user => (user.NormalizedUserName == normalizedUserNameOrEmailAddress || user.NormalizedEmailAddress == normalizedUserNameOrEmailAddress)
            );
        }

        /// <summary>
        /// Tries to find a user with user name or email address in given tenant.
        /// </summary>
        /// <param name="tenantId">Tenant Id</param>
        /// <param name="userNameOrEmailAddress">User name or email address</param>
        /// <returns>User or null</returns>
        [UnitOfWork]
        public virtual async Task<TUser> FindByNameOrEmailAsync(int? tenantId, string userNameOrEmailAddress)
        {
            using (_unitOfWorkManager.Current.SetTenantId(tenantId))
            {
                return await FindByNameOrEmailAsync(userNameOrEmailAddress);
            }
        }

        #endregion

        #region IUserPasswordStore

        public virtual Task SetPasswordHashAsync(TUser user, string passwordHash)
        {
            user.Password = passwordHash;
            return Task.FromResult(0);
        }

        public virtual Task<string> GetPasswordHashAsync(TUser user)
        {
            return Task.FromResult(user.Password);
        }

        public virtual Task<bool> HasPasswordAsync(TUser user)
        {
            return Task.FromResult(!string.IsNullOrEmpty(user.Password));
        }

        #endregion

        #region IUserEmailStore

        public virtual Task SetEmailAsync(TUser user, string email)
        {
            user.EmailAddress = email;
            return Task.FromResult(0);
        }

        public virtual Task<string> GetEmailAsync(TUser user)
        {
            return Task.FromResult(user.EmailAddress);
        }

        public virtual Task<bool> GetEmailConfirmedAsync(TUser user)
        {
            return Task.FromResult(user.IsEmailConfirmed);
        }

        public virtual Task SetEmailConfirmedAsync(TUser user, bool confirmed)
        {
            user.IsEmailConfirmed = confirmed;
            return Task.FromResult(0);
        }

        #endregion

        #region IUserLoginStore

        public virtual async Task AddLoginAsync(TUser user, UserLoginInfo login)
        {
            await _userLoginRepository.InsertAsync(
                new UserLogin
                {
                    TenantId = user.TenantId,
                    LoginProvider = login.LoginProvider,
                    ProviderKey = login.ProviderKey,
                    UserId = user.Id
                });
        }

        public virtual async Task RemoveLoginAsync(TUser user, UserLoginInfo login)
        {
            await _userLoginRepository.DeleteAsync(
                ul => ul.UserId == user.Id &&
                      ul.LoginProvider == login.LoginProvider &&
                      ul.ProviderKey == login.ProviderKey
            );
        }

        public virtual async Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user)
        {
            return (await _userLoginRepository.GetAllListAsync(ul => ul.UserId == user.Id))
                .Select(ul => new UserLoginInfo(ul.LoginProvider, ul.ProviderKey))
                .ToList();
        }

        public virtual async Task<TUser> FindAsync(UserLoginInfo login)
        {
            var userLogin = await _userLoginRepository.FirstOrDefaultAsync(
                ul => ul.LoginProvider == login.LoginProvider && ul.ProviderKey == login.ProviderKey
            );

            if (userLogin == null)
            {
                return null;
            }

            return await _userRepository.FirstOrDefaultAsync(u => u.Id == userLogin.UserId);
        }

        [UnitOfWork]
        public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
        {
            var query = from userLogin in _userLoginRepository.GetAll()
                        join user in _userRepository.GetAll() on userLogin.UserId equals user.Id
                        where userLogin.LoginProvider == login.LoginProvider && userLogin.ProviderKey == login.ProviderKey
                        select user;

            return Task.FromResult(query.ToList());
        }

        public virtual Task<TUser> FindAsync(int? tenantId, UserLoginInfo login)
        {
            using (_unitOfWorkManager.Current.SetTenantId(tenantId))
            {
                var query = from userLogin in _userLoginRepository.GetAll()
                            join user in _userRepository.GetAll() on userLogin.UserId equals user.Id
                            where userLogin.LoginProvider == login.LoginProvider && userLogin.ProviderKey == login.ProviderKey
                            select user;

                return Task.FromResult(query.FirstOrDefault());
            }
        }

        #endregion

        #region IUserRoleStore

        public virtual async Task AddToRoleAsync(TUser user, string roleName)
        {
            var role = await GetRoleByNameAsync(roleName);
            await _userRoleRepository.InsertAsync(new UserRole(user.TenantId, user.Id, role.Id));
        }

        public virtual async Task RemoveFromRoleAsync(TUser user, string roleName)
        {
            var role = await GetRoleByNameAsync(roleName);
            var userRole = await _userRoleRepository.FirstOrDefaultAsync(ur => ur.UserId == user.Id && ur.RoleId == role.Id);
            if (userRole == null)
            {
                return;
            }

            await _userRoleRepository.DeleteAsync(userRole);
        }

        [UnitOfWork]
        public virtual async Task<IList<string>> GetRolesAsync(TUser user)
        {
            var userRoles = from userRole in _userRoleRepository.GetAll()
                            join role in _roleRepository.GetAll() on userRole.RoleId equals role.Id
                            where userRole.UserId == user.Id
                            select role.Name;

            var userOrganizationUnitRoles = from userOu in _userOrganizationUnitRepository.GetAll()
                                            join roleOu in _organizationUnitRoleRepository.GetAll() on userOu.OrganizationUnitId equals roleOu.OrganizationUnitId
                                            join userOuRoles in _roleRepository.GetAll() on roleOu.RoleId equals userOuRoles.Id
                                            where userOu.UserId == user.Id
                                            select userOuRoles.Name;

            return await AsyncQueryableExecuter.ToListAsync(userRoles.Union(userOrganizationUnitRoles));
        }

        public virtual async Task<bool> IsInRoleAsync(TUser user, string roleName)
        {
            return (await GetRolesAsync(user)).Any(r => r == roleName);
        }

        #endregion

        #region IUserPermissionStore

        public virtual async Task AddPermissionAsync(TUser user, PermissionGrantInfo permissionGrant)
        {
            if (await HasPermissionAsync(user.Id, permissionGrant))
            {
                return;
            }

            await _userPermissionSettingRepository.InsertAsync(
                new UserPermissionSetting
                {
                    TenantId = user.TenantId,
                    UserId = user.Id,
                    Name = permissionGrant.Name,
                    IsGranted = permissionGrant.IsGranted
                });
        }

        public virtual async Task RemovePermissionAsync(TUser user, PermissionGrantInfo permissionGrant)
        {
            await _userPermissionSettingRepository.DeleteAsync(
                permissionSetting => permissionSetting.UserId == user.Id &&
                                     permissionSetting.Name == permissionGrant.Name &&
                                     permissionSetting.IsGranted == permissionGrant.IsGranted
            );
        }

        public virtual async Task<IList<PermissionGrantInfo>> GetPermissionsAsync(long userId)
        {
            return (await _userPermissionSettingRepository.GetAllListAsync(p => p.UserId == userId))
                .Select(p => new PermissionGrantInfo(p.Name, p.IsGranted))
                .ToList();
        }

        public virtual async Task<bool> HasPermissionAsync(long userId, PermissionGrantInfo permissionGrant)
        {
            return await _userPermissionSettingRepository.FirstOrDefaultAsync(
                       p => p.UserId == userId &&
                            p.Name == permissionGrant.Name &&
                            p.IsGranted == permissionGrant.IsGranted
                   ) != null;
        }

        public virtual async Task RemoveAllPermissionSettingsAsync(TUser user)
        {
            await _userPermissionSettingRepository.DeleteAsync(s => s.UserId == user.Id);
        }

        #endregion

        #region IUserLockoutStore

        public Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user)
        {
            return Task.FromResult(
                user.LockoutEndDateUtc.HasValue
                    ? new DateTimeOffset(DateTime.SpecifyKind(user.LockoutEndDateUtc.Value, DateTimeKind.Utc))
                    : new DateTimeOffset()
            );
        }

        public Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd)
        {
            user.LockoutEndDateUtc = lockoutEnd == DateTimeOffset.MinValue ? new DateTime?() : lockoutEnd.UtcDateTime;
            return Task.FromResult(0);
        }

        public Task<int> IncrementAccessFailedCountAsync(TUser user)
        {
            return Task.FromResult(++user.AccessFailedCount);
        }

        public Task ResetAccessFailedCountAsync(TUser user)
        {
            user.AccessFailedCount = 0;
            return Task.FromResult(0);
        }

        public Task<int> GetAccessFailedCountAsync(TUser user)
        {
            return Task.FromResult(user.AccessFailedCount);
        }

        public Task<bool> GetLockoutEnabledAsync(TUser user)
        {
            return Task.FromResult(user.IsLockoutEnabled);
        }

        public Task SetLockoutEnabledAsync(TUser user, bool enabled)
        {
            user.IsLockoutEnabled = enabled;
            return Task.FromResult(0);
        }

        #endregion

        #region IUserPhoneNumberStore

        public Task SetPhoneNumberAsync(TUser user, string phoneNumber)
        {
            user.PhoneNumber = phoneNumber;
            return Task.FromResult(0);
        }

        public Task<string> GetPhoneNumberAsync(TUser user)
        {
            return Task.FromResult(user.PhoneNumber);
        }

        public Task<bool> GetPhoneNumberConfirmedAsync(TUser user)
        {
            return Task.FromResult(user.IsPhoneNumberConfirmed);
        }

        public Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed)
        {
            user.IsPhoneNumberConfirmed = confirmed;
            return Task.FromResult(0);
        }

        #endregion

        #region IUserClaimStore

        public async Task<IList<Claim>> GetClaimsAsync(TUser user)
        {
            var userClaims = await _userClaimRepository.GetAllListAsync(uc => uc.UserId == user.Id);
            return userClaims.Select(uc => new Claim(uc.ClaimType, uc.ClaimValue)).ToList();
        }

        public Task AddClaimAsync(TUser user, Claim claim)
        {
            return _userClaimRepository.InsertAsync(new UserClaim(user, claim));
        }

        public Task RemoveClaimAsync(TUser user, Claim claim)
        {
            return _userClaimRepository.DeleteAsync(
                uc => uc.UserId == user.Id &&
                      uc.ClaimType == claim.Type &&
                      uc.ClaimValue == claim.Value
            );
        }

        #endregion

        #region IDisposable

        public virtual void Dispose()
        {
            //No need to dispose since using IOC.
        }

        #endregion

        #region Helpers

        protected virtual string NormalizeKey(string key)
        {
            return key.ToUpperInvariant();
        }

        private async Task<TRole> GetRoleByNameAsync(string roleName)
        {
            var normalizedName = NormalizeKey(roleName);
            var role = await _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName == normalizedName);
            if (role == null)
            {
                throw new AbpException("Could not find a role with name: " + normalizedName);
            }

            return role;
        }

        #endregion

        #region IUserSecurityStampStore

        public Task SetSecurityStampAsync(TUser user, string stamp)
        {
            user.SecurityStamp = stamp;
            return Task.FromResult(0);
        }

        public Task<string> GetSecurityStampAsync(TUser user)
        {
            return Task.FromResult(user.SecurityStamp);
        }

        #endregion

        public Task SetTwoFactorEnabledAsync(TUser user, bool enabled)
        {
            user.IsTwoFactorEnabled = enabled;
            return Task.FromResult(0);
        }

        public Task<bool> GetTwoFactorEnabledAsync(TUser user)
        {
            return Task.FromResult(user.IsTwoFactorEnabled);
        }

        public async Task<string> GetUserNameFromDatabaseAsync(long userId)
        {
            //note: This workaround will not be needed after fixing https://github.com/aspnetboilerplate/aspnetboilerplate/issues/1828
            var outerUow = _unitOfWorkManager.Current;
            using (var uow = _unitOfWorkManager.Begin(new UnitOfWorkOptions
            {
                Scope = TransactionScopeOption.RequiresNew,
                IsTransactional = false,
                IsolationLevel = IsolationLevel.ReadUncommitted
            }))
            {
                if (outerUow != null)
                {
                    _unitOfWorkManager.Current.SetTenantId(outerUow.GetTenantId());
                }

                var user = await _userRepository.GetAsync(userId);
                await uow.CompleteAsync();
                return user.UserName;
            }
        }
    }
}


text:
/**
 * @file 同步组件
 * @author mengke01(kekee000@gmail.com)
 */

define(
    function (require) {
        var i18n = require('../i18n/i18n');
        var Resolver = require('common/promise');
        var string = require('common/string');
        var project = require('./project');
        var program = require('./program');
        var resolvettf = require('./util/resolvettf');
        var font = require('fonteditor-core/ttf/font');
        var ttf2woff = require('fonteditor-core/ttf/ttf2woff');
        var ttf2eot = require('fonteditor-core/ttf/ttf2eot');
        var base642bytes = require('fonteditor-core/ttf/util/base642bytes');
        var loader = require('./loader');
        var SyncForm = require('./SyncForm');
        var syncStatus = require('./sync-status');
        var curSyncStatus = {};
        var DEFAULT_FONTTYPE = 'ttf'; // 同步默认的字体类型
        var exports = {};

        /**
         * 设置资源的同步能力
         *
         * @param {string} url 当前的同步资源
         * @param {number} status 状态
         */
        function setSyncStatus(url, status) {
            curSyncStatus[url] = (curSyncStatus[url] || 0xffff) & status;
            if (!status) {
                delete curSyncStatus[url];
            }
        }

        /**
         * 获取资源同步能力
         * @param  {string} url 当前的同步资源
         * @return {number} 状态
         */
        function getSyncStatus(url) {
            return curSyncStatus[url] || 0;
        }

        /**
         * 检查同步状态,是否有新的记录
         *
         * @return {promise}
         */
        function checkSync(syncConfig) {
            var data = {
                action: 'pull',
                encode: 'base64',
                fontName: syncConfig.name,
                fontType: DEFAULT_FONTTYPE, // 暂时只接收ttf类型的字体
                timestamp: syncConfig.timestamp || 0
            };

            var resolver = new Resolver();
            $.ajax({
                url: syncConfig.url,
                dataType: 'jsonp',
                data: data
            }).then(function (data) {
                if (data && data.status === 0) {
                    resolver.resolve(data.data);
                }
                // 有些服务器不支持拉取,这里也处理为有响应
                else {
                    setSyncStatus(syncConfig.url, syncStatus.pullNoResponse);
                    resolver.resolve({
                        status: syncStatus.parseDataError
                    });
                }
            }, function (reason) {
                setSyncStatus(syncConfig.url, syncStatus.pullNoResponse);
                // 不支持拉取,但有可能支持推送,这里也处理为成功
                if (reason.status === 200) {
                    resolver.resolve({
                        status: syncStatus.pullNoResponse
                    });
                }
                else {
                    setSyncStatus(syncConfig.url, syncStatus.serviceNotAvailable);
                    resolver.reject({
                        status: syncStatus.serviceNotAvailable,
                        reason: 'sync no response'
                    });
                    alert(i18n.lang.msg_error_sync_font_address);
                }
            });
            return resolver.promise();
        }

        /**
         * 检查是否带有更新的字体,有更新则解析
         *
         * @param  {Object} data 解析的数据
         * @return {promise}
         */
        function confirmSync(data) {
            var resolver = new Resolver();
            if (data.hasNew && (data.fontType === DEFAULT_FONTTYPE && data[data.fontType])) {
                if (window.confirm(string.format(i18n.lang.msg_has_new_font_version, data.fontName))) {
                    // 解析后台传送过来的ttf字形
                    var ttfBuffer = new Int8Array(base642bytes(data[data.fontType])).buffer;
                    loader.load(ttfBuffer, {
                        type: data.fontType,
                        success: function (ttfObject) {
                            resolver.resolve({
                                status: 0,
                                hasNew: 1,
                                newData: ttfObject,
                                timestamp: data.timestamp
                            });
                        },
                        error: function () {
                            data.status = syncStatus.parseFontError;
                            resolver.reject(data);
                            alert(i18n.lang.msg_error_sync_font_version);
                        }
                    });
                }
                else {
                    data.status = syncStatus.cancelSync;
                    resolver.reject(data);
                }
            }
            else {
                data.status = syncStatus.noHasNew;
                resolver.reject(data);
            }
            return resolver.promise();
        }

        /**
         * 根据配置获取需要同步的数据
         * @param  {Object} syncConfig 同步配置
         * @param  {Object} ttf        ttf对象
         * @return {Object}            同步的数据字段
         */
        function getSyncData(syncConfig, ttf) {
            var fontType = [];
            var syncData = {};

            if (syncConfig.woff || syncConfig.ttf || syncConfig.eot) {
                ttf = resolvettf(ttf);
                try {
                    var buffer = font.create(ttf).write({
                        type: 'ttf'
                    });
                }
                catch (e) {
                    program.fire('font-error', e);
                    alert(e.message);
                    throw e;
                }

                if (syncConfig.ttf) {
                    fontType.push('ttf');
                    syncData.ttf = font.toBase64(buffer);
                }

                if (syncConfig.woff) {
                    fontType.push('woff');
                    syncData.woff = font.toBase64(ttf2woff(buffer));
                }

                if (syncConfig.eot) {
                    fontType.push('eot');
                    syncData.eot = font.toBase64(ttf2eot(buffer));
                }

                buffer = null;
            }

            if (syncConfig.svg) {
                fontType.push('svg');
                var svg = font.create(ttf).write({
                    type: 'svg'
                });
                syncData.svg = font.toBase64(svg);
            }

            syncData.encode = 'base64';
            syncData.fontName = syncConfig.name;
            syncData.fontType = fontType.join(',');
            return syncData;
        }

        /**
         * 进行远程同步
         *
         * @param  {Object} syncConfig 同步配置
         * @param  {Object} ttf        ttf对象
         * @param  {Object} resolver   resolver对象
         */
        function doSync(syncConfig, ttf, resolver) {
            var form = new SyncForm(syncConfig.url, {
                serviceStatus: getSyncStatus(syncConfig.url)
            });
            var syncData = getSyncData(syncConfig, ttf);
            form.submit(syncData).then(function (data) {
                if (data.status === 0) {
                    resolver.resolve(data.data);
                }
                else {
                    data.status = syncStatus.parseDataError;
                    resolver.reject(data);
                }
            }, function (data) {
                // 推送无响应
                if (data.status === syncStatus.pushNoResponse) {
                    setSyncStatus(syncConfig.url, syncStatus.pushNoResponse);
                }
                resolver.reject(data);
            });
        }

        /**
         * 进行远程推送服务
         *
         * @param  {Object} syncConfig 同步配置
         * @param  {Object} ttf        ttf对象
         * @param  {Object} resolver   resolver对象
         */
        function doPush(syncConfig, ttf, resolver) {
            if (!syncConfig.pushUrl) {
                resolver.resolve({});
                return;
            }

            var form = new SyncForm(syncConfig.pushUrl, {
                serviceStatus: syncStatus.pushNoResponse // 推送服务不检查是否有返回
            });
            var syncData = getSyncData(syncConfig, ttf);
            form.submit(syncData).then(function (data) {
                resolver.resolve(data);
            }, function (data) {
                resolver.reject(data);
            });
        }

        /**
         * 更新推送时间戳,在下一次推送的时候发送时间戳
         *
         * @param  {string} projectId  项目编号
         * @param  {number} timestamp  当前记录时间戳
         * @param  {Object} syncConfig 同步配置
         */
        function updateSyncTimestamp(projectId, timestamp, syncConfig) {
            if (!syncConfig) {
                syncConfig = project.getConfig(projectId).sync;
            }
            syncConfig.timestamp = timestamp || 0;
            project.updateConfig(projectId, {
                sync: syncConfig
            });
        }

        /**
         * 添加一个任务
         *
         * @param {Object} options 任务参数
         * @param {string} options.type 同步类型,push or pull
         * @param {string} options.projectId 项目编号或者同步选项
         * @param {?Object} options.ttf 字体对象
         * @param {?Object} options.config 同步选项
         *
         * @return {Object} Promise对象
         */
        exports.addTask = function (options) {
            var syncType = options.type || 'push';
            var projectId = options.projectId;
            var ttf = options.ttf;
            var syncConfig = options.config;
            options = null;

            if (!syncConfig) {
                syncConfig = project.getConfig(projectId).sync;
            }

            if (!syncConfig || (!syncConfig.url && !syncConfig.pushUrl)) {
                return Resolver.rejected({
                    status: 2,
                    statusInfo: i18n.lang.msg_not_set_sync_info
                });
            }

            var resolver = new Resolver();
            var promise = resolver.promise();
            // 仅设置推送地址,不设置同步地址则只进行推送
            if (syncType === 'push' && !syncConfig.url && syncConfig.pushUrl) {
                doPush(syncConfig, ttf, resolver);
                return promise;
            }

            if (syncType === 'pull') {
                // 同步之后,如果有新纪录,则更新记录
                checkSync(syncConfig).then(confirmSync).then(function (data) {
                    resolver.resolve(data);
                }, function (data) {
                    resolver.reject(data);
                });
            }
            else {
                // 同步之后,如果有新纪录,则更新记录,不更新记录则进行推送
                checkSync(syncConfig).then(confirmSync).then(function (data) {
                    resolver.resolve(data);
                }, function (data) {
                    if (data.status === syncStatus.serviceNotAvailable) {
                        resolver.reject(data);
                        return;
                    }

                    // 获取当前推送的ttf,如果没有,则从本地存储中获取
                    if (!ttf) {
                        resolver.reject({
                            status: 2,
                            statusInfo: i18n.lang.msg_no_sync_font
                        });
                    }
                    else {
                        // 推送数据到同步服务器
                        doSync(syncConfig, ttf, resolver);
                        // 推送数据到推送地址
                        if(syncConfig.pushUrl && syncConfig.pushUrl !== syncConfig.url) {
                            setTimeout(function() {
                                doPush(syncConfig, ttf, new Resolver());
                            }, 200);
                        }
                    }
                });
            }

            // 更新当前的时间戳,这里包含两个来源,拉取新纪录的时间戳和推送成功后的时间戳
            promise.then(function (data) {
                if (data && data.timestamp) {
                    updateSyncTimestamp(projectId, data.timestamp, syncConfig);
                }
            });

            return promise;
        };

        return exports;
    }
);


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;

using AM.IO;

namespace UnitTests.AM.IO
{
    [TestClass]
    public class CompressionUtilityTest
    {
        private void _TestCompression
            (
                byte[] first
            )
        {
            byte[] zipped = CompressionUtility.Compress(first);

            byte[] second = CompressionUtility.Decompress(zipped);

            Assert.AreEqual(first.Length, second.Length);

            for (int i = 0; i < first.Length; i++)
            {
                Assert.AreEqual(first[i], second[i]);
            }
        }

        [TestMethod]
        public void CompressionUtility_Compress_Decompress()
        {
            byte[] bytes = new byte[0];
            _TestCompression(bytes);

            bytes = new byte[] { 0 };
            _TestCompression(bytes);

            bytes = new byte[] { 0, 1, 2, 3 };
            _TestCompression(bytes);
        }
    }
}


text:
Raspberry Pi Face Recognition Treasure Box
==========================================

Raspberry Pi powered box which uses face recognition with OpenCV to lock and unlock itself.  See the tutorial [on the Adafruit learning system](http://learn.adafruit.com/raspberry-pi-face-recognition-treasure-box/overview).


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>NFC tag ID reader</title>

Escoja el sensor que desee utilizar

<form name="sensores">
 Id del mote: <input id="idMote" type="text"></input>

 Introduzca la ip del servidor: <input id="ip" type="text" name="ip">

  Introduzca el puerto del servidor: <input id="puerto" type="text" name="puerto">

<select id="lista" size="1">
<option>Acelerometro</option>
<option>Sensor de luz</option>
</select>
<input type="button" value="Selecciona sensor" onClick="seleccionar()">
</form>


text:
/*
 * File:   MainMenu.cpp
 * Author: danny
 *
 * Created on February 12, 2015, 12:44 PM
 */

#include "WebMenu.h"
#include "ThingsPage.h"
#include "AddressesPage.h"
#include "EventsPage.h"
#include "EventConfigPage.h"
#include "MailConfigPage.h"
#include "ServerSettingsPage.h"
#include "TrafficPage.h"
#include "AuthorizedTrafficPage.h"
#include <Poco/Format.h>

WebMenu::WebMenu()
{
    _navbarItems.push_back(MenuItem(ThingsPage::Title, ThingsPage::Link));
    _navbarItems.push_back(MenuItem(AddressesPage::Title, AddressesPage::Link));
    _navbarItems.push_back(MenuItem(EventsPage::Title, EventsPage::Link));
    _navbarItems.push_back(MenuItem(TrafficPage::Title, TrafficPage::Link));
    _navbarItems.push_back(MenuItem(AuthorizedTrafficPage::Title, AuthorizedTrafficPage::Link));
    _navbarItems.push_back(MenuItem(EventConfigPage::Title, EventConfigPage::Link));
    _navbarItems.push_back(MenuItem(MailConfigPage::Title, MailConfigPage::Link));
    _navbarItems.push_back(MenuItem(ServerSettingsPage::Title, ServerSettingsPage::Link));
}

WebMenu::~WebMenu()
{
}

void WebMenu::renderNavBar(std::ostream& output, const std::string& activeTitle)
{
    output << "";
    output << "
";
    output << "
";
    output << "            <button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#navbar' aria-expanded='false' aria-controls='navbar'>";
    output << "                Toggle navigation";
    output << "                ";
    output << "                ";
    output << "                ";
    output << "            </button>";
    output << Poco::format("%s", ThingsPage::Link, _productName);
    output << "
";
    output << "
";
    output << "
";
    output << "
Site
";
    output << "
About
";
    output << "
";
    output << "
";
    output << "
";
    output << "";
    output << "";
    output << "
";
    output << "
";
    output << "
";
    output << "
";
    for (auto item : _navbarItems) {
        output << "<li";
        if (item.first == activeTitle) {

            output << " class='active'";
        }
        output << "><a href = '";
        output << item.second;
        output << "'>";
        output << item.first;
        output << "
";
    }
    output << "
";
    output << "
";
    output << "
";
    output << "
";
}

void WebMenu::renderHomeButton(std::ostream& output, const std::string& text)
{
    renderLinkButton(output, text, ThingsPage::Link);
}

void WebMenu::renderLinkButton(std::ostream& output, const std::string& text, const std::string& target)
{
    output << Poco::format("%s ", target, text);
}


text:
author: Elliot Forbes
date: 2019-05-25T14:08:54.000+00:00
desc: In this tutorial, we are going to be looking at how you can add authentication
  to your NodeJS Services using JWTs.
series: nodejs
image: node.png
tags:
- Authentication
title: NodeJS JWT Authentication Tutorial
twitter: https://twitter.com/Elliot_F
authorImage: https://images.tutorialedge.net/authors/profile.jpeg

---
Welcome fellow programmers! In this tutorial, we are going to be looking at how we can add authentication to our NodeJS applications using JWTs.

We'll be creating a REST API that feature a mixture of authenticated and un-authenticated JSON endpoints and we'll be implementing a nice and simple JWT validation function that will verify incoming requests to ensure they have the appropriate authorization header set and that the value of that header is a verified JSON Web Token!

# Goals

By the end of this tutorial, we will have covered the following:

* We will have created a really simple REST API using ExpressJS
* We will understand how we can create middleware functions that we can wrap endpoints with.
* We will understand how to add JWT Authentication to these middleware functions to ensure only authorized requestors can hit our REST API endpoints.

# Prerequisites

In order to complete this tutorial, you will need to have the following:

* NodeJS installed on your machine
* A Text Editor (I recommend Visual Studio Code)

# Video Tutorial

This tutorial is available in video format if you prefer:

{{< youtube id="0g0Of8jlhN8" autoplay="false" >}}

# Introduction

Being able to verify who is hitting your API endpoints is incredibly important. It allows you to determine if the requestor is an authorized person who is allowed to actually interact with your service.

This is where JWT authentication can solve our problems. We can create use JWTs in combination with request headers to help us validate that an incoming request is authorized or not.

# JWTs or JSON Web Tokens

JWTs or a JSON Web Token, to use its full name, is a means of representing claims between two parties.

## Structure

A typical JWT features a Header, a Payload, and a Signature.

![JWT Structure](https://images.tutorialedge.net/node/node-jwt-authentication-tutorial/jwt-structure.svg)

Let's break down what each of these is used for:

* **The Header** - This contains metadata about the JWT such as the type of token and the cryptographic algorithm used to secure it.
* **The Payload** - This is the _set of claims_ contained within the JWT that contains a series of key/value pairs. The payload can be read by anyone, so ensure that you don't add any confidential to the payload.
* **The Signature** - This is used to validate that everything in the JWT has not been tampered with in any way and is generated using the header, the payload and a signing key or passphrase.

In this tutorial, we are going to be creating JWTs that feature an incredibly simple payload. We'll be then signing any JWTs we create using a private RSA key.

This private RSA key is _only_ known by the server issuing any JWTs used and thus, unless a bad actor gets a hold of this key, it's almost impossible to generate a JWT token that will have a valid signature.

# A Basic REST API

Now that we have covered the theory, let's set about creating a simple REST API in NodeJS that uses Express.JS. Create a new directory in which our project will live and run the following:

```output
$ npm init
```

Keep everything as default values for now, we can edit this later should we need to.

Now that we have initialized our project, we'll need to install the express.js Node Module:

```output
$ npm install express --save
```

This will go away and fetch the required express node module which we'll be using to construct the REST API that we will be securing.

> **Note** - We are using Express here in this particular example, but the concepts in this tutorial are framework-agnostic and can be used with other web application frameworks such as Koa.

Now that we have all of our dependencies installed, we can go ahead and write some code! Create a new file within your project directory called `index.js`.

 index.js

```js
const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port,
    () => console.log(`Simple Express app listening on port ${port}!`))
```

This is an incredibly simple application that returns `Hello World!` whenever you hit the `/` path on port `3000`. You can subsequently start this application like so:

 $ node index.js

```output
Example app listening on port 3000!
```

With this now running, navigate to `http://localhost:3000/` in your browser and you will see your application returning the expected `Hello World!` back to you.

# Adding a few Endpoints

Now that we have a basic NodeJS application up and running on port 3000, let's look at how we can extend this and add a few endpoints which we can subsequently protect.

I'm going to keep this super simple for now so that we can focus on the JWT authorization and not the underlying application.

Open up your `index.js` file once again. Let's add a few new `HTTP GET` endpoints:

 index.js

```js
const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

// let's first add a /secret api endpoint that we will be protecting
app.get('/secret', (req, res) => {
    res.json({ "message" : "THIS IS SUPER SECRET, DO NOT SHARE!" })
})

// and a /readme endpoint which will be open for the world to see
app.get('/readme', (req, res) => {
    res.json({ "message" : "This is open to the world!" })
})

app.listen(port,
    () => console.log(`Simple Express app listening on port ${port}!`))
```

Now that we have these endpoints, let's re-run our application to ensure we haven't broken anything:

 $ node index.js

```output
Simple Express app listening on port 3000!
```

Let's open up `http://localhost:3000/secret` in our browser window now that this is up and running. You will see the following response:

 http://localhost:3000/secret

```js
{
    "message": "THIS IS SUPER SECRET, DO NOT SHARE!"
}
```

And when we open up the `/readme` endpoint, we should see the following:

 http://localhost:3000/secret

```js
{
    "message": "This is open to the world!"
}
```

Perfect, in this step we have been able to add 2 additional endpoints to our application that we will be attempting to protect with JWT validation in the next step of this tutorial.

# Generating a Valid JWT

In this step, we are going to create 1 additional endpoint for our application that will return a valid JWT token for us to test out the authentication in subsequent steps.

In order for us to generate and validate these JWTs, we'll need to first import the `jsonwebtoken` node module:

```output
$ npm install --save jsonwebtoken
```

Once we have this node module installed, we can then go ahead and create a custom `/jwt` endpoint which will create a JWT token for us which features an incredibly simple payload `{ "body": "stuff" }` and is signed using a private key that I generated for a deprecated project.

Create a new file within your project direct called `private.pem` and add the following key:

 private.pem

```output
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAyVTQ9QxfutaYXKBbYfZbH2vhIWoIPEjAFSbsy1PZoIcclUQR
hJ8t2m7v47M8eEyYd7EvXTNdoN6CDs0DoNC9KESATZV5SUVr7sk9pOcMrm0VryAd
h7hQbbHWqyKmOehCt1JdX7gV2i5XnRb5qYQSyoB8sGdfR4SQ9q1XPRIpBP8RYXCP
WPmwnmtzYjfs+VVMp+ByNWgM8Qvyc3Z13tHKHWfTokbEbJJE0xfFG6CVFZy+T7uq
0UxhkWh8tekaDbfrIYtgC8HRHfRPcqvsN/pkJM0DIU4UNIf2TeLARa+iATNiF5IX
DeAAkIqoQL0tgt6S+8HIEPGiQ3gpGE56DON06QIDAQABAoIBAAvIxyJQwxmwjeJ+
EFs/jD3elqLaDflZWMTkLmAIXGik/+tMvKnCl3B9pdTyHMv9z77RxC/0XbqYy4wK
O/ghv7CnscrYwOyk/5hOdyk7zOY4xFgnzRKwmySQkDwcHxasnZsVWxnLMJxAsigj
vCFL9b2cn6/DnTQWclW996k/ct8z5DzodH/O+JyQl2MvLgjtf1OupbNZcjt4kMRP
GS5em5banlycUtPE0NAcS0QXleHLj5BXOp0AyD+PWfzhWcctiK7p+vmwXv6OVtlu
DIiTTOnsjoMq7skfVzRpjmAesllXBb1evwsrVK7cjYefEsVZ5DzOVLNU5Iug3HCf
RnftUAECgYEA6uWhJ9la1VpiYgEai4F61Rxs/MAQzmWVl0NQhPrczLCdRXfhmeBP
w1a4VkCD7FlZq/UuL4bSnU2JINL/enmrfZfdLdQgjY1VgPNki6v4Da9sqi+D17Wb
w863h/X29cukttFgUQdPO66bwsitoNVDsBqyf2hlFWC+rRPovoFA9WkCgYEA22s2
njRgoV6mTTCgXoZMs8unJ2CTd+BuVP1wDVsHR0VnK7blVlIW9Hop0ZmFK3I41kw3
3LXT6RSmZXsdgAsm3VuWlDVFY6t+JUUGYOfZZVNgUX0J597hf2SwxfJ8cgNHuSEO
glxc/dzHXMgamf8+84RCK3NSGP8xmuI/Wm5JE4ECgYEAmFelVTradlTQSc99b8zh
5SUyahoGzFWF1zyJFDW+zeIdndhKMIoSMRYlJ4tgBAFO7v9snNZL8kk/DlLJ7pzK
ZAICKJ7THfrz4VX5d7xofDexug5m65eVFkETNtKHAJK6mPbiCKs87/AmhQWx1gV6
iNRHv+ns5RiBka6/3A3oG0ECgYEAl+qIO0rqaG++1ozHTArSCl4DUlkkYQhLe56p
OSYASRE9WF/eM0DM0eHPGGahdC42OfE1cCOYH7WDa5mtGB0ggHxMKjsj2tk+kpFS
1D9SHjx24JShCiAfonNVjQfRr6KjwwKnKAzI+Z8ljRCikmLN9A5rPegvPE1by++/
i132TIECgYAiDd+OSokfZYi8mqjIoMI946+Hlb7lisb7CXksM69A+oWJrfkCwOMq
O3tExLbxtd7KZuAg1xH2thimIeT6tuCbCSAFGzr4EWCe7iavVzevHr98ivPLYXte
dyWl3YlvqO+SUuieGvHISlekblMO/4tcUscmKmo+FgkMroBsePcdEA==
-----END RSA PRIVATE KEY-----
```

Next, open up your `index.js` and add the following:

 index.js

```js
const jwt = require('jsonwebtoken');
const fs = require('fs')

// ... our other endpoints

app.get('/jwt', (req, res) => {
    let privateKey = fs.readFileSync('./private.pem', 'utf8');
    let token = jwt.sign({ "body": "stuff" }, "MySuperSecretPassPhrase", { algorithm: 'HS256'});
    res.send(token);
})

// ... the rest of our index.js
```

When we open up `http://localhost:3000/jwt` in our browser after restarting our application, we should see a valid JSON Web Token returned to us:

 http://localhost:3000/jwt

```output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJib2R5Ijoic3R1ZmYiLCJpYXQiOjE1NTg4MTUyMzl9.3Z8G-kCEfr2Xch1FnaEAOeywcVs6aJZ3sbCARybWCgM
```

Awesome, we now have a valid JWT that we can use to test the authentication we are going to be building in the next part of this tutorial!

# Authentication Middleware

Let's have a look at the authentication function which will look at an incoming request and parse it for an `Authorization` header.

 index.js

```js
function isAuthenticated(req, res, next) {
    if (typeof req.headers.authorization !== "undefined") {
        // retrieve the authorization header and parse out the
        // JWT using the split function
        let token = req.headers.authorization.split(" ")[1];
        let privateKey = fs.readFileSync('./private.pem', 'utf8');
        // Here we validate that the JSON Web Token is valid and has been
        // created using the same private pass phrase
        jwt.verify(token, privateKey, { algorithm: "HS256" }, (err, user) => {

            // if there has been an error...
            if (err) {
                // shut them out!
                res.status(500).json({ error: "Not Authorized" });
                throw new Error("Not Authorized");
            }
            // if the JWT is valid, allow them to hit
            // the intended endpoint
            return next();
        });
    } else {
        // No authorization header exists on the incoming
        // request, return not authorized and throw a new error
        res.status(500).json({ error: "Not Authorized" });
        throw new Error("Not Authorized");
    }
}
```

Now that we have this `isAuthorized` function, we can update our `/secret` endpoint to use this function as middleware.

 index.js

```js
app.get('/secret', isAuthorized, (req, res) => {
    res.json({ "message" : "THIS IS SUPER SECRET, DO NOT SHARE!" })
})
```

If we restart our application and try hitting the `/secret` endpoint once again, we should see the following response:

 http://localhost:3000/secret

```js
{
    "error": "Not Authorized"
}
```

Perfect, this has worked exactly as expected and we aren't able to access our `/secret` endpoint without the appropriate `Authorization` header set. Let's attempt to hit this endpoint with a `curl` command, we'll add the `Authorization` header and set it to `jwt` along with a valid JWT retrieved from our `/jwt` endpoint.

 curl -H "Authorization: jwt <VALID JWT>" http://localhost:3000/secret

```output
{"message":"THIS IS SUPER SECRET, DO NOT SHARE!"}%
```

Awesome, with this valid JWT in our `Authorization` header, we've been able to access the `/secret` endpoint!

# Conclusion

So, in this tutorial, we have managed to create an `isAuthenticated` middleware function that we can wrap our express API Endpoints with. This `isAuthenticated` function parses incoming `HTTP` requests to check if they have the appropriate `Authorization` header set and then checks to see whether the value of this header is a valid JWT token that has been signed with a specific private key.

> **Source Code** - The full source code for this tutorial can be found here: [TutorialEdge/node-jwt-authentication-tutorial](https://github.com/TutorialEdge/node-jwt-authentication-tutorial)

## Further Reading

If you enjoyed this article, you may also enjoy these other articles:

* [Creating a Web Server with NodeJS](/nodejs/creating-a-webserver-with-nodejs/)
* [RFC-7519 - JSON Web Tokens](https://tools.ietf.org/html/rfc7519)


text:
<!--

    Licensed under the Apache License, Version 2.0 (the "License"); you may not
    use this file except in compliance with the License. You may obtain a copy of
    the License at
        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    License for the specific language governing permissions and limitations under
    the License.

-->
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="CommandsSuite" verbose="1"
       object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
    <test name="Commands">
        <packages>
            <package name="com.github.pires.obd.commands.*"/>
        </packages>
    </test>
</suite>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE locale SYSTEM "../../../../../lib/pkp/dtd/locale.dtd">

<!--
  * plugins/oaiMetadataFormats/marcxml/locale/fa_IR/locale.xml
  *
  * Copyright (c) 2003-2013 John Willinsky
  * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  *
  * Localization strings for the en_US (U.S. English) locale.
  *
  -->

<locale name="en_US" full_name="U.S. English">
	<message key="plugins.OAIMetadata.marcxml.displayName">فرمت متاداده مارک ۲۱</message>
	<message key="plugins.OAIMetadata.marcxml.description">ساختار متاداده باید با فرمت مارک ۲۱ سازگار باشد</message>
</locale>


text:
ionicApp.directive('ionslider',function($timeout){
    return{
        restrict:'E',
        scope:{min:'=',
            max:'=',
            type:'@',
            prefix:'@',
            maxPostfix:'@',
            prettify:'@',
            grid:'@',
            gridMargin:'@',
            postfix:'@',
            step:'@',
            hideMinMax:'@',
            hideFromTo:'@',
            from:'=',
			to:'=',
            disable:'=',
            onChange:'=',
            onFinish:'=',
			values:'=',

        },
        template:'

',
        replace:true,
        link:function($scope,$element,attrs){
            (function init(){
                $element.ionRangeSlider({
                    min: $scope.min,
                    max: $scope.max,
                    type: $scope.type,
                    prefix: $scope.prefix,
                    maxPostfix: $scope.maxPostfix,
                    prettify: $scope.prettify,
                    grid: $scope.grid,
                    gridMargin: $scope.gridMargin,
                    postfix:$scope.postfix,
                    step:$scope.step,
                    hideMinMax:$scope.hideMinMax,
                    hideFromTo:$scope.hideFromTo,
                    from:$scope.from,
                    disable:$scope.disable,
                    onChange:$scope.onChange,
                    onFinish:$scope.onFinish,
					to:$scope.to,
					values:$scope.values
                });
            })();
            $scope.$watch('min', function(value) {
                $timeout(function(){ $element.data("ionRangeSlider").update({min: value}); });
            },true);
            $scope.$watch('max', function(value) {
                $timeout(function(){ $element.data("ionRangeSlider").update({max: value}); });
            });
            $scope.$watch('from', function(value) {
                $timeout(function(){ $element.data("ionRangeSlider").update({from: value}); });
            });
			$scope.$watch('to', function(value) {
                $timeout(function(){ $element.data("ionRangeSlider").update({to: value}); });
            });
            $scope.$watch('disable', function(value) {
                $timeout(function(){ $element.data("ionRangeSlider").update({disable: value}); });
            });
        }
    }
});

ionicApp.directive('selectWheel', function($ionicScrollDelegate, $ionicGesture, $window, $timeout, Lang) {
    return {
      restrict: 'E',
      scope: {
        itemHeight: '@',
        amplitude: '@',
        ngModel: '=',
        options: '=',
        index: '=',
		minWidth: '=',
		maxWidth: '=',
		type: '@',
		refresh: '=',
		usefulLength: '='
      },
      templateUrl: 'lib/slider.html',
      compile: function(element) {
        var id = 'handle-' + Math.random();
        element.find('ion-scroll').attr('delegate-handle', id);
        return function(scope, element) {
          var _fixed = true,
            scrollHandle = $ionicScrollDelegate.$getByHandle(id);
			scope.touched = false;
          scope.itemHeight = (scope.itemHeight | 0) || 50;
          scope.amplitude = (scope.amplitude | 0) || 5;

		  scope.options = scope.options || [];

		  scope.index = (scope.ngModel | 0) || -1;

		  scope.minWidth = scope.minWidth || 35;

		  scope.maxWidth = scope.maxWidth || 200;

		  scope.type = scope.type || 1;

		  scope.usefulLength = scope.usefulLength  || -1;

		  scope.lang = Lang;

          var resize = function()
		  {
			var yOffset = (scope.index + 1) * (scope.itemHeight ) - scope.itemHeight /2;
            scrollHandle.scrollTo(0, yOffset);
          };

		  scope.refresh = function refresh()
		  {
			scope.index = scope.ngModel || 0;
			resize();
		  };

		  scope.setIndex = function setIndex(i)
		  {
			scope.index = i;
			resize();
		  }

          scope.onScroll = function(event, scrollTop)
		  {
            scrollTop = Math.round(scrollTop);
            var height = scope.itemHeight,
              amplitude = scope.amplitude,
              remainder = (scrollTop  -height/2) % height ,
              distance, nearestPos,
              middle = Math.floor(height / 2),
              index,
              minDist = middle - amplitude;

            /*
             Find the distance between the item and the center:
             So if the height of the item is 50, it finds the nearest
             integer for scrollTop to reach a multiple of 50
             160 = 3 * 50 + 10 => For 160, the distance is 10
             145 = 3 * 50 - 5 => For 145, the distance is 5
             */
            if (remainder > middle) {
              distance = height - remainder;
              nearestPos = scrollTop + distance;
              index = Math.floor((scrollTop- scope.itemHeight/2)/ height) + 1;
            } else {
              distance = remainder;
              nearestPos = scrollTop - distance;
              index = Math.floor((scrollTop - scope.itemHeight/2)/ height);
            }

			var usedLength = scope.usefulLength > 0 ? scope.usefulLength : scope.options.length;

			if(index < 0)
			{
				index = 0;
				nearestPos = +scope.itemHeight/2;
			}
			else if(index >= usedLength && usedLength > 0)
			{
				index = usedLength-1;
				nearestPos = scope.itemHeight*(index)+ scope.itemHeight/2;
			}

			if(scope.index != index)
			{
				scope.$apply(function() {
					scope.index = index;
				  });

				try { navigator.notification.vibrate(10); }
				catch(e) {}
			}

			if (!scope.touched && !_fixed)
			{
				if(nearestPos != scrollTop)
					scrollHandle.scrollTo(0, nearestPos);
				_fixed = true;
				scope.$apply(function() {
					scope.ngModel = scope.index;
				  });
			}
          };

          // Bind events
          angular.element($window).bind('resize', resize);

          var unWatchModel = scope.$watch('ngModel', function(newVal) {
            if (typeof newVal != 'undefined' && newVal != scope.index/*&& newVal*/)
			{

			   scope.index = newVal;
			   //resize();
            }

          });

		  var unWatchOptions = scope.$watch('options', function(newVal) {
            if (newVal) {

				//scope.options = newVal;

				var usedLength = scope.usefulLength > 0 ? scope.usefulLength : scope.options.length;

				if(usedLength > 0)
				{
					if(scope.index >= usedLength)
					{
						scope.index = usedLength-1;
					}

					resize();
				}
			}

          });

		  var unWatchUsedLength = scope.$watch('usefulLength', function(newVal) {
            if (newVal) {

				//scope.usefulLength = newVal;

				if(newVal > 0)
				{
					if(scope.index >= newVal)
					{
						scope.index = newVal-1;
					}

					resize();
				}
			}

          });

          $ionicGesture.on('touch', function() {
            scope.touched = true;
            _fixed = false;
          }, element, {});

          $ionicGesture.on('release', function() {
            scope.touched = false;
          }, element, {});

          scope.$on('destroy', function() {
            // Unbind events
            $ionicGesture.off('touch', element);
            $ionicGesture.off('release', element);
            angular.element($window).off('resize', resize);
            unWatchModel();
			unWatchOptions();
			unWatchUsedLength();
          });

          // Resize on start
		  $timeout(resize());
        };

      },
    };
  });


text:
class AddMissingUniquenessIndexes < ActiveRecord::Migration
  def up
    add_index :additional_registrant_accesses, [:registrant_id, :user_id], unique: true, name: "ada_reg_user"

    add_index :age_group_entries, [:age_group_type_id, :short_description], unique: true, name: "age_type_desc"

    add_index :age_group_types, :name, unique: true

    add_index :boundary_scores, [:judge_id, :competitor_id], unique: true

    add_index :combined_competitions, :name, unique: true

    add_index :competition_wheel_sizes, [:registrant_id, :event_id], unique: true

    add_index :event_categories, [:event_id, :name], unique: true
    add_index :event_categories, [:event_id, :position], unique: true

    add_index :event_choices, :export_name, unique: true
    remove_index :event_choices, name: :index_event_choices_event_id
    add_index :event_choices, [:event_id, :position], unique: true

    add_index :heat_times, [:competition_id, :heat], unique: true

    add_index :judges, [:judge_type_id, :competition_id, :user_id], unique: true

    add_index :judge_types, :name, unique: true

    add_index :lane_assignments, [:competition_id, :heat, :lane], unique: true

    add_index :registrant_choices, [:registrant_id, :event_choice_id], unique: true

    add_index :registrant_event_sign_ups, [:registrant_id, :event_id], unique: true

    add_index :registrant_group_members, [:registrant_id, :registrant_group_id], unique: true, name: "reg_group_reg_group"

    add_index :results, [:competitor_id, :result_type], unique: true

    add_index :scores, [:competitor_id, :judge_id], unique: true

    add_index :songs, [:user_id, :registrant_id, :event_id], unique: true

    add_index :standard_difficulty_scores, [:judge_id, :standard_skill_routine_entry_id, :competitor_id], unique: true, name: "standard_diff_judge_routine_comp"

    add_index :standard_execution_scores, [:judge_id, :standard_skill_routine_entry_id, :competitor_id], unique: true, name: "standard_exec_judge_routine_comp"

    add_index :standard_skill_entries, [:letter, :number], unique: true

    add_index :standard_skill_routines, :registrant_id, unique: true

    add_index :tie_break_adjustments, [:competitor_id, :judge_id], unique: true

    # has_one

    add_index :competitions, :combined_competition_id, unique: true

    add_index :tie_break_adjustments, :competitor_id, unique: true

    remove_index :refund_details, :payment_detail_id
    add_index :refund_details, :payment_detail_id, unique: true

    add_index :contact_details, :registrant_id, unique: true
  end

  def down
    remove_index :additional_registrant_accesses, name: "ada_reg_user"

    remove_index :age_group_entries, name: "age_type_desc"

    remove_index :age_group_types, :name

    remove_index :boundary_scores, [:judge_id, :competitor_id]

    remove_index :combined_competitions, :name

    remove_index :competition_wheel_sizes, [:registrant_id, :event_id]

    remove_index :event_categories, [:event_id, :name]
    remove_index :event_categories, [:event_id, :position]

    remove_index :event_choices, :export_name
    remove_index :event_choices, [:event_id, :position]
    add_index :event_choices, [:event_id, :position], name: :index_event_choices_event_id

    remove_index :heat_times, [:competition_id, :heat]

    remove_index :judges, [:judge_type_id, :competition_id, :user_id]

    remove_index :judge_types, :name

    remove_index :lane_assignments, [:competition_id, :heat, :lane]

    remove_index :registrant_choices, [:registrant_id, :event_choice_id]

    remove_index :registrant_event_sign_ups, [:registrant_id, :event_id]

    remove_index :registrant_group_members, name: "reg_group_reg_group"

    remove_index :results, [:competitor_id, :result_type]

    remove_index :scores, [:competitor_id, :judge_id]

    remove_index :songs, [:user_id, :registrant_id, :event_id]

    remove_index :standard_difficulty_scores, name: "standard_diff_judge_routine_comp"

    remove_index :standard_execution_scores, name: "standard_exec_judge_routine_comp"

    remove_index :standard_skill_entries, [:letter, :number]

    remove_index :standard_skill_routines, :registrant_id

    remove_index :tie_break_adjustments, [:competitor_id, :judge_id]

    # has_one

    remove_index :competitions, :combined_competition_id

    remove_index :tie_break_adjustments, :competitor_id

    remove_index :refund_details, :payment_detail_id
    add_index :refund_details, :payment_detail_id

    remove_index :contact_details, :registrant_id
  end
end


text:
/*
 * @name Sístemas-L
 * @description Este bosquejo crea un dibujo automatizado basado en un sistema Lindenmayer
 * o sistema-L. Los sistemas-L son utilizados a menudo en gráfica procedural para hacer
 * patrones naturales, geométricos o de tipo fractal.

 * Ejemplo creado por R. Luke DuBois.

 * https://en.wikipedia.org/wiki/L-system
 */
// SECCIÓN TORTUGA:
let x, y; // la posición actual de la tortuga
let currentangle = 0; // hacia dónde apunta la tortuga
let step = 20; // cuánto se mueve la tortuga en cada 'F'
let angle = 90; // cuánto gira la tortuga con un '-' or '+'

// SECCIÓN LINDENMAYER (SISTEMAS-L)
let thestring = 'A'; // "axioma" o inicio de la cadena
let numloops = 5; // cuántas iteraciones a pre-computar
let therules = []; // arreglo para las reglas
therules[0] = ['A', '-BF+AFA+FB-']; // primera regla
therules[1] = ['B', '+AF-BFB-FA+']; // segunda regla

let whereinstring = 0; // dónde estamos en el sistema-L

function setup() {
  createCanvas(710, 400);
  background(255);
  stroke(0, 0, 0, 255);

  // inicializar la posición x e y en la esquina inferior izquierda
  x = 0;
  y = height - 1;

  // CALCULAR EL SISTEMA-L
  for (let i = 0; i < numloops; i++) {
    thestring = lindenmayer(thestring);
  }
}

function draw() {

  // dibujar el caracter actual en la pantalla
  drawIt(thestring[whereinstring]);

  // incrementar el punto de donde leemos la cadena.
  // si sobrepasamos el final, volver al inicio.
  whereinstring++;
  if (whereinstring > thestring.length - 1) whereinstring = 0;

}

// interpretar un sistema-L
function lindenmayer(s) {
  let outputstring = ''; // inicializar una cadena de salida en blanco

  // iterar a lo largo de las  'reglas' buscando coincidencias de símbolo:
  for (let i = 0; i < s.length; i++) {
    let ismatch = 0; // por defecto, sin coincidencia
    for (let j = 0; j < therules.length; j++) {
      if (s[i] == therules[j][0])  {
        outputstring += therules[j][1]; //escribir substitución
        ismatch = 1; //si  tenemos una coincidencia, no copiemos el símbolo
        break; // salir de este bucle for()
      }
    }
    // si nada coincide, simplemente copia el símbolo.
    if (ismatch == 0) outputstring += s[i];
  }

  return outputstring; // enviar la cadena modificada
}

// esta es una función que dibuja los comandos de la tortuga
function drawIt(k) {

  if (k=='F') { // dibujar hacia adelante
    // de polar a cartesiano basado en paso y ángulo actual:
    let x1 = x + step * cos(radians(currentangle));
    let y1 = y + step * sin(radians(currentangle));
    line(x, y, x1, y1); // conectar el anterior y el nuevo

    // actualizar la posición de la tortuga:
    x = x1;
    y = y1;
  } else if (k == '+') {
    currentangle += angle; // doblar hacia la izquierda
  } else if (k == '-') {
    currentangle -= angle; // doblar hacia la derecha
  }

  // valores aleatorios de color:
  let r = random(128, 255);
  let g = random(0, 192);
  let b = random(0, 50);
  let a = random(50, 100);

  // escoger una distribución gaussiana (D&D) para el radio:
  let radius = 0;
  radius += random(0, 15);
  radius += random(0, 15);
  radius += random(0, 15);
  radius = radius / 3;

  // dibujar:
  fill(r, g, b, a);
  ellipse(x, y, radius, radius);
}


text:
namespace flare {
	class Mesh_Platform;

	class Mesh {
	public:
		std::vector<Vertex> m_vertices;
		std::vector<unsigned int> m_vertexIndices;

		Mesh();
		~Mesh();
	protected:
		friend class Model;
		void Refresh( Renderer::GraphicsAPI a_api );

		Mesh_Platform* m_pMesh;
	private:

	};
}


text:
.PHONY: setup
setup:
	setup-blog -d . -n database.db --create-database -u admin --gen-config

.PHONY: certs
certs:
	sudo ./bin/gen-key.sh --self-signed

.PHONY: start
start: create
	docker-compose -f docker-compose.yml up -d cjblog

.PHONY: dev-server
dev-server: create
	docker-compose -f docker-compose.yml up cjblog

.PHONY: create
create: clean
	docker-compose -f docker-compose.yml build cjblog

.PHONY: clean
clean:
	docker-compose -f docker-compose.yml down


text:
require 'spec_helper'

describe SaasRunner::Client, :vcr do
  let(:client) { SaasRunner::Client.new(api_key: "00b4040a-ed54-4524-a33e-f992298383cc") }
  let(:subscriber_uid) { "sub#{Time.now.to_i}" }

  describe "activations" do
    it "should add an activation" do
      resource = client.activations
      resource.create!(subscriber_uid: subscriber_uid)
      expect(resource.response.status).to eq(201)
    end
  end
end


text:
**1. Accuracy of 86% achieved for "Naive Bayes Model"**

* Naïve Bayes Model is well trained and implemented to attain a overall accuracy of 86% that was achieved by splitting up the training
and testing set in a ratio of 7:3 as learnt from the coursera machine learning course.

**2. Training (70%) and Testing (30%)**

* A total of 10944 rows of text were made to undergo training and testing out of which 7660 rows of text were used for training and
3284 rows of text were used for testing. I attained this accuracy after days of training started from few sets of data, gradually
increased and ultimately ended up with this result.

**3.  Quality of data**

* Quality (structure) of data is also one factor that determines the accuracy of the model. Accuracy can be attained even more
by increasing the data set for training.

**4.  Usefulness of the proposed work**

* People would find this proposed work, an application helpful as it crunches the huge opinions of tweeple about the movie in numbers and emotions that reflect the state of mind of the tweeple.


text:
class RemindersController < ApplicationController
  def self.attestation_day
    User.available.each do |user|
      if (Date.today.mjd - user.hire_date.mjd) - 60 == 0 || (Date.today.mjd - user.hire_date.mjd) % 180 == 0
        NotifMailer.attestation(user).deliver_now!
      end
    end
  end

  def self.birth_dates
    User.available.each do |user|
      if user.birth_date.strftime("%m") == (Date.today + 10).strftime("%m") && user.birth_date.strftime("%d") == (Date.today + 10).strftime("%d")
        NotifMailer.birth_dates(user).deliver_now!
      end
    end
  end
end


text:
package com.hazelcast.client.impl.protocol.codec;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.Generated;
import com.hazelcast.client.impl.protocol.codec.builtin.*;
import com.hazelcast.client.impl.protocol.codec.custom.*;

import javax.annotation.Nullable;

import static com.hazelcast.client.impl.protocol.ClientMessage.*;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;

/*
 * This file is auto-generated by the Hazelcast Client Protocol Code Generator.
 * To change this file, edit the templates or the protocol
 * definitions on the https://github.com/hazelcast/hazelcast-client-protocol
 * and regenerate it.
 */

/**
 * Adds a new cardinality estimator configuration to a running cluster.
 * If a cardinality estimator configuration with the given {@code name} already exists, then
 * the new configuration is ignored and the existing one is preserved.
 */
@Generated("dc92f32aa090ba2600d6da132447d73e")
public final class DynamicConfigAddCardinalityEstimatorConfigCodec {
    //hex: 0x1B0300
    public static final int REQUEST_MESSAGE_TYPE = 1770240;
    //hex: 0x1B0301
    public static final int RESPONSE_MESSAGE_TYPE = 1770241;
    private static final int REQUEST_BACKUP_COUNT_FIELD_OFFSET = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int REQUEST_ASYNC_BACKUP_COUNT_FIELD_OFFSET = REQUEST_BACKUP_COUNT_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int REQUEST_MERGE_BATCH_SIZE_FIELD_OFFSET = REQUEST_ASYNC_BACKUP_COUNT_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int REQUEST_INITIAL_FRAME_SIZE = REQUEST_MERGE_BATCH_SIZE_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES;

    private DynamicConfigAddCardinalityEstimatorConfigCodec() {
    }

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"})
    public static class RequestParameters {

        /**
         * name of the cardinality estimator configuration
         */
        public java.lang.String name;

        /**
         * number of synchronous backups
         */
        public int backupCount;

        /**
         * number of asynchronous backups
         */
        public int asyncBackupCount;

        /**
         * name of an existing configured split brain protection to be used to determine the minimum number of members
         * required in the cluster for the lock to remain functional. When {@code null}, split brain protection does not
         * apply to this lock configuration's operations.
         */
        public @Nullable java.lang.String splitBrainProtectionName;

        /**
         * Name of a class implementing SplitBrainMergePolicy that handles merging of values for this cache
         * while recovering from network partitioning.
         */
        public java.lang.String mergePolicy;

        /**
         * Number of entries to be sent in a merge operation.
         */
        public int mergeBatchSize;
    }

    public static ClientMessage encodeRequest(java.lang.String name, int backupCount, int asyncBackupCount, @Nullable java.lang.String splitBrainProtectionName, java.lang.String mergePolicy, int mergeBatchSize) {
        ClientMessage clientMessage = ClientMessage.createForEncode();
        clientMessage.setRetryable(false);
        clientMessage.setOperationName("DynamicConfig.AddCardinalityEstimatorConfig");
        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);
        encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE);
        encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1);
        encodeInt(initialFrame.content, REQUEST_BACKUP_COUNT_FIELD_OFFSET, backupCount);
        encodeInt(initialFrame.content, REQUEST_ASYNC_BACKUP_COUNT_FIELD_OFFSET, asyncBackupCount);
        encodeInt(initialFrame.content, REQUEST_MERGE_BATCH_SIZE_FIELD_OFFSET, mergeBatchSize);
        clientMessage.add(initialFrame);
        StringCodec.encode(clientMessage, name);
        CodecUtil.encodeNullable(clientMessage, splitBrainProtectionName, StringCodec::encode);
        StringCodec.encode(clientMessage, mergePolicy);
        return clientMessage;
    }

    public static DynamicConfigAddCardinalityEstimatorConfigCodec.RequestParameters decodeRequest(ClientMessage clientMessage) {
        ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();
        RequestParameters request = new RequestParameters();
        ClientMessage.Frame initialFrame = iterator.next();
        request.backupCount = decodeInt(initialFrame.content, REQUEST_BACKUP_COUNT_FIELD_OFFSET);
        request.asyncBackupCount = decodeInt(initialFrame.content, REQUEST_ASYNC_BACKUP_COUNT_FIELD_OFFSET);
        request.mergeBatchSize = decodeInt(initialFrame.content, REQUEST_MERGE_BATCH_SIZE_FIELD_OFFSET);
        request.name = StringCodec.decode(iterator);
        request.splitBrainProtectionName = CodecUtil.decodeNullable(iterator, StringCodec::decode);
        request.mergePolicy = StringCodec.decode(iterator);
        return request;
    }

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"})
    public static class ResponseParameters {
    }

    public static ClientMessage encodeResponse() {
        ClientMessage clientMessage = ClientMessage.createForEncode();
        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);
        encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE);
        clientMessage.add(initialFrame);

        return clientMessage;
    }

    public static DynamicConfigAddCardinalityEstimatorConfigCodec.ResponseParameters decodeResponse(ClientMessage clientMessage) {
        ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();
        ResponseParameters response = new ResponseParameters();
        //empty initial frame
        iterator.next();
        return response;
    }

}


text:
<?php

namespace Mcwork\Mapper\Blog;

use ContentinumComponents\Mapper\Worker;

/**
 * Query contents for this request
 *
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 */
class Article extends Worker
{
    /**
     * Content query
     * @param array $params query conditions
     * @return multitype:
     */
    public function fetchContent(array $params = null)
    {
        return $this->getStorage()->getRepository( $this->getEntityName() )->findBy(array('contentGroupName' => 'news'),array('publishDate' => 'DESC'),250,0);
    }

    /**
     *
     * @param array $params
     * @param string $posts
     */
    public function processRequest(array $params = null, $posts = null)
    {
        if (is_array($posts)){
            $params = array_merge($params,$posts);
        }
        return $this->fetchContent($params);
    }
}


text:
void parse_pmt_input(void);
void parse_pmt_data(void);
void parse_pmt_empty_data(void);

int main(int argc, char **argv)
{
    parse_pmt_input();
    parse_pmt_data();
    parse_pmt_empty_data();
    return 0;
}

void parse_pmt_input(void)
{
    test_start("parse pmt input");

    TSDemuxContext ctx;
    TSDCode res;
    TSDPMTData pmt;
    memset(&pmt, 0, sizeof(pmt));

    uint8_t data[] = {
        0x01, 0x02, 0x03, 0x04
    };

    res = tsd_parse_pmt(NULL, NULL, 0, NULL);
    test_assert_equal(TSD_INVALID_CONTEXT, res, "invalid context");
    res = tsd_parse_pmt(&ctx, NULL, 0, NULL);
    test_assert_equal(TSD_INVALID_DATA, res, "invalid data");
    res = tsd_parse_pmt(&ctx, data, 0, NULL);
    test_assert_equal(TSD_INVALID_DATA_SIZE, res, "invalid size");
    res = tsd_parse_pmt(&ctx, data, sizeof(data), NULL);
    test_assert_equal(TSD_INVALID_ARGUMENT, res, "invalid TSDPMTData");

    test_end();
}

void parse_pmt_data(void)
{
    test_start("parse pmt data");

    TSDemuxContext ctx;
    TSDPMTData pmt;
    TSDCode res;

    tsd_context_init(&ctx);
    memset(&pmt, 0, sizeof(pmt));

    uint8_t data[] = {
        0xE0, 0x99, // PCR PID = 0x99
        0xF0, 0x09, // program info length = 9
        0x9A, 0x03, 0xFA, 0xFA, 0xFA, // program descriptor
        0x8B, 0x02, 0xBB, 0xCC, // program descriptor
        0xEF, // stream type
        0xE0, 0x3E, // elementary PID
        0xF0, 0x03, // ES Info Length = 3
        0x11, 0x01, 0x12, // descriptor
        0x44, // stream type
        0xE1, 0x51, // elementary PID
        0xF0, 0x0A, // ES Info Length = 10
        0x19, 0x03, 0x2B, 0x45, 0xFE, // descriptor
        0x18, 0x03, 0xB2, 0x54, 0xEF, // descriptor
        0xCC, 0xCC, 0xEE, 0x54, // CRC32
    };

    res = tsd_parse_pmt(&ctx, data, sizeof(data), &pmt);
    test_assert_equal(TSD_OK, res, "parse valid data");
    test_assert_equal(0x99, pmt.pcr_pid, "PCR PID");
    test_assert_equal(0x09, pmt.program_info_length, "program info length");
    test_assert_equal(2, pmt.descriptors_length, "descriptors length");
    test_assert_equal(0x9A, pmt.descriptors[0].tag, "descriptor tag 1");
    test_assert_equal(0x03, pmt.descriptors[0].length, "descriptor length 1");
    test_assert_equal(0x05, pmt.descriptors[0].data_length, "descriptor data length 1");
    test_assert_equal(memcmp(pmt.descriptors[0].data, &data[4], 3), 0, "descriptor data 1");
    test_assert_equal(0x8B, pmt.descriptors[1].tag, "descriptor tag 2");
    test_assert_equal(0x02, pmt.descriptors[1].length, "descriptor length 2");
    test_assert_equal(0x04, pmt.descriptors[1].data_length, "descriptor data length 2");
    test_assert_equal(memcmp(pmt.descriptors[1].data, &data[9], 2), 0, "descriptor data 2");
    test_assert_equal(2, pmt.program_elements_length, "program elements length");

    test_assert_equal(0xEF, pmt.program_elements[0].stream_type, "stream tpye 1");
    test_assert_equal(0x003E, pmt.program_elements[0].elementary_pid, "elementary pid 1");
    test_assert_equal(0x03, pmt.program_elements[0].es_info_length, "es info lenth 1");
    test_assert_equal(1, pmt.program_elements[0].descriptors_length, "program elements descriptor length 1");
    test_assert_equal(0x11, pmt.program_elements[0].descriptors[0].tag, "program elements descriptor tag 1");
    test_assert_equal(1, pmt.program_elements[0].descriptors[0].length, "program elements descriptor length 1");
    test_assert_equal(3, pmt.program_elements[0].descriptors[0].data_length, "program elements descriptor data length 1");
    test_assert_equal(memcmp(pmt.program_elements[0].descriptors[0].data, &data[18], 1), 0, "program element descriptor data 1");

    test_assert_equal(0x44, pmt.program_elements[1].stream_type, "stream type 1");
    test_assert_equal(0x0151, pmt.program_elements[1].elementary_pid, "elementary pid 1");
    test_assert_equal(0x0A, pmt.program_elements[1].es_info_length, "es info lenth 1");
    test_assert_equal(2, pmt.program_elements[1].descriptors_length, "program elements 2 descriptor length 1");
    test_assert_equal(0x19, pmt.program_elements[1].descriptors[0].tag, "program elements 2 descriptor tag 1");
    test_assert_equal(3, pmt.program_elements[1].descriptors[0].length, "program elements 2 descriptor length 1");
    test_assert_equal(5, pmt.program_elements[1].descriptors[0].data_length, "program elements 2 descriptor data length 1");
    test_assert_equal(memcmp(pmt.program_elements[1].descriptors[0].data, &data[26], 3), 0, "program element 2 descriptor data 1");
    test_assert_equal(0x18, pmt.program_elements[1].descriptors[1].tag, "program elements 2 descriptor tag 2");
    test_assert_equal(3, pmt.program_elements[1].descriptors[1].length, "program elements 2 descriptor length 2");
    test_assert_equal(5, pmt.program_elements[1].descriptors[1].data_length, "program elements 2 descriptor data length 2");
    test_assert_equal(memcmp(pmt.program_elements[1].descriptors[1].data, &data[31], 3), 0, "program element 2 descriptor data 2");

    test_assert_equal(0xCCCCEE54, pmt.crc_32, "crc32");

    test_end();
}

void parse_pmt_empty_data(void)
{
    test_start("parse pmt empty data");

    TSDemuxContext ctx;
    TSDPMTData pmt;
    TSDCode res;

    tsd_context_init(&ctx);
    memset(&pmt, 0, sizeof(pmt));

    uint8_t data[] = {
        0xE0, 0x99, // PCR PID = 0x99
        0xF0, 0x00, // program info length = 9
        0xEF, // stream type
        0xE0, 0x3E, // elementary PID
        0xF0, 0x00, // ES Info Length = 0
        0x44, // stream type
        0xE1, 0x51, // elementary PID
        0xF0, 0x00, // ES Info Length = 10
        0xCC, 0xCC, 0xEE, 0x54, // CRC32
    };

    res = tsd_parse_pmt(&ctx, data, sizeof(data), &pmt);
    test_assert_equal(TSD_OK, res, "parse valid data");
    test_assert_equal(0x99, pmt.pcr_pid, "PCR PID");
    test_assert_equal(0x00, pmt.program_info_length, "program info length");
    test_assert_equal(0, pmt.descriptors_length, "descriptors length");
    test_assert_equal(2, pmt.program_elements_length, "program elements length");
    test_assert_equal(0xEF, pmt.program_elements[0].stream_type, "stream tpye 1");
    test_assert_equal(0x003E, pmt.program_elements[0].elementary_pid, "elementary pid 1");
    test_assert_equal(0x00, pmt.program_elements[0].es_info_length, "es info lenth 1");
    test_assert_equal(0, pmt.program_elements[0].descriptors_length, "program elements descriptor length 1");
    test_assert_equal(0x44, pmt.program_elements[1].stream_type, "stream type 1");
    test_assert_equal(0x0151, pmt.program_elements[1].elementary_pid, "elementary pid 1");
    test_assert_equal(0x00, pmt.program_elements[1].es_info_length, "es info lenth 1");
    test_assert_equal(0, pmt.program_elements[1].descriptors_length, "program elements 2 descriptor length 1");
    test_assert_equal(0xCCCCEE54, pmt.crc_32, "crc32");

    test_end();
}


text:
from setuptools import setup

setup(
    name = 'JSONMapper',
    version = '0.1',
    description = 'Python JSON mapper',
    long_description = '',
    author = 'Matt Good',
    author_email = 'matt@matt-good.net',
    license = 'BSD',
    url = '',
    packages = ['jsonmapper'],
)


text:
$A.bind(window, "load", function() {
  // Configure ARIA Tabs

  $A.setTabs(
    "a.accTab",
    {
      // Set the AccDC Object to render literal content
      mode: 0,

      // Allow tabs to be toggled
      // isToggle: true,

      // Customize the Start and End boundary text keywords for screen reader users for localization if needed
      role: "Tab",
      accStart: "Start",
      accEnd: "End",

      // Customize the heading level for screen reader users (defaults to 3 if omitted)
      ariaLevel: 2,

      // Set a className that will be added to the triggering element for the currently active tab
      toggleClass: "active"

      // Any other AccDC API properties and methods can be applied here as overrides if desired
    },
    true,
    document,
    function(dc) {
      // Optional callback that runs after a tab finishes loading
      // 'this' refers to the triggering element
      // E.G alert( this.id )
      // 'dc' refers to the current AccDC Object for the tab content, so all AccDC API properties and methods apply to this object as well.
      // E.G The property dc.containerDiv provides access to the DOM node where the tab content is rendered
      // alert(dc.containerDiv.innerHTML);
    }
  );
});


text:
module Types
  class SiteAggFieldType < Types::BaseObject
    field :name, String, null: false
    field :rank, Integer, null: true
    field :auto_suggest, Boolean, null: false
    field :display, FieldDisplayType, null: false
    field :display_name, String,null: false
    field :agg_sublabel, String, null: true
    field :preselected, SiteSelectType, null: false
    field :visible_options, SiteSelectType, null: false
    field :order, SiteOrderType, null:true
    field :range_start_label, String, null: true
    field :range_end_label, String, null: true
    field :bucket_key_value_pairs, [BucketKeyValuePairsType], null: true
    field :show_allow_missing,  Boolean, null: true
    field :show_filter_toolbar,  Boolean, null: true
    field :default_to_open, Boolean, null: true
    field :layout, String, null: true
    field :max_crumbs, Integer, null: true

    def display
      object[:display]
    end
    def display_name
      object[:displayName]
    end

    def agg_sublabel
      object[:aggSublabel]
    end

    def auto_suggest
      object[:autoSuggest]
    end

    def visible_options
      object[:visibleOptions]
    end
    def range_start_label
      object[:rangeStartLabel]
    end
    def range_end_label
      object[:rangeEndLabel]
    end

    def bucket_key_value_pairs
      object[:bucketKeyValuePairs]
    end

    def show_allow_missing
      object[:showAllowMissing]
    end
    def show_filter_toolbar
      object[:showFilterToolbar]
    end

    def default_to_open
      object[:defaultToOpen]
    end

    def layout
      object[:layout]
    end
    def max_crumbs
      object[:maxCrumbs]
    end

  end
end


text:
<?xml version="1.0"?>
<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist">
<emItems>
  <emItem id="restartless-addon@quality.mozilla.org" blockID="em1">
    <versionRange security="0">
      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
        <versionRange minVersion="3.5.*" maxVersion="*"/>
      </targetApplication>
    </versionRange>
  </emItem>
  <emItem id="restartless-inlinesettings@quality.mozilla.org" blockID="em1">
    <versionRange severity="1">
      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
        <versionRange minVersion="3.5.*" maxVersion="*"/>
      </targetApplication>
    </versionRange>
  </emItem>
</emItems>
</blocklist>