text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Models.Common;
using Models.ProfileModels;
using EM = Data;
using Utilities;
using Views = Data.Views;
using ViewContext = Data.Views.CTIEntities1;
namespace Factories
{
	public class DurationProfileManager : BaseFactory
	{
		#region persistance ==================

		public bool Save( DurationProfile profile, int userId, ref List<string> messages )
		{
			bool isValid = true;
			if ( profile == null || profile.EntityId == 0 )
			{
				messages.Add( "Error: the parent identifier was not provided." );
                return false;
            }

			int count = 0;

			EM.Entity_DurationProfile efEntity = new EM.Entity_DurationProfile();

			using ( var context = new Data.CTIEntities() )
			{
				//check add/updates first

				bool isEmpty = false;

				if ( ValidateDurationProfile( profile, ref isEmpty, ref messages ) == false )
				{
					return false;
				}
				if ( isEmpty )
				{
					messages.Add( "Error - no data was entered." );
					return false;
				}

				//just in case
				//profile.ParentTypeId = parent.EntityTypeId;

				if ( profile.Id == 0 )
				{
					//How to check if already exists for parent?
					//add
					efEntity = new EM.Entity_DurationProfile();
					MapToDB( profile, efEntity );
					efEntity.EntityId = profile.EntityId;
					efEntity.Created = efEntity.LastUpdated = DateTime.Now;
					efEntity.CreatedById = efEntity.LastUpdatedById = userId;

					//LoggingHelper.DoTrace( 2, string.Format( "DurationProfileManager.DurationProfile_Update. EntityId: {0} DOING ADD - context.Add: ", profile.EntityId ) );

					context.Entity_DurationProfile.Add( efEntity );
					count = context.SaveChanges();
					//update profile record so doesn't get deleted
					profile.Id = efEntity.Id;

					if ( count == 0 )
					{
						messages.Add( " Unable to add Duration Profile" ) ;
						isValid = false;
					}
				}
				else
				{
					efEntity = context.Entity_DurationProfile.SingleOrDefault( s => s.Id == profile.Id );
					if ( efEntity != null && efEntity.Id > 0 )
					{
						//update
						MapToDB( profile, efEntity );
						//has changed?
						if ( HasStateChanged( context ) )
						{
							//note: testing - the latter may be true if the child has changed - but shouldn't as the mapping only updates the parent
							efEntity.LastUpdated = System.DateTime.Now;
							efEntity.LastUpdatedById = userId;

							count = context.SaveChanges();
						}
					}
					else
					{
						//??? shouldn't happen unless deleted somehow
						messages.Add( " Unable to update Duration Profile - the profile was not found." );
					}
				}
			}

			return isValid;
		}
		public bool DurationProfile_Delete( int recordId, ref string statusMessage )
		{
			bool isOK = true;
			using ( var context = new Data.CTIEntities() )
			{
				EM.Entity_DurationProfile p = context.Entity_DurationProfile.FirstOrDefault( s => s.Id == recordId );
				if ( p != null && p.Id > 0 )
				{
					context.Entity_DurationProfile.Remove( p );
					int count = context.SaveChanges();
				}
				else
				{
					statusMessage = string.Format( "DurationProflie record was not found: {0}", recordId );
					isOK = false;
				}
			}
			return isOK;

		}
        public bool DeleteAll( Guid parentUid, int typeId, ref List<string> messages )
        {
            bool isValid = true;
            Entity parent = EntityManager.GetEntity( parentUid );
            if ( parent == null || parent.Id == 0 )
            {
                messages.Add( "Error - the provided target parent entity was not found." );
                return false;
            }
            using ( var context = new EM.CTIEntities() )
            {
                if ( typeId == 3 ) //renewal frequency only
                {
                    context.Entity_DurationProfile.RemoveRange( context.Entity_DurationProfile
                        .Where( s => s.EntityId == parent.Id
                        && s.TypeId == typeId ) );
                }
                else
                {
                    context.Entity_DurationProfile.RemoveRange( context.Entity_DurationProfile
                        .Where( s => s.EntityId == parent.Id
                        && s.TypeId < 3 ) );
                }
                int count = context.SaveChanges();
                if ( count > 0 )
                {
                    isValid = true;
                }
            }

            return isValid;
        }
        ///
		private void MapToDB( DurationProfile from, EM.Entity_DurationProfile to )
		{
			int totalMinutes = 0;
			to.Id = from.Id;
			//make sure EntityId is not wiped out. Also can't actually chg
			if ( (to.EntityId ?? 0) == 0)
				to.EntityId = from.EntityId;

			if ( to.Id == 0 )
			{
				//to.ParentUid = from.ParentUid;
				//to.ParentTypeId = from.ParentTypeId;
			}

			//TODO - remove profileName
			to.ProfileName = from.ProfileName ?? "";
			to.DurationComment = from.Description;

			bool hasExactDuration = false;
			bool hasRangeDuration = false;
			if ( HasDurationItems( from.ExactDuration ) )
				hasExactDuration = true;
			if ( HasDurationItems( from.MinimumDuration ) || HasDurationItems( from.MaximumDuration ) )
				hasRangeDuration = true;

			to.TypeId = 0;
			//validations should be done before here
			if ( hasExactDuration )
			{
				//if ( hasRangeDuration )
				//{
				//	//inconsistent, take exact for now
				//	ConsoleMessageHelper.SetConsoleErrorMessage( "Error - you must either enter just an exact duration or a 'from - to' duration, not both. For now, the exact duration was used", "", false );
				//}
				to.FromYears = from.ExactDuration.Years;
				to.FromMonths = from.ExactDuration.Months;
				to.FromWeeks = from.ExactDuration.Weeks;
				to.FromDays = from.ExactDuration.Days;
				to.FromHours = from.ExactDuration.Hours;

				to.FromMinutes  = from.ExactDuration.Minutes;
				to.FromDuration = AsSchemaDuration( from.ExactDuration, ref totalMinutes );
                to.AverageMinutes = totalMinutes;

				to.TypeId = from.DurationProfileTypeId == 3 ? from.DurationProfileTypeId : 1 ;
				//reset any to max duration values
				to.ToYears = null;
				to.ToMonths = null;
				to.ToWeeks = null;
				to.ToDays = null;
				to.ToHours = null;
				to.ToMinutes = null;
				to.ToDuration = "";
			}
			else if ( hasRangeDuration )
			{
				to.FromYears = from.MinimumDuration.Years;
				to.FromMonths = from.MinimumDuration.Months;
				to.FromWeeks = from.MinimumDuration.Weeks;
				to.FromDays = from.MinimumDuration.Days;
				to.FromHours = from.MinimumDuration.Hours;
				to.FromMinutes = from.MinimumDuration.Minutes;
				to.FromDuration = AsSchemaDuration( from.MinimumDuration, ref totalMinutes );
                int fromMin = totalMinutes;
				to.ToYears = from.MaximumDuration.Years;
				to.ToMonths = from.MaximumDuration.Months;
				to.ToWeeks = from.MaximumDuration.Weeks;
				to.ToDays = from.MaximumDuration.Days;
				to.ToHours = from.MaximumDuration.Hours;
				to.ToMinutes = from.MaximumDuration.Minutes;
				to.ToDuration = AsSchemaDuration( from.MaximumDuration, ref totalMinutes );
				to.TypeId = 2;
                to.AverageMinutes = ( fromMin + totalMinutes ) / 2;
			}

		}

		private static void MapFromDB( EM.Entity_DurationProfile from, DurationProfile to )
		{
			DurationItem duration = new DurationItem();
			int totalMinutes = 0;
			to.Id = from.Id;
			to.EntityId = from.EntityId ?? 0;
			to.ProfileName = from.ProfileName ?? "";

			//to.ParentUid = from.ParentUid;
			//to.ParentTypeId = from.ParentTypeId;

			to.Conditions = from.DurationComment;
			to.Created = from.Created != null ? ( DateTime ) from.Created : DateTime.Now;
			to.CreatedById = from.CreatedById != null ? ( int ) from.CreatedById : 0;
			to.Created = from.LastUpdated != null ? ( DateTime ) from.LastUpdated : DateTime.Now;
			to.LastUpdatedById = from.LastUpdatedById != null ? ( int ) from.LastUpdatedById : 0;

			duration = new DurationItem();
			duration.Years = from.FromYears == null ? 0 : ( int ) from.FromYears;
			duration.Months = from.FromMonths == null ? 0 : ( int ) from.FromMonths;
			duration.Weeks = from.FromWeeks == null ? 0 : ( int ) from.FromWeeks;
			duration.Days = from.FromDays == null ? 0 : ( int ) from.FromDays;
			duration.Hours = from.FromHours == null ? 0 : ( int ) from.FromHours;
			duration.Minutes = from.FromMinutes == null ? 0 : ( int ) from.FromMinutes;

			if ( HasToDurations( from ) )
			{
				//format as from and to
				to.MinimumDuration = duration;
				to.MinimumDurationISO8601 = AsSchemaDuration( duration, ref totalMinutes );
				to.ProfileSummary = DurationSummary( to.Conditions, duration );

				duration = new DurationItem();
				duration.Years = from.ToYears == null ? 0 : ( int ) from.ToYears;
				duration.Months = from.ToMonths == null ? 0 : ( int ) from.ToMonths;
				duration.Weeks = from.ToWeeks == null ? 0 : ( int ) from.ToWeeks;
				duration.Days = from.ToDays == null ? 0 : ( int ) from.ToDays;
				duration.Hours = from.ToHours == null ? 0 : ( int ) from.ToHours;
				duration.Minutes = from.ToMinutes == null ? 0 : ( int ) from.ToMinutes;

				to.MaximumDuration = duration;
				to.MaximumDurationISO8601 = AsSchemaDuration( duration, ref totalMinutes );

				to.ProfileSummary += DurationSummary( " to ", duration );

			}
			else
			{
				to.ExactDuration = duration;
				to.ExactDurationISO8601 = AsSchemaDuration( duration, ref totalMinutes );
				to.ProfileSummary = DurationSummary( to.Conditions, duration );
			}

			if ( string.IsNullOrWhiteSpace( to.ProfileName ) )
				to.ProfileName = to.ProfileSummary;
		}
		#endregion

		#region  retrieval ==================

		///
		/// Retrieve and fill duration profiles for parent entity
		///
		/// <param name="parentUid"></param>
		public static List<DurationProfile> GetAll( Guid parentUid, int typeId = 0 )
		{
			DurationProfile row = new DurationProfile();
			DurationItem duration = new DurationItem();
			List<DurationProfile> profiles = new List<DurationProfile>();
			Entity parent = EntityManager.GetEntity( parentUid );
			if ( parent == null || parent.Id == 0 )
			{
				return profiles;
			}

			using ( var context = new Data.CTIEntities() )
			{
				List results = context.Entity_DurationProfile
						.Where( s => s.EntityId == parent.Id
							&& (( typeId == 0 && s.TypeId < 3 ) || s.TypeId == typeId)
							)
						.OrderBy( s => s.Id )
						.ToList();

				if ( results != null && results.Count > 0 )
				{
					foreach ( EM.Entity_DurationProfile item in results )
					{
						row = new DurationProfile();
						MapFromDB( item, row );
						profiles.Add( row );
					}
				}
				return profiles;
			}

		}//
		///
		/// Get a single DurationProfile by integer Id
		///
		/// <param name="id"></param>
		/// <returns></returns>
		public static DurationProfile Get( int id )
		{
			DurationProfile entity = new DurationProfile();
			using ( var context = new Data.CTIEntities() )
			{
				EM.Entity_DurationProfile item = context.Entity_DurationProfile
							.SingleOrDefault( s => s.Id == id );

				if ( item != null && item.Id > 0 )
				{
					MapFromDB( item, entity );
				}
			}

			return entity;
		}

		public bool ValidateDurationProfile( DurationProfile profile, ref bool isEmpty, ref List<string> messages )
		{
			bool isValid = true;
			bool hasConditions = false;
			isEmpty = false;
			//string message = "";
			if ( string.IsNullOrWhiteSpace( profile.Conditions ) == false )
			{
				hasConditions = true;
			}
			bool hasExactDuration = false;
			bool hasRangeDuration = false;
			if ( HasDurationItems( profile.ExactDuration ) )
				hasExactDuration = true;
			if ( HasDurationItems( profile.MinimumDuration ) || HasDurationItems( profile.MaximumDuration ) )
				hasRangeDuration = true;

			//validations should be done before here
			if ( hasExactDuration )
			{
				if ( hasRangeDuration )
				{
					//inconsistent, take exact for now
					messages.Add( "Error - you must either enter an Exact duration or a Minimum/Maximum range duration but not both. For now, the exact duration was used" );
					isValid = false;
				}

			}
			else if ( hasRangeDuration == false && hasConditions == false )
			{
				//nothing,
				messages.Add( "Error - you must enter either an Exact duration or a Minimum/Maximum range duration (but not both).
");
				isValid = false;
				isEmpty = true;
			}
            else if ( hasRangeDuration )
            {
                var minDuration = profile.MinimumDuration.TotalMinutes();
                var maxDuration = profile.MaximumDuration.TotalMinutes();
                if ( minDuration > maxDuration )
                {
                    messages.Add( "Error - Minimum Duration should be less than Maximum Duration.
" );
                    isValid = false;
                }
            }

            //if ( !string.IsNullOrWhiteSpace( profile.ProfileName ) && profile.ProfileName.Length > 200 )
            //{
            //	//nothing,
            //	messages.Add( "Error - the profile name is too long, the maximum length is 200 characters.
" );
            //	isValid = false;
            //	isEmpty = false;
            //}
            if ( !string.IsNullOrWhiteSpace( profile.Conditions ) && profile.Conditions.Length > 999 )
			{
				//nothing,
				messages.Add( "Error - the description is too long, the maximum length is 1000 characters.
" );
				isValid = false;
				isEmpty = false;
			}
			return isValid;
		}
		public static bool HasDurationItems( DurationItem item )
		{
			bool result = false;
			if ( item == null )
				return false;

			if ( item.Years > 0
				|| item.Months > 0
				|| item.Weeks > 0
				|| item.Days > 0
				|| item.Hours > 0
				|| item.Minutes > 0
				)
				result = true;

			return result;
		}

		private static bool HasToDurations( EM.Entity_DurationProfile item )
		{
			bool result = false;
			if ( item.ToYears.HasValue
				|| item.ToMonths.HasValue
				|| item.ToWeeks.HasValue
				|| item.ToDays.HasValue
				|| item.ToHours.HasValue
				|| item.ToMinutes.HasValue
				)
				result = true;

			return result;
		}

		private static string DurationSummary( string conditions, DurationItem entity )
		{
			string duration = "";
			string comma = "";
			if ( string.IsNullOrWhiteSpace( conditions ) )
				duration = "Duration: ";
			else
				duration = conditions + " ";

			if ( entity.Years > 0 )
			{
				duration += SetLabel( entity.Years, "Year" );
				comma = ", ";
			}
			if ( entity.Months > 0 )
			{
				duration += comma + SetLabel( entity.Months, "Month" );
				comma = ", ";
			}
			if ( entity.Weeks > 0 )
			{
				duration += comma + SetLabel( entity.Weeks, "Week" );
				comma = ", ";
			}
			if ( entity.Days > 0 )
			{
				duration += comma + SetLabel( entity.Days, "Day" );
				comma = ", ";
			}
			if ( entity.Hours > 0 )
			{
				duration += comma + SetLabel( entity.Hours, "Hour" );
				comma = ", ";
			}
			if ( entity.Minutes > 0 )
			{
				duration += comma + SetLabel( entity.Minutes, "Minute" );
				comma = ", ";
			}

			//TODO could replace last comma with And
			int lastPos = duration.LastIndexOf( "," );
			if ( lastPos > 0 )
			{
				duration = duration.Substring( 0, lastPos ) + " and " + duration.Substring( lastPos + 1 );
			}
			return duration;
		}
		static string SetLabel( int value, string unit )
		{
			string label = "";
			if ( value > 1 )
				label = string.Format( "{0} {1}s", value, unit );
			else
				label = string.Format( "{0} {1}", value, unit );

			return label;
		}
		public static string AsSchemaDuration( DurationItem entity, ref int totalMinutes )
		{
			string duration = "P";
			totalMinutes = 0;

			if ( entity.Years > 0 )
			{
				duration += entity.Years.ToString() + "Y";
				totalMinutes += entity.Years * 365 * 24 * 3600;
			}
			if ( entity.Months > 0 )
			{
				duration += entity.Months.ToString() + "M";
				totalMinutes += entity.Months * 30 * 24 * 3600;
			}

			if ( entity.Weeks > 0 )
			{
				duration += entity.Weeks.ToString() + "W";
				totalMinutes += entity.Weeks * 5 * 24 * 3600;
			}

			if ( entity.Days > 0 )
			{
				duration += entity.Days.ToString() + "D";
				totalMinutes += entity.Days * 24 * 3600;
			}

			if ( entity.Hours > 0 || entity.Minutes > 0 )
				duration += "T";

			if ( entity.Hours > 0 )
			{
				duration += entity.Hours.ToString() + "H";
				totalMinutes += entity.Hours * 3600;
			}

			if ( entity.Minutes > 0 )
			{
				duration += entity.Minutes.ToString() + "M";
				totalMinutes += entity.Minutes;
			}

			return duration;
		}
		//private string AsSchemaDuration( int years, int mths, int weeks, int days = 0, int hours = 0, int minutes = 0 )
		//{
		//	string duration = "P";

		//	if ( years > 0 )
		//		duration += years.ToString() + "Y";
		//	if ( mths > 0 )
		//		duration += mths.ToString() + "M";
		//	if ( weeks > 0 )
		//		duration += weeks.ToString() + "W";
		//	if ( days > 0 )
		//		duration += days.ToString() + "D";
		//	if ( hours > 0 || minutes > 0 )
		//		duration += "T";

		//	if ( hours > 0 )
		//		duration += hours.ToString() + "H";
		//	if ( minutes > 0 )
		//		duration += minutes.ToString() + "M";
		//	return duration;
		//}
		#endregion
	}
}


text:
<!DOCTYPE html>

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

  <title>DevFolio Bootstrap Portfolio Template - Blog Single</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <link href="assets/img/favicon.png" rel="icon">
  <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet">
  <link href="assets/vendor/ionicons/css/ionicons.min.css" rel="stylesheet">
  <link href="assets/vendor/owl.carousel/assets/owl.carousel.min.css" rel="stylesheet">
  <link href="assets/vendor/venobox/venobox.css" rel="stylesheet">

  <link href="assets/css/style.css" rel="stylesheet">

      DevFolio
      <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarDefault" aria-controls="navbarDefault" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home

            About

            Services

            Work

            Blog

            Contact

Blog Details

              Home

              Library

Data

Lorem ipsum dolor sit amet consec tetur adipisicing

                    Jason London

                    Web Design

                    14

                  Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Cras ultricies ligula sed magna dictum
                  porta. Quisque velit
                  nisi, pretium ut lacinia in, elementum id enim. Praesent sapien massa, convallis a pellentesque
                  nec, egestas non nisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere
                  cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula.
                  Nulla quis lorem ut libero malesuada feugiat.

                  Nulla porttitor accumsan tincidunt. Cras ultricies ligula sed magna dictum porta. Mauris blandit
                  aliquet elit, eget tincidunt
                  nibh pulvinar a. Cras ultricies ligula sed magna dictum porta. Lorem ipsum dolor sit amet,
                  consectetur adipiscing elit. Donec sollicitudin molestie malesuada.

                  Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Lorem ipsum dolor sit amet, consectetur
                  adipiscing elit. Praesent
                  sapien massa, convallis a pellentesque nec, egestas non nisi. Lorem ipsum dolor sit amet,
                  consectetur adipiscing elit. Curabitur arcu erat, accumsan id imperdiet et, porttitor at
                  sem. Donec rutrum congue leo eget malesuada.

                  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis lorem ut libero malesuada feugiat.
                  Curabitur arcu erat,
                  accumsan id imperdiet et, porttitor at sem. Vivamus suscipit tortor eget felis porttitor
                  volutpat. Vivamus suscipit tortor eget felis porttitor volutpat. Quisque velit nisi, pretium
                  ut lacinia in, elementum id enim.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

                  Nulla porttitor accumsan tincidunt. Cras ultricies ligula sed magna dictum porta. Mauris blandit
                  aliquet elit, eget tincidunt
                  nibh pulvinar a. Cras ultricies ligula sed magna dictum porta. Lorem ipsum dolor sit amet,
                  consectetur adipiscing elit. Donec sollicitudin molestie malesuada.

Comments (34)

Oliver Colmenares

                    18 Sep 2017

                      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores reprehenderit, provident cumque
                      ipsam temporibus maiores
                      quae natus libero optio, at qui beatae ducimus placeat debitis voluptates amet corporis.

                    Reply

Carmen Vegas

                    18 Sep 2017

                      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores reprehenderit, provident cumque
                      ipsam temporibus maiores
                      quae natus libero optio, at qui beatae ducimus placeat debitis voluptates amet corporis,
                      veritatis deserunt.

                    Reply

Oliver Colmenares

                    18 Sep 2017

                      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores reprehenderit, provident cumque
                      ipsam temporibus maiores
                      quae.

                    Reply

Oliver Colmenares

                    18 Sep 2017

                      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores reprehenderit, provident cumque
                      ipsam temporibus maiores
                      quae natus libero optio.

                    Reply

                  Leave a Reply

              <form class="form-mf">

                      <input type="text" class="form-control input-mf" id="inputName" placeholder="Name *" required>

                      <input type="email" class="form-control input-mf" id="inputEmail1" placeholder="Email *" required>

                      <input type="url" class="form-control input-mf" id="inputUrl" placeholder="Website">

                      <textarea id="textMessage" class="form-control input-mf" placeholder="Comment *" name="message" cols="45" rows="8" required></textarea>

                    <button type="submit" class="button button-a button-big button-rouded">Send Message</button>

              </form>

Search

                <form>

                    <input type="text" class="form-control" placeholder="Search for..." aria-label="Search for...">

                      <button class="btn btn-secondary btn-search" type="button">

                      </button>

                </form>

Recent Post

                    Atque placeat maiores.

                    Lorem ipsum dolor sit amet consectetur

                    Nam quo autem exercitationem.

                    Atque placeat maiores nam quo autem

                    Nam quo autem exercitationem.

Archives

                    September, 2017.

                    April, 2017.

                    Nam quo autem exercitationem.

                    Atque placeat maiores nam quo autem

                    Nam quo autem exercitationem.

Tags

                    Web.

                    Design.

                    Travel.

                    Photoshop

                    Corel Draw

                    JavaScript

© Copyright DevFolio. All Rights Reserved

              Designed by BootstrapMade

redpajama_set_name: RedPajamaGithub


text:
package apply

import (
	"context"
	"io"

	"github.com/go-kit/kit/endpoint"
	"github.com/micromdm/dep"
	"github.com/micromdm/micromdm/blueprint"
	"github.com/micromdm/micromdm/profile"
)

type Endpoints struct {
	ApplyBlueprintEndpoint   endpoint.Endpoint
	ApplyDEPTokensEndpoint   endpoint.Endpoint
	ApplyProfileEndpoint     endpoint.Endpoint
	DefineDEPProfileEndpoint endpoint.Endpoint
	AppUploadEndpoint        endpoint.Endpoint
}

func (e Endpoints) UploadApp(ctx context.Context, manifestName string, manifest io.Reader, pkgName string, pkg io.Reader) error {
	request := appUploadRequest{
		ManifestName: manifestName,
		ManifestFile: manifest,
		PKGFilename:  pkgName,
		PKGFile:      pkg,
	}
	resp, err := e.AppUploadEndpoint(ctx, request)
	if err != nil {
		return err
	}
	return resp.(appUploadResponse).Err
}

func (e Endpoints) DefineDEPProfile(ctx context.Context, p *dep.Profile) (*dep.ProfileResponse, error) {
	request := depProfileRequest{Profile: p}
	resp, err := e.DefineDEPProfileEndpoint(ctx, request)
	if err != nil {
		return nil, err
	}
	response := resp.(depProfileResponse)
	return response.ProfileResponse, response.Err
}

func (e Endpoints) ApplyBlueprint(ctx context.Context, bp *blueprint.Blueprint) error {
	request := blueprintRequest{Blueprint: bp}
	resp, err := e.ApplyBlueprintEndpoint(ctx, request)
	if err != nil {
		return err
	}
	return resp.(blueprintResponse).Err
}

func (e Endpoints) ApplyDEPToken(ctx context.Context, P7MContent []byte) error {
	req := depTokensRequest{P7MContent: P7MContent}
	resp, err := e.ApplyDEPTokensEndpoint(ctx, req)
	if err != nil {
		return err
	}
	return resp.(depTokensResponse).Err
}

func (e Endpoints) ApplyProfile(ctx context.Context, p *profile.Profile) error {
	request := profileRequest{Profile: p}
	resp, err := e.ApplyProfileEndpoint(ctx, request)
	if err != nil {
		return err
	}
	return resp.(profileResponse).Err
}

func MakeApplyBlueprintEndpoint(svc Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(blueprintRequest)
		err = svc.ApplyBlueprint(ctx, req.Blueprint)
		return blueprintResponse{
			Err: err,
		}, nil
	}
}

func MakeApplyDEPTokensEndpoint(svc Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(depTokensRequest)
		err = svc.ApplyDEPToken(ctx, req.P7MContent)
		return depTokensResponse{
			Err: err,
		}, nil
	}
}

func MakeApplyProfileEndpoint(svc Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(profileRequest)
		err = svc.ApplyProfile(ctx, req.Profile)
		return profileResponse{
			Err: err,
		}, nil
	}
}

func MakeDefineDEPProfile(svc Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(depProfileRequest)
		resp, err := svc.DefineDEPProfile(ctx, req.Profile)
		return &depProfileResponse{
			ProfileResponse: resp,
			Err:             err,
		}, nil
	}
}

func MakeUploadAppEndpiont(svc Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(appUploadRequest)
		err = svc.UploadApp(ctx, req.ManifestName, req.ManifestFile, req.PKGFilename, req.PKGFile)
		return &appUploadResponse{
			Err: err,
		}, nil
	}
}

type appUploadRequest struct {
	ManifestName string
	ManifestFile io.Reader

	PKGFilename string
	PKGFile     io.Reader
}

type appUploadResponse struct {
	Err error `json:"err,omitempty"`
}

func (r appUploadResponse) error() error { return r.Err }

type blueprintRequest struct {
	Blueprint *blueprint.Blueprint `json:"blueprint"`
}

type blueprintResponse struct {
	Err error `json:"err,omitempty"`
}

func (r blueprintResponse) error() error { return r.Err }

type profileRequest struct {
	Profile *profile.Profile `json:"profile"`
}

type profileResponse struct {
	Err error `json:"err,omitempty"`
}

func (r profileResponse) error() error { return r.Err }

type depTokensRequest struct {
	P7MContent []byte `json:"p7m_content"`
}

type depTokensResponse struct {
	Err error `json:"err,omitempty"`
}

func (r depTokensResponse) error() error { return r.Err }

type depProfileRequest struct{ *dep.Profile }
type depProfileResponse struct {
	*dep.ProfileResponse
	Err error `json:"err,omitempty"`
}

func (r *depProfileResponse) error() error { return r.Err }


text:
using System.Collections.Generic;
using Xabaril.Store;

namespace Xabaril.RedisStore
{
    public class RedisOptions
    {
        private List<FeatureConfigurer> _featuresConfiguration;
        private string _defaultRedisHost = "localhost:6379";

        public List<FeatureConfigurer> FeatureConfiguration => _featuresConfiguration;

        public string RedisHost
        {
            get
            {
                return _defaultRedisHost;
            }
            set
            {
                _defaultRedisHost = value;
            }
        }

        public FeatureConfigurer AddFeature(Feature feature)
        {
            if (_featuresConfiguration == null)
            {
                _featuresConfiguration = new List<FeatureConfigurer>();
            }

            var featureConfiguration = new FeatureConfigurer(feature);

            _featuresConfiguration.Add(featureConfiguration);

            return featureConfiguration;
        }
    }
}


text:
function math.sign(number)
	if number < 0 then
		return -1
	elseif number > 0 then
		return 1
	else
		return 0
	end
end

function toRadians(angle)
	return angle * ( math.pi / 180.0)
end

function toDegrees(angle)
	return angle * (180.0 / math.pi)
end

local function quatAxisAngle(axis, angle)
	local quat = _Quaternion()

	angle = toRadians(angle) /2
	temp = math.sin(angle)
	quat.x = axis.x * temp
	quat.y = axis.y * temp
	quat.z = axis.z * temp
	quat.angle = math.cos(angle)
	quat = quat:normalized()
	return quat
end

local function quatAxisAxis(axis1, axis2)
	local costheta = axis1:dot(axis2)
	local theta = math.acos(costheta)
	local nAxis = axis1:cross(axis2)
	return quatAxisAngle(nAxis, toDegrees(theta))
end

function Quaternion(axis, angle)

	if axis == nil then
		return _Quaternion()
	elseif type(angle) == "number" then
		return quatAxisAngle(axis, angle)
	elseif type(angle) == "table" then
		return quatAxisAxis(axis, angle)
	else
		assert(false, "Invalid Input for Quaternion Constructor!")
	end

end

function math.clamp(value, min, max)

	if value < min then
		return min
	end

	if value > max then
		return max
	end
	return value
end


text:
/* global -name*/
"use strict";

var mine = require("mine");
var pathJoin = require("pathjoin");
var binary = require('bodec');
var modes = require('js-git/lib/modes');
module.exports = amdTree;

function amdTree(servePath, req, callback) {

  var path = pathJoin(req.paths.root, req.input, req.paths.local);
  servePath(path, function (err, result) {
    if (err) return callback(err);
    if (!shouldHandle(path, result)) return callback();
    return callback(null, {
      mode: result.mode,
      hash: result.hash + "-" + req.codeHash,
      root: result.root,
      fetch : fetch
    });

    function fetch(callback) {
      result.fetch(function (err, value) {
        if (err) return callback(err);
        if (modes.isFile(result.mode)) {
          return compile(path, value, callback);
        }
        if (result.mode === modes.tree) {
          var tree = {};
          Object.keys(value).forEach(function (key) {
            var entry = value[key];
            if (shouldHandle(key, entry)) {
              entry.hash += "-" + req.codeHash;
              tree[key] = entry;
            }
          });
          value = tree;
        }
        return callback(null, value);
      });
    }
  });

  function shouldHandle(path, entry) {
    return entry && (entry.mode === modes.tree ||
           modes.isFile(entry.mode) && /\.js$/i.test(path));
  }

  function compile(path, blob, callback) {
    var prefix = pathJoin(req.paths.rule, "..", req.base || ".");
    var js = binary.toUnicode(blob);
    var deps = mine(js);
    var length = deps.length;
    var paths = new Array(length);
    var full = req.paths.full;
    var localPath = prefix ? full.substring(prefix.length + 1) : full;
    var base = localPath.substring(0, localPath.lastIndexOf("/"));

    for (var i = length - 1; i >= 0; i--) {
      var dep = deps[i];
      var depPath = dep.name[0] === "." ? pathJoin(base, dep.name) : dep.name;
      if (!(/\.[^\/]+$/.test(depPath))) depPath += ".js";
      paths[i] = depPath;
      js = js.substr(0, dep.offset) + depPath + js.substr(dep.offset + dep.name.length);
    }
    js = "define(" + JSON.stringify(localPath) + ", " +
        JSON.stringify(paths) + ", function (module, exports) { " +
        js + "\n});\n";
    callback(null, binary.fromUnicode(js));
  }
}


text:
'use strict';
const fs = require('fs');
const assert = require('assert');
const sinon = require('sinon');
const rule = require('../lib/rules/bowerrc-home');

describe('global .bowerrc rule', () => {
  beforeEach(function () {
    this.sandbox = sinon.sandbox.create();
  });

  afterEach(function () {
    this.sandbox.restore();
  });

  it('pass if there is no .bowerrc file in user home', async function () {
    const mock = this.sandbox.mock(fs);
    mock.expects('existsSync').once().withArgs(rule.bowerrcPath).returns(false);
    const error = await rule.verify();
    assert(!error);
    mock.verify();
  });

  it('fail if there is a .bowerrc file in user home', async function () {
    const mock = this.sandbox.mock(fs);
    mock.expects('existsSync').once().withArgs(rule.bowerrcPath).returns(true);
    const error = await rule.verify();
    assert.equal(error, rule.errors.fileExists());
    mock.verify();
  });
});


text:
require 'rubygems'
require 'bundler'

Bundler.require

require 'dotme'

require 'test/unit'
require 'rack/test'

class DotmeTest < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  def test_my_default
    get '/'
    assert last_response.ok?
  end
end


text: AngularJS implementation of core HTML elements built by OS Elements


text:
import './test-element-a_test.js';
import './test-element-props_test.js';
import './test-element-events_test.js';
import './test-element-slots_test.js';


text:
var settings = require('../../../core/settings');
var Effect = require('../Effect');
var effectComposer = require('../effectComposer');
var fboHelper = require('../../fboHelper');

var glslify = require('glslify');
var THREE = require('three');

var undef;

var exports = module.exports = new Effect();
var _super = Effect.prototype;

exports.init = init;
exports.render = render;

var _depth1Material;
var _depth1;
var _depth1Buffer;

function init() {

    _depth1 = fboHelper.createRenderTarget(1, 1, THREE.RGBAFormat, THREE.FloatType);

    _super.init.call(this, {
        uniforms: {
            u_distance: { type: 't', value: undef },
            u_dofDistance: { type: 'f', value: 0 },
            u_delta: { type: 'v2', value: new THREE.Vector2() },
            u_mouse: { type: 'v2', value: settings.mouse },
            u_amount: { type: 'f', value: 1 }
        },
        fragmentShader: glslify('./dof.frag')
    });

    _depth1Buffer = new Float32Array(4);
    _depth1Material = new THREE.RawShaderMaterial({
        uniforms: {
            u_distance: { type: 't', value: undef },
            u_mouse: { type: 'v2', value: settings.mouse }
        },
        transparent: true,
        blending: THREE.NoBlending,
        vertexShader: this.vertexShader,
        fragmentShader: fboHelper.rawShaderPrefix + glslify('./depth1.frag')
    });

}

function render(dt, renderTarget, toScreen) {

    var cameraDistance = effectComposer.camera.position.length();
    var distance = cameraDistance;

    if(settings.dofMouse) {
        _depth1Material.uniforms.u_distance.value = settings.distanceMap;
        fboHelper.render(_depth1Material, _depth1);
        effectComposer.renderer.readRenderTargetPixels ( _depth1, 0, 0, 1, 1, _depth1Buffer );
        distance = _depth1Buffer[0] || distance;
    }

    var uniforms = this.uniforms;
    var prevDistance = uniforms.u_dofDistance.value;
    uniforms.u_dofDistance.value += (distance - prevDistance) * 0.1;

    uniforms.u_amount.value = settings.dof;
    uniforms.u_distance.value = settings.distanceMap;
    uniforms.u_delta.value.set(1, 0);
    renderTarget = _super.render.call(this, dt, renderTarget);
    uniforms.u_delta.value.set(0, 1);
    _super.render.call(this, dt, renderTarget, toScreen);

}


text:
import logging
import logging.handlers
import os

_LOG_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"

class ResultsLogger(object):
    """Logger used to log results of OSTF tests. Resutls are stored in
    /var/log/ostf/ dir. Each cluster has one log file per each set of tests.
    """

    def __init__(self, testset, cluster_id):
        self.testset = testset
        self.cluster_id = cluster_id
        self.filename = self._make_filename()
        self._logger = self._init_file_logger()

    def _init_file_logger(self):
        logger = logging.getLogger('ostf-results-log-{0}-{1}'.format(
            self.cluster_id, self.testset))

        if not logger.handlers:
            log_dir = '/var/log/ostf'
            log_file = os.path.join(log_dir, self.filename)

            file_handler = logging.handlers.WatchedFileHandler(log_file)
            file_handler.setLevel(logging.DEBUG)

            formatter = logging.Formatter(
                '%(asctime)s %(message)s',
                _LOG_TIME_FORMAT)
            file_handler.setFormatter(formatter)

            logger.addHandler(file_handler)

        logger.propagate = 0

        return logger

    def _make_filename(self):
        return 'cluster_{cluster_id}_{testset}.log'.format(
            testset=self.testset, cluster_id=self.cluster_id)

    def log_results(self, test_id, test_name, status, message, traceback):
        status = status.upper()
        msg = "{status} {test_name} ({test_id}) {message} {traceback}".format(
            test_name=test_name, test_id=test_id, status=status,
            message=message, traceback=traceback)
        self._logger.info(msg)

def setup(log_file=None):
    formatter = logging.Formatter(
        '%(asctime)s %(levelname)s (%(module)s) %(message)s',
        _LOG_TIME_FORMAT)
    log = logging.getLogger(None)
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.INFO)
    stream_handler.setFormatter(formatter)
    log.addHandler(stream_handler)

    if log_file:
        log_file = os.path.abspath(log_file)
        file_handler = logging.handlers.WatchedFileHandler(log_file)
        file_handler.setLevel(logging.DEBUG)
        mode = int('0644', 8)
        os.chmod(log_file, mode)
        file_handler.setFormatter(formatter)
        log.addHandler(file_handler)

    log.setLevel(logging.INFO)


text:
import { describe, it } from '@ephox/bedrock-client';
import { Unicode } from '@ephox/katamari';
import { TinySelections, TinyHooks } from '@ephox/wrap-mcagar';
import { assert } from 'chai';

import RangeUtils from 'tinymce/core/api/dom/RangeUtils';
import Editor from 'tinymce/core/api/Editor';

describe('browser.tinymce.core.api.dom.RangeExpandTest', () => {
  const hook = TinyHooks.bddSetupLight<Editor>({
    indent: false,
    base_url: '/project/tinymce/js/tinymce'
  }, []);

  const textEntry = 'A B ' + Unicode.nbsp + 'C D';

  const makeBaseRange = (editor: Editor, startOffset: number, endOffset: number, nodeOffset: number = 0) => {
    const body = editor.getBody();
    const range = editor.dom.createRng();
    const node = body.childNodes[0].childNodes[nodeOffset];
    range.setStart(node, startOffset);
    range.setEnd(node, endOffset);
    return range;
  };

  const compareRanges = (range1: Range, range2: Range) => {
    assert.equal(range1.startContainer, range2.startContainer, 'Mismatching start container');
    assert.equal(range1.startOffset, range2.startOffset, 'Mismatching start offset');
    assert.equal(range1.endContainer, range2.endContainer, 'Mismatching end container');
    assert.equal(range1.endOffset, range2.endOffset, 'Mismatching end offset');
  };

  it('TINY-9001: The content is empty', () => {
    const editor = hook.editor();
    editor.setContent('');
    TinySelections.setSelection(editor, [ 0 ], 0, [ 0 ], 0);
    const startRange = editor.selection.getRng();
    const endRange = RangeUtils(editor.dom).expand(startRange);
    const body = editor.getBody();
    const expectedRange = editor.dom.createRng();
    expectedRange.setStart(body, 0);
    expectedRange.setEnd(body, 1);
    compareRanges(expectedRange, endRange);
  });

  it('TINY-9001: The cursor is in between two spaces', () => {
    const editor = hook.editor();
    editor.setContent(textEntry);
    const startRange = makeBaseRange(editor, 4, 4);
    const endRange = RangeUtils(editor.dom).expand(startRange);
    compareRanges(startRange, endRange);
  });

  it('TINY-9001: The cursor is between a space and a word on the right', () => {
    const editor = hook.editor();
    editor.setContent(textEntry);
    const startRange = makeBaseRange(editor, 5, 5);
    const endRange = RangeUtils(editor.dom).expand(startRange);
    compareRanges(makeBaseRange(editor, 5, 6), endRange);
  });

  it('TINY-9001: The cursor is between a space and a word on the left', () => {
    const editor = hook.editor();
    editor.setContent(textEntry);
    const startRange = makeBaseRange(editor, 3, 3);
    const endRange = RangeUtils(editor.dom).expand(startRange);
    compareRanges(makeBaseRange(editor, 2, 3), endRange);
  });

  it('TINY-9001: The cursor is in the middle of a word', () => {
    const editor = hook.editor();
    editor.setContent('
A B12C D
');
    const startRange = makeBaseRange(editor, 4, 4);
    const endRange = RangeUtils(editor.dom).expand(startRange);
    compareRanges(makeBaseRange(editor, 2, 6), endRange);
  });
});


text:
define.class(function(require, screen, view,menuitem, menubar, edit, text, icon, treeview, ruler, foldcontainer,button, splitcontainer, scrollbar, editlayout){

	this.render = function(){

		return[
		view({rotation:0,position: "relative",   flexdirection: "column", height: 20, bgcolor: "black", flex:1},[
			view({position: "relative",  cornerradius:"vec4(0,0,0,14)" , borderwidth:1,  flexdirection: "row", bgcolor2: "#404080",
				'bg.bgcolorfn':function(pos,b){
					return demos.highdefblirpy(pos*vec2(2.,0.1), time * 2, 1.) * vec4(mesh.x * bgcolor.rgb, 1.0)
					//'red'//vec4(mesh.x * bgcolor.rgb, 1.0)
				} , alignitems:"stretch", alignself: "stretch" , flex: undefined}
				,icon({icon:"windows", fgcolor:"white", marginleft: 15, fontsize:18})
				,text({fontsize: 20, text:"Visionary Studio 3016", width: 200, bgcolor: "transparent" , marginbottom:10, marginleft:15})
			)
			,menubar({}
						,menuitem({text: "File"}
							,menuitem({text: "Load"})
							,menuitem({text: "Save"})
							,menuitem({text: "Save as"})
							,menuitem({text: "Revert"})
						)
						,menuitem({text: "Edit"}
							,menuitem({text: "Copy"})
							,menuitem({text: "Paste"})
							,menuitem({text: "Undo"})
							,menuitem({text: "Redo"})
							,menuitem({text: "Options"})
						)
						,menuitem({text: "Help"}
									,menuitem({text: "Manual"})
									,menuitem({text: "About"})
						)
					)

			,splitcontainer({vertical:false, position: "relative",   flexdirection: "row", bgcolor: "black", alignitems:"stretch", alignself: "stretch" , flex:1}
				,view({position: "relative", flex: 0.2,  flexdirection: "column", bgcolor: "#b0b0b0", alignself: "stretch", borderwidth: 1,cornerradius: "vec4(0,14,0,0)" , bordercolor: "gray" }
					,treeview({})
					)
				,view({position: "relative", flex:0.34,  flexdirection: "column", bgcolor: "darkgray",padding: 1, cornerradius: 0, clipping: true}
					,ruler({height: 20})
					,view({position: "relative", flex: 1.0, padding: 0, bgcolor: "#f0f0f0", alignitems: "stretch", flexdirection: "row" }
						,ruler({width: 20, vertical: true, offset:0})
						,view({position: "relative", flex: 1.0, padding: 4, bgcolor: "#f0f0f0", alignitems: "stretch", flexdirection:"row" ,clipping: false}
						,editlayout({flex:1.0,padding:10,  composition:'minidialog', clipping: true})

						,scrollbar({width:15, position:'relative'})

						)
					)
				)
				,view({position: "relative", flex: 0.2,  flexdirection: "column", bgcolor: "#808090", alignself: "stretch" , borderwidth: 1, padding: 3,cornerradius: "vec4(0,0,14,0)" , bordercolor: "gray" , clipping: true}
					,foldcontainer({title:"Class Library", icon:'files', alignself: "stretch",marginbottom: 2})
					,foldcontainer({title:"Attributes", icon:'gears', alignself: "stretch",marginbottom: 2},
						text({fontsize: 26, text:"Visionary Studio 3016",bgcolor: "transparent" , margin: 5})
					)
					,foldcontainer({title:"Fancy buttons", icon:'gamepad', marginbottom: 2}
						,view({ position:"relative", flexwrap:"wrap", alignitems: "stretch", bgcolor: "transparent"}
							,button({text:"Youtube",icon:"youtube", click:function(){
								this.screen.openModal(
									view({
										click:function(){
											this.screen.closeModal(1)
										},position:'absolute',bgcolor:'red',w:100,h:100})
								).then(function(result){
									console.log('resolved',result)
								})
							}})
							,button({text:"Github", icon:"github"})
							,button({text:"Google", icon: "gear"})
							,button({text:"me me me me!"})
						)
					)
					,foldcontainer({title:"Attributes", icon:'list-ul', alignself: "stretch", marginbottom: 2}
						,view({position: "relative", flex: 1.0, padding: 4, bgcolor: "#f0f0f0", alignitems: "stretch", flexdirection:"row" }
							,edit({fontsize:20, height: 100, width:100,position:"relative" , cursorcolor: "black", markercolor:"#9090f0", flex: 1.0,fgcolor: "black",'bg.color':function(){return vec4("#f0f0f0")} ,text:'another editbox1'})
							//,edit({fontsize:20, height: 100, width:100,position:"relative" , cursorcolor: "black", markercolor:"#9090f0", flex: 1.0,fgcolor: "black",'bg.color':function(){return vec4("#f0f0f0")} ,text:'another editbox2'})
						)
					)
					,foldcontainer({title:"Split Test", alignself: "stretch", marginbottom: 2}
						,view({position: "relative", flex: 1.0, padding: 4, bgcolor: "#f0f0f0", alignitems: "stretch", flexdirection:"column" }
						,splitcontainer({vertical: false, margin: 4},[
						text({fontsize: 26, text:"A", bgcolor: "transparent" , fgcolor:"black", margin: 2})
						,text({fontsize: 26, text:"B", bgcolor: "transparent" ,fgcolor:"black", margin: 2})
						,text({fontsize: 26, text:"C", bgcolor: "transparent" , fgcolor:"black",margin: 2})
						,text({fontsize: 26, text:"D", bgcolor: "transparent" , fgcolor:"black",margin: 2})
						]
						)
						,splitcontainer({vertical: true, margin: 4},[
						text({fontsize: 26, text:"A", bgcolor: "transparent" , fgcolor:"black", margin: 2})
						,text({fontsize: 26, text:"B", bgcolor: "transparent" ,fgcolor:"black", margin: 2})
						,text({fontsize: 26, text:"C", bgcolor: "transparent" , fgcolor:"black",margin: 2})
						,text({fontsize: 26, text:"D", bgcolor: "transparent" , fgcolor:"black",margin: 2})
						]
						))
					)

				)
			)
		])
	]}
});


text:
<!doctype html>
<html>

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

<style>
	q { display: block; position: absolute }
</style>

<body>

<script src="-/web.js" charset="utf-8"></script>
<script>

	addEventListener( 'load' , function() {
		var script = document.createElement( 'script' )
		script.src = '-/web.test.js'
		document.body.appendChild( script )
	} )

</script>


text:
require 'httparty'
require 'json'

module Probe
  class Notification

    include HTTParty

    NOTIFIER_NAME = 'Probe Notifier'
    NOTIFIER_VERSION = Probe::VERSION
    DEFAULT_OFFSET = 600
    DEFAULT_NEXT_RUN = 86400

    default_timeout 5
    headers  "Content-Type" => "application/json"

    attr_accessor :category, :action, :config, :next_run, :offset, :last_run, :force

    def initialize(category, action, config, options = {})
      self.category = category
      self.action = action.is_a?(Array) ? action.join('/') : action
      self.config = config
      self.next_run = options[:next_run] ? options[:next_run].to_i : default_next_run
      self.offset = options[:offset] || DEFAULT_OFFSET
      self.last_run = Time.now.to_i
      self.force = options[:force]
    end

    def default_next_run
      Time.now.to_i + DEFAULT_NEXT_RUN
    end

    def deliver

      return unless config.enabled? or force

      if @config.api_key.nil?
        Probe.warn("No API key configured, couldn't notify")
        return
      end

      if @config.endpoint.nil?
        Probe.warn("No endpoint configured, couldn't notify")
        return
      end

      endpoint = (config.use_ssl ? "https://" : "http://") + config.endpoint
      Probe.log("Notifying #{endpoint} of #{category}, #{action} from api_key #{config.api_key}")

      Notification.deliver_payload(endpoint, @config.api_key, payload)

    end

    def payload
      {
        notifier: {
          name: NOTIFIER_NAME,
          version: NOTIFIER_VERSION
        },
        events: [as_json]
      }
    end

    def next_run_with_offset
      next_run + offset
    end

    def as_json
      {
        category: category,
        action: action,
        last_run: last_run,
        next_run: next_run_with_offset,
        environment: config.environment
      }
    end

    class << self

      def deliver_payload(endpoint, key, payload)
        begin
          payload_string = JSON.dump(payload)
          options = { body: payload_string, headers: { 'X-API-KEY' => key } }
          response = post(endpoint, options)
          Probe.debug("Notification to #{endpoint} finished, response was #{response.code}, payload was #{payload_string}")
        rescue StandardError => e
          Probe.warn("Notification to #{endpoint} failed, #{e.inspect}")
        end
      end

    end

  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:gravity="center"
    android:orientation="horizontal">

    <com.wang.avi.AVLoadingIndicatorView
        style="@style/AVLoadingIndicatorView.Small"
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:indicatorColor="@color/tab_def_pager_primary_color"
        app:indicatorName="PacmanIndicator" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:text="正在加载..."
        android:textColor="@color/tab_def_pager_primary_color"
        android:textSize="14sp" />
</LinearLayout>


text:
package org.neo4j.doc.cypherdoc;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;

import org.neo4j.graphdb.Transaction;
import org.neo4j.visualization.asciidoc.AsciidocHelper;
import org.neo4j.visualization.graphviz.AsciiDocSimpleStyle;
import org.neo4j.visualization.graphviz.GraphvizWriter;
import org.neo4j.walk.Walker;

enum BlockType
{
    TITLE
    {
        @Override
        boolean isA( List<String> block )
        {
            int size = block.size();
            return size > 0 &&
                ( ( block.get( 0 ).startsWith( "=" )
                 && !block.get( 0 ).startsWith( "==" )));
        }

        @Override
        String process( Block block, State state )
        {
            String title = block.lines.get( 0 )
                    .replace( "=", "" )
                    .trim();
            String id = "cypherdoc-" + title.replace( ' ', '-' ).replaceAll( "[^\\w-]", "" ).toLowerCase();
            return "[[" + id + "]]" + CypherDoc.EOL + "= " + title + " ="
                   + CypherDoc.EOL;
        }
    },
    HIDE
    {
        @Override
        String process( Block block, State state )
        {
            return OutputHelper.passthroughMarker( "hide-query", "span", "simpara" );
        }

        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "hide" );
        }
    },
    SETUP
    {
        @Override
        String process( Block block, State state )
        {
            return OutputHelper.passthroughMarker( "setup-query", "span", "simpara" );
        }

        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "setup" );
        }
    },
    OUTPUT
    {
        @Override
        String process( Block block, State state )
        {
            return OutputHelper.passthroughMarker( "query-output", "span", "simpara" );
        }

        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "output" );
        }
    },
    PROFILE
    {
        @Override
        String process( Block block, State state )
        {
            return AsciidocHelper.createOutputSnippet( state.latestResult.profile );
        }

        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "profile" );
        }
    },
    TABLE
    {
        @Override
        String process( Block block, State state )
        {
            return AsciidocHelper.createQueryResultSnippet( state.latestResult.text );
        }

        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "table" );
        }
    },
    SQL_TABLE
    {
        @Override
        String process( Block block, State state )
        {
            return AsciidocHelper.createQueryResultSnippet( state.latestSqlResult.text );
        }

        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "sqltable" );
        }
    },
    QUERYTEST
    {
        @Override
        String process( Block block, State state )
        {
            if ( state.latestResult == null && state.latestSqlResult == null )
            {
                throw new IllegalArgumentException( "Nothing to test" );
            }
            List<String> tests = block.lines.subList( 1, block.lines.size() - 1 );
            boolean checkCypherResults = state.latestResult != null && state.latestResult != state.testedResult;
            boolean checkSqlResults = state.latestSqlResult != null && state.latestSqlResult != state.testedSqlResult;
            String result = checkCypherResults ? state.latestResult.text : null;
            String sqlResult = checkSqlResults ? state.latestSqlResult.text : null;
            List<String> failures = new ArrayList<>();
            List<String> sqlFailures = new ArrayList<>();
            for ( String test : tests )
            {
                if ( result != null && !result.contains( test ) )
                {
                    failures.add( test );
                }
                if ( sqlResult != null && !sqlResult.contains( test ) )
                {
                    sqlFailures.add( test );
                }
            }
            if ( !failures.isEmpty() )
            {
                throw new TestFailureException( state.latestResult, failures );
            }
            if ( !sqlFailures.isEmpty() )
            {
                throw new TestFailureException( state.latestSqlResult, sqlFailures );
            }

            state.testedResult = state.latestResult;
            state.testedSqlResult = state.latestSqlResult;

            return "";
        }

        @Override
        boolean isA( List<String> block )
        {
            return isCodeBlock( "querytest", block );
        }
    },
    PROFILETEST
    {
        @Override
        String process( Block block, State state )
        {
            if ( state.latestResult == null )
            {
                throw new IllegalArgumentException( "Nothing to test" );
            }
            List<String> tests = block.lines.subList( 1, block.lines.size() - 1 );
            String profile = state.latestResult.profile;
            List<String> failures = new ArrayList<>();
            for ( String test : tests )
            {
                if ( profile != null && !profile.contains( test ) )
                {
                    failures.add( test );
                }
            }
            if ( !failures.isEmpty() )
            {
                throw new TestFailureException( state.latestResult, failures );
            }
            return "";
        }

        @Override
        boolean isA( List<String> block )
        {
            return isCodeBlock( "profiletest", block );
        }
    },
    PARAMETERS
    {
        @Override
        boolean isA( List<String> block )
        {
            String first = block.get( 0 );
            return isCodeBlock( "json", block ) && first.contains( "role" )
                   && first.contains( "parameters" );
        }

        @Override
        String process( Block block, State state )
        {
            String json = getRawCodeBlockContent( block );
            try
            {
                state.parameters.clear();
                state.parameters.putAll( JSON_MAPPER.readValue( json, HashMap.class ) );
            }
            catch ( IOException e )
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String prettifiedJson = null;
            try
            {
                prettifiedJson = JSON_WRITER.writeValueAsString( state.parameters );
            }
            catch ( IOException e )
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "\n[source,json]\n----\n" + ( prettifiedJson == null ? json : prettifiedJson ) + "\n----\n\n";
        }
    },
    CYPHER
    {
        @Override
        boolean isA( List<String> block )
        {
            return isCodeBlock( "cypher", block );
        }

        @Override
        String process( Block block, State state )
        {
            String firstLine = block.lines.get( 0 );
            boolean exec = !(firstLine.contains( "noexec" ) || firstLine.contains( "hideexec" ));
            List<String> statements = getQueriesBlockContent( block );
            List<String> prettifiedStatements = new ArrayList<>();
            String webQuery = null;
            String fileQuery = null;
            for ( String query : statements )
            {
                webQuery = query;
                fileQuery = query;
                for ( String file : state.knownFiles )
                {
                    File absolutePath = new File( state.parentDirectory, file );
                    String fileUrl = absolutePath.toURI().toString();
                    fileQuery = replaceFilename( fileQuery, file, fileUrl );
                    webQuery = replaceFilename( webQuery, file, state.url + file );
                }
                if ( exec )
                {
                    state.latestResult =
                            new Result( fileQuery, state.engine.profile( fileQuery, state.parameters ), state.database );
                    prettifiedStatements.add( state.engine.prettify( webQuery ) );
                    try (Transaction tx = state.database.beginTx())
                    {
                        state.database.schema().awaitIndexesOnline( 10000, TimeUnit.SECONDS );
                        tx.success();
                    }
                }
                else
                {
                    prettifiedStatements.add( webQuery );
                }
            }

            state.parameters.clear();
            String cypher = StringUtils.join( prettifiedStatements, CypherDoc.EOL );
            return AsciidocHelper.createCypherSnippetFromPreformattedQuery( cypher, exec ) + CypherDoc.EOL
                   + CypherDoc.EOL;
        }
    },
    SQL
    {
        @Override
        boolean isA( List<String> block )
        {
            return isCodeBlock( "sql", block );
        }

        @Override
        String process( Block block, State state )
        {
            List<String> statements = getQueriesBlockContent( block );
            for ( String query : statements )
            {
                String result = executeSql( query, state.sqlDatabase );
                state.latestSqlResult = new Result( query, result );
            }
            String printQuery = StringUtils.join( statements, CypherDoc.EOL );
            return AsciidocHelper.createSqlSnippet( printQuery ) + CypherDoc.EOL + CypherDoc.EOL;
        }
    },
    GRAPH_RESULT
    {
        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "graph_result" );
        }

        @Override
        String process( Block block, State state )
        {
            return writeGraph( block, state, true );
        }
    },
    GRAPH
    {
        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "graph" );
        }

        @Override
        String process( Block block, State state )
        {
            return writeGraph( block, state, false );
        }
    },
    CONSOLE
    {
        @Override
        boolean isA( List<String> block )
        {
            return isACommentWith( block, "console" );
        }

        @Override
        String process( Block block, State state )
        {
            return OutputHelper.passthroughMarker( "cypherdoc-console", "p", "simpara" );
        }
    },
    FILE
            {
                @Override
                boolean isA( List<String> block )
                {
                    return isACommentWith( block, "file:" );
                }

                @Override
                String process( Block block, State state )
                {
                    String fileLine = block.lines.get( 0 );
                    String[] split = fileLine.split( ":" );
                    assert split.length == 2;
                    String fileName = split[1];
                    state.knownFiles.add( fileName );
                    return "";
                }
            },
    TEXT
    {
        @Override
        boolean isA( List<String> block )
        {
            return true;
        }

        @Override
        String process( Block block, State state )
        {
            return StringUtils.join( block.lines, CypherDoc.EOL ) + CypherDoc.EOL;
        }
    };

    private static final String CODE_BLOCK = "----";
    private static final int COLUMN_MAX_WIDTH = 25;
    private static final String LINE_SEGMENT = new String( new char[COLUMN_MAX_WIDTH] ).replace( '\0', '-' );
    private static final String SPACE_SEGMENT = new String( new char[COLUMN_MAX_WIDTH] ).replace( '\0', ' ' );
    private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
    private static final ObjectWriter JSON_WRITER = JSON_MAPPER.writerWithDefaultPrettyPrinter();

    abstract boolean isA( List<String> block );

    abstract String process( Block block, State state );

    private static String writeGraph( Block block, State state, boolean resultOnly )
    {
        String first = block.lines.get( 0 );
        String id = "";
        if ( first.length() > 8 )
        {
            id = first.substring( first.indexOf( "graph" ) + 5 ).trim();
            if ( id.indexOf( ':' ) != -1 )
            {
                id = first.substring( first.indexOf( ':' ) + 1 ).trim();
            }
            else if ( id.startsWith( "_result" ) )
            {
                id = "result";
            }
        }
        GraphvizWriter writer = new GraphvizWriter(
                AsciiDocSimpleStyle.withAutomaticRelationshipTypeColors() );
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (Transaction tx = state.database.beginTx())
        {
            if ( resultOnly )
            {
                writer.emit( out, ResultWalker.result( state ) );
            }
            else
            {
                writer.emit( out, Walker.fullGraph( state.database ) );
            }
            tx.success();
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
        StringBuilder output = new StringBuilder( 512 );
        try
        {
            String dot = out.toString( "UTF-8" );
            output.append( "[\"dot\", \"cypherdoc-" )
                    .append( id )
                    .append( '-' )
                    .append( Integer.toHexString( dot.hashCode() ) )
                    .append( ".svg\", \"neoviz\"]\n----\n" )
                    .append( dot )
                    .append( "----\n" );
        }
        catch ( UnsupportedEncodingException e )
        {
            e.printStackTrace();
        }
        return output.toString();
    }

    private static boolean isABlockOfType( List<String> block, String type )
    {
        if ( block.size() >= 3 )
        {
            String first = block.get( 0 );
            if ( first.startsWith( "[" + type + "]" ) )
            {
                return true;
            }
        }
        return false;
    }

    private static boolean isACommentWith( List<String> block, String command )
    {
        String first = block.get( 0 );
        return first.startsWith( "//" + command ) || first.startsWith( "// " + command );
    }

    private static boolean isCodeBlock( String language, List<String> block )
    {
        String first = block.get( 0 );
        if ( first.charAt( 0 ) != '[' )
        {
            return false;
        }
        if ( first.contains( "source" ) && first.contains( language ) )
        {
            return true;
        }
        if ( block.size() > 4 && first.startsWith( "[[" ) )
        {
            String second = block.get( 1 );
            if ( second.contains( "source" ) && second.contains( language ) )
            {
                return true;
            }
        }
        return false;
    }

    private static List<String> getQueriesBlockContent( Block block )
    {
        List<String> statements = new ArrayList<>();
        List<String> queryLines = new ArrayList<>();
        boolean queryStarted = false;
        for ( String line : block.lines )
        {
            if ( !queryStarted )
            {
                if ( line.startsWith( CODE_BLOCK ) )
                {
                    queryStarted = true;
                }
            }
            else
            {
                if ( line.startsWith( CODE_BLOCK ) )
                {
                    break;
                }
                else
                {
                    queryLines.add( line );
                    if ( line.endsWith( ";" ) )
                    {
                        statements.add( StringUtils.join( queryLines, CypherDoc.EOL ) );
                        queryLines.clear();
                    }
                }
            }
        }
        if ( queryLines.size() > 0 )
        {
            statements.add( StringUtils.join( queryLines, CypherDoc.EOL ) );
        }
        return statements;
    }

    private static String getRawCodeBlockContent( Block block )
    {
        List<String> lines = new ArrayList<>();
        boolean codeStarted = false;
        for ( String line : block.lines )
        {
            if ( !codeStarted )
            {
                if ( line.startsWith( CODE_BLOCK ) )
                {
                    codeStarted = true;
                }
            }
            else
            {
                if ( line.startsWith( CODE_BLOCK ) )
                {
                    break;
                }
                else
                {
                    lines.add( line );
                }
            }
        }
        return StringUtils.join( lines, "\n" );
    }

    private static String executeSql( String sql, Connection sqldb )
    {
        StringBuilder builder = new StringBuilder( 512 );
        try (Statement statement = sqldb.createStatement())
        {
            if ( statement.execute( sql ) )
            {
                try (ResultSet result = statement.getResultSet())
                {
                    ResultSetMetaData meta = result.getMetaData();
                    int rowCount = 0;
                    int columnCount = meta.getColumnCount();
                    String line = new String( new char[columnCount] ).replace( "\0", "+" + LINE_SEGMENT ) + "+\n";
                    builder.append( line );

                    for ( int i = 1; i <= columnCount; i++ )
                    {
                        String output = meta.getColumnLabel( i );
                        printColumn( builder, output );
                    }
                    builder.append( "|\n" ).append( line );
                    while ( result.next() )
                    {
                        rowCount++;
                        for ( int i = 1; i <= columnCount; i++ )
                        {
                            String output = result.getString( i );
                            printColumn( builder, output );
                        }
                        builder.append( "|\n" );
                    }

                    builder.append( line ).append( rowCount ).append( " rows\n" );
                }
            }
        }
        catch ( SQLException sqlException )
        {
            throw new RuntimeException( sqlException );
        }
        return builder.toString();
    }

    private static void printColumn( StringBuilder builder, String value )
    {
        if ( value == null )
        {
            value = "<null>";
        }
        builder.append( "| " ).append( value ).append( SPACE_SEGMENT.substring( value.length() + 1 ) );
    }

    private static String replaceFilename( String query, String filename, String replacement )
    {
        return query.replace( "'" + filename + "'", "'" + replacement + "'" )
                    .replace( '"' + filename + '"', '"' + replacement + '"' );
    }
}


text:
// -------------------------------------------------------
// PSAccount.h
//
// Copyright (c) 2010-11 Jakub Suder <jakub.suder@gmail.com>
// Licensed under MIT license
// -------------------------------------------------------

/*
  User account model, with username and password fields by default. Can be subclassed to add more fields
  (in that case, override 'propertyList' or 'propertiesSavedInSettings' and 'isPropertySavedSecurely' if necessary).

  Provides methods to load and save fields from settings/keychain and to clear them. This class is also used
  by PSConnector for HTTP Authentication (though you can use any other class that has username and password fields).

  Usage:
      PSConnector *connector = [PSConnector sharedConnector];
      connector.account = [PSAccount accountFromSettings];
      connector.usesHTTPAuthentication = YES;
      // connect ...

      [connector.account setPassword: @"updated"];
      [connector.account save];
*/

#import <Foundation/Foundation.h>
#import "PSModel.h"

@protocol PSConnectorAccount;

@interface PSAccount : PSModel <PSConnectorAccount> {
  NSString *username;
  NSString *password;
}

@property (nonatomic, copy) NSString *username;
@property (nonatomic, copy) NSString *password;

// fields that will be saved and loaded from settings/keychain (by default all fields listed in 'propertyList')
+ (NSArray *) propertiesSavedInSettings;

// callback that tells if a property is a password (by default only 'password' is a treated as a password)
+ (BOOL) isPropertySavedSecurely: (NSString *) property;

// settings key for a given property (by default 'account.<property>')
+ (NSString *) settingNameForProperty: (NSString *) property;

// loads account data from settings/keychain and returns a new account, or nil if not all fields are set
+ (id) accountFromSettings;

// tells if all fields listed in propertiesSavedInSettings are set and non-empty
- (BOOL) hasAllRequiredProperties;

// saves account data to settings/keychain
- (void) save;

// clears account data in settings/keychain and sets all fields to nil
- (void) clear;

@end


text:
layout: base
title:  'Statistics of expl in UD_Albanian-TSA'
udver: '2'
---

## Treebank Statistics: UD_Albanian-TSA: Relations: `expl`

This relation is universal.

6 nodes (1%) are attached to their parents as `expl`.

6 instances of `expl` (100%) are right-to-left (child precedes parent).
Average distance between parent and child is 1.

The following 1 pairs of parts of speech are connected with `expl`: <tt>VERB</tt>-<tt>PRON</tt> (6; 100% instances).

~~~ conllu
# visual-style 3	bgColor:blue
# visual-style 3	fgColor:white
# visual-style 4	bgColor:blue
# visual-style 4	fgColor:white
# visual-style 4 3 expl	color:blue
1	Disa	disa	PRON	_	Case=Nom|Gender=Masc|Number=Plur|PronType=Ind	4	nsubj	_	_
2	madje	madje	PART	_	_	4	advmod	_	_
3	e	ai	PRON	_	Case=Acc|Gender=Fem|Number=Sing|PronType=Emp	4	expl	_	_
4	mohojnë	mohoj	VERB	_	Aspect=Imp|Mood=Ind|Number=Plur|Person=3|Tense=Pres|Voice=Act	0	root	_	_
5	qenësinë	qenësinë	NOUN	_	Case=Acc|Definite=Def|Gender=Fem|Number=Sing	4	obj	_	_
6	e	i	DET	_	Gender=Fem	7	det:pron	_	_
7	saj	ajo	PRON	_	Case=Gen|Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs	5	nmod:poss	_	SpaceAfter=No
8	.	.	PUNCT	_	_	4	punct	_	_

~~~


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

namespace Logikfabrik.Umbraco.Jet.Data
{
    /// <summary>
    /// The <see cref="ITypeRepository" /> interface.
    /// </summary>
    public interface ITypeRepository : IContentTypeRepository, IDataTypeRepository
    {
    }
}


text:
var browsers = [
  // 'Firefox',
  'Chrome',
  'IE',
  'PhantomJS'
];

var plugins = [
  'karma-mocha-reporter',
  'karma-mocha',
  'karma-chai',
  'karma-sinon',
  'karma-firefox-launcher',
  'karma-chrome-launcher',
  'karma-ie-launcher',
  'karma-phantomjs-launcher',
  'karma-es6-shim'
];

module.exports = function (config) {

  'use strict';

  config.set({
    singleRun: true,
    basePath: '',
    frameworks: ['mocha', 'chai', 'sinon', 'es6-shim'],
    browsers: browsers,
    reporters: ['mocha'],
    plugins: plugins,
    files: [
      { pattern: 'node_modules/reflect-metadata/Reflect.js', include: true },
      { pattern: 'test/bundle.test.js', included: true }
    ],
    port: 9876,
    colors: true,
    autoWatch: false,
    logLevel: config.LOG_INFO
  });

};


text:
#ifndef ORGANIZER_UDRAGGABLEITEM_H
#define ORGANIZER_UDRAGGABLEITEM_H

#include <QtWidgets/QFrame>
#include <QtGui/QMouseEvent>
#include <QtWidgets/QVBoxLayout>

class UDraggableItem : public QWidget {
    unsigned long item_id;
    QVBoxLayout *marginLayout;
    QSpacerItem *topMargin, *bottomMargin;

public:
    UDraggableItem(unsigned long id);

    bool eventFilter(QObject *watched, QEvent *event) override;

    // For child event handling
    virtual bool itemEventFilter(QObject *watched, QEvent *event);

    virtual void itemDropped(unsigned long dropped_id, unsigned long at_id);

protected:
    void addLayout(QBoxLayout *l);

    void setMarginFromPos(int py);

    void installDragFilter(QList<QWidget *> list);

    void dragEnterEvent(QDragEnterEvent *event) override;

    void dragMoveEvent(QDragMoveEvent *event) override;

    void dragLeaveEvent(QDragLeaveEvent *event) override;

    void dropEvent(QDropEvent *event) override;
};

#endif //ORGANIZER_UDRAGGABLEITEM_H


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('domain_api', '0042_remove_registereddomain_domain'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='registereddomain',
            unique_together=set([('name', 'tld', 'active')]),
        ),
    ]


text:
#include "VIDSdefs.h"
TAEVariable	*GetVariable();
#define GRAB(x) {v = GetVariable(env,x); if (v == NULL) return FAIL;}
/************************************************************************/
/* jmovie_set_do sets up the frame size and the number of frames
 * for VIDS movies.
 */
int jmovie_set_do(env)
  VIDSEnvironment		*env;	/* The VIDS environment		*/
{
  TAEVariable	*v;			/* temp variable ptr		*/
  register int	nl,nf;			/* local frame size,nframes	*/
  int		nlVideo,nsVideo;	/* size of screen		*/

  nlVideo = VideoLines(env);
  nsVideo = VideoSamps(env);

  GRAB("NLFRAME");
  if (v->v_count == 0)
    nl = nlVideo;
  else
    nl = MIN(nlVideo, IVAL(*v, 0));

  GRAB("NFRAMES");
  nf = (v->v_count == 0) ? 0 : IVAL(*v, 0);

  if (nl <= 0)
    ABORT(FAIL,"Sorry, NLFRAME (lines per frame) must be greater than zero",
          "VIDS-BADPARM");

  env->movie.movieZoom = nlVideo / nl;
  env->movie.nlFrame = nlVideo / env->movie.movieZoom;
  env->movie.nsFrame = nsVideo / env->movie.movieZoom;
  nl = MIN(env->nlMax / env->movie.nlFrame, env->nsMax / env->movie.nsFrame);
  env->movie.bwFrames = env->nimps * nl * nl;
  env->movie.nFrames = (nf == 0) ? env->movie.bwFrames :
				   MIN(nf, env->movie.bwFrames);
  env->movie.colorFrames = (env->nimps > 3) ? (env->movie.bwFrames / 4) :
					      (env->movie.bwFrames / 3);
  GiveFrameSizes(env);

  GRAB("REVERSE");
  env->movie.reverseKey = *SVAL(*v, 0);

  GRAB("FASTER");
  env->movie.fastKey = *SVAL(*v, 0);

  GRAB("SLOWER");
  env->movie.slowKey = *SVAL(*v, 0);

  GRAB("PAUSE");
  env->movie.pauseKey = *SVAL(*v, 0);

  return SUCCESS;
}
/************************************************************************/
/* jmovie_load_do loads up frames for a VIDS movie.
 */
int jmovie_load_do(env)
  VIDSEnvironment		*env;	/* The VIDS environment		*/
{
  int		i,j;			/* increment variables		*/
  int		plane,lastPlane;	/* first plane for a given frame*/
  int		frame;			/* frame to load		*/
  int		zoom;			/* zoom factor to apply		*/
  int		area[4];		/* image area to be displayed	*/
  Point		topLeft;		/* top left of each frame	*/
  FileInfo	*files[3];		/* current file of interest	*/
  int		nfiles;			/* number of input files	*/
  int		bands[3];		/* current band of interest	*/
  PlaneInfo	*p;			/* temp plane ptr		*/
  MessageType	messages,GetMessage();	/* saved value of message level	*/

  if (GetMovieLoadParms(env, &frame, area, &zoom) != SUCCESS) return FAIL;
  CheckSettings(env);
  i = env->isColor ? env->movie.colorFrames : env->movie.bwFrames;
  if (frame > i)
  {
    NotifyUser(Inform, "", "Sorry, can not load frame %d, highest frame is %d",
               frame, i);
    NotifyUser(Inform,"","Note sizes, and use JMOVIE-SET to modify them:");
    GiveFrameSizes(env);
    ABORT(FAIL,"Unable to load frame","VIDS-BADPARM");
  }
  FrameToPlane(env, frame, &plane, &topLeft);
  if (GetFileBand(env, files, bands, &nfiles) != SUCCESS) return FAIL;
  if (env->isColor)
  {
    lastPlane = plane + 2;
    env->redIMP = plane;
    env->greenIMP = plane + 1;
    env->blueIMP = plane + 2;
  }
  else
  {
    lastPlane = plane;
    env->bwIMP = plane;
  }
  SendLuts(env);
  lastPlane = MIN(lastPlane, env->nimps);
  NotifyUser(Inform,"","Loading frame number %d",frame);
  for (j = plane, i = 0; j <= lastPlane; j++, i++)
  {
    if ((i >= nfiles) && (bands[i] > (files[i])->nb)) break;
    p = &env->planes[j];
    TieImp(p, files[i], bands[i]);
    SetFileWindow(p, area[0], area[1], area[2], area[3]);
    SetMLoadZoom(env, p, files[i], zoom);
    p->accessWindow.sl = topLeft.v;
    p->accessWindow.ss = topLeft.h;
    p->accessWindow.nl = env->movie.nlFrame;
    p->accessWindow.ns = env->movie.nsFrame;
    p->subPixel.left = p->subPixel.top = 0;
    messages = GetMessage();
    if (messages != Verbose)		/* If not Verbose messages,	*/
      SetMessage(Silent);		/* make the updates silent.	*/
    LoadIMP(env, j);
    SetMessage(messages);
  }
  i = SUCCESS;
  switch (nfiles)
  {
    case 3 : CloseFile(files[2]);
    case 2 : CloseFile(files[1]);
    case 1 : i = CloseFile(files[0]);
  }
  if (i != SUCCESS)
    ABORT(FAIL,"Could not close all files, proceed with caution",
          "VIDS-CLOSFAIL");
  return SUCCESS;
}
/************************************************************************/
/* jmovie_run_do runs a vids movie.
 */
int jmovie_run_do(env)
  VIDSEnvironment		*env;	/* The VIDS environment		*/
{
  int		start;			/* starting frame of animation	*/
  int		frames;			/* number of frames to show	*/
  Boolean	forward;		/* direction: reverse if False.	*/
  Boolean	reverse;		/* True to reverse direction.	*/
  Boolean	terminate;		/* Flag to end looping		*/
  float		rate;			/* rate at which to run		*/
  int		nskip;			/* number of frames to skip	*/
  int		loops;			/* times to repeat animation	*/
  int		zoom;			/* hardwar zoom factor to apply	*/
  int		i,j;			/* increment variables		*/
  int		curPlane,lastPlane;	/* current,last planes		*/
  Point		curPt,lastPt;		/* upper left corner of plane	*/
  int		curFrame;		/* current frame		*/
  int		end;			/* ending frame of animation	*/
  int		nf;			/* nFrames limited by # available */
  Boolean	EqualPoint();

  i = GetRunParms(env, &start, &frames, &forward, &rate, &nskip,
    &loops,&zoom);
  if (i != SUCCESS) return FAIL;
  CheckSettings(env);		/* make sure sizes are good		*/
  nf = MIN(env->movie.nFrames, (env->isColor ? env->movie.colorFrames :
					       env->movie.bwFrames));
  if (frames <= 0)
    frames = nf;
  frames = MIN(nf, frames);

  if (loops <= 0) loops = 32767;
  if (nskip < 0)
    ABORT(FAIL,"Sorry, NSKIP may not be less than zero","VIDS-BADPARM");
  if (rate <= 0.0)
    ABORT(FAIL,"Sorry, RATE must be greater than zero","VIDS-BADPARM");
  if (! env->movie.indPan) zdeaction(1, 2, 2);
  FrameToPlane(env, start, &curPlane, &curPt);
  if (zoom <= 0) zoom = env->movie.movieZoom;
  for (i = 1; i <= env->nimps; i++)
  {
    zdidwset(env->devUnit, i, curPt.h, curPt.v);
    zdizoom(env->devUnit, i, zoom);
  }

  rate = 1.0 / rate;		/* convert from frames/second to seconds*/
  nskip += 1;			/* convert nskip to an increment var.	*/

  if (frames > ((nf - start) / nskip) + 1)
    frames = ((nf - start) / nskip) + 1;
  end = start + ((frames-1) * nskip);
  if (!forward) nskip = -nskip;

  NotifyUser(Inform,"","Control keys are as follows:");
  NotifyUser(Inform,"","\t%c to reverse direction",env->movie.reverseKey);
  NotifyUser(Inform,"","\t%c to increase speed",env->movie.fastKey);
  NotifyUser(Inform,"","\t%c to decrease speed",env->movie.slowKey);
  NotifyUser(Inform,"","\t%c to pause",env->movie.pauseKey);
  NotifyUser(Inform,"","Any other key will stop the movie.");
  lastPlane = 0;
  terminate = False;
  reverse = False;	/* means we changed, not absolute reverse direction */
  StartTimer();
  for (i = 0; i < loops; i++)	/* for each loop of the movie...	*/
  {
    if (nskip >= 0)
      curFrame = start;			/* forward */
    else
      curFrame = end;			/* reverse */

    while (curFrame >= start && curFrame <= end)	/* for each plane */
    {
      CheckButtons(env, &rate, &reverse, &terminate);
      if (reverse)
        nskip = -nskip;
      if (terminate) break;
      FrameToPlane(env, curFrame, &curPlane, &curPt);
      WaitElapsed(rate);
      if (curPlane == lastPlane)
      {
        if (!EqualPoint(&curPt, &lastPt))
	  SetCorner(env, curPlane, &curPt);
      }
      else
      {
	SetCorner(env, curPlane, &curPt);
	SetPlane(env, curPlane);
      }
      StartTimer();
      lastPlane = curPlane;
      lastPt.h = curPt.h; lastPt.v = curPt.v;
      curFrame += nskip;
    }
    if (terminate) break;
  }
  FixPlanes(env);
  if (! env->movie.indPan) zdeaction(2, 2, 2);
  return SUCCESS;
}
/************************************************************************/
/* jmovie_show_do will display the given frame of an already loaded movie.
 */
int jmovie_show_do(env)
  VIDSEnvironment		*env;	/* The VIDS environment		*/
{
  int		theFrame;		/* the frame to show		*/
  int		thePlane;		/* image plane of the frame	*/
  int		nf;			/* local max number of frames	*/
  Point		loc;			/* upper left corner of frame	*/
  TAEVariable	*v;

  GRAB("FRAME");
  theFrame = IVAL(*v, 0);

  CheckSettings(env);

  if (theFrame <= 0)
    ABORT(FAIL,"Sorry, FRAME must be greater than zero","VIDS-BADPARM");
  nf = env->isColor ? env->movie.colorFrames : env->movie.bwFrames;
  if (theFrame > nf)
  {
    if (theFrame <= nf)
      NotifyUser(Inform,"","Frame is outside of movie loop, showing anyway");
    else
      ABORT(FAIL,"Sorry, FRAME must be less than the number of frames",
	"VIDS-BADPARM");
  }

  FrameToPlane(env, theFrame, &thePlane, &loc);
  if (!env->movie.indPan) zdeaction(1, 2, 2);
  zdizoom(env->devUnit, thePlane, env->movie.movieZoom);
  SetCorner(env, thePlane, &loc);
  if (!env->movie.indPan) zdeaction(2, 2, 2);
  SetPlane(env, thePlane);
  FixPlanes(env);
  return SUCCESS;
}
/************************************************************************/
int GetMovieLoadParms(env, frame, area, zoom)
  VIDSEnvironment	*env;		/* The VIDS environment		*/
  int			*frame;		/* out: frame to load		*/
  int			area[];		/* out: area of image to load	*/
  int			*zoom;		/* out: zoom factor		*/
{
  TAEVariable	*v;

  env->movie.prevFrame++;
  if (env->movie.prevFrame > env->movie.nFrames) env->movie.prevFrame = 1;
  GRAB("FRAME");
  if (v->v_count == 1)
    env->movie.prevFrame = IVAL(*v, 0);
  *frame = env->movie.prevFrame;

  GRAB("AREA");
  if (v->v_count == 4)
  {
    area[0] = IVAL(*v, 0);	area[1] = IVAL(*v, 1);
    area[2] = IVAL(*v, 2);	area[3] = IVAL(*v, 3);
  }
  else
  {
    area[0] = area[1] = 1;	area[2] = area[3] = 0;
  }

  *zoom = 0;
  GRAB("ZOOM");
  if (v->v_count == 1)
    *zoom = IVAL(*v, 0);
  else
  {
    GRAB("SCALE");
    if (EQUAL(SVAL(*v, 0), "NONE")) *zoom = 1;
  }
  return SUCCESS;
}
/************************************************************************/
int GetRunParms(env, start, frames, forward, rate, nskip, loops, zoom)
  VIDSEnvironment	*env;		/* The VIDS environment		*/
  int			*start;		/* starting frame of animation	*/
  int			*frames;	/* number of frames to show	*/
  Boolean		*forward;	/* direction: reverse if False.	*/
  float			*rate;		/* rate at which to run		*/
  int			*nskip;		/* number of frames to skip	*/
  int			*loops;		/* times to repeat animation	*/
  int			*zoom;		/* zoom factor to use		*/
{
  TAEVariable	*v;

  GRAB("START");
  *start = IVAL(*v, 0);
  GRAB("NFRAMES");
  *frames = (v->v_count == 0) ? 0 : IVAL(*v, 0);
  GRAB("DIRECTN");
  *forward = (*SVAL(*v, 0) == 'R') ? False : True;
  GRAB("RATE");
  *rate = RVAL(*v, 0);
  GRAB("NSKIP");
  *nskip = IVAL(*v, 0);
  GRAB("LOOPS");
  *loops = (v->v_count == 0) ? 0 : IVAL(*v, 0);
  GRAB("ZOOM");
  *zoom = (v->v_count == 0) ? 0 : IVAL(*v, 0);
  return SUCCESS;
}
/************************************************************************/
/* GetFileBand looks at the INP parameter and fills in three file/band
 * pairs if color, 1 pair if bw into the files and the bands arguments.
 */
int GetFileBand(env, files, bands, nfiles)
  VIDSEnvironment	*env;
  FileInfo		*files[3];	/* out: files to be loaded	*/
  int			bands[3];	/* out: respective file bands	*/
  int			*nfiles;	/* number of input files	*/
{
  char		*names[3];		/* file names			*/
  char		*memMsg="Sorry, insufficient memory to open any more files";
  char		*opnfail="Sorry, could not open input file";
  int		i;			/* increment variable		*/
  TAEVariable	*v;			/* TAE variable structure	*/
  FileInfo	*findFileSlot();

  names[0] = names[1] = names[2] = NULL;
  GRAB("INP");
  *nfiles = v->v_count;
  for (i = 0; i < *nfiles; i++)
    names[i] = SVAL(*v, i);

  bands[0] = 1;
  switch (*nfiles)
  {
    case 3 :
      bands[1] = bands[2] = 1;
      files[2] = findFileSlot(env, names[2]);
      if (files[2] == NULL) ABORT(FAIL, memMsg, "VIDS-INSUFMEM");
      if (OpenFile(files[2]) != SUCCESS) ABORT(FAIL, opnfail, "VIDS-OPENFAIL");
      files[1] = findFileSlot(env, names[1]);
      if (files[1] == NULL) ABORT(FAIL, memMsg, "VIDS-INSUFMEM");
      if (OpenFile(files[1]) != SUCCESS) ABORT(FAIL, opnfail, "VIDS-OPENFAIL");
      files[0] = findFileSlot(env, names[0]);
      if (files[0] == NULL) ABORT(FAIL, memMsg, "VIDS-INSUFMEM");
      if (OpenFile(files[0]) != SUCCESS) ABORT(FAIL, opnfail, "VIDS-OPENFAIL");
      break;
    case 2 :
      bands[1] = 1; bands[2] = 2;
      files[1] = findFileSlot(env, names[1]);
      if (files[1] == NULL) ABORT(FAIL, memMsg, "VIDS-INSUFMEM");
      if (OpenFile(files[1]) != SUCCESS) ABORT(FAIL, opnfail, "VIDS-OPENFAIL");
      files[0] = findFileSlot(env, names[0]);
      if (files[0] == NULL) ABORT(FAIL, memMsg, "VIDS-INSUFMEM");
      if (OpenFile(files[0]) != SUCCESS) ABORT(FAIL, opnfail, "VIDS-OPENFAIL");
      files[2] = files[1];
      break;
    case 1 :
      bands[1] = 2; bands[2] = 3;
      files[0] = findFileSlot(env, names[0]);
      if (files[0] == NULL) ABORT(FAIL, memMsg, "VIDS-INSUFMEM");
      if (OpenFile(files[0]) != SUCCESS) ABORT(FAIL, opnfail, "VIDS-OPENFAIL");
      files[2] = files[1] = files[0];
      break;
  }
  GRAB("BANDS");
  for (i = 0; i < v->v_count; i++)
    bands[i] = IVAL(*v, i);

  return SUCCESS;
}
/************************************************************************/
int SetMLoadZoom(env, p, file, zoom)
  VIDSEnvironment	*env;
  PlaneInfo	*p;
  FileInfo	*file;
  int		zoom;
{
  int	i;
  float	x,y;

  if (zoom != 0)
  {
    p->softZoom = zoom;
    return SUCCESS;
  }
  if (file == NULL)	/* just in case ... */
  {
    p->softZoom = 1;
    return SUCCESS;
  }
  i = p->imageWindow.nl;
  if (i == 0) i = file->nl - p->imageWindow.sl + 1;
  y = (float) (env->movie.nlFrame) / (float) (i);

  i = p->imageWindow.ns;
  if (i == 0) i = file->ns - p->imageWindow.ss + 1;
  x = (float) (env->movie.nsFrame) / (float) (i);

  x = MIN(x,y);
  p->softZoom = (int) ((x < 1.0) ? -(1.0/x + 0.999) : x);
  return SUCCESS;
}
/************************************************************************/
/* converts a frame number to a plane number and a display window
 * coordinate.
 */
int FrameToPlane(env, frame, plane, topLeft)
  VIDSEnvironment	*env;
  int			frame;
  int			*plane;
  Point			*topLeft;
{
  int frameZoom;

  frameZoom = MIN(env->nlMax / env->movie.nlFrame,
		  env->nsMax / env->movie.nsFrame);
  frame--;
  *plane = (frame / (frameZoom * frameZoom)) + 1;

  topLeft->v = (frame % frameZoom) * env->movie.nlFrame + 1;
  topLeft->h = ((frame % (frameZoom * frameZoom)) / frameZoom) *
							env->movie.nsFrame + 1;

  if ((env->movie.indPan == False) && (*plane % 2) == 0)
  {
    topLeft->v = env->nlMax - topLeft->v - env->movie.nlFrame + 2;
    topLeft->h = env->nsMax - topLeft->h - env->movie.nsFrame + 2;
  }
  if (env->isColor)
    *plane = (*plane - 1) * 4 + 1;		/* 4 for Adage 3000	*/
  return SUCCESS;
}
/************************************************************************/
int SetPlane(env, plane)
  VIDSEnvironment	*env;
  int			plane;
{
  if (env->isColor)
  {
    env->redIMP = plane;
    env->greenIMP = plane + 1;
    env->blueIMP = plane + 2;
  }
  else
  {
    env->bwIMP = plane;
  }
  SendLuts(env);
  return SUCCESS;
}
/************************************************************************/
int SetCorner(env, plane, topLeft)
  VIDSEnvironment	*env;
  int			plane;
  Point			*topLeft;
{
  if (env->isColor)
  {
    zdidwset(env->devUnit, plane, topLeft->h, topLeft->v);
    plane++;
    zdidwset(env->devUnit, plane, topLeft->h, topLeft->v);
    plane++;
    zdidwset(env->devUnit, plane, topLeft->h, topLeft->v);
  }
  else
    zdidwset(env->devUnit, plane, topLeft->h, topLeft->v);
  return SUCCESS;
}
/************************************************************************/
/* CheckSettings checks the frame sizes and other globals for movies
 * and ensures that everything is valid.
 */
int CheckSettings(env)
  VIDSEnvironment	*env;
{
  static int		maxZoom;	/* maximum zoom supported	*/
  int 			unit;		/* device unit number		*/

  unit = env->devUnit;
  zddinfo(unit, 20, 1, &env->movie.indPan);
  zddinfo(unit, 38, 1, &maxZoom);
  if (env->movie.movieZoom <= 0) env->movie.movieZoom = 1;
  else if (env->movie.movieZoom > maxZoom) env->movie.movieZoom = maxZoom;
  env->movie.nlFrame = VideoLines(env) / env->movie.movieZoom;
  env->movie.nsFrame = VideoSamps(env) / env->movie.movieZoom;

  maxZoom = MIN(env->nlMax / env->movie.nlFrame,
		env->nsMax / env->movie.nsFrame);
  if (env->movie.bwFrames == 0)
    env->movie.bwFrames = env->nimps * maxZoom * maxZoom;
  env->movie.colorFrames = (env->nimps > 3) ? (env->movie.bwFrames / 4) :
					      (env->movie.bwFrames / 3);
  if (env->movie.nFrames == 0)
    env->movie.nFrames = env->isColor ? env->movie.colorFrames :
					env->movie.bwFrames;

  env->movie.reverseKey = toupper(env->movie.reverseKey);
  env->movie.fastKey = toupper(env->movie.fastKey);
  env->movie.slowKey = toupper(env->movie.slowKey);
  env->movie.pauseKey = toupper(env->movie.pauseKey);
  env->movie.stepKey = toupper(env->movie.stepKey);

  return SUCCESS;
}
/************************************************************************/
int FixPlanes(env)
  VIDSEnvironment	*env;
{
  int i,x,y;
  PlaneInfo *p;
  int	unit;

  unit = env->devUnit;
  for (i = 1; i <= env->nimps; i++)		/* make sure saved locs	*/
  {						/* are correct.		*/
    p = &env->planes[i];			/* Ignore errors and try to */
    zdidwlocation(unit, i, &x, &y);		/* do as many as possible.  */
  }
  return SUCCESS;
}
/************************************************************************/
#define CHANGERATE 0.5
int CheckButtons(env, rate, reverse, terminate)
  VIDSEnvironment	*env;
  float			*rate;
  Boolean		*reverse;
  Boolean		*terminate;
{
  char PeekChar(),c;

  *terminate = False;
  *reverse = False;
  c = PeekChar(False);
  if (c == '\0') return SUCCESS;
  c = toupper(c);
  if (c == env->movie.fastKey)
    *rate *= CHANGERATE;
  else if (c == env->movie.slowKey)
    *rate /= CHANGERATE;
  else if (c == env->movie.reverseKey)
    *reverse = True;
  else if (c == env->movie.pauseKey)
    while (PeekChar(False) == '\0');
/*  else if (c == env->movie.stepKey)*/
  else
    *terminate = True;
  if (*rate > 2.0) *rate = 2.0;
  return SUCCESS;
}
/************************************************************************/
int GiveFrameSizes(env)
  VIDSEnvironment	*env;
{
  int cFrames;

  NotifyUser(Inform, "", "\tAvailable frame size is %d lines by %d samples",
             env->movie.nlFrame, env->movie.nsFrame);
  NotifyUser(Inform, "", "\t%d frames are available in black and white,",
             env->movie.bwFrames);
  NotifyUser(Inform, "", "\t%d frames are available in color.",
	     env->movie.colorFrames);
  cFrames = MIN(env->movie.colorFrames, env->movie.nFrames);
  NotifyUser(Inform,"","\t%d b&w (%d color) frames are currently in use",
             env->movie.nFrames,cFrames);
  return SUCCESS;
}
/************************************************************************/
/* Initialize the movie state variables in the environment structure.
 */
InitMovie(env)
  VIDSEnvironment	*env;
{
  env->movie.nlFrame = 0;
  env->movie.nsFrame = 0;
  env->movie.nFrames = 0;
  env->movie.bwFrames = 0;
  env->movie.colorFrames = 0;
  env->movie.movieZoom = 0;
  env->movie.prevFrame = 0;

  env->movie.reverseKey = 'r';
  env->movie.fastKey = '2';
  env->movie.slowKey = '1';
  env->movie.pauseKey = 'p';
  env->movie.stepKey = 's';
}
/************************************************************************/


text:
<?php

namespace Symfony\Component\Messenger\Transport\Doctrine;

use Symfony\Component\Messenger\Bridge\Doctrine\Transport\DoctrineTransport as BridgeDoctrineTransport;

@trigger_error(sprintf('The "%s" class is deprecated since Symfony 5.1, use "%s" instead. The Doctrine transport has been moved to package "symfony/doctrine-messenger" and will not be included by default in 6.0. Run "composer require symfony/doctrine-messenger".', DoctrineTransport::class, BridgeDoctrineTransport::class), E_USER_DEPRECATED);

class_exists(BridgeDoctrineTransport::class);

if (false) {
    /**
     * @deprecated since Symfony 5.1, to be removed in 6.0. Use symfony/doctrine-messenger instead.
     */
    class DoctrineTransport
    {
    }
}